max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
629 | <reponame>unghee/TorchCraftAI
/*
* Copyright (c) 2017-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "sarsa.h"
#include "batcher.h"
#include "common/autograd.h"
#include "sampler.h"
namespace {
const std::string kValueKey = "V";
const std::string kQKey = "Q";
const std::string kPiKey = "Pi";
const std::string kSigmaKey = "std";
const std::string kActionQKey = "actionQ";
const std::string kActionKey = "action";
const std::string kPActionKey = "pAction";
} // namespace
namespace cpid {
Sarsa::Sarsa(
ag::Container model,
ag::Optimizer optim,
std::unique_ptr<BaseSampler> sampler,
std::unique_ptr<AsyncBatcher> batcher,
int returnsLength,
int trainerBatchSize,
float discount,
bool gpuMemoryEfficient)
: SyncTrainer(
model,
optim,
std::move(sampler),
std::move(batcher),
returnsLength,
1,
trainerBatchSize,
false,
true,
gpuMemoryEfficient),
discount_(discount) {}
void Sarsa::doUpdate(
const std::vector<std::shared_ptr<SyncFrame>>& seq,
torch::Tensor terminal) {
optim_->zero_grad();
bool isCuda = model_->options().device().is_cuda();
int batchSize = terminal.size(1);
common::assertSize("terminal", terminal, {returnsLength_, batchSize});
auto notTerminal = (1 - terminal);
notTerminal = notTerminal.to(at::kFloat).set_requires_grad(false);
torch::Tensor totValueLoss = torch::zeros({1});
if (isCuda) {
notTerminal = notTerminal.to(model_->options().device());
totValueLoss = totValueLoss.to(model_->options().device());
}
// We will query the model for the current value of the action played at
// eval time
for (const auto& f : seq) {
auto frame = std::static_pointer_cast<BatchedFrame>(f);
frame->state = ag::VariantDict(
{{"state", frame->state}, {kActionQKey, frame->action}});
}
computeAllForward(seq, batchSize);
auto lastFrame = std::static_pointer_cast<BatchedFrame>(seq.back());
ag::Variant& lastOut = lastFrame->forwarded_state;
auto Q = lastOut[kQKey].view({batchSize});
common::assertSize("Q", Q, {batchSize});
auto discounted_reward =
Q.detach().set_requires_grad(false).view({batchSize});
common::assertSize("discounted_reward", discounted_reward, {batchSize});
common::assertSize("notterminal", notTerminal, {returnsLength_, batchSize});
for (int i = (int)seq.size() - 2; i >= 0; --i) {
auto currentFrame = std::static_pointer_cast<BatchedFrame>(seq[i]);
// ag::tensor_list currentOut = model_->forward(currentFrame->state);
ag::Variant& currentOut = currentFrame->forwarded_state;
auto currentQ = currentOut[kQKey].view({batchSize});
// break the chain for terminal state, otherwise decay
discounted_reward =
(discounted_reward * discount_ * notTerminal[i]) + currentFrame->reward;
auto valueLoss = at::smooth_l1_loss(currentQ, discounted_reward);
totValueLoss = totValueLoss + valueLoss;
}
metricsContext_->pushEvent("value_loss", totValueLoss.item<float>());
totValueLoss.backward();
doOptimStep();
}
} // namespace cpid
| 1,206 |
1,748 | package com.sparrowrecsys.online.util;
public class ABTest {
final static int trafficSplitNumber = 5;
final static String bucketAModel = "emb";
final static String bucketBModel = "nerualcf";
final static String defaultModel = "emb";
public static String getConfigByUserId(String userId){
if (null == userId || userId.isEmpty()){
return defaultModel;
}
if(userId.hashCode() % trafficSplitNumber == 0){
System.out.println(userId + " is in bucketA.");
return bucketAModel;
}else if(userId.hashCode() % trafficSplitNumber == 1){
System.out.println(userId + " is in bucketB.");
return bucketBModel;
}else{
System.out.println(userId + " isn't in AB test.");
return defaultModel;
}
}
}
| 354 |
4,216 | /**
* @file core/data/load_vec_impl.hpp
* @author <NAME>
*
* Implementation of templatized load() function defined in load.hpp for
* vectors.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#ifndef MLPACK_CORE_DATA_LOAD_VEC_IMPL_HPP
#define MLPACK_CORE_DATA_LOAD_VEC_IMPL_HPP
// In case it hasn't already been included.
#include "load.hpp"
namespace mlpack {
namespace data {
// Load column vector.
template<typename eT>
bool Load(const std::string& filename,
arma::Col<eT>& vec,
const bool fatal)
{
// First load into auxiliary matrix.
arma::Mat<eT> tmp;
bool success = Load(filename, tmp, fatal, false);
if (!success)
{
vec.clear();
return false;
}
// Now check the size to see that it is a vector, and return a vector.
if (tmp.n_cols > 1)
{
if (tmp.n_rows > 1)
{
// Problem: invalid size!
if (fatal)
{
Log::Fatal << "Matrix in file '" << filename << "' is not a vector, but"
<< " instead has size " << tmp.n_rows << "x" << tmp.n_cols << "!"
<< std::endl;
}
else
{
Log::Warn << "Matrix in file '" << filename << "' is not a vector, but "
<< "instead has size " << tmp.n_rows << "x" << tmp.n_cols << "!"
<< std::endl;
}
vec.clear();
return false;
}
else
{
/**
* It's loaded as a row vector (more than one column). So we need to
* manually modify the shape of the matrix. We can do this without
* damaging the data since it is only a vector.
*/
arma::access::rw(tmp.n_rows) = tmp.n_cols;
arma::access::rw(tmp.n_cols) = 1;
/**
* Now we can call the move operator, but it has to be the move operator
* for Mat, not for Col. This will avoid copying the data.
*/
*((arma::Mat<eT>*) &vec) = std::move(tmp);
return true;
}
}
else
{
// It's loaded as a column vector. We can call the move constructor
// directly.
*((arma::Mat<eT>*) &vec) = std::move(tmp);
return true;
}
}
// Load row vector.
template<typename eT>
bool Load(const std::string& filename,
arma::Row<eT>& rowvec,
const bool fatal)
{
arma::Mat<eT> tmp;
bool success = Load(filename, tmp, fatal, false);
if (!success)
{
rowvec.clear();
return false;
}
if (tmp.n_rows > 1)
{
if (tmp.n_cols > 1)
{
// Problem: invalid size!
if (fatal)
{
Log::Fatal << "Matrix in file '" << filename << "' is not a vector, but"
<< " instead has size " << tmp.n_rows << "x" << tmp.n_cols << "!"
<< std::endl;
}
else
{
Log::Warn << "Matrix in file '" << filename << "' is not a vector, but "
<< "instead has size " << tmp.n_rows << "x" << tmp.n_cols << "!"
<< std::endl;
}
rowvec.clear();
return false;
}
else
{
/**
* It's loaded as a column vector (more than one row). So we need to
* manually modify the shape of the matrix. We can do this without
* damaging the data since it is only a vector.
*/
arma::access::rw(tmp.n_cols) = tmp.n_rows;
arma::access::rw(tmp.n_rows) = 1;
/**
* Now we can call the move operator, but it has to be the move operator
* for Mat, not for Col. This will avoid copying the data.
*/
*((arma::Mat<eT>*) &rowvec) = std::move(tmp);
return true;
}
}
else
{
// It's loaded as a row vector. We can call the move constructor directly.
*((arma::Mat<eT>*) &rowvec) = std::move(tmp);
return true;
}
}
} // namespace data
} // namespace mlpack
#endif
| 1,705 |
716 | <filename>runtime/flang/gerror3f.c
/*
* Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
* See https://llvm.org/LICENSE.txt for license information.
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*
*/
/* clang-format off */
/* gerror3f.c - Implements LIB3F gerror subprogram. */
/* must include ent3f.h AFTER io3f.h */
#include "io3f.h"
#include "ent3f.h"
#include "utils3f.h"
#include "error.h"
#define Ftn_errmsg __fortio_errmsg
#if !defined(WIN64) && !defined(WIN32)
extern char *strerror(); /* SVR4 only ? */
#endif
void ENT3F(GERROR, gerror)(DCHAR(str) DCLEN(str))
{
char *p;
p = strerror(__io_errno());
__fcp_cstr(CADR(str), CLEN(str), p);
return;
}
void ENT3F(GET_IOSTAT_MSG, get_iostat_msg)(int *ios, DCHAR(str) DCLEN(str))
{
const char *p;
p = Ftn_errmsg(*ios);
__fcp_cstr(CADR(str), CLEN(str), p);
}
/* for -Msecond_underscore */
void ENT3F(GET_IOSTAT_MSG_, get_iostat_msg_)(int *ios, DCHAR(str) DCLEN(str))
{
const char *p;
p = Ftn_errmsg(*ios);
__fcp_cstr(CADR(str), CLEN(str), p);
}
| 475 |
315 | /**
* 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.inlong.tubemq.server.common.utils;
import java.util.concurrent.atomic.AtomicLong;
public class SerialIdUtils {
public static void updTimeStampSerialIdValue(final AtomicLong serialId) {
long curSerialId = serialId.get();
long newSerialId = System.currentTimeMillis();
do {
if (newSerialId > curSerialId) {
if (serialId.compareAndSet(curSerialId, newSerialId)) {
break;
}
}
curSerialId = serialId.get();
newSerialId = curSerialId + 10;
} while (true);
}
}
| 514 |
348 | {"nom":"Saint-Etienne-la-Geneste","dpt":"Corrèze","inscrits":84,"abs":9,"votants":75,"blancs":4,"nuls":7,"exp":64,"res":[{"panneau":"1","voix":49},{"panneau":"2","voix":15}]} | 76 |
1,825 | <reponame>thy486/unidbg<gh_stars>1000+
package com.github.unidbg.debugger.gdb;
import com.github.unidbg.Emulator;
class DetachCommand implements GdbStubCommand {
@Override
public boolean processCommand(Emulator<?> emulator, GdbStub stub, String command) {
stub.makePacketAndSend("OK");
stub.detachServer();
return true;
}
}
| 144 |
1,900 | <reponame>Goldwood1024/ehcache3<filename>transactions/src/main/java/org/ehcache/transactions/xa/internal/journal/Journal.java
/*
* Copyright Terracotta, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ehcache.transactions.xa.internal.journal;
import org.ehcache.transactions.xa.internal.TransactionId;
import java.io.IOException;
import java.util.Collection;
import java.util.Map;
/**
* XA transactions journal used to record the state of in-flight transactions.
*
* @author <NAME>
*/
public interface Journal<K> {
/**
* Save that a transaction has committed.
*
* @param transactionId the ID of the transaction.
* @param heuristicDecision true if the state change is being done upon a heuristic decision.
*/
void saveCommitted(TransactionId transactionId, boolean heuristicDecision);
/**
* Save that a transaction has rolled back.
*
* @param transactionId the ID of the transaction.
* @param heuristicDecision true if the state change is being done upon a heuristic decision.
*/
void saveRolledBack(TransactionId transactionId, boolean heuristicDecision);
/**
* Save that a transaction is in-doubt.
*
* @param transactionId the ID of the transaction.
* @param inDoubtKeys a {@link Collection} of keys modified by the transaction.
*/
void saveInDoubt(TransactionId transactionId, Collection<K> inDoubtKeys);
/**
* Check if a transaction has been saved as in-doubt.
*
* @param transactionId the ID of the transaction.
* @return true if the transaction is in-doubt.
*/
boolean isInDoubt(TransactionId transactionId);
/**
* Get a {@link Collection} of keys modified by a transaction still in-doubt.
*
* @param transactionId the ID of the transaction.
* @return a {@link Collection} of keys modified by the transaction.
*/
Collection<K> getInDoubtKeys(TransactionId transactionId);
/**
* Recover the state of all in-doubt transactions.
*
* @return a map using the transaction ID as the key and the state as value.
*/
Map<TransactionId, Collection<K>> recover();
/**
* Check if a transaction has been terminated by a heuristic decision.
*
* @param transactionId the ID of the transaction.
* @return true if the transaction has been terminated by a heuristic decision.
*/
boolean isHeuristicallyTerminated(TransactionId transactionId);
/**
* Recover the state of all transactions that were terminated upon a heuristic decision.
*
* @return a map using the transaction ID as the key and the value true if the state is committed,
* false if it is rolled back.
*/
Map<TransactionId, Boolean> heuristicDecisions();
/**
* Forget a transaction that was terminated upon a heuristic decision.
*
* @param transactionId the Id of the transaction.
*/
void forget(TransactionId transactionId);
/**
* Open the journal.
* @throws IOException if there was an error opening the journal.
*/
void open() throws IOException;
/**
* Close the journal.
*
* @throws IOException if there was an error closing the journal.
*/
void close() throws IOException;
}
| 1,052 |
10,225 | <filename>integration-tests/qute/src/main/java/io/quarkus/it/qute/Brewery.java<gh_stars>1000+
package io.quarkus.it.qute;
import javax.enterprise.event.Observes;
import javax.transaction.Transactional;
import io.quarkus.runtime.StartupEvent;
public class Brewery {
@Transactional
void onStart(@Observes StartupEvent event) {
Beer myBeer = new Beer();
myBeer.name = "Pilsner";
myBeer.completed = true;
myBeer.done = true;
myBeer.persist();
}
}
| 212 |
4,054 | // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.prelude.query.parser.test;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import com.yahoo.prelude.query.CompositeItem;
import com.yahoo.prelude.query.WordItem;
import com.yahoo.search.Query;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
/**
* Check Substring in conjunction with query tokenization and parsing behaves properly.
*
* @author <a href="mailto:<EMAIL>"><NAME></a>
*/
public class SubstringTestCase {
@Test
public final void testTokenLengthAndLowercasing() {
Query q = new Query("/?query=\u0130");
WordItem root = (WordItem) q.getModel().getQueryTree().getRoot();
assertEquals("\u0130", root.getRawWord());
}
@Test
public final void testBug5968479() {
String first = "\u0130\u015EBANKASI";
String second = "GAZ\u0130EM\u0130R";
Query q = new Query("/?query=" + enc(first) + "%20" + enc(second));
CompositeItem root = (CompositeItem) q.getModel().getQueryTree().getRoot();
assertEquals(first, ((WordItem) root.getItem(0)).getRawWord());
assertEquals(second, ((WordItem) root.getItem(1)).getRawWord());
}
private String enc(String s) {
try {
return URLEncoder.encode(s, "utf-8");
}
catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
}
| 590 |
4,339 | /*
* 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.ignite.internal.processors.cache.transactions;
import org.apache.ignite.IgniteSystemProperties;
import org.apache.ignite.internal.IgniteEx;
import org.apache.ignite.lang.IgniteRunnable;
import org.apache.ignite.resources.IgniteInstanceResource;
/**
* Change tx collisions interval or negative for disabling.
*/
public class TxCollisionsDumpSettingsClosure implements IgniteRunnable {
/** Serialization ID. */
private static final long serialVersionUID = 0L;
/** Auto-inject Ignite instance. */
@IgniteInstanceResource
private IgniteEx ignite;
/**
* Tx key collision dump interval.
* Check {@link IgniteSystemProperties#IGNITE_DUMP_TX_COLLISIONS_INTERVAL} for additional info.
*/
private final int interval;
/** Constructor.
*
* @param timeout New interval for key collisions collection.
*/
TxCollisionsDumpSettingsClosure(int timeout) {
interval = timeout;
}
/** {@inheritDoc} */
@Override public void run() {
ignite.context().cache().context().tm().txCollisionsDumpInterval(interval);
}
}
| 568 |
443 | <filename>changes/experimental/__init__.py
__author__ = 'ar'
| 22 |
4,959 | import os
from sanic import Sanic
from sanic.log import logger as log
from sanic import response
from sanic.exceptions import ServerError
app = Sanic(__name__)
@app.route("/")
async def test_async(request):
return response.json({"test": True})
@app.route("/sync", methods=['GET', 'POST'])
def test_sync(request):
return response.json({"test": True})
@app.route("/dynamic/<name>/<i:int>")
def test_params(request, name, i):
return response.text("yeehaww {} {}".format(name, i))
@app.route("/exception")
def exception(request):
raise ServerError("It's dead jim")
@app.route("/await")
async def test_await(request):
import asyncio
await asyncio.sleep(5)
return response.text("I'm feeling sleepy")
@app.route("/file")
async def test_file(request):
return await response.file(os.path.abspath("setup.py"))
@app.route("/file_stream")
async def test_file_stream(request):
return await response.file_stream(os.path.abspath("setup.py"),
chunk_size=1024)
# ----------------------------------------------- #
# Exceptions
# ----------------------------------------------- #
@app.exception(ServerError)
async def test(request, exception):
return response.json({"exception": "{}".format(exception), "status": exception.status_code},
status=exception.status_code)
# ----------------------------------------------- #
# Read from request
# ----------------------------------------------- #
@app.route("/json")
def post_json(request):
return response.json({"received": True, "message": request.json})
@app.route("/form")
def post_form_json(request):
return response.json({"received": True, "form_data": request.form, "test": request.form.get('test')})
@app.route("/query_string")
def query_string(request):
return response.json({"parsed": True, "args": request.args, "url": request.url,
"query_string": request.query_string})
# ----------------------------------------------- #
# Run Server
# ----------------------------------------------- #
@app.listener('before_server_start')
def before_start(app, loop):
log.info("SERVER STARTING")
@app.listener('after_server_start')
def after_start(app, loop):
log.info("OH OH OH OH OHHHHHHHH")
@app.listener('before_server_stop')
def before_stop(app, loop):
log.info("SERVER STOPPING")
@app.listener('after_server_stop')
def after_stop(app, loop):
log.info("TRIED EVERYTHING")
if __name__ == '__main__':
app.run(host="0.0.0.0", port=8000, debug=True)
| 900 |
522 | <gh_stars>100-1000
package algs.model.performance.tree;
import java.util.Iterator;
import algs.model.tree.BinaryNode;
import algs.model.tree.BinaryTree;
/**
* Performance tests.
*
* @author <NAME>
*/
public class EvaluateBinaryTreeMain {
/**
* Build a left-linear tree with n nodes.
*
* This is a totally unbalanced tree starting with root and having only left children
* all the way to the only leaf.
*
* @param n
* @return
*/
static BinaryTree<Integer> buildLeftLinear (int n) {
BinaryTree<Integer> bt = new BinaryTree<Integer>();
for (int i = n; i > 0; i--) {
bt.insert(i);
}
return bt;
}
/**
* Build a right-linear tree with n nodes.
*
* @param n
* @return
*/
static BinaryTree<Integer> buildRightLinear (int n) {
BinaryTree<Integer> bt = new BinaryTree<Integer>();
for (int i = 0; i < n; i++) {
bt.insert(i);
}
return bt;
}
/**
* Build a complete tree with 2^n - 1 nodes.
*
* @param n
* @return
*/
static BinaryTree<Integer> buildComplete(int n) {
BinaryTree<Integer> bt = new BinaryTree<Integer>();
// construct complete tree
int b = (int) Math.pow(2, n-1);
for (int i = 0; i < n; i++) {
bt.insert(b);
for (int j = 1; j <= Math.pow(2, i) - 1; j++) {
bt.insert (b + 2*b*j);
}
b = b / 2;
}
return bt;
}
public static void main (String args[]) {
//int n = Integer.valueOf(args[0]);
int n = 20;
long sum = 0;
long now = System.currentTimeMillis();
//BinaryTree<Integer> bt = buildComplete(n);
BinaryTree<Integer> bt = buildComplete(n);
long ending = System.currentTimeMillis();
System.out.println ("create time: " + (ending-now));
// traverse everything with some meaningless computation.
now = System.currentTimeMillis();
for (Iterator<Integer> it = bt.inorder(); it.hasNext(); ) {
sum += (it.next());
sum = sum & 0xffff;
}
ending = System.currentTimeMillis();
System.out.println ("inorder time: " + (ending-now));
System.out.println ("checksum: " + sum);
// recursive in-order traversal
sum = 0;
now = System.currentTimeMillis();
sum = inorder(0, bt.getRoot());
ending = System.currentTimeMillis();
System.out.println ("inorder time: " + (ending-now));
System.out.println ("checksum: " + sum);
}
private static long inorder(long runningSum, BinaryNode<Integer> n) {
BinaryNode<Integer> tmp;
if ((tmp = n.getLeftSon()) != null) {
runningSum = inorder (runningSum, tmp);
}
runningSum += (Integer) n.getValue();
runningSum = runningSum & 0xffff;
if ((tmp = n.getRightSon()) != null) {
runningSum = inorder (runningSum, tmp);
}
return runningSum;
}
}
| 1,088 |
302 | <filename>elasticsearch-sql-jdbc/src/main/java/io/github/iamazy/elasticsearch/dsl/jdbc/elastic/ElasticClientProvider.java
package io.github.iamazy.elasticsearch.dsl.jdbc.elastic;
import org.elasticsearch.client.RestHighLevelClient;
/**
* @author iamazy
* @date 2019/12/21
**/
public interface ElasticClientProvider {
/**
* create client from url
* @param url
* @param username
* @param password
* @return
*/
RestHighLevelClient fromUrl(String url, String username, String password);
}
| 193 |
354 | <filename>Kruskal's(MST).cpp
//weighted undirected graph
//greedy algorithm
//spanning tree which connects all vertices of graph i.e v-1 edges , no cycles , subsets of edges
//single connected edges
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class DSU{
int *parent;
int *rank;
public:
DSU(int n){
parent=new int[n];
rank=new int[n];
//parent -1,rank 1
for(int i=0;i<n;i++){
parent[i]=-1;
rank[i]=1;
}
}
//find function
int find(int i){
if(parent[i]==-1){
return i;
}
//otherwise
return parent[i]=find(parent[i]);
}
//unite (union)
void unite(int x,int y){
int s1=find(x);
int s2=find(y);
if(s1!=s2){
//union by rank
if(rank[s1]<rank[s2]){
parent[s1]=s2;
rank[s2]+=rank[s1];
}
else
{
parent[s2]=s1;
rank[s1]+=rank[s2];
}
}
}
};
class Graph{
vector<vector<int>>edgelist;
int V;
public:
Graph(int V){
this->V=V;
}
void addEdge(int x,int y,int w){
edgelist.push_back({w,x,y});
}
int kruskal_mst(){
//sort all the edges
sort(edgelist.begin(),edgelist.end());
//init a DSU
DSU s(V);
int ans=0;
for(auto edge:edgelist){
int w=edge[0];
int x=edge[1];
int y=edge[2];
//take that edge in MST if it doesnt form a cycle
if(s.find(x)!=s.find(y)){
s.unite(x,y);
ans+=w;
}
}
return ans;
}
};
int main(){
Graph g(4);
g.addEdge(0,1,1);
g.addEdge(1,3,3);
g.addEdge(3,2,4);
g.addEdge(2,0,2);
g.addEdge(0,3,2);
g.addEdge(1,2,2);
cout<<g.kruskal_mst()<<endl;
return 0;
} | 900 |
1,346 | import logging
log = logging.getLogger(__name__)
def import_backend(module, name):
try:
m = __import__(module, fromlist=[name])
return getattr(m, name, None)
except ImportError, ex:
log.warn('Unable to import %r - %s', name, ex, exc_info=True)
return None
StashBackend = import_backend('trakt_sync.cache.backends.stash_', 'StashBackend')
__all__ = [
'StashBackend'
]
| 177 |
1,338 | <gh_stars>1000+
/*
* Copyright 2009 Haiku Inc. All rights reserved.
* Distributed under the terms of the MIT License.
*/
#ifndef INFO_VIEW_H
#define INFO_VIEW_H
#include <GroupView.h>
class InfoView : public BGroupView {
public:
InfoView();
virtual ~InfoView();
};
#endif /* INFO_VIEW_H */
| 117 |
322 | /*
*
* * 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.eagle.alert.engine.topology;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;
import org.junit.Ignore;
import org.junit.Test;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.Serializable;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.Properties;
/**
* Created on 3/12/16.
*/
@SuppressWarnings( {"serial", "unchecked", "rawtypes", "resource"})
public class SendData2KafkaTest implements Serializable {
/**
* {"timestamp": 10000, "metric": "esErrorLogEvent", "instanceUuid": "vm-InstanceId1", "host":"test-host1", "type":"nova", "stack":"NullPointException-..........."}
* {"timestamp": 10000, "metric": "instanceFailureLogEvent", "instanceUuid": "vm-InstanceId1", "message":"instance boot failure for user liasu!"}
*/
@Test
@Ignore
public void testOutput() throws Exception {
String s1 = "{\"timestamp\": %d, \"metric\": \"esErrorLogEvent\", \"instanceUuid\": \"vm-InstanceId%d\", \"host\":\"test-host1\", \"type\":\"nova\", \"stack\":\"NullPointException-...........\"}";
String s2 = "{\"timestamp\": %d, \"metric\": \"instanceFailureLogEvent\", \"instanceUuid\": \"vm-InstanceId%d\", \"message\":\"instance boot failure for user liasu!\"}";
PrintWriter espw = new PrintWriter(new FileWriter("src/test/resources/es.log"));
PrintWriter ifpw = new PrintWriter(new FileWriter("src/test/resources/if.log"));
long base = System.currentTimeMillis();
long timestamp = 10000;
for (int i = 0; i < 10; i++) {
timestamp = base + i * 10000;
for (int j = 0; j < 10; j++) {
timestamp = timestamp + j * 1000;
espw.println(String.format(s1, timestamp, i));
}
ifpw.println(String.format(s2, timestamp, i));
}
espw.flush();
ifpw.flush();
}
@Test
@Ignore
public void sendKakfa() throws Exception {
List<String> eslogs = Files.readAllLines(Paths.get(SendData2KafkaTest.class.getResource("/es.log").toURI()), Charset.defaultCharset());
List<String> iflogs = Files.readAllLines(Paths.get(SendData2KafkaTest.class.getResource("/if.log").toURI()), Charset.defaultCharset());
Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
props.put("value.serializer", StringSerializer.class.getCanonicalName());
props.put("key.serializer", StringSerializer.class.getCanonicalName());
KafkaProducer producer = new KafkaProducer<>(props);
while (true) {
for (String s : eslogs) {
ProducerRecord<String, String> record = new ProducerRecord<>("nn_jmx_metric_sandbox", s);
producer.send(record);
}
for (String s : iflogs) {
ProducerRecord<String, String> record = new ProducerRecord<>("nn_jmx_metric_sandbox", s);
producer.send(record);
}
Thread.sleep(5000);
}
}
} | 1,540 |
938 | <filename>src/main/resources/assets/tconstruct/book/puny_smelting/en_us/upgrades/armor/item_frame.json<gh_stars>100-1000
{
"modifier_id": "tconstruct:item_frame",
"text": [
{
"text": "Tired of holding you clock and compass? Why not wear it instead?"
}
],
"effects": [
"Adds slots to the helmet, interact to access",
"Helmet will render items when worn",
"Requires 1 Upgrade Slot per level"
]
}
| 159 |
500 | /*
* Copyright 2017 The Native Object Protocols 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.
*/
#ifndef LIBNOP_INCLUDE_NOP_BASE_TABLE_H_
#define LIBNOP_INCLUDE_NOP_BASE_TABLE_H_
#include <nop/base/encoding.h>
#include <nop/base/members.h>
#include <nop/base/utility.h>
#include <nop/table.h>
#include <nop/utility/bounded_reader.h>
#include <nop/utility/bounded_writer.h>
namespace nop {
//
// Entry<T, Id, ActiveEntry> encoding format:
//
// +----------+------------+-------+---------+
// | INT64:ID | INT64:SIZE | VALUE | PADDING |
// +----------+------------+-------+---------+
//
// VALUE must be a valid encoding of type T. If the entry is empty it is not
// encoded. The encoding of type T is wrapped in a sized binary encoding to
// allow deserialization to skip unknown entry types without parsing the full
// encoded entry. SIZE is equal to the total number of bytes in VALUE and
// PADDING.
//
// Entry<T, Id, DeletedEntry> encoding format:
//
// +----------+------------+--------------+
// | INT64:ID | INT64:SIZE | OPAQUE BYTES |
// +----------+------------+--------------+
//
// A deleted entry is never written, but may be encountered by code using newer
// table definitions to read older data streams.
//
// Table encoding format:
//
// +-----+------------+---------+-----------+
// | TAB | INT64:HASH | INT64:N | N ENTRIES |
// +-----+------------+---------+-----------+
//
// Where HASH is derived from the table label and N is the number of non-empty,
// active entries in the table. Older code may encounter unknown entry ids when
// reading data from newer table definitions.
//
template <typename Table>
struct Encoding<Table, EnableIfHasEntryList<Table>> : EncodingIO<Table> {
static constexpr EncodingByte Prefix(const Table& /*value*/) {
return EncodingByte::Table;
}
static constexpr std::size_t Size(const Table& value) {
return BaseEncodingSize(Prefix(value)) +
Encoding<std::uint64_t>::Size(
EntryListTraits<Table>::EntryList::Hash) +
Encoding<SizeType>::Size(ActiveEntryCount(value, Index<Count>{})) +
Size(value, Index<Count>{});
}
static constexpr bool Match(EncodingByte prefix) {
return prefix == EncodingByte::Table;
}
template <typename Writer>
static constexpr Status<void> WritePayload(EncodingByte /*prefix*/,
const Table& value,
Writer* writer) {
auto status = Encoding<std::uint64_t>::Write(
EntryListTraits<Table>::EntryList::Hash, writer);
if (!status)
return status;
status = Encoding<SizeType>::Write(ActiveEntryCount(value, Index<Count>{}),
writer);
if (!status)
return status;
return WriteEntries(value, writer, Index<Count>{});
}
template <typename Reader>
static constexpr Status<void> ReadPayload(EncodingByte /*prefix*/,
Table* value, Reader* reader) {
// Clear entries so that we can detect whether there are duplicate entries
// for the same id during deserialization.
ClearEntries(value, Index<Count>{});
std::uint64_t hash = 0;
auto status = Encoding<std::uint64_t>::Read(&hash, reader);
if (!status)
return status;
else if (hash != EntryListTraits<Table>::EntryList::Hash)
return ErrorStatus::InvalidTableHash;
SizeType count = 0;
status = Encoding<SizeType>::Read(&count, reader);
if (!status)
return status;
return ReadEntries(value, count, reader);
}
private:
enum : std::size_t { Count = EntryListTraits<Table>::EntryList::Count };
template <std::size_t Index>
using PointerAt =
typename EntryListTraits<Table>::EntryList::template At<Index>;
static constexpr std::size_t ActiveEntryCount(const Table& /*value*/,
Index<0>) {
return 0;
}
template <std::size_t index>
static constexpr std::size_t ActiveEntryCount(const Table& value,
Index<index>) {
using Pointer = PointerAt<index - 1>;
const std::size_t count = Pointer::Resolve(value) ? 1 : 0;
return ActiveEntryCount(value, Index<index - 1>{}) + count;
}
template <typename T, std::uint64_t Id>
static constexpr std::size_t Size(const Entry<T, Id, ActiveEntry>& entry) {
if (entry) {
const std::size_t size = Encoding<T>::Size(entry.get());
return Encoding<std::uint64_t>::Size(Id) +
Encoding<std::uint64_t>::Size(size) + size;
} else {
return 0;
}
}
template <typename T, std::uint64_t Id>
static constexpr std::size_t Size(
const Entry<T, Id, DeletedEntry>& /*entry*/) {
return 0;
}
static constexpr std::size_t Size(const Table& /*value*/, Index<0>) {
return 0;
}
template <std::size_t index>
static constexpr std::size_t Size(const Table& value, Index<index>) {
using Pointer = PointerAt<index - 1>;
return Size(value, Index<index - 1>{}) + Size(Pointer::Resolve(value));
}
static void ClearEntries(Table* /*value*/, Index<0>) {}
template <std::size_t index>
static void ClearEntries(Table* value, Index<index>) {
ClearEntries(value, Index<index - 1>{});
PointerAt<index - 1>::Resolve(value)->clear();
}
template <typename T, std::uint64_t Id, typename Writer>
static constexpr Status<void> WriteEntry(
const Entry<T, Id, ActiveEntry>& entry, Writer* writer) {
if (entry) {
auto status = Encoding<std::uint64_t>::Write(Id, writer);
if (!status)
return status;
const SizeType size = Encoding<T>::Size(entry.get());
status = Encoding<SizeType>::Write(size, writer);
if (!status)
return status;
// Use a BoundedWriter to track the number of bytes written. Since a few
// encodings overestimate their size, the remaining bytes must be padded
// out to match the size written above. This is a tradeoff that
// potentially increases the encoding size to avoid unnecessary dynamic
// memory allocation during encoding; some size savings could be made by
// encoding the entry to a temporary buffer and then writing the exact
// size for the binary container. However, overestimation is rare and
// small, making the savings not worth the expense of the temporary
// buffer.
BoundedWriter<Writer> bounded_writer{writer, size};
status = Encoding<T>::Write(entry.get(), &bounded_writer);
if (!status)
return status;
return bounded_writer.WritePadding();
} else {
return {};
}
}
template <typename T, std::uint64_t Id, typename Writer>
static constexpr Status<void> WriteEntry(
const Entry<T, Id, DeletedEntry>& /*entry*/, Writer* /*writer*/) {
return {};
}
template <typename Writer>
static constexpr Status<void> WriteEntries(const Table& /*value*/,
Writer* /*writer*/, Index<0>) {
return {};
}
template <std::size_t index, typename Writer>
static constexpr Status<void> WriteEntries(const Table& value, Writer* writer,
Index<index>) {
auto status = WriteEntries(value, writer, Index<index - 1>{});
if (!status)
return status;
using Pointer = PointerAt<index - 1>;
return WriteEntry(Pointer::Resolve(value), writer);
}
template <typename T, std::uint64_t Id, typename Reader>
static constexpr Status<void> ReadEntry(Entry<T, Id, ActiveEntry>* entry,
Reader* reader) {
// At the beginning of reading the table the destination entries are
// cleared. If an entry is not cleared here then more than one entry for
// the same id was written in violation of the table protocol.
if (entry->empty()) {
SizeType size = 0;
auto status = Encoding<SizeType>::Read(&size, reader);
if (!status)
return status;
// Default construct the entry;
*entry = T{};
// Use a BoundedReader to handle any padding that might follow the
// value and catch invalid sizes while decoding inside the binary
// container.
BoundedReader<Reader> bounded_reader{reader, size};
status = Encoding<T>::Read(&entry->get(), &bounded_reader);
if (!status)
return status;
return bounded_reader.ReadPadding();
} else {
return ErrorStatus::DuplicateTableEntry;
}
}
// Skips over the binary container for an entry.
template <typename Reader>
static constexpr Status<void> SkipEntry(Reader* reader) {
SizeType size = 0;
auto status = Encoding<SizeType>::Read(&size, reader);
if (!status)
return status;
return reader->Skip(size);
}
template <typename T, std::uint64_t Id, typename Reader>
static constexpr Status<void> ReadEntry(Entry<T, Id, DeletedEntry>* /*entry*/,
Reader* reader) {
return SkipEntry(reader);
}
template <typename Reader>
static constexpr Status<void> ReadEntryForId(Table* /*value*/,
std::uint64_t /*id*/,
Reader* reader, Index<0>) {
return SkipEntry(reader);
}
template <typename Reader, std::size_t index>
static constexpr Status<void> ReadEntryForId(Table* value, std::uint64_t id,
Reader* reader, Index<index>) {
using Pointer = PointerAt<index - 1>;
using Type = typename Pointer::Type;
if (Type::Id == id)
return ReadEntry(Pointer::Resolve(value), reader);
else
return ReadEntryForId(value, id, reader, Index<index - 1>{});
}
template <typename Reader>
static constexpr Status<void> ReadEntries(Table* value, SizeType count,
Reader* reader) {
for (SizeType i = 0; i < count; i++) {
std::uint64_t id = 0;
auto status = Encoding<std::uint64_t>::Read(&id, reader);
if (!status)
return status;
status = ReadEntryForId(value, id, reader, Index<Count>{});
if (!status)
return status;
}
return {};
}
};
} // namespace nop
#endif // LIBNOP_INCLUDE_NOP_BASE_TABLE_H_
| 4,171 |
14,425 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.yarn.server.resourcemanager.placement;
/**
* Each placement rule when it successfully places an application onto a queue
* returns a PlacementRuleContext which encapsulates the queue the
* application was mapped to and any parent queue for the queue (if configured)
*/
public class ApplicationPlacementContext {
private String queue;
private String parentQueue;
public ApplicationPlacementContext(String queue) {
this(queue,null);
}
public ApplicationPlacementContext(String queue, String parentQueue) {
this.queue = queue;
this.parentQueue = parentQueue;
}
public String getQueue() {
return queue;
}
public void setQueue(String q) {
queue = q;
}
public String getParentQueue() {
return parentQueue;
}
public boolean hasParentQueue() {
return parentQueue != null;
}
public String getFullQueuePath() {
if (parentQueue != null) {
return parentQueue + "." + queue;
} else {
return queue;
}
}
}
| 500 |
1,253 | //This is for connect.java
import java.util.*;
import java.io.*;
import java.util.Map;
import java.lang.*;
class InvalidRowException extends Exception
{
public InvalidRowException()
{
}
}
class InvalidColumnException extends Exception
{
public InvalidColumnException()
{
}
}
class connectFour
{
int NONE = 0;
int RED = 1;
int BLACK = 2;
int boardColumns, boardRows, turn, winner, count; //= 7, 6
int[][] board; // = new int[boardRows][boardColumns];
int[][] neighbors = {{0,1},{1,1},{1,0},{1,-1},
{0,-1},{-1,-1},{-1,0},{-1,1}};
boolean gameOver;
//GameState gameState = new GameState();
public connectFour () // constructor
{
this.boardColumns = 7;
this.boardRows = 6;
this.turn = RED;
this.winner = NONE;
board = new int[boardRows][boardColumns];
}
public void createNewGame()
{
this.turn = RED;
this.winner = NONE;
this.board = new int[boardRows][boardColumns];
gameOver = false;
//gameState = new GameState(boardRows, boardColumns, playerTurn);
}
public void drop(int columnNum) throws InvalidRowException, InvalidColumnException
{
if (checkValidColumnNumber(columnNum))
{
int rowNum = getEmptyBottomRowOfColumn(columnNum);
if (checkValidRowNumber(rowNum))
{
board[rowNum][columnNum] = turn;
checkIfGameOver(rowNum, columnNum);
changeTurn();
}
else
{
throw new InvalidRowException();
}
}
else
{
throw new InvalidColumnException();
}
}
public void printBoard()
{
int spot;
for (int i = 0; i < boardRows; i++)
{
for (int j = 0; j < boardColumns; j++)
{
spot = board[i][j];
if (spot == RED)
System.out.print("R ");
else if (spot == BLACK)
System.out.print("B ");
else
System.out.print(". ");
}
System.out.println();
}
}
public void printTurn()
{
System.out.println("TURN: " + ((turn == RED) ? "RED" : "BLACK"));
}
public void printWinner()
{
System.out.println("WINNER: " + ((winner == RED) ? "RED" : "BLACK"));
}
public void printNoWinner()
{
System.out.println("WINNER: DRAW");
}
private void changeTurn()
{
this.turn = ((this.turn == RED) ? BLACK : RED);
}
private int getEmptyBottomRowOfColumn(int colNum)
{
for (int i = boardRows - 1; i >= 0; i--)
{
if (board[i][colNum] == NONE)
{
return i;
}
}
return -1;
}
private boolean checkValidColumnNumber(int colNum)
{
return (0 <= colNum && colNum < boardColumns);
}
private boolean checkValidRowNumber(int rowNum)
{
return (0 <= rowNum && rowNum < boardRows);
}
private boolean isFourInARow(int rowNum, int colNum, int adjRow, int adjCol)
{
int startingCell;
boolean result = false;
if (checkValidRowNumber(rowNum) && checkValidColumnNumber(colNum))
startingCell = board[rowNum][colNum];
else
return result;
if (startingCell != NONE)
{
int newRow, newCol;
for (int i = 1; i <= 3; i++)
{
newRow = rowNum + (adjRow * i);
newCol = colNum + (adjCol * i);
if (!checkValidRowNumber(newRow) || !checkValidColumnNumber(newCol) ||
board[newRow][newCol] != startingCell)
{
return result;
}
}
result = true;
}
return result;
}
private boolean checkForWinner(int rowNum, int colNum)
{
int rowNeighbor, colNeighbor;
for (int i = 0; i < 8; i++)
{
rowNeighbor = neighbors[i][0];
colNeighbor = neighbors[i][1];
if (isFourInARow(rowNum, colNum, rowNeighbor, colNeighbor))
return true;
for (int j = 0; j < 8; j++)
{
if (isFourInARow((rowNum + rowNeighbor), (colNum + colNeighbor),
(neighbors[j][0]),(neighbors[j][1])))
return true;
}
}
return false;
}
private void checkIfGameOver(int rowNum, int columnNum)
{
if (checkForWinner(rowNum, columnNum))
{
winner = turn;
printBoard();
printWinner();
gameOver = true;
}
else
{
count = 0;
for (int i = 0; i < boardRows; i++)
{
for (int j = 0; j < boardColumns; j++)
{
if (board[i][j] == NONE)
count++;
}
}
if (count == 0)
{
printBoard();
printNoWinner();
gameOver = true;
}
}
}
public boolean isGameOver()
{
return gameOver;
}
public void quit()
{
gameOver = true;
}
}
public class connect
{
public static void printCommands()
{
System.out.println("--------------- WELCOME TO CONNECT FOUR ---------------");
System.out.print("Player Red will always start first. The grid is set to \n" +
"6 x 7 and cannot be modified. To play, the player may \n" +
"input the column they wish to enter from the range of \n" +
"1 - 7. The game will automatically place the piece to \n" +
"the bottom of the board for the specified column. The \n" +
"Winner is the first to connect 4 pieces.\n\n");
System.out.println("* To quit the game, enter '0' at any time.");
System.out.println("* To place a piece, enter a number from 1 - 7. When a \n" +
" Column is full, you are no longer able to put a piece\n" +
" in that column.");
}
public static void main(String[] args) throws IOException
{
int input;
boolean quit = false;
connectFour CFour = new connectFour();
CFour.createNewGame();
printCommands();
while(!CFour.isGameOver())
{
CFour.printBoard();
CFour.printTurn();
Scanner in = new Scanner(System.in);
try
{
input = in.nextInt();
System.out.println("Your Input:" + input);
if (input == 0)
{
CFour.quit();
}
else
{
try
{
CFour.drop(input-1);
}
catch (InvalidRowException ex)
{
System.out.println("ERROR: The column number used cannot be " +
"placed anymore. Try a different column.");
}
catch (InvalidColumnException ex)
{
System.out.println("ERROR: The column number used is invalid." +
"Try a different column.");
}
}
}
catch (InputMismatchException ex)
{
System.out.println("Invalid Input. Must be a number from 1 - 7");
}
}
}
} | 2,656 |
382 | /*
* Copyright 2020 YANDEX LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.clouddriver.yandex.deploy.ops;
import com.netflix.spinnaker.clouddriver.orchestration.AtomicOperation;
import com.netflix.spinnaker.clouddriver.yandex.deploy.description.EnableDisableYandexServerGroupDescription;
import com.netflix.spinnaker.clouddriver.yandex.model.YandexCloudLoadBalancer;
import com.netflix.spinnaker.clouddriver.yandex.model.YandexCloudServerGroup;
import java.util.List;
import java.util.Optional;
public class DisableYandexServerGroupAtomicOperation
extends AbstractYandexAtomicOperation<EnableDisableYandexServerGroupDescription>
implements AtomicOperation<Void> {
private static final String BASE_PHASE = "DISABLE_SERVER_GROUP";
public DisableYandexServerGroupAtomicOperation(
EnableDisableYandexServerGroupDescription description) {
super(description);
}
@Override
public Void operate(List<Void> priorOutputs) {
String serverGroupName = description.getServerGroupName();
status(BASE_PHASE, "Initializing disable server group operation for '%s'...", serverGroupName);
YandexCloudServerGroup serverGroup = getServerGroup(BASE_PHASE, serverGroupName);
status(BASE_PHASE, "Disabling server group '%s'...", serverGroupName);
Optional.of(serverGroup)
.map(YandexCloudServerGroup::getLoadBalancerIntegration)
.ifPresent(this::disableInstanceGroup);
status(BASE_PHASE, "Done disabling server group '%s'.", serverGroupName);
return null;
}
private void disableInstanceGroup(YandexCloudServerGroup.LoadBalancerIntegration loadBalancer) {
for (YandexCloudLoadBalancer balancer : loadBalancer.getBalancers()) {
status(
BASE_PHASE, "Deregistering server group from load balancer '%s'...", balancer.getName());
yandexCloudFacade.detachTargetGroup(
BASE_PHASE, credentials, balancer, loadBalancer.getTargetGroupId());
status(
BASE_PHASE,
"Done deregistering server group from load balancer '%s'.",
balancer.getName());
}
}
}
| 844 |
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 "rtc_base/experiments/jitter_upper_bound_experiment.h"
#include <stdio.h>
#include <string>
#include "rtc_base/logging.h"
#include "system_wrappers/include/field_trial.h"
namespace webrtc {
const char JitterUpperBoundExperiment::kJitterUpperBoundExperimentName[] =
"WebRTC-JitterUpperBound";
absl::optional<double> JitterUpperBoundExperiment::GetUpperBoundSigmas() {
if (!field_trial::IsEnabled(kJitterUpperBoundExperimentName)) {
return absl::nullopt;
}
const std::string group =
webrtc::field_trial::FindFullName(kJitterUpperBoundExperimentName);
double upper_bound_sigmas;
if (sscanf(group.c_str(), "Enabled-%lf", &upper_bound_sigmas) != 1) {
RTC_LOG(LS_WARNING) << "Invalid number of parameters provided.";
return absl::nullopt;
}
if (upper_bound_sigmas < 0) {
RTC_LOG(LS_WARNING) << "Invalid jitter upper bound sigmas, must be >= 0.0: "
<< upper_bound_sigmas;
return absl::nullopt;
}
return upper_bound_sigmas;
}
} // namespace webrtc
| 519 |
473 | <filename>src/core/imports/lapack.cpp
/*
Copyright (c) 2009-2016, <NAME>
All rights reserved.
This file is part of Elemental and is under the BSD 2-Clause License,
which can be found in the LICENSE file in the root directory, or at
http://opensource.org/licenses/BSD-2-Clause
*/
#include <El-lite.hpp>
#include <El/lapack_like.hpp>
using El::FortranLogical;
using El::BlasInt;
using El::scomplex;
using El::dcomplex;
extern "C" {
// Copy matrices
void EL_LAPACK(slacpy)
( const char* uplo, const BlasInt* m, const BlasInt* n,
const float* A, const BlasInt* lda, float* B, const BlasInt* ldb );
void EL_LAPACK(dlacpy)
( const char* uplo, const BlasInt* m, const BlasInt* n,
const double* A, const BlasInt* lda, double* B, const BlasInt* ldb );
void EL_LAPACK(clacpy)
( const char* uplo, const BlasInt* m, const BlasInt* n,
const scomplex* A, const BlasInt* lda, scomplex* B, const BlasInt* ldb );
void EL_LAPACK(zlacpy)
( const char* uplo, const BlasInt* m, const BlasInt* n,
const dcomplex* A, const BlasInt* lda, dcomplex* B, const BlasInt* ldb );
// Symmetric tridiagonal eigensolvers (via MRRR)
void EL_LAPACK(sstevr)
( const char* job, const char* range, const BlasInt* n,
float* d, float* e, const float* vl, const float* vu,
const BlasInt* il, const BlasInt* iu, const float* absTol, BlasInt * m,
float* w, float* Z, const BlasInt* ldZ, BlasInt* isuppZ,
float* work, const BlasInt* workSize,
BlasInt* iWork, const BlasInt* iWorkSize,
BlasInt* info );
void EL_LAPACK(dstevr)
( const char* job, const char* range, const BlasInt* n,
double* d, double* e, const double* vl, const double* vu,
const BlasInt* il, const BlasInt* iu, const double* absTol, BlasInt * m,
double* w, double* Z, const BlasInt* ldZ, BlasInt* isuppZ,
double* work, const BlasInt* workSize,
BlasInt* iWork, const BlasInt* iWorkSize,
BlasInt* info );
// Hermitian eigensolvers (via MRRR)
void EL_LAPACK(ssyevr)
( const char* job, const char* range, const char* uplo, const BlasInt* n,
float* A, const BlasInt* ldA, const float* vl, const float* vu,
const BlasInt* il, const BlasInt* iu, const float* absTol, BlasInt * m,
float* w, float* Z, const BlasInt* ldZ, BlasInt* isuppZ,
float* work, const BlasInt* workSize,
BlasInt* iWork, const BlasInt* iWorkSize,
BlasInt* info );
void EL_LAPACK(dsyevr)
( const char* job, const char* range, const char* uplo, const BlasInt* n,
double* A, const BlasInt* ldA, const double* vl, const double* vu,
const BlasInt* il, const BlasInt* iu, const double* absTol, BlasInt * m,
double* w, double* Z, const BlasInt* ldZ, BlasInt* isuppZ,
double* work, const BlasInt* workSize,
BlasInt* iWork, const BlasInt* iWorkSize,
BlasInt* info );
void EL_LAPACK(cheevr)
( const char* job, const char* range, const char* uplo, const BlasInt* n,
scomplex* A, const BlasInt* ldA, const float* vl, const float* vu,
const BlasInt* il, const BlasInt* iu, const float* absTol, BlasInt* m,
float* w, scomplex* Z, const BlasInt* ldZ, BlasInt* isuppZ,
scomplex* work, const BlasInt* workSize,
float* rWork, const BlasInt* rWorkSize,
BlasInt* iWork, const BlasInt* iWorkSize, BlasInt* info );
void EL_LAPACK(zheevr)
( const char* job, const char* range, const char* uplo, const BlasInt* n,
dcomplex* A, const BlasInt* ldA, const double* vl, const double* vu,
const BlasInt* il, const BlasInt* iu, const double* absTol, BlasInt* m,
double* w, dcomplex* Z, const BlasInt* ldZ, BlasInt* isuppZ,
dcomplex* work, const BlasInt* workSize,
double* rWork, const BlasInt* rWorkSize,
BlasInt* iWork, const BlasInt* iWorkSize, BlasInt* info );
// Bidiagonal DQDS
void EL_LAPACK(slasq1)
( const BlasInt* n, float* d, float* e, float* work, BlasInt* info );
void EL_LAPACK(dlasq1)
( const BlasInt* n, double* d, double* e, double* work, BlasInt* info );
// Bidiagonal QR
void EL_LAPACK(sbdsqr)
( const char* uplo, const BlasInt* n,
const BlasInt* numColsVT, const BlasInt* numRowsU,
const BlasInt* numColsC, float* d, float* e,
float* VTrans, const BlasInt* ldVT,
float* U, const BlasInt* ldU, float* C, const BlasInt* ldC,
float* work, BlasInt* info );
void EL_LAPACK(dbdsqr)
( const char* uplo, const BlasInt* n,
const BlasInt* numColsVT, const BlasInt* numRowsU,
const BlasInt* numColsC, double* d, double* e,
double* VTrans, const BlasInt* ldVT, double* U, const BlasInt* ldU,
double* C, const BlasInt* ldC, double* work, BlasInt* info );
void EL_LAPACK(cbdsqr)
( const char* uplo, const BlasInt* n,
const BlasInt* numColsVH, const BlasInt* numRowsU,
const BlasInt* numColsC, float* d, float* e,
scomplex* VH, const BlasInt* ldVH, scomplex* U, const BlasInt* ldU,
scomplex* C, const BlasInt* ldC, float* work, BlasInt* info );
void EL_LAPACK(zbdsqr)
( const char* uplo, const BlasInt* n,
const BlasInt* numColsVH, const BlasInt* numRowsU,
const BlasInt* numColsC, double* d, double* e,
dcomplex* VH, const BlasInt* ldVH, dcomplex* U, const BlasInt* ldU,
dcomplex* C, const BlasInt* ldC, double* work, BlasInt* info );
// Divide and Conquer SVD
void EL_LAPACK(sgesdd)
( const char* jobz, const BlasInt* m, const BlasInt* n,
float* A, const BlasInt* ldA,
float* s, float* U, const BlasInt* ldu,
float* VTrans, const BlasInt* ldvt,
float* work, const BlasInt* workSize, BlasInt* iWork, BlasInt* info );
void EL_LAPACK(dgesdd)
( const char* jobz, const BlasInt* m, const BlasInt* n,
double* A, const BlasInt* ldA,
double* s, double* U, const BlasInt* ldu,
double* VTrans, const BlasInt* ldvt,
double* work, const BlasInt* workSize, BlasInt* iWork, BlasInt* info );
void EL_LAPACK(cgesdd)
( const char* jobz, const BlasInt* m, const BlasInt* n,
scomplex* A, const BlasInt* ldA, float* s,
scomplex* U, const BlasInt* ldu, scomplex* VTrans, const BlasInt* ldvt,
scomplex* work, const BlasInt* workSize, float* rWork,
BlasInt* iWork, BlasInt* info );
void EL_LAPACK(zgesdd)
( const char* jobz, const BlasInt* m, const BlasInt* n,
dcomplex* A, const BlasInt* ldA, double* s,
dcomplex* U, const BlasInt* ldu, dcomplex* VH, const BlasInt* ldva,
dcomplex* work, const BlasInt* workSize, double* rWork,
BlasInt* iWork, BlasInt* info );
// QR-algorithm SVD [DQDS when no singular vectors desired]
void EL_LAPACK(sgesvd)
( const char* jobU, const char* jobVT, const BlasInt* m, const BlasInt* n,
float* A, const BlasInt* ldA,
float* s, float* U, const BlasInt* ldu, float* VTrans, const BlasInt* ldvt,
float* work, const BlasInt* workSize, BlasInt* info );
void EL_LAPACK(dgesvd)
( const char* jobU, const char* jobVT, const BlasInt* m, const BlasInt* n,
double* A, const BlasInt* ldA,
double* s, double* U, const BlasInt* ldu, double* VTrans, const BlasInt* ldvt,
double* work, const BlasInt* workSize, BlasInt* info );
void EL_LAPACK(cgesvd)
( const char* jobU, const char* jobVH, const BlasInt* m, const BlasInt* n,
scomplex* A, const BlasInt* ldA, float* s,
scomplex* U, const BlasInt* ldu, scomplex* VTrans, const BlasInt* ldvt,
scomplex* work, const BlasInt* workSize, float* rWork, BlasInt* info );
void EL_LAPACK(zgesvd)
( const char* jobU, const char* jobVH, const BlasInt* m, const BlasInt* n,
dcomplex* A, const BlasInt* ldA, double* s,
dcomplex* U, const BlasInt* ldu, dcomplex* VH, const BlasInt* ldva,
dcomplex* work, const BlasInt* workSize, double* rWork, BlasInt* info );
// Reduction to Hessenberg form
void EL_LAPACK(sgehrd)
( const BlasInt* n,
const BlasInt* ilo, const BlasInt* ihi,
float* A, const BlasInt* ldA,
float* tau,
float* work, const BlasInt* workSize,
BlasInt* info );
void EL_LAPACK(dgehrd)
( const BlasInt* n,
const BlasInt* ilo, const BlasInt* ihi,
double* A, const BlasInt* ldA,
double* tau,
double* work, const BlasInt* workSize,
BlasInt* info );
void EL_LAPACK(cgehrd)
( const BlasInt* n,
const BlasInt* ilo, const BlasInt* ihi,
scomplex* A, const BlasInt* ldA,
scomplex* tau,
scomplex* work, const BlasInt* workSize,
BlasInt* info );
void EL_LAPACK(zgehrd)
( const BlasInt* n,
const BlasInt* ilo, const BlasInt* ihi,
dcomplex* A, const BlasInt* ldA,
dcomplex* tau,
dcomplex* work, const BlasInt* workSize,
BlasInt* info );
// Generates a unitary matrix defined as the product of Householder reflectors
void EL_LAPACK(sorghr)
( const BlasInt* n,
const BlasInt* ilo, const BlasInt* ihi,
float* A, const BlasInt* ldA,
const float* tau,
float* work, const BlasInt* workSize,
BlasInt* info );
void EL_LAPACK(dorghr)
( const BlasInt* n,
const BlasInt* ilo, const BlasInt* ihi,
double* A, const BlasInt* ldA,
const double* tau,
double* work, const BlasInt* workSize,
BlasInt* info );
void EL_LAPACK(cunghr)
( const BlasInt* n,
const BlasInt* ilo, const BlasInt* ihi,
scomplex* A, const BlasInt* ldA,
const scomplex* tau,
scomplex* work, const BlasInt* workSize,
BlasInt* info );
void EL_LAPACK(zunghr)
( const BlasInt* n,
const BlasInt* ilo, const BlasInt* ihi,
dcomplex* A, const BlasInt* ldA,
const dcomplex* tau,
dcomplex* work, const BlasInt* workSize,
BlasInt* info );
// Hessenberg QR algorithm (with AED)
void EL_LAPACK(shseqr)
( const char* job, const char* compZ, const BlasInt* n,
const BlasInt* ilo, const BlasInt* ihi,
float* H, const BlasInt* ldH,
float* wr, float* wi,
float* Z, const BlasInt* ldZ,
float* work, const BlasInt* workSize,
BlasInt* info );
void EL_LAPACK(dhseqr)
( const char* job, const char* compZ, const BlasInt* n,
const BlasInt* ilo, const BlasInt* ihi,
double* H, const BlasInt* ldH,
double* wr, double* wi,
double* Z, const BlasInt* ldZ,
double* work, const BlasInt* workSize,
BlasInt* info );
void EL_LAPACK(chseqr)
( const char* job, const char* compZ, const BlasInt* n,
const BlasInt* ilo, const BlasInt* ihi,
scomplex* H, const BlasInt* ldH,
scomplex* w,
scomplex* Z, const BlasInt* ldZ,
scomplex* work, const BlasInt* workSize,
BlasInt* info );
void EL_LAPACK(zhseqr)
( const char* job, const char* compZ, const BlasInt* n,
const BlasInt* ilo, const BlasInt* ihi,
dcomplex* H, const BlasInt* ldH,
dcomplex* w,
dcomplex* Z, const BlasInt* ldZ,
dcomplex* work, const BlasInt* workSize,
BlasInt* info );
// Hessenberg QR algorithm (without AED)
void EL_LAPACK(slahqr)
( const FortranLogical* wantT,
const FortranLogical* wantZ,
const BlasInt* n,
const BlasInt* ilo, const BlasInt* ihi,
float* H, const BlasInt* ldH,
float* wr, float* wi,
const BlasInt* iloZ, const BlasInt* ihiZ,
float* Z, const BlasInt* ldZ,
BlasInt* info );
void EL_LAPACK(dlahqr)
( const FortranLogical* wantT,
const FortranLogical* wantZ,
const BlasInt* n,
const BlasInt* ilo, const BlasInt* ihi,
double* H, const BlasInt* ldH,
double* wr, double* wi,
const BlasInt* iloZ, const BlasInt* ihiZ,
double* Z, const BlasInt* ldZ,
BlasInt* info );
void EL_LAPACK(clahqr)
( const FortranLogical* wantT,
const FortranLogical* wantZ,
const BlasInt* n,
const BlasInt* ilo, const BlasInt* ihi,
scomplex* H, const BlasInt* ldH,
scomplex* w,
const BlasInt* iloZ, const BlasInt* ihiZ,
scomplex* Z, const BlasInt* ldZ,
BlasInt* info );
void EL_LAPACK(zlahqr)
( const FortranLogical* wantT,
const FortranLogical* wantZ,
const BlasInt* n,
const BlasInt* ilo, const BlasInt* ihi,
dcomplex* H, const BlasInt* ldH,
dcomplex* w,
const BlasInt* iloZ, const BlasInt* ihiZ,
dcomplex* Z, const BlasInt* ldZ,
BlasInt* info );
} // extern "C"
namespace El {
namespace lapack {
// Copy a matrix
// =============
template<typename T>
void Copy
( char uplo, BlasInt m, BlasInt n,
const T* A, BlasInt lda,
T* B, BlasInt ldb )
{
if( std::toupper(uplo) == 'L' )
{
for( Int j=0; j<n; ++j )
for( Int i=j; i<m; ++i )
B[i+j*ldb] = A[i+j*lda];
}
else if( std::toupper(uplo) == 'U' )
{
for( Int j=0; j<n; ++j )
for( Int i=0; i<=j; ++i )
B[i+j*ldb] = A[i+j*lda];
}
else
{
for( Int j=0; j<n; ++j )
for( Int i=0; i<m; ++i )
B[i+j*ldb] = A[i+j*lda];
}
}
template void Copy
( char uplo, BlasInt m, BlasInt n,
const Int* A, BlasInt lda,
Int* B, BlasInt ldb );
#ifdef EL_HAVE_QD
template void Copy
( char uplo, BlasInt m, BlasInt n,
const DoubleDouble* A, BlasInt lda,
DoubleDouble* B, BlasInt ldb );
template void Copy
( char uplo, BlasInt m, BlasInt n,
const QuadDouble* A, BlasInt lda,
QuadDouble* B, BlasInt ldb );
template void Copy
( char uplo, BlasInt m, BlasInt n,
const Complex<DoubleDouble>* A, BlasInt lda,
Complex<DoubleDouble>* B, BlasInt ldb );
template void Copy
( char uplo, BlasInt m, BlasInt n,
const Complex<QuadDouble>* A, BlasInt lda,
Complex<QuadDouble>* B, BlasInt ldb );
#endif
#ifdef EL_HAVE_QUAD
template void Copy
( char uplo, BlasInt m, BlasInt n,
const Quad* A, BlasInt lda,
Quad* B, BlasInt ldb );
template void Copy
( char uplo, BlasInt m, BlasInt n,
const Complex<Quad>* A, BlasInt lda,
Complex<Quad>* B, BlasInt ldb );
#endif
#ifdef EL_HAVE_MPC
template void Copy
( char uplo, BlasInt m, BlasInt n,
const BigInt* A, BlasInt lda,
BigInt* B, BlasInt ldb );
template void Copy
( char uplo, BlasInt m, BlasInt n,
const BigFloat* A, BlasInt lda,
BigFloat* B, BlasInt ldb );
template void Copy
( char uplo, BlasInt m, BlasInt n,
const Complex<BigFloat>* A, BlasInt lda,
Complex<BigFloat>* B, BlasInt ldb );
#endif
void Copy
( char uplo, BlasInt m, BlasInt n,
const float* A, BlasInt lda, float* B, BlasInt ldb )
{ EL_LAPACK(slacpy)( &uplo, &m, &n, A, &lda, B, &ldb ); }
void Copy
( char uplo, BlasInt m, BlasInt n,
const double* A, BlasInt lda, double* B, BlasInt ldb )
{ EL_LAPACK(dlacpy)( &uplo, &m, &n, A, &lda, B, &ldb ); }
void Copy
( char uplo, BlasInt m, BlasInt n,
const scomplex* A, BlasInt lda, scomplex* B, BlasInt ldb )
{ EL_LAPACK(clacpy)( &uplo, &m, &n, A, &lda, B, &ldb ); }
void Copy
( char uplo, BlasInt m, BlasInt n,
const dcomplex* A, BlasInt lda, dcomplex* B, BlasInt ldb )
{ EL_LAPACK(zlacpy)( &uplo, &m, &n, A, &lda, B, &ldb ); }
// Generate a Householder reflector
// ================================
// NOTE:
// Since LAPACK chooses to use the identity matrix, rather than a single
// coordinate negation, in cases where the mass is already entirely in the
// first entry, and the identity matrix cannot be represented as a Householder
// reflector, Elemental does not ever directly call LAPACK's Householder
// routines. Otherwise, the logic of routines such as ApplyPackedReflectors
// would need to be (unnecessarily) complicated.
//
// Furthermore, LAPACK defines H = I - tau [1; v] [1; v]' such that
// adjoint(H) [chi; x] = [beta; 0], but Elemental instead defines
// H = I - tau [1; v] [1; v]' such that H [chi; x] = [beta; 0].
//
template<typename F>
F Reflector( BlasInt n, F& chi, F* x, BlasInt incx )
{
EL_DEBUG_CSE
typedef Base<F> Real;
const Real zero(0);
Real norm = blas::Nrm2( n-1, x, incx );
F alpha = chi;
if( norm == zero && ImagPart(alpha) == zero )
{
chi *= -1;
return F(2);
}
Real beta;
if( RealPart(alpha) <= zero )
beta = SafeNorm( alpha, norm );
else
beta = -SafeNorm( alpha, norm );
// Rescale if the vector is too small
const Real safeMin = limits::SafeMin<Real>();
const Real epsilon = limits::Epsilon<Real>();
const Real safeInv = safeMin/epsilon;
Int count = 0;
if( Abs(beta) < safeInv )
{
Real invOfSafeInv = Real(1)/safeInv;
do
{
++count;
blas::Scal( n-1, invOfSafeInv, x, incx );
alpha *= invOfSafeInv;
beta *= invOfSafeInv;
} while( Abs(beta) < safeInv );
norm = blas::Nrm2( n-1, x, incx );
if( RealPart(alpha) <= 0 )
beta = SafeNorm( alpha, norm );
else
beta = -SafeNorm( alpha, norm );
}
F tau = (beta-Conj(alpha)) / beta;
blas::Scal( n-1, Real(1)/(alpha-beta), x, incx );
// Undo the scaling
for( Int j=0; j<count; ++j )
beta *= safeInv;
chi = beta;
return tau;
}
template float Reflector
( BlasInt n, float& chi, float* x, BlasInt incx );
template Complex<float> Reflector
( BlasInt n, Complex<float>& chi, Complex<float>* x, BlasInt incx );
template double Reflector
( BlasInt n, double& chi, double* x, BlasInt incx );
template Complex<double> Reflector
( BlasInt n, Complex<double>& chi, Complex<double>* x, BlasInt incx );
#ifdef EL_HAVE_QD
template DoubleDouble Reflector
( BlasInt n, DoubleDouble& chi, DoubleDouble* x, BlasInt incx );
template QuadDouble Reflector
( BlasInt n, QuadDouble& chi, QuadDouble* x, BlasInt incx );
template Complex<DoubleDouble> Reflector
( BlasInt n,
Complex<DoubleDouble>& chi,
Complex<DoubleDouble>* x, BlasInt incx );
template Complex<QuadDouble> Reflector
( BlasInt n,
Complex<QuadDouble>& chi,
Complex<QuadDouble>* x, BlasInt incx );
#endif
#ifdef EL_HAVE_QUAD
template Quad Reflector
( BlasInt n, Quad& chi, Quad* x, BlasInt incx );
template Complex<Quad> Reflector
( BlasInt n, Complex<Quad>& chi, Complex<Quad>* x, BlasInt incx );
#endif
#ifdef EL_HAVE_MPC
template BigFloat Reflector
( BlasInt n, BigFloat& chi, BigFloat* x, BlasInt incx );
template Complex<BigFloat> Reflector
( BlasInt n, Complex<BigFloat>& chi, Complex<BigFloat>* x, BlasInt incx );
#endif
// Cf. LAPACK's ?LARF
//
// TODO(poulson):
// Provide wrappers for LAPACK for standard datatypes since, despite the
// differences in handling identity transformations, LAPACK's routine should
// always correctly apply a true Householder transformation.
//
template<typename F>
void ApplyReflector
( bool onLeft,
BlasInt m,
BlasInt n,
const F* v, BlasInt vInc,
const F& tau,
F* C, BlasInt CLDim,
F* work )
{
// TODO(poulson): Add shortcuts for sparse v
const F zero(0);
if( onLeft )
{
for( BlasInt i=0; i<n; ++i )
work[i] = zero;
blas::Gemv( 'C', m, n, F(1), C, CLDim, v, vInc, F(0), work, 1 );
blas::Ger( m, n, -tau, v, vInc, work, 1, C, CLDim );
}
else
{
for( BlasInt i=0; i<m; ++i )
work[i] = zero;
blas::Gemv( 'N', m, n, F(1), C, CLDim, v, vInc, F(0), work, 1 );
blas::Ger( m, n, -tau, work, 1, v, vInc, C, CLDim );
}
}
template<typename F>
void ApplyReflector
( bool onLeft,
BlasInt m,
BlasInt n,
const F* v, BlasInt vInc,
const F& tau,
F* C, BlasInt CLDim )
{
std::vector<F> work;
if( onLeft )
work.resize( n );
else
work.resize( m );
ApplyReflector( onLeft, m, n, v, vInc, tau, C, CLDim, work.data() );
}
template void ApplyReflector
( bool onLeft, BlasInt m, BlasInt n,
const float* v, BlasInt vInc,
const float& tau,
float* C, BlasInt CLDim );
template void ApplyReflector
( bool onLeft, BlasInt m, BlasInt n,
const Complex<float>* v, BlasInt vInc,
const Complex<float>& tau,
Complex<float>* C, BlasInt CLDim );
template void ApplyReflector
( bool onLeft, BlasInt m, BlasInt n,
const double* v, BlasInt vInc,
const double& tau,
double* C, BlasInt CLDim );
template void ApplyReflector
( bool onLeft, BlasInt m, BlasInt n,
const Complex<double>* v, BlasInt vInc,
const Complex<double>& tau,
Complex<double>* C, BlasInt CLDim );
#ifdef EL_HAVE_QD
template void ApplyReflector
( bool onLeft, BlasInt m, BlasInt n,
const DoubleDouble* v, BlasInt vInc,
const DoubleDouble& tau,
DoubleDouble* C, BlasInt CLDim );
template void ApplyReflector
( bool onLeft, BlasInt m, BlasInt n,
const Complex<DoubleDouble>* v, BlasInt vInc,
const Complex<DoubleDouble>& tau,
Complex<DoubleDouble>* C, BlasInt CLDim );
template void ApplyReflector
( bool onLeft, BlasInt m, BlasInt n,
const QuadDouble* v, BlasInt vInc,
const QuadDouble& tau,
QuadDouble* C, BlasInt CLDim );
template void ApplyReflector
( bool onLeft, BlasInt m, BlasInt n,
const Complex<QuadDouble>* v, BlasInt vInc,
const Complex<QuadDouble>& tau,
Complex<QuadDouble>* C, BlasInt CLDim );
#endif
#ifdef EL_HAVE_QUAD
template void ApplyReflector
( bool onLeft, BlasInt m, BlasInt n,
const Quad* v, BlasInt vInc,
const Quad& tau,
Quad* C, BlasInt CLDim );
template void ApplyReflector
( bool onLeft, BlasInt m, BlasInt n,
const Complex<Quad>* v, BlasInt vInc,
const Complex<Quad>& tau,
Complex<Quad>* C, BlasInt CLDim );
#endif
#ifdef EL_HAVE_MPC
template void ApplyReflector
( bool onLeft, BlasInt m, BlasInt n,
const BigFloat* v, BlasInt vInc,
const BigFloat& tau,
BigFloat* C, BlasInt CLDim );
template void ApplyReflector
( bool onLeft, BlasInt m, BlasInt n,
const Complex<BigFloat>* v, BlasInt vInc,
const Complex<BigFloat>& tau,
Complex<BigFloat>* C, BlasInt CLDim );
#endif
template void ApplyReflector
( bool onLeft, BlasInt m, BlasInt n,
const float* v, BlasInt vInc,
const float& tau,
float* C, BlasInt CLDim,
float* work );
template void ApplyReflector
( bool onLeft, BlasInt m, BlasInt n,
const Complex<float>* v, BlasInt vInc,
const Complex<float>& tau,
Complex<float>* C, BlasInt CLDim,
Complex<float>* work );
template void ApplyReflector
( bool onLeft, BlasInt m, BlasInt n,
const double* v, BlasInt vInc,
const double& tau,
double* C, BlasInt CLDim,
double* work );
template void ApplyReflector
( bool onLeft, BlasInt m, BlasInt n,
const Complex<double>* v, BlasInt vInc,
const Complex<double>& tau,
Complex<double>* C, BlasInt CLDim,
Complex<double>* work );
#ifdef EL_HAVE_QD
template void ApplyReflector
( bool onLeft, BlasInt m, BlasInt n,
const DoubleDouble* v, BlasInt vInc,
const DoubleDouble& tau,
DoubleDouble* C, BlasInt CLDim,
DoubleDouble* work );
template void ApplyReflector
( bool onLeft, BlasInt m, BlasInt n,
const Complex<DoubleDouble>* v, BlasInt vInc,
const Complex<DoubleDouble>& tau,
Complex<DoubleDouble>* C, BlasInt CLDim,
Complex<DoubleDouble>* work );
template void ApplyReflector
( bool onLeft, BlasInt m, BlasInt n,
const QuadDouble* v, BlasInt vInc,
const QuadDouble& tau,
QuadDouble* C, BlasInt CLDim,
QuadDouble* work );
template void ApplyReflector
( bool onLeft, BlasInt m, BlasInt n,
const Complex<QuadDouble>* v, BlasInt vInc,
const Complex<QuadDouble>& tau,
Complex<QuadDouble>* C, BlasInt CLDim,
Complex<QuadDouble>* work );
#endif
#ifdef EL_HAVE_QUAD
template void ApplyReflector
( bool onLeft, BlasInt m, BlasInt n,
const Quad* v, BlasInt vInc,
const Quad& tau,
Quad* C, BlasInt CLDim,
Quad* work );
template void ApplyReflector
( bool onLeft, BlasInt m, BlasInt n,
const Complex<Quad>* v, BlasInt vInc,
const Complex<Quad>& tau,
Complex<Quad>* C, BlasInt CLDim,
Complex<Quad>* work );
#endif
#ifdef EL_HAVE_MPC
template void ApplyReflector
( bool onLeft, BlasInt m, BlasInt n,
const BigFloat* v, BlasInt vInc,
const BigFloat& tau,
BigFloat* C, BlasInt CLDim,
BigFloat* work );
template void ApplyReflector
( bool onLeft, BlasInt m, BlasInt n,
const Complex<BigFloat>* v, BlasInt vInc,
const Complex<BigFloat>& tau,
Complex<BigFloat>* C, BlasInt CLDim,
Complex<BigFloat>* work );
#endif
// Compute the EVD of a symmetric tridiagonal matrix
// =================================================
BlasInt SymmetricTridiagEigWrapper
( char job,
char range,
BlasInt n,
float* d,
float* e,
float vl, float vu,
BlasInt il, BlasInt iu,
float absTol,
float* w,
float* Z, BlasInt ldZ )
{
EL_DEBUG_CSE
if( n == 0 )
return 0;
vector<BlasInt> isuppZ( 2*n );
BlasInt workSize=-1, iWorkSize=-1, m, info;
BlasInt iWorkDummy;
float workDummy;
EL_LAPACK(sstevr)
( &job, &range, &n, d, e, &vl, &vu, &il, &iu, &absTol, &m,
w, Z, &ldZ, isuppZ.data(), &workDummy, &workSize, &iWorkDummy, &iWorkSize,
&info );
workSize = workDummy;
iWorkSize = iWorkDummy;
vector<float> work(workSize);
vector<BlasInt> iWork(iWorkSize);
EL_LAPACK(sstevr)
( &job, &range, &n, d, e, &vl, &vu, &il, &iu, &absTol, &m,
w, Z, &ldZ, isuppZ.data(), work.data(), &workSize,
iWork.data(), &iWorkSize, &info );
if( info < 0 )
RuntimeError("Argument ",-info," had an illegal value");
else if( info > 0 )
RuntimeError("sstevr's failed");
return m;
}
BlasInt SymmetricTridiagEigWrapper
( char job, char range, BlasInt n, double* d, double* e, double vl, double vu,
BlasInt il, BlasInt iu, double absTol, double* w, double* Z, BlasInt ldZ )
{
EL_DEBUG_CSE
if( n == 0 )
return 0;
vector<BlasInt> isuppZ( 2*n );
BlasInt workSize=-1, iWorkSize=-1, m, info;
BlasInt iWorkDummy;
double workDummy;
EL_LAPACK(dstevr)
( &job, &range, &n, d, e, &vl, &vu, &il, &iu, &absTol, &m,
w, Z, &ldZ, isuppZ.data(), &workDummy, &workSize, &iWorkDummy, &iWorkSize,
&info );
workSize = workDummy;
iWorkSize = iWorkDummy;
vector<double> work(workSize);
vector<BlasInt> iWork(iWorkSize);
EL_LAPACK(dstevr)
( &job, &range, &n, d, e, &vl, &vu, &il, &iu, &absTol, &m,
w, Z, &ldZ, isuppZ.data(), work.data(), &workSize,
iWork.data(), &iWorkSize, &info );
if( info < 0 )
RuntimeError("Argument ",-info," had an illegal value");
else if( info > 0 )
RuntimeError("dstevr's failed");
return m;
}
// Compute eigenvalues
// -------------------
// All eigenvalues
// ^^^^^^^^^^^^^^^
void SymmetricTridiagEig
( BlasInt n, float* d, float* e, float* w, float absTol )
{
EL_DEBUG_CSE
SymmetricTridiagEigWrapper
( 'N', 'A', n, d, e, 0, 0, 0, 0, absTol, w, 0, 1 );
}
void SymmetricTridiagEig
( BlasInt n, double* d, double* e, double* w, double absTol )
{
EL_DEBUG_CSE
SymmetricTridiagEigWrapper
( 'N', 'A', n, d, e, 0, 0, 0, 0, absTol, w, 0, 1 );
}
// Floating-point range
// ^^^^^^^^^^^^^^^^^^^^
BlasInt SymmetricTridiagEig
( BlasInt n, float* d, float* e, float* w, float vl, float vu,
float absTol )
{
EL_DEBUG_CSE
return SymmetricTridiagEigWrapper
( 'N', 'V', n, d, e, vl, vu, 0, 0, absTol, w, 0, 1 );
}
BlasInt SymmetricTridiagEig
( BlasInt n, double* d, double* e, double* w, double vl, double vu,
double absTol )
{
EL_DEBUG_CSE
return SymmetricTridiagEigWrapper
( 'N', 'V', n, d, e, vl, vu, 0, 0, absTol, w, 0, 1 );
}
// Index range
// ^^^^^^^^^^^^^
void SymmetricTridiagEig
( BlasInt n, float* d, float* e, float* w, BlasInt il, BlasInt iu,
float absTol )
{
EL_DEBUG_CSE
SymmetricTridiagEigWrapper
( 'N', 'I', n, d, e, 0, 0, il+1, iu+1, absTol, w, 0, 1 );
}
void SymmetricTridiagEig
( BlasInt n, double* d, double* e, double* w, BlasInt il, BlasInt iu,
double absTol )
{
EL_DEBUG_CSE
SymmetricTridiagEigWrapper
( 'N', 'I', n, d, e, 0, 0, il+1, iu+1, absTol, w, 0, 1 );
}
// Compute eigenpairs
// ------------------
// All eigenpairs
// ^^^^^^^^^^^^^^
void SymmetricTridiagEig
( BlasInt n, float* d, float* e, float* w, float* Z, BlasInt ldZ,
float absTol )
{
EL_DEBUG_CSE
SymmetricTridiagEigWrapper
( 'V', 'A', n, d, e, 0, 0, 0, 0, absTol, w, Z, ldZ );
}
void SymmetricTridiagEig
( BlasInt n, double* d, double* e, double* w, double* Z, BlasInt ldZ,
double absTol )
{
EL_DEBUG_CSE
SymmetricTridiagEigWrapper
( 'V', 'A', n, d, e, 0, 0, 0, 0, absTol, w, Z, ldZ );
}
// Floating-point range
// ^^^^^^^^^^^^^^^^^^^^
BlasInt SymmetricTridiagEig
( BlasInt n, float* d, float* e, float* w, float* Z, BlasInt ldZ,
float vl, float vu, float absTol )
{
EL_DEBUG_CSE
return SymmetricTridiagEigWrapper
( 'V', 'V', n, d, e, vl, vu, 0, 0, absTol, w, Z, ldZ );
}
BlasInt SymmetricTridiagEig
( BlasInt n, double* d, double* e, double* w, double* Z, BlasInt ldZ,
double vl, double vu, double absTol )
{
EL_DEBUG_CSE
return SymmetricTridiagEigWrapper
( 'V', 'V', n, d, e, vl, vu, 0, 0, absTol, w, Z, ldZ );
}
// Index range
// ^^^^^^^^^^^^^
void SymmetricTridiagEig
( BlasInt n, float* d, float* e, float* w, float* Z, BlasInt ldZ,
BlasInt il, BlasInt iu, float absTol )
{
EL_DEBUG_CSE
SymmetricTridiagEigWrapper
( 'V', 'I', n, d, e, 0, 0, il+1, iu+1, absTol, w, Z, ldZ );
}
void SymmetricTridiagEig
( BlasInt n, double* d, double* e, double* w, double* Z, BlasInt ldZ,
BlasInt il, BlasInt iu, double absTol )
{
EL_DEBUG_CSE
SymmetricTridiagEigWrapper
( 'V', 'I', n, d, e, 0, 0, il+1, iu+1, absTol, w, Z, ldZ );
}
// Compute the EVD of a Hermitian matrix
// =====================================
BlasInt HermitianEigWrapper
( char job, char range, char uplo, BlasInt n, float* A, BlasInt ldA,
float vl, float vu, BlasInt il, BlasInt iu, float absTol,
float* w, float* Z, BlasInt ldZ )
{
EL_DEBUG_CSE
if( n == 0 )
return 0;
vector<BlasInt> isuppZ( 2*n );
BlasInt workSize=-1, iWorkSize=-1, m, info;
BlasInt iWorkDummy;
float workDummy;
EL_LAPACK(ssyevr)
( &job, &range, &uplo, &n, A, &ldA, &vl, &vu, &il, &iu, &absTol, &m,
w, Z, &ldZ, isuppZ.data(), &workDummy, &workSize, &iWorkDummy, &iWorkSize,
&info );
workSize = workDummy;
iWorkSize = iWorkDummy;
vector<float> work(workSize);
vector<BlasInt> iWork(iWorkSize);
EL_LAPACK(ssyevr)
( &job, &range, &uplo, &n, A, &ldA, &vl, &vu, &il, &iu, &absTol, &m,
w, Z, &ldZ, isuppZ.data(), work.data(), &workSize,
iWork.data(), &iWorkSize, &info );
if( info < 0 )
RuntimeError("Argument ",-info," had an illegal value");
else if( info > 0 )
RuntimeError("ssyevr's failed");
return m;
}
BlasInt HermitianEigWrapper
( char job, char range, char uplo, BlasInt n, double* A, BlasInt ldA,
double vl, double vu, BlasInt il, BlasInt iu, double absTol,
double* w, double* Z, BlasInt ldZ )
{
EL_DEBUG_CSE
if( n == 0 )
return 0;
vector<BlasInt> isuppZ( 2*n );
BlasInt workSize=-1, iWorkSize=-1, m, info;
BlasInt iWorkDummy;
double workDummy;
EL_LAPACK(dsyevr)
( &job, &range, &uplo, &n, A, &ldA, &vl, &vu, &il, &iu, &absTol, &m,
w, Z, &ldZ, isuppZ.data(), &workDummy, &workSize,
&iWorkDummy, &iWorkSize, &info );
workSize = workDummy;
iWorkSize = iWorkDummy;
vector<double> work(workSize);
vector<BlasInt> iWork(iWorkSize);
EL_LAPACK(dsyevr)
( &job, &range, &uplo, &n, A, &ldA, &vl, &vu, &il, &iu, &absTol, &m,
w, Z, &ldZ, isuppZ.data(), work.data(), &workSize,
iWork.data(), &iWorkSize, &info );
if( info < 0 )
RuntimeError("Argument ",-info," had an illegal value");
else if( info > 0 )
RuntimeError("dsyevr's failed");
return m;
}
BlasInt HermitianEigWrapper
( char job, char range, char uplo, BlasInt n, scomplex* A, BlasInt ldA,
float vl, float vu, BlasInt il, BlasInt iu, float absTol,
float* w, scomplex* Z, BlasInt ldZ )
{
EL_DEBUG_CSE
if( n == 0 )
return 0;
vector<BlasInt> isuppZ( 2*n );
BlasInt workSize=-1, rWorkSize=-1, iWorkSize=-1, m, info;
BlasInt iWorkDummy;
float rWorkDummy;
scomplex workDummy;
EL_LAPACK(cheevr)
( &job, &range, &uplo, &n, A, &ldA, &vl, &vu, &il, &iu, &absTol, &m,
w, Z, &ldZ, isuppZ.data(), &workDummy, &workSize, &rWorkDummy, &rWorkSize,
&iWorkDummy, &iWorkSize, &info );
workSize = workDummy.real();
rWorkSize = rWorkDummy;
iWorkSize = iWorkDummy;
vector<scomplex> work(workSize);
vector<float> rWork(rWorkSize);
vector<BlasInt> iWork(iWorkSize);
EL_LAPACK(cheevr)
( &job, &range, &uplo, &n, A, &ldA, &vl, &vu, &il, &iu, &absTol, &m,
w, Z, &ldZ, isuppZ.data(), work.data(), &workSize,
rWork.data(), &rWorkSize, iWork.data(), &iWorkSize, &info );
if( info < 0 )
RuntimeError("Argument ",-info," had an illegal value");
else if( info > 0 )
RuntimeError("cheevr's failed");
return m;
}
BlasInt HermitianEigWrapper
( char job, char range, char uplo, BlasInt n, dcomplex* A, BlasInt ldA,
double vl, double vu, BlasInt il, BlasInt iu, double absTol,
double* w, dcomplex* Z, BlasInt ldZ )
{
EL_DEBUG_CSE
if( n == 0 )
return 0;
vector<BlasInt> isuppZ( 2*n );
BlasInt workSize=-1, rWorkSize=-1, iWorkSize=-1, m, info;
BlasInt iWorkDummy;
double rWorkDummy;
dcomplex workDummy;
EL_LAPACK(zheevr)
( &job, &range, &uplo, &n, A, &ldA, &vl, &vu, &il, &iu, &absTol, &m,
w, Z, &ldZ, isuppZ.data(), &workDummy, &workSize, &rWorkDummy, &rWorkSize,
&iWorkDummy, &iWorkSize, &info );
workSize = workDummy.real();
rWorkSize = rWorkDummy;
iWorkSize = iWorkDummy;
vector<dcomplex> work(workSize);
vector<double> rWork(rWorkSize);
vector<BlasInt> iWork(iWorkSize);
EL_LAPACK(zheevr)
( &job, &range, &uplo, &n, A, &ldA, &vl, &vu, &il, &iu, &absTol, &m,
w, Z, &ldZ, isuppZ.data(), work.data(), &workSize,
rWork.data(), &rWorkSize, iWork.data(), &iWorkSize, &info );
if( info < 0 )
RuntimeError("Argument ",-info," had an illegal value");
else if( info > 0 )
RuntimeError("zheevr's failed");
return m;
}
// Compute the eigenvalues
// -----------------------
// All eigenvalues
// ^^^^^^^^^^^^^^^
void HermitianEig
( char uplo, BlasInt n, float* A, BlasInt ldA, float* w, float absTol )
{
EL_DEBUG_CSE
HermitianEigWrapper
( 'N', 'A', uplo, n, A, ldA, 0, 0, 0, 0, absTol, w, 0, 1 );
}
void HermitianEig
( char uplo, BlasInt n, double* A, BlasInt ldA, double* w, double absTol )
{
EL_DEBUG_CSE
HermitianEigWrapper
( 'N', 'A', uplo, n, A, ldA, 0, 0, 0, 0, absTol, w, 0, 1 );
}
void HermitianEig
( char uplo, BlasInt n, scomplex* A, BlasInt ldA, float* w, float absTol )
{
EL_DEBUG_CSE
HermitianEigWrapper
( 'N', 'A', uplo, n, A, ldA, 0, 0, 0, 0, absTol, w, 0, 1 );
}
void HermitianEig
( char uplo, BlasInt n, dcomplex* A, BlasInt ldA, double* w, double absTol )
{
EL_DEBUG_CSE
HermitianEigWrapper
( 'N', 'A', uplo, n, A, ldA, 0, 0, 0, 0, absTol, w, 0, 1 );
}
// Floating-point range
// ^^^^^^^^^^^^^^^^^^^^
BlasInt HermitianEig
( char uplo, BlasInt n, float* A, BlasInt ldA, float* w,
float vl, float vu, float absTol )
{
EL_DEBUG_CSE
return HermitianEigWrapper
( 'N', 'V', uplo, n, A, ldA, vl, vu, 0, 0, absTol, w, 0, 1 );
}
BlasInt HermitianEig
( char uplo, BlasInt n, double* A, BlasInt ldA, double* w,
double vl, double vu, double absTol )
{
EL_DEBUG_CSE
return HermitianEigWrapper
( 'N', 'V', uplo, n, A, ldA, vl, vu, 0, 0, absTol, w, 0, 1 );
}
BlasInt HermitianEig
( char uplo, BlasInt n, scomplex* A, BlasInt ldA, float* w,
float vl, float vu, float absTol )
{
EL_DEBUG_CSE
return HermitianEigWrapper
( 'N', 'V', uplo, n, A, ldA, vl, vu, 0, 0, absTol, w, 0, 1 );
}
BlasInt HermitianEig
( char uplo, BlasInt n, dcomplex* A, BlasInt ldA, double* w,
double vl, double vu, double absTol )
{
EL_DEBUG_CSE
return HermitianEigWrapper
( 'N', 'V', uplo, n, A, ldA, vl, vu, 0, 0, absTol, w, 0, 1 );
}
// Index range
// ^^^^^^^^^^^
void HermitianEig
( char uplo, BlasInt n, float* A, BlasInt ldA, float* w,
BlasInt il, BlasInt iu, float absTol )
{
EL_DEBUG_CSE
HermitianEigWrapper
( 'N', 'I', uplo, n, A, ldA, 0, 0, il+1, iu+1, absTol, w, 0, 1 );
}
void HermitianEig
( char uplo, BlasInt n, double* A, BlasInt ldA, double* w,
BlasInt il, BlasInt iu, double absTol )
{
EL_DEBUG_CSE
HermitianEigWrapper
( 'N', 'I', uplo, n, A, ldA, 0, 0, il+1, iu+1, absTol, w, 0, 1 );
}
void HermitianEig
( char uplo, BlasInt n, scomplex* A, BlasInt ldA, float* w,
BlasInt il, BlasInt iu, float absTol )
{
EL_DEBUG_CSE
HermitianEigWrapper
( 'N', 'I', uplo, n, A, ldA, 0, 0, il+1, iu+1, absTol, w, 0, 1 );
}
void HermitianEig
( char uplo, BlasInt n, dcomplex* A, BlasInt ldA, double* w,
BlasInt il, BlasInt iu, double absTol )
{
EL_DEBUG_CSE
HermitianEigWrapper
( 'N', 'I', uplo, n, A, ldA, 0, 0, il+1, iu+1, absTol, w, 0, 1 );
}
// Compute the eigenpairs
// ----------------------
// All eigenpairs
// ^^^^^^^^^^^^^^
void HermitianEig
( char uplo, BlasInt n, float* A, BlasInt ldA, float* w, float* Z, BlasInt ldZ,
float absTol )
{
EL_DEBUG_CSE
HermitianEigWrapper
( 'V', 'A', uplo, n, A, ldA, 0, 0, 0, 0, absTol, w, Z, ldZ );
}
void HermitianEig
( char uplo, BlasInt n,
double* A, BlasInt ldA, double* w, double* Z, BlasInt ldZ,
double absTol )
{
EL_DEBUG_CSE
HermitianEigWrapper
( 'V', 'A', uplo, n, A, ldA, 0, 0, 0, 0, absTol, w, Z, ldZ );
}
void HermitianEig
( char uplo, BlasInt n,
scomplex* A, BlasInt ldA, float* w, scomplex* Z, BlasInt ldZ,
float absTol )
{
EL_DEBUG_CSE
HermitianEigWrapper
( 'V', 'A', uplo, n, A, ldA, 0, 0, 0, 0, absTol, w, Z, ldZ );
}
void HermitianEig
( char uplo, BlasInt n,
dcomplex* A, BlasInt ldA, double* w, dcomplex* Z, BlasInt ldZ,
double absTol )
{
EL_DEBUG_CSE
HermitianEigWrapper
( 'V', 'A', uplo, n, A, ldA, 0, 0, 0, 0, absTol, w, Z, ldZ );
}
// Floating-point range
// ^^^^^^^^^^^^^^^^^^^^
BlasInt HermitianEig
( char uplo, BlasInt n,
float* A, BlasInt ldA, float* w, float* Z, BlasInt ldZ,
float vl, float vu, float absTol )
{
EL_DEBUG_CSE
return HermitianEigWrapper
( 'V', 'V', uplo, n, A, ldA, vl, vu, 0, 0, absTol, w, Z, ldZ );
}
BlasInt HermitianEig
( char uplo, BlasInt n,
double* A, BlasInt ldA, double* w, double* Z, BlasInt ldZ,
double vl, double vu, double absTol )
{
EL_DEBUG_CSE
return HermitianEigWrapper
( 'V', 'V', uplo, n, A, ldA, vl, vu, 0, 0, absTol, w, Z, ldZ );
}
BlasInt HermitianEig
( char uplo, BlasInt n,
scomplex* A, BlasInt ldA, float* w, scomplex* Z, BlasInt ldZ,
float vl, float vu, float absTol )
{
EL_DEBUG_CSE
return HermitianEigWrapper
( 'V', 'V', uplo, n, A, ldA, vl, vu, 0, 0, absTol, w, Z, ldZ );
}
BlasInt HermitianEig
( char uplo, BlasInt n,
dcomplex* A, BlasInt ldA, double* w, dcomplex* Z, BlasInt ldZ,
double vl, double vu, double absTol )
{
EL_DEBUG_CSE
return HermitianEigWrapper
( 'V', 'V', uplo, n, A, ldA, vl, vu, 0, 0, absTol, w, Z, ldZ );
}
// Index range
// ^^^^^^^^^^^
void HermitianEig
( char uplo, BlasInt n,
float* A, BlasInt ldA, float* w, float* Z, BlasInt ldZ,
BlasInt il, BlasInt iu, float absTol )
{
EL_DEBUG_CSE
HermitianEigWrapper
( 'V', 'I', uplo, n, A, ldA, 0, 0, il+1, iu+1, absTol, w, Z, ldZ );
}
void HermitianEig
( char uplo, BlasInt n,
double* A, BlasInt ldA, double* w, double* Z, BlasInt ldZ,
BlasInt il, BlasInt iu, double absTol )
{
EL_DEBUG_CSE
HermitianEigWrapper
( 'V', 'I', uplo, n, A, ldA, 0, 0, il+1, iu+1, absTol, w, Z, ldZ );
}
void HermitianEig
( char uplo, BlasInt n,
scomplex* A, BlasInt ldA, float* w, scomplex* Z, BlasInt ldZ,
BlasInt il, BlasInt iu, float absTol )
{
EL_DEBUG_CSE
HermitianEigWrapper
( 'V', 'I', uplo, n, A, ldA, 0, 0, il+1, iu+1, absTol, w, Z, ldZ );
}
void HermitianEig
( char uplo, BlasInt n,
dcomplex* A, BlasInt ldA, double* w, dcomplex* Z, BlasInt ldZ,
BlasInt il, BlasInt iu, double absTol )
{
EL_DEBUG_CSE
HermitianEigWrapper
( 'V', 'I', uplo, n, A, ldA, 0, 0, il+1, iu+1, absTol, w, Z, ldZ );
}
// Bidiagonal DQDS for singular values
// ===================================
void BidiagDQDS( BlasInt n, float* d, float* e )
{
EL_DEBUG_CSE
BlasInt info;
vector<float> work( 4*n );
EL_LAPACK(slasq1)( &n, d, e, work.data(), &info );
if( info != 0 )
{
ostringstream msg;
if( info < 0 )
msg << "Argument " << -info << " had an illegal value";
else if( info == 1 )
msg << "A split was marked in a positive value in E";
else if( info == 2 )
msg << "Current block of Z not bidiagonalized after 30*k its";
else if( info == 3 )
msg << "Termination criterion of outer while loop not met";
RuntimeError( msg.str() );
}
}
void BidiagDQDS( BlasInt n, double* d, double* e )
{
EL_DEBUG_CSE
BlasInt info;
vector<double> work( 4*n );
EL_LAPACK(dlasq1)( &n, d, e, work.data(), &info );
if( info != 0 )
{
ostringstream msg;
if( info < 0 )
msg << "Argument " << -info << " had an illegal value";
else if( info == 1 )
msg << "A split was marked in a positive value in E";
else if( info == 2 )
msg << "Current block of Z not bidiagonalized after 30*k its";
else if( info == 3 )
msg << "Termination criterion of outer while loop not met";
RuntimeError( msg.str() );
}
}
// Bidiagonal QR algorithm for SVD
// ===============================
void BidiagSVDQRAlg
( char uplo, BlasInt n, BlasInt numColsVT, BlasInt numRowsU,
float* d, float* e, float* VTrans, BlasInt ldVT, float* U, BlasInt ldU )
{
EL_DEBUG_CSE
if( n==0 )
return;
BlasInt info;
float* C=0;
const BlasInt numColsC=0, ldC=1;
vector<float> work( 4*n );
EL_LAPACK(sbdsqr)
( &uplo, &n, &numColsVT, &numRowsU, &numColsC,
d, e,
VTrans, &ldVT,
U, &ldU,
C, &ldC,
work.data(), &info );
if( info < 0 )
RuntimeError("Argument ",-info," had an illegal value");
else if( info > 0 )
RuntimeError("sbdsqr had ",info," elements of e not converge");
}
void BidiagSVDQRAlg
( char uplo, BlasInt n, BlasInt numColsVT, BlasInt numRowsU,
double* d, double* e, double* VTrans, BlasInt ldVT, double* U, BlasInt ldU )
{
EL_DEBUG_CSE
if( n==0 )
return;
BlasInt info;
double* C=0;
const BlasInt numColsC=0, ldC=1;
vector<double> work( 4*n );
EL_LAPACK(dbdsqr)
( &uplo, &n, &numColsVT, &numRowsU, &numColsC,
d, e,
VTrans, &ldVT,
U, &ldU,
C, &ldC,
work.data(), &info );
if( info < 0 )
RuntimeError("Argument ",-info," had an illegal value");
else if( info > 0 )
RuntimeError("dbdsqr had ",info," elements of e not converge");
}
void BidiagSVDQRAlg
( char uplo, BlasInt n, BlasInt numColsVH, BlasInt numRowsU,
float* d, float* e,
scomplex* VH, BlasInt ldVH,
scomplex* U, BlasInt ldU )
{
EL_DEBUG_CSE
if( n==0 )
return;
BlasInt info;
scomplex* C=0;
const BlasInt numColsC=0, ldC=1;
vector<float> realWork;
if( numColsVH == 0 && numRowsU == 0 && numColsC == 0 )
realWork.resize( 2*n );
else
realWork.resize( Max(1,4*n-4) );
EL_LAPACK(cbdsqr)
( &uplo, &n, &numColsVH, &numRowsU, &numColsC,
d, e,
VH, &ldVH,
U, &ldU,
C, &ldC,
realWork.data(), &info );
if( info < 0 )
RuntimeError("Argument ",-info," had an illegal value");
else if( info > 0 )
RuntimeError("cbdsqr had ",info," elements of e not converge");
}
void BidiagSVDQRAlg
( char uplo, BlasInt n, BlasInt numColsVH, BlasInt numRowsU,
double* d, double* e,
dcomplex* VH, BlasInt ldVH,
dcomplex* U, BlasInt ldU )
{
EL_DEBUG_CSE
if( n==0 )
return;
BlasInt info;
dcomplex* C=0;
const BlasInt numColsC=0, ldC=1;
vector<double> realWork;
if( numColsVH == 0 && numRowsU == 0 && numColsC == 0 )
realWork.resize( 2*n );
else
realWork.resize( Max(1,4*n-4) );
EL_LAPACK(zbdsqr)
( &uplo, &n, &numColsVH, &numRowsU, &numColsC,
d, e,
VH, &ldVH,
U, &ldU,
C, &ldC,
realWork.data(), &info );
if( info < 0 )
RuntimeError("Argument ",-info," had an illegal value");
else if( info > 0 )
RuntimeError("zbdsqr had ",info," elements of e not converge");
}
// Divide and Conquer SVD
// ======================
void DivideAndConquerSVD
( BlasInt m, BlasInt n,
float* A, BlasInt ldA,
float* s,
float* U, BlasInt ldu,
float* VTrans, BlasInt ldvt,
bool thin )
{
EL_DEBUG_CSE
if( m==0 || n==0 )
return;
const char jobz = ( thin ? 'S' : 'A' );
BlasInt workSize=-1, info;
float workDummy;
const BlasInt k = Min(m,n);
vector<BlasInt> iWork(8*k);
EL_LAPACK(sgesdd)
( &jobz, &m, &n,
A, &ldA,
s,
U, &ldu,
VTrans, &ldvt,
&workDummy, &workSize,
iWork.data(),
&info );
workSize = workDummy;
vector<float> work(workSize);
EL_LAPACK(sgesdd)
( &jobz, &m, &n,
A, &ldA,
s,
U, &ldu,
VTrans, &ldvt,
work.data(), &workSize,
iWork.data(),
&info );
if( info < 0 )
RuntimeError("Argument ",-info," had an illegal value");
else if( info > 0 )
RuntimeError("sgesdd's updating process failed");
}
void DivideAndConquerSVD
( BlasInt m, BlasInt n,
double* A, BlasInt ldA,
double* s,
double* U, BlasInt ldu,
double* VTrans, BlasInt ldvt,
bool thin )
{
EL_DEBUG_CSE
if( m==0 || n==0 )
return;
const char jobz = ( thin ? 'S' : 'A' );
BlasInt workSize=-1, info;
double workDummy;
const BlasInt k = Min(m,n);
vector<BlasInt> iWork(8*k);
EL_LAPACK(dgesdd)
( &jobz, &m, &n,
A, &ldA,
s,
U, &ldu,
VTrans, &ldvt,
&workDummy, &workSize,
iWork.data(),
&info );
workSize = workDummy;
vector<double> work(workSize);
EL_LAPACK(dgesdd)
( &jobz, &m, &n,
A, &ldA,
s,
U, &ldu,
VTrans, &ldvt,
work.data(), &workSize,
iWork.data(),
&info );
if( info < 0 )
RuntimeError("Argument ",-info," had an illegal value");
else if( info > 0 )
RuntimeError("dgesdd's updating process failed");
}
void DivideAndConquerSVD
( BlasInt m, BlasInt n,
scomplex* A, BlasInt ldA,
float* s,
scomplex* U, BlasInt ldu,
scomplex* VH, BlasInt ldva,
bool thin )
{
EL_DEBUG_CSE
if( m==0 || n==0 )
return;
const char jobz = ( thin ? 'S' : 'A' );
BlasInt workSize=-1, info;
const BlasInt k = Min(m,n);
const BlasInt K = Max(m,n);
const BlasInt rWorkSize = k*Max(5*k+7,2*K+2*k+1);
vector<float> rWork(rWorkSize);
vector<BlasInt> iWork(8*k);
scomplex workDummy;
EL_LAPACK(cgesdd)
( &jobz, &m, &n,
A, &ldA,
s,
U, &ldu,
VH, &ldva,
&workDummy, &workSize,
rWork.data(),
iWork.data(),
&info );
workSize = workDummy.real();
vector<scomplex> work(workSize);
EL_LAPACK(cgesdd)
( &jobz, &m, &n,
A, &ldA,
s,
U, &ldu,
VH, &ldva,
work.data(), &workSize,
rWork.data(),
iWork.data(),
&info );
if( info < 0 )
RuntimeError("Argument ",-info," had an illegal value");
else if( info > 0 )
RuntimeError("cgesdd's updating process failed");
}
void DivideAndConquerSVD
( BlasInt m, BlasInt n,
dcomplex* A, BlasInt ldA,
double* s,
dcomplex* U, BlasInt ldu,
dcomplex* VH, BlasInt ldva,
bool thin )
{
EL_DEBUG_CSE
if( m==0 || n==0 )
return;
const char jobz = ( thin ? 'S' : 'A' );
BlasInt workSize=-1, info;
dcomplex workDummy;
const BlasInt k = Min(m,n);
const BlasInt K = Max(m,n);
const BlasInt rWorkSize = k*Max(5*k+7,2*K+2*k+1);
vector<double> rWork(rWorkSize);
vector<BlasInt> iWork(8*k);
EL_LAPACK(zgesdd)
( &jobz, &m, &n,
A, &ldA,
s,
U, &ldu,
VH, &ldva,
&workDummy, &workSize,
rWork.data(),
iWork.data(),
&info );
workSize = workDummy.real();
vector<dcomplex> work(workSize);
EL_LAPACK(zgesdd)
( &jobz, &m, &n,
A, &ldA,
s,
U, &ldu,
VH, &ldva,
work.data(), &workSize,
rWork.data(),
iWork.data(),
&info );
if( info < 0 )
RuntimeError("Argument ",-info," had an illegal value");
else if( info > 0 )
RuntimeError("zgesdd's updating process failed");
}
// QR-algorithm SVD
// ================
void QRSVD
( BlasInt m, BlasInt n,
float* A, BlasInt ldA,
float* s,
float* U, BlasInt ldu,
float* VTrans, BlasInt ldvt,
bool thin, bool avoidU, bool avoidV )
{
EL_DEBUG_CSE
if( m==0 || n==0 )
return;
const char jobU= ( avoidU ? 'N' : ( thin ? 'S' : 'A' ) ),
jobVT= ( avoidV ? 'N' : ( thin ? 'S' : 'A' ) );
BlasInt workSize=-1, info;
float workDummy;
EL_LAPACK(sgesvd)
( &jobU, &jobVT, &m, &n,
A, &ldA,
s,
U, &ldu,
VTrans, &ldvt,
&workDummy, &workSize,
&info );
workSize = workDummy;
vector<float> work(workSize);
EL_LAPACK(sgesvd)
( &jobU, &jobVT, &m, &n,
A, &ldA,
s,
U, &ldu,
VTrans, &ldvt,
work.data(), &workSize,
&info );
if( info < 0 )
RuntimeError("Argument ",-info," had an illegal value");
else if( info > 0 )
RuntimeError("sgesvd's updating process failed");
}
void QRSVD
( BlasInt m, BlasInt n,
double* A, BlasInt ldA,
double* s,
double* U, BlasInt ldu,
double* VTrans, BlasInt ldvt,
bool thin, bool avoidU, bool avoidV )
{
EL_DEBUG_CSE
if( m==0 || n==0 )
return;
const char jobU= ( avoidU ? 'N' : ( thin ? 'S' : 'A' ) ),
jobVT= ( avoidV ? 'N' : ( thin ? 'S' : 'A' ) );
BlasInt workSize=-1, info;
double workDummy;
EL_LAPACK(dgesvd)
( &jobU, &jobVT, &m, &n,
A, &ldA,
s,
U, &ldu,
VTrans, &ldvt,
&workDummy, &workSize,
&info );
workSize = workDummy;
vector<double> work(workSize);
EL_LAPACK(dgesvd)
( &jobU, &jobVT, &m, &n,
A, &ldA,
s,
U, &ldu,
VTrans, &ldvt,
work.data(), &workSize,
&info );
if( info < 0 )
RuntimeError("Argument ",-info," had an illegal value");
else if( info > 0 )
RuntimeError("dgesvd's updating process failed");
}
void QRSVD
( BlasInt m, BlasInt n,
scomplex* A, BlasInt ldA,
float* s,
scomplex* U, BlasInt ldu,
scomplex* VH, BlasInt ldva,
bool thin, bool avoidU, bool avoidV )
{
EL_DEBUG_CSE
if( m==0 || n==0 )
return;
const char jobU= ( avoidU ? 'N' : ( thin ? 'S' : 'A' ) ),
jobVH= ( avoidV ? 'N' : ( thin ? 'S' : 'A' ) );
BlasInt workSize=-1, info;
const BlasInt k = Min(m,n);
vector<float> rWork(5*k);
scomplex workDummy;
EL_LAPACK(cgesvd)
( &jobU, &jobVH, &m, &n,
A, &ldA,
s,
U, &ldu,
VH, &ldva,
&workDummy, &workSize,
rWork.data(),
&info );
workSize = workDummy.real();
vector<scomplex> work(workSize);
EL_LAPACK(cgesvd)
( &jobU, &jobVH, &m, &n,
A, &ldA,
s,
U, &ldu,
VH, &ldva,
work.data(), &workSize,
rWork.data(),
&info );
if( info < 0 )
RuntimeError("Argument ",-info," had an illegal value");
else if( info > 0 )
RuntimeError("cgesvd's updating process failed");
}
void QRSVD
( BlasInt m, BlasInt n,
dcomplex* A, BlasInt ldA,
double* s,
dcomplex* U, BlasInt ldu,
dcomplex* VH, BlasInt ldva,
bool thin, bool avoidU, bool avoidV )
{
EL_DEBUG_CSE
if( m==0 || n==0 )
return;
const char jobU= ( avoidU ? 'N' : ( thin ? 'S' : 'A' ) ),
jobVH= ( avoidV ? 'N' : ( thin ? 'S' : 'A' ) );
BlasInt workSize=-1, info;
dcomplex workDummy;
const BlasInt k = Min(m,n);
vector<double> rWork(5*k);
EL_LAPACK(zgesvd)
( &jobU, &jobVH, &m, &n,
A, &ldA,
s,
U, &ldu,
VH, &ldva,
&workDummy, &workSize,
rWork.data(),
&info );
workSize = workDummy.real();
vector<dcomplex> work(workSize);
EL_LAPACK(zgesvd)
( &jobU, &jobVH, &m, &n,
A, &ldA,
s,
U, &ldu,
VH, &ldva,
work.data(), &workSize,
rWork.data(),
&info );
if( info < 0 )
RuntimeError("Argument ",-info," had an illegal value");
else if( info > 0 )
RuntimeError("zgesvd's updating process failed");
}
// Compute singular values (with DQDS)
// ===================================
void SVD( BlasInt m, BlasInt n, float* A, BlasInt ldA, float* s )
{
EL_DEBUG_CSE
if( m==0 || n==0 )
return;
const char jobU='N', jobVT='N';
BlasInt fakeLDim=1, workSize=-1, info;
float workDummy;
EL_LAPACK(sgesvd)
( &jobU, &jobVT, &m, &n, A, &ldA, s, 0, &fakeLDim, 0, &fakeLDim,
&workDummy, &workSize, &info );
workSize = workDummy;
vector<float> work(workSize);
EL_LAPACK(sgesvd)
( &jobU, &jobVT, &m, &n, A, &ldA, s, 0, &fakeLDim, 0, &fakeLDim,
work.data(), &workSize, &info );
if( info < 0 )
RuntimeError("Argument ",-info," had an illegal value");
else if( info > 0 )
RuntimeError("sgesvd's updating process failed");
}
void SVD( BlasInt m, BlasInt n, double* A, BlasInt ldA, double* s )
{
EL_DEBUG_CSE
if( m==0 || n==0 )
return;
const char jobU='N', jobVT='N';
BlasInt fakeLDim=1, workSize=-1, info;
double workDummy;
EL_LAPACK(dgesvd)
( &jobU, &jobVT, &m, &n, A, &ldA, s, 0, &fakeLDim, 0, &fakeLDim,
&workDummy, &workSize, &info );
workSize = workDummy;
vector<double> work(workSize);
EL_LAPACK(dgesvd)
( &jobU, &jobVT, &m, &n, A, &ldA, s, 0, &fakeLDim, 0, &fakeLDim,
work.data(), &workSize, &info );
if( info < 0 )
RuntimeError("Argument ",-info," had an illegal value");
else if( info > 0 )
RuntimeError("dgesvd's updating process failed");
}
void SVD( BlasInt m, BlasInt n, scomplex* A, BlasInt ldA, float* s )
{
EL_DEBUG_CSE
if( m==0 || n==0 )
return;
const char jobU='N', jobVH='N';
BlasInt fakeLDim=1, workSize=-1, info;
scomplex workDummy;
const BlasInt k = Min(m,n);
vector<float> rWork(5*k);
EL_LAPACK(cgesvd)
( &jobU, &jobVH, &m, &n, A, &ldA, s, 0, &fakeLDim, 0, &fakeLDim,
&workDummy, &workSize, rWork.data(), &info );
workSize = workDummy.real();
vector<scomplex> work(workSize);
EL_LAPACK(cgesvd)
( &jobU, &jobVH, &m, &n, A, &ldA, s, 0, &fakeLDim, 0, &fakeLDim,
work.data(), &workSize, rWork.data(), &info );
if( info < 0 )
RuntimeError("Argument ",-info," had an illegal value");
else if( info > 0 )
RuntimeError("cgesvd's updating process failed");
}
void SVD( BlasInt m, BlasInt n, dcomplex* A, BlasInt ldA, double* s )
{
EL_DEBUG_CSE
if( m==0 || n==0 )
return;
const char jobU='N', jobVH='N';
BlasInt fakeLDim=1, workSize=-1, info;
dcomplex workDummy;
const BlasInt k = Min(m,n);
vector<double> rWork(5*k);
EL_LAPACK(zgesvd)
( &jobU, &jobVH, &m, &n, A, &ldA, s, 0, &fakeLDim, 0, &fakeLDim,
&workDummy, &workSize, rWork.data(), &info );
workSize = workDummy.real();
vector<dcomplex> work(workSize);
EL_LAPACK(zgesvd)
( &jobU, &jobVH, &m, &n, A, &ldA, s, 0, &fakeLDim, 0, &fakeLDim,
work.data(), &workSize, rWork.data(), &info );
if( info < 0 )
RuntimeError("Argument ",-info," had an illegal value");
else if( info > 0 )
RuntimeError("zgesvd's updating process failed");
}
// Reduce a general square matrix to upper Hessenberg form
// =======================================================
void Hessenberg
( BlasInt n,
float* A, BlasInt ldA,
float* tau )
{
// Query the workspace size
BlasInt ilo=1, ihi=n, workSize=-1, info;
float workDummy;
EL_LAPACK(sgehrd)
( &n, &ilo, &ihi,
A, &ldA,
tau,
&workDummy, &workSize,
&info );
workSize = workDummy;
// Reduce to Hessenberg form
vector<float> work( workSize );
EL_LAPACK(sgehrd)
( &n, &ilo, &ihi,
A, &ldA,
tau,
work.data(), &workSize,
&info );
if( info < 0 )
RuntimeError("Argument ",-info," of reduction had an illegal value");
}
void Hessenberg
( BlasInt n,
double* A, BlasInt ldA,
double* tau )
{
// Query the workspace size
BlasInt ilo=1, ihi=n, workSize=-1, info;
double workDummy;
EL_LAPACK(dgehrd)
( &n, &ilo, &ihi,
A, &ldA,
tau,
&workDummy, &workSize,
&info );
workSize = workDummy;
// Reduce to Hessenberg form
vector<double> work( workSize );
EL_LAPACK(dgehrd)
( &n, &ilo, &ihi,
A, &ldA,
tau,
work.data(), &workSize,
&info );
if( info < 0 )
RuntimeError("Argument ",-info," of reduction had an illegal value");
}
void Hessenberg
( BlasInt n,
scomplex* A, BlasInt ldA,
scomplex* tau )
{
// Query the workspace size
BlasInt ilo=1, ihi=n, workSize=-1, info;
scomplex workDummy;
EL_LAPACK(cgehrd)
( &n, &ilo, &ihi,
A, &ldA,
tau,
&workDummy, &workSize,
&info );
workSize = workDummy.real();
// Reduce to Hessenberg form
vector<scomplex> work( workSize );
EL_LAPACK(cgehrd)
( &n, &ilo, &ihi,
A, &ldA,
tau,
work.data(), &workSize,
&info );
if( info < 0 )
RuntimeError("Argument ",-info," of reduction had an illegal value");
}
void Hessenberg
( BlasInt n,
dcomplex* A, BlasInt ldA,
dcomplex* tau )
{
// Query the workspace size
BlasInt ilo=1, ihi=n, workSize=-1, info;
dcomplex workDummy;
EL_LAPACK(zgehrd)
( &n, &ilo, &ihi,
A, &ldA,
tau,
&workDummy, &workSize,
&info );
workSize = workDummy.real();
// Reduce to Hessenberg form
vector<dcomplex> work( workSize );
EL_LAPACK(zgehrd)
( &n, &ilo, &ihi,
A, &ldA,
tau,
work.data(), &workSize,
&info );
if( info < 0 )
RuntimeError("Argument ",-info," of reduction had an illegal value");
}
// Generate the unitary matrix used within the reduction to Hessenberg form
// ------------------------------------------------------------------------
void HessenbergGenerateUnitary
( BlasInt n,
float* A, BlasInt ldA,
const float* tau )
{
// Query the workspace size
BlasInt ilo=1, ihi=n, workSize=-1, info;
float workDummy;
EL_LAPACK(sorghr)
( &n, &ilo, &ihi,
A, &ldA,
tau,
&workDummy, &workSize,
&info );
workSize = workDummy;
// Generate the unitary matrix
vector<float> work( workSize );
EL_LAPACK(sorghr)
( &n, &ilo, &ihi,
A, &ldA,
tau,
work.data(), &workSize,
&info );
if( info < 0 )
RuntimeError("Argument ",-info," of reduction had an illegal value");
}
void HessenbergGenerateUnitary
( BlasInt n,
double* A, BlasInt ldA,
const double* tau )
{
// Query the workspace size
BlasInt ilo=1, ihi=n, workSize=-1, info;
double workDummy;
EL_LAPACK(dorghr)
( &n, &ilo, &ihi,
A, &ldA,
tau,
&workDummy, &workSize,
&info );
workSize = workDummy;
// Generate the unitary matrix
vector<double> work( workSize );
EL_LAPACK(dorghr)
( &n, &ilo, &ihi,
A, &ldA,
tau,
work.data(), &workSize,
&info );
if( info < 0 )
RuntimeError("Argument ",-info," of reduction had an illegal value");
}
void HessenbergGenerateUnitary
( BlasInt n,
scomplex* A, BlasInt ldA,
const scomplex* tau )
{
// Query the workspace size
BlasInt ilo=1, ihi=n, workSize=-1, info;
scomplex workDummy;
EL_LAPACK(cunghr)
( &n, &ilo, &ihi,
A, &ldA,
tau,
&workDummy, &workSize,
&info );
workSize = workDummy.real();
// Generate the unitary matrix
vector<scomplex> work( workSize );
EL_LAPACK(cunghr)
( &n, &ilo, &ihi,
A, &ldA,
tau,
work.data(), &workSize,
&info );
if( info < 0 )
RuntimeError("Argument ",-info," of reduction had an illegal value");
}
void HessenbergGenerateUnitary
( BlasInt n,
dcomplex* A, BlasInt ldA,
const dcomplex* tau )
{
// Query the workspace size
BlasInt ilo=1, ihi=n, workSize=-1, info;
dcomplex workDummy;
EL_LAPACK(zunghr)
( &n, &ilo, &ihi,
A, &ldA,
tau,
&workDummy, &workSize,
&info );
workSize = workDummy.real();
// Generate the unitary matrix
vector<dcomplex> work( workSize );
EL_LAPACK(zunghr)
( &n, &ilo, &ihi,
A, &ldA,
tau,
work.data(), &workSize,
&info );
if( info < 0 )
RuntimeError("Argument ",-info," of reduction had an illegal value");
}
// Solve a 2x2 linear system using LU with full pivoting, perturbing the
// matrix as necessary to ensure sufficiently large pivots.
// NOTE: This is primarily a helper function for SmallSylvester
template<typename Real>
bool Solve2x2FullPiv
( const Real* A,
Real* b,
Real& scale,
const Real& smallNum,
const Real& minPiv )
{
EL_DEBUG_CSE
const Real one(1), two(2);
// Avoid tedious index calculations for the 2x2 LU with full pivoting
// using cached tables in the same manner as LAPACK's {s,d}lasy2
const BlasInt lambda21Ind[4] = { 1, 0, 3, 2 };
const BlasInt ups12Ind[4] = { 2, 3, 0, 1 };
const BlasInt ups22Ind[4] = { 3, 2, 1, 0 };
const bool XSwapTable[4] = { false, false, true, true };
const bool BSwapTable[4] = { false, true, false, true };
bool perturbed = false;
BlasInt iPiv = blas::MaxInd( 4, A, 1 );
Real ups11 = A[iPiv];
if( Abs(ups11) < minPiv )
{
ups11 = minPiv;
perturbed = true;
}
Real ups12 = A[ups12Ind[iPiv]];
Real lambda21 = A[lambda21Ind[iPiv]] / ups11;
Real ups22 = A[ups22Ind[iPiv]] - ups12*lambda21;
if( Abs(ups22) < minPiv )
{
ups22 = minPiv;
perturbed = true;
}
if( BSwapTable[iPiv] )
{
Real tmp = b[1];
b[1] = b[0] - lambda21*tmp;
b[0] = tmp;
}
else
{
b[1] -= lambda21*b[0];
}
scale = one;
if( (two*smallNum)*Abs(b[1]) > Abs(ups22) ||
(two*smallNum)*Abs(b[0]) > Abs(ups11) )
{
b[0] *= scale;
b[1] *= scale;
}
b[1] /= ups22;
b[0] = b[0] / ups11 - (ups12/ups11)*b[1];
if( XSwapTable[iPiv] )
{
Real tmp = b[1];
b[1] = b[0];
b[0] = tmp;
}
return perturbed;
}
template bool Solve2x2FullPiv
( const float* A,
float* b,
float& scale,
const float& smallNum,
const float& minPiv );
template bool Solve2x2FullPiv
( const double* A,
double* b,
double& scale,
const double& smallNum,
const double& minPiv );
#ifdef EL_HAVE_QUAD
template bool Solve2x2FullPiv
( const Quad* A,
Quad* b,
Quad& scale,
const Quad& smallNum,
const Quad& minPiv );
#endif
#ifdef EL_HAVE_QD
template bool Solve2x2FullPiv
( const DoubleDouble* A,
DoubleDouble* b,
DoubleDouble& scale,
const DoubleDouble& smallNum,
const DoubleDouble& minPiv );
template bool Solve2x2FullPiv
( const QuadDouble* A,
QuadDouble* b,
QuadDouble& scale,
const QuadDouble& smallNum,
const QuadDouble& minPiv );
#endif
#ifdef EL_HAVE_MPC
template bool Solve2x2FullPiv
( const BigFloat* A,
BigFloat* b,
BigFloat& scale,
const BigFloat& smallNum,
const BigFloat& minPiv );
#endif
// Solve a 4x4 linear system using LU with full pivoting, perturbing the
// matrix as necessary to ensure sufficiently large pivots.
// NOTE: This is primarily a helper function for SmallSylvester
template<typename Real>
bool Solve4x4FullPiv
( Real* A,
Real* b,
Real& scale,
const Real& smallNum,
const Real& minPiv )
{
EL_DEBUG_CSE
const Real zero(0), one(1), eight(8);
bool perturbed = false;
BlasInt iPiv, jPiv;
BlasInt p[4];
for( BlasInt i=0; i<3; ++i )
{
iPiv=jPiv=0;
Real AMax = zero;
for( BlasInt iMax=i; iMax<4; ++iMax )
{
for( BlasInt jMax=i; jMax<4; ++jMax )
{
if( Abs(A[iMax+jMax*4]) >= AMax )
{
AMax = Abs(A[iMax+jMax*4]);
iPiv = iMax;
jPiv = jMax;
}
}
}
if( iPiv != i )
{
blas::Swap( 4, &A[iPiv], 4, &A[i], 4 );
Real tmp = b[i];
b[i] = b[iPiv];
b[iPiv] = tmp;
}
if( jPiv != i )
{
blas::Swap( 4, &A[jPiv*4], 1, &A[i*4], 1 );
}
p[i] = jPiv;
if( Abs(A[i+i*4]) < minPiv )
{
A[i+i*4] = minPiv;
perturbed = true;
}
for( BlasInt j=i+1; j<4; ++j )
{
A[j+i*4] /= A[i+i*4];
b[j] -= A[j+i*4]*b[i];
for( BlasInt k=i+1; k<4; ++k )
{
A[j+k*4] -= A[j+i*4]*A[i+k*4];
}
}
}
if( Abs(A[3+3*4]) < minPiv )
{
A[3+3*4] = minPiv;
perturbed = true;
}
scale = one;
if( (eight*smallNum)*Abs(b[0]) > Abs(A[0+0*4]) ||
(eight*smallNum)*Abs(b[1]) > Abs(A[1+1*4]) ||
(eight*smallNum)*Abs(b[2]) > Abs(A[2+2*4]) ||
(eight*smallNum)*Abs(b[3]) > Abs(A[3+3*4]) )
{
const Real xMax = blas::NrmInf( 4, b, 1 );
scale = (one/eight) / xMax;
b[0] *= scale;
b[1] *= scale;
b[2] *= scale;
b[3] *= scale;
}
for( BlasInt i=0; i<4; ++i )
{
BlasInt k = 3-i;
Real tmp = one / A[k+k*4];
b[k] *= tmp;
for( BlasInt j=k+1; j<4; ++j )
b[k] -= (tmp*A[k+j*4])*b[j];
}
for( BlasInt i=0; i<3; ++i )
{
if( p[2-i] != 2-i )
{
Real tmp = b[2-i];
b[2-i] = b[p[2-i]];
b[p[2-i]] = tmp;
}
}
return perturbed;
}
template bool Solve4x4FullPiv
( float* A,
float* b,
float& scale,
const float& smallNum,
const float& minPiv );
template bool Solve4x4FullPiv
( double* A,
double* b,
double& scale,
const double& smallNum,
const double& minPiv );
#ifdef EL_HAVE_QUAD
template bool Solve4x4FullPiv
( Quad* A,
Quad* b,
Quad& scale,
const Quad& smallNum,
const Quad& minPiv );
#endif
#ifdef EL_HAVE_QD
template bool Solve4x4FullPiv
( DoubleDouble* A,
DoubleDouble* b,
DoubleDouble& scale,
const DoubleDouble& smallNum,
const DoubleDouble& minPiv );
template bool Solve4x4FullPiv
( QuadDouble* A,
QuadDouble* b,
QuadDouble& scale,
const QuadDouble& smallNum,
const QuadDouble& minPiv );
#endif
#ifdef EL_HAVE_MPC
template bool Solve4x4FullPiv
( BigFloat* A,
BigFloat* b,
BigFloat& scale,
const BigFloat& smallNum,
const BigFloat& minPiv );
#endif
// Solve a 1x1, 1x2, 2x1, or 2x2 Sylvester equation,
//
// op_C(C) X +- X op_D(D) = scale*B,
//
// where op_C(C) is either C or C^T, op_D(D) is either D or D^T,
// and scale in (0,1] is determined by the subroutine.
//
// The fundamental technique is Gaussian Elimination with full pivoting,
// with pivots forced to be sufficiently large (and, if such a perturbation was
// performed, the routine returns 'true').
//
// The analogous LAPACK routines are {s,d}lasy2.
//
template<typename Real>
bool SmallSylvester
( bool transC,
bool transD,
bool negate,
BlasInt nC, BlasInt nD,
const Real* C, BlasInt CLDim,
const Real* D, BlasInt DLDim,
const Real* B, BlasInt BLDim,
Real& scale,
Real* X, BlasInt XLDim,
Real& XInfNorm )
{
EL_DEBUG_CSE
const Real one(1);
const Real epsilon = limits::Epsilon<Real>();
const Real smallNum = limits::SafeMin<Real>() / epsilon;
const Real sgn = ( negate ? Real(-1) : Real(1) );
bool perturbed = false;
if( nC == 1 && nD == 1 )
{
// psi*chi + sgn*chi = beta
const Real& psi = C[0+0*CLDim];
const Real& delta = D[0+0*DLDim];
const Real& beta = B[0+0*BLDim];
Real& chi = X[0+0*XLDim];
Real tau = psi + sgn*delta;
Real tauAbs = Abs(tau);
if( tauAbs <= smallNum )
{
tau = tauAbs = smallNum;
perturbed = true;
}
Real gamma = Abs(beta);
scale = one;
if( smallNum*gamma > tauAbs )
scale = one/gamma;
chi = (beta*scale) / tau;
XInfNorm = Abs(chi);
}
else if( nC == 1 && nD == 2 )
{
// psi*x +- x*op(D) = b,
//
// where x = [chi0, chi1], D = |delta00, delta01|, b = [beta0, beta1].
// |delta10, delta11|
//
const Real& psi = C[0+0*CLDim];
const Real& delta00 = D[0+0*DLDim];
const Real& delta01 = D[0+1*DLDim];
const Real& delta10 = D[1+0*DLDim];
const Real& delta11 = D[1+1*DLDim];
const Real& beta0 = B[0+0*BLDim];
const Real& beta1 = B[0+1*BLDim];
Real& chi0 = X[0+0*XLDim];
Real& chi1 = X[0+1*XLDim];
Real maxCD = Max( Abs(delta00), Abs(delta01) );
maxCD = Max( maxCD, Abs(delta10) );
maxCD = Max( maxCD, Abs(delta11) );
maxCD = Max( maxCD, Abs(psi) );
const Real minPiv = Max( epsilon*maxCD, smallNum );
//
// In the case of no transpositions, solve
//
// | psi +- delta00, +-delta01 | | chi0 | = | beta0 |
// | +-delta10, psi +- delta11 | | chi1 | | beta1 |
//
Real A[4], b[2];
A[0] = psi + sgn*delta00;
A[3] = psi + sgn*delta11;
if( transD )
{
A[1] = sgn*delta10;
A[2] = sgn*delta01;
}
else
{
A[1] = sgn*delta01;
A[2] = sgn*delta10;
}
b[0] = beta0;
b[1] = beta1;
perturbed = Solve2x2FullPiv( A, b, scale, smallNum, minPiv );
chi0 = b[0];
chi1 = b[1];
XInfNorm = Abs(chi0) + Abs(chi1);
}
else if( nC == 2 && nD == 1 )
{
// op(C)*x +- x*delta = b,
//
// where x = |chi0|, C = |psi00, psi01|, b = |beta0|.
// |chi1| |psi10, psi11| |beta1|
//
const Real& psi00 = C[0+0*CLDim];
const Real& psi01 = C[0+1*CLDim];
const Real& psi10 = C[1+0*CLDim];
const Real& psi11 = C[1+1*CLDim];
const Real& delta = D[0+0*DLDim];
const Real& beta0 = B[0+0*BLDim];
const Real& beta1 = B[1+0*BLDim];
Real& chi0 = X[0+0*XLDim];
Real& chi1 = X[1+0*XLDim];
Real maxCD = Max( Abs(psi00), Abs(psi01) );
maxCD = Max( maxCD, Abs(psi10) );
maxCD = Max( maxCD, Abs(psi11) );
maxCD = Max( maxCD, Abs(delta) );
const Real minPiv = Max( epsilon*maxCD, smallNum );
//
// In the case of no transpositions, solve
//
// | psi00 +- delta, psi01 | | chi0 | = | beta0 |
// | psi10, psi11 +- delta | | chi1 | | beta1 |
//
Real A[4], b[2];
A[0] = psi00 + sgn*delta;
A[3] = psi11 + sgn*delta;
if( transC )
{
A[1] = psi01;
A[2] = psi10;
}
else
{
A[1] = psi10;
A[2] = psi01;
}
b[0] = beta0;
b[1] = beta1;
perturbed = Solve2x2FullPiv( A, b, scale, smallNum, minPiv );
chi0 = b[0];
chi1 = b[1];
XInfNorm = Max( Abs(chi0), Abs(chi1) );
}
else if( nC == 2 && nD == 2 )
{
// op(C)*X +- X*op(D) = B
const Real& psi00 = C[0+0*CLDim];
const Real& psi01 = C[0+1*CLDim];
const Real& psi10 = C[1+0*CLDim];
const Real& psi11 = C[1+1*CLDim];
const Real& delta00 = D[0+0*DLDim];
const Real& delta01 = D[0+1*DLDim];
const Real& delta10 = D[1+0*DLDim];
const Real& delta11 = D[1+1*DLDim];
const Real& beta00 = B[0+0*BLDim];
const Real& beta01 = B[0+1*BLDim];
const Real& beta10 = B[1+0*BLDim];
const Real& beta11 = B[1+1*BLDim];
Real& chi00 = X[0+0*XLDim];
Real& chi01 = X[0+1*XLDim];
Real& chi10 = X[1+0*XLDim];
Real& chi11 = X[1+1*XLDim];
Real maxCD = Max( Abs(psi00), Abs(psi01) );
maxCD = Max( maxCD, Abs(psi10) );
maxCD = Max( maxCD, Abs(psi11) );
maxCD = Max( maxCD, Abs(delta00) );
maxCD = Max( maxCD, Abs(delta01) );
maxCD = Max( maxCD, Abs(delta10) );
maxCD = Max( maxCD, Abs(delta11) );
const Real minPiv = Max( epsilon*maxCD, smallNum );
Real A[16], b[4];
A[0+0*4] = psi00 + sgn*delta00;
A[1+1*4] = psi11 + sgn*delta00;
A[2+2*4] = psi00 + sgn*delta11;
A[3+3*4] = psi11 + sgn*delta11;
if( transC )
{
A[0+1*4] = psi10;
A[1+0*4] = psi01;
A[2+3*4] = psi10;
A[3+2*4] = psi01;
}
else
{
A[0+1*4] = psi01;
A[1+0*4] = psi10;
A[2+3*4] = psi01;
A[3+2*4] = psi10;
}
if( transD )
{
A[0+2*4] = sgn*delta01;
A[1+3*4] = sgn*delta01;
A[2+0*4] = sgn*delta10;
A[3+1*4] = sgn*delta10;
}
else
{
A[0+2*4] = sgn*delta10;
A[1+3*4] = sgn*delta10;
A[2+0*4] = sgn*delta01;
A[3+1*4] = sgn*delta01;
}
A[0+3*4] = A[1+2*4] = A[2+1*4] = A[3+0*4] = 0;
b[0] = beta00;
b[1] = beta10;
b[2] = beta01;
b[3] = beta11;
perturbed = Solve4x4FullPiv( A, b, scale, smallNum, minPiv );
chi00 = b[0];
chi10 = b[1];
chi01 = b[2];
chi11 = b[3];
XInfNorm = Max( Abs(chi00)+Abs(chi01), Abs(chi10)+Abs(chi11) );
}
else
LogicError("Invalid SmallSylvester sizes");
return perturbed;
}
template bool SmallSylvester
( bool transC,
bool transD,
bool negate,
BlasInt nC, BlasInt nD,
const float* C, BlasInt CLDim,
const float* D, BlasInt DLDim,
const float* B, BlasInt BLDim,
float& scale,
float* X, BlasInt XLDim,
float& XInfNorm );
template bool SmallSylvester
( bool transC,
bool transD,
bool negate,
BlasInt nC, BlasInt nD,
const double* C, BlasInt CLDim,
const double* D, BlasInt DLDim,
const double* B, BlasInt BLDim,
double& scale,
double* X, BlasInt XLDim,
double& XInfNorm );
#ifdef EL_HAVE_QUAD
template bool SmallSylvester
( bool transC,
bool transD,
bool negate,
BlasInt nC, BlasInt nD,
const Quad* C, BlasInt CLDim,
const Quad* D, BlasInt DLDim,
const Quad* B, BlasInt BLDim,
Quad& scale,
Quad* X, BlasInt XLDim,
Quad& XInfNorm );
#endif
#ifdef EL_HAVE_QD
template bool SmallSylvester
( bool transC,
bool transD,
bool negate,
BlasInt nC, BlasInt nD,
const DoubleDouble* C, BlasInt CLDim,
const DoubleDouble* D, BlasInt DLDim,
const DoubleDouble* B, BlasInt BLDim,
DoubleDouble& scale,
DoubleDouble* X, BlasInt XLDim,
DoubleDouble& XInfNorm );
template bool SmallSylvester
( bool transC,
bool transD,
bool negate,
BlasInt nC, BlasInt nD,
const QuadDouble* C, BlasInt CLDim,
const QuadDouble* D, BlasInt DLDim,
const QuadDouble* B, BlasInt BLDim,
QuadDouble& scale,
QuadDouble* X, BlasInt XLDim,
QuadDouble& XInfNorm );
#endif
#ifdef EL_HAVE_MPC
template bool SmallSylvester
( bool transC,
bool transD,
bool negate,
BlasInt nC, BlasInt nD,
const BigFloat* C, BlasInt CLDim,
const BigFloat* D, BlasInt DLDim,
const BigFloat* B, BlasInt BLDim,
BigFloat& scale,
BigFloat* X, BlasInt XLDim,
BigFloat& XInfNorm );
#endif
namespace adjacent_schur {
// See the paper
//
// <NAME> and <NAME>,
// "On swapping diagonal blocks in real Schur form",
// Linear Algebra and its Applications, 186:73--95, 1993,
//
// and the corresponding implementations in LAPACK's {s,d}laexc.
//
template<typename Real>
void Helper
( bool wantSchurVecs,
BlasInt n,
Real* T, BlasInt TLDim,
Real* Q, BlasInt QLDim,
BlasInt j1,
BlasInt n1,
BlasInt n2,
Real* work,
bool testAccuracy )
{
EL_DEBUG_CSE
// Uphold LAPACK's conventions for allowing n1, n2 in {0,1,2}
EL_DEBUG_ONLY(
if( n1 < 0 || n1 > 2 )
LogicError("n1 must be in {0,1,2}");
if( n2 < 0 || n2 > 2 )
LogicError("n2 must be in {0,1,2}");
)
if( n == 0 || n1 == 0 || n2 == 0 || j1+n1 >= n )
return;
// As discussed by Bai/Demmel (building on a theorem of Ng/Peyton),
// given the relationship
//
// | A11, A12 | = | I, -X | | A11, 0 | | I, X |,
// | 0, A22 | | 0, I | | 0, A22 | | 0, I |
//
// where X is the solution of the Sylvester equation
//
// A11 X - X A22 = A12,
//
// a Householder QR factorization of [-X; I] or [I, X], depending upon
// which requires fewer reflections, can be used to swap A11 and A22
// via a similarity transformation.
//
// For example,
//
// Q' | -X | = | R |
// | I | | 0 |
//
// implies
//
// | Q11', Q21' | | I, -X | = | Q11', R |
// | Q12', Q22' | | 0, I | | Q12', 0 |
//
// and therefore
//
// Q' A Q
//
// = | Q11', R | | A11, 0 | | Q11', R |^{-1}
// | Q12', 0 | | 0, A22 | | Q12', 0 |
//
// = | Q11', R | | A11, 0 | | 0, inv(Q12)' |,
// | Q12', 0 | | 0, A22 | | inv(R), -inv(R) Q11' inv(Q12)' |
//
// = | R A22 inv(R), Q11' A11 inv(Q12)' - R A22 inv(R) Q11' inv(Q12)' |.
// | 0, Q12' A11 inv(Q12)' |
//
// On the other hand, should X have fewer rows than columns, it might
// be preferable to instead pick a unitary Q such that
//
// | I, X | | Q11, Q12 | = | 0, R |,
// | 0, I | | Q21, Q22 | | Q21, Q22 |
//
// and therefore
//
// Q' A Q
//
// = | 0, R |^{-1} | A11, 0 | | 0, R |
// | Q21, Q22 | | 0, A22 | | Q21, Q22 |
//
// = | -inv(Q21)' Q22 inv(R), inv(Q21) | | A11, 0 | | 0, R |
// | inv(R), 0 | | 0, A22 | | Q21, Q22 |
//
// = | -inv(Q21)' Q22 inv(R) A11, inv(Q21) A22 | | 0, R |
// | inv(R) A11, 0 | | Q21, Q22 |
//
// = |inv(Q21) A22 Q21, -inv(Q21)' Q22 inv(R) A11 R + inv(Q21) A22 Q22|.
// | 0, inv(R) A11 R |
//
if( n1 == 1 && n2 == 1 )
{
Real tau11 = T[ j1 + j1 *TLDim];
Real tau12 = T[ j1 +(j1+1)*TLDim];
Real tau22 = T[(j1+1)+(j1+1)*TLDim];
// Force the bottom-left entry of the similarity transformation
//
// | c, s | | tau11 tau12 | | c, -s |
// | -s c | | 0 tau22 | | s, c |
//
// to remain zero (and therefore swapping tau11 and tau22 and preserving
// tau12)
Real c, s;
Givens( tau12, tau22-tau11, c, s );
if( j1+2 < n )
{
blas::Rot
( n-(j1+2),
&T[ j1 +(j1+2)*TLDim], TLDim,
&T[(j1+1)+(j1+2)*TLDim], TLDim, c, s );
}
blas::Rot
( j1,
&T[0+ j1 *TLDim], 1,
&T[0+(j1+1)*TLDim], 1, c, s );
T[ j1 + j1 *TLDim] = tau22;
T[(j1+1)+(j1+1)*TLDim] = tau11;
if( wantSchurVecs )
{
blas::Rot
( n,
&Q[0+ j1 *QLDim], 1,
&Q[0+(j1+1)*QLDim], 1, c, s );
}
}
else
{
Real D[16], X[4];
const BlasInt XLDim = 2;
const BlasInt nSum = n1 + n2;
for( BlasInt j=0; j<nSum; ++j )
for( BlasInt i=0; i<nSum; ++i )
D[i+j*nSum] = T[(j1+i)+(j1+j)*TLDim];
const Real DMax = blas::NrmInf( nSum*nSum, D, 1 );
const Real epsilon = limits::Epsilon<Real>();
const Real smallNum = limits::SafeMin<Real>() / epsilon;
// NOTE: This value was increased from 10 because of slight failures
const Real fudge = 20;
const Real thresh = Max( fudge*epsilon*DMax, smallNum );
// Solve the Sylvester equation T11*X - X*T22 = scale*T12 for X
Real scale, XInfNorm;
const bool transT11=false, transT22=false, negate=true;
SmallSylvester
( transT11, transT22, negate, n1, n2,
&D[0 +0 *nSum], nSum,
&D[n1+n1*nSum], nSum,
&D[0 +n1*nSum], nSum,
scale, X, XLDim, XInfNorm );
Real innerProd;
const Real zero(0);
if( n1 == 1 && n2 == 2 )
{
const Real tau11 = T[j1+j1*TLDim];
// Compute the Householder reflection which satisfies
//
// | 1, x | | gamma11, q12 | = | 0, r |,
// | 0, I | | q21, Q22 | | q21, Q22 |
//
// where x is a row vector, gamma11 is scalar, q12 is a row vector,
// q21 is a column vector, and r is a row vector.
//
// This can be accomplished via the Householder reflection
//
// (I - phi [nu0; nu1; 1] [nu0, nu1, 1]) | 1 | = | 0 |
// | chi0 | | 0 |
// | chi1 | | rho |
// // which is simply a permutation of the standard formulation
// (and this fact is exploited by LAPACK).
Real v[3];
v[0] = scale;
v[1] = X[0*XLDim];
v[2] = X[1*XLDim];
Real phi = Reflector( 3, v[2], v, 1 );
v[2] = 1;
if( testAccuracy )
{
// Perform the candidate rotation out-of-place on D
// ------------------------------------------------
// Apply the rotation from the left,
// D := (I - phi v v') D = D - v (phi v' D)
ApplyReflector( true, 3, 3, v, 1, phi, D, nSum, work );
// Apply the rotation from the right,
// D := D (I - phi v v') = D - (phi D v) v'
ApplyReflector( false, 3, 3, v, 1, phi, D, nSum, work );
// Throw an exception if the rotation would be too inaccurate.
// As in LAPACK, rather than simply measuring the size of the
// bottom-left block of the rotation of D (which should ideally
// be zero), we also take into account our knowledge that the
// bottom-right entry of D should by T(j1,j1)
Real errMeasure = Max( Abs(D[2+0*3]), Abs(D[2+1*3]) );
errMeasure = Max( errMeasure, Abs(D[2+2*3]-tau11) );
if( errMeasure > thresh )
RuntimeError
("Unacceptable Schur block swap: errMeasure, ",errMeasure,
" was greater than ",thresh);
}
// Perform the rotation on T
// -------------------------
// Apply the rotation from the left,
// T := (I - phi v v') T = T - v (phi v' T)
ApplyReflector
( true, 3, n-j1, v, 1, phi, &T[j1+j1*TLDim], TLDim, work );
// Apply the rotation from the right,
// T := T (I - phi v v') = T - (phi T v) v'
ApplyReflector
( false, j1+2, 3, v, 1, phi, &T[j1*TLDim], TLDim, work );
// Force our a priori knowledge that T is block upper-triangular
T[(j1+2)+ j1 *TLDim] = zero;
T[(j1+2)+(j1+1)*TLDim] = zero;
T[(j1+2)+(j1+2)*TLDim] = tau11;
if( wantSchurVecs )
{
// Apply the rotation from the right,
// Q := Q (I - phi v v') = Q - (phi Q v) v'
ApplyReflector
( false, n, 3, v, 1, phi, &Q[j1*QLDim], QLDim, work );
}
}
else if( n1 == 2 && n2 == 1 )
{
const Real tau22 = T[(j1+2)+(j1+2)*TLDim];
// Compute the Householder reflection which satisfies
//
// | Q11, q12 |^T | I, -x | = | Q11^T, r |,
// | q21, gamma22 | | 0, 1 | | q12^T, 0 |
//
// where x is a column vector, gamma22 is scalar, q21 is a row
// vector, q12 is a column vector, and r is a column vector.
//
Real v[3];
v[0] = -X[0];
v[1] = -X[1];
v[2] = scale;
Real phi = Reflector( 3, v[0], &v[1], 1 );
v[0] = 1;
if( testAccuracy )
{
// Perform the candidate rotation out-of-place on D
// ------------------------------------------------
// Apply the rotation from the left,
// D := (I - phi v v') D = D - v (phi v' D)
ApplyReflector( true, 3, 3, v, 1, phi, D, nSum, work );
// Apply the rotation from the right,
// D := D (I - phi v v') = D - (phi D v) v'
ApplyReflector( false, 3, 3, v, 1, phi, D, nSum, work );
// Throw an exception if the rotation would be too inaccurate.
// As in LAPACK, rather than simply measuring the size of the
// bottom-left block of the rotation of D (which should ideally
// be zero), we also take into account our knowledge that the
// top-left entry of D should by tau22
Real errMeasure = Max( Abs(D[1+0*3]), Abs(D[2+0*3]) );
errMeasure = Max( errMeasure, Abs(D[0+0*3]-tau22) );
if( errMeasure > thresh )
RuntimeError
("Unacceptable Schur block swap: errMeasure, ",errMeasure,
" was greater than ",thresh);
}
// Perform the rotation on T
// -------------------------
// Apply the rotation from the right,
// T := T (I - phi v v') = T - (phi T v) v'
ApplyReflector
( false, j1+3, 3, v, 1, phi, &T[j1*TLDim], TLDim, work );
// Apply the rotation from the left,
// T := (I - phi v v') T = T - v (phi v' T)
ApplyReflector
( true, 3, n-j1-1, v, 1, phi, &T[j1+(j1+1)*TLDim], TLDim, work );
// Force our a priori knowledge that T is block upper-triangular
T[ j1 +j1*TLDim] = tau22;
T[(j1+1)+j1*TLDim] = zero;
T[(j1+2)+j1*TLDim] = zero;
if( wantSchurVecs )
{
// Apply the rotation from the right,
// Q := Q (I - phi v v') = Q - (phi Q v) v'
ApplyReflector
( false, n, 3, v, 1, phi, &Q[j1*QLDim], QLDim, work );
}
}
else
{
// Compute the Householder reflections which satisfy
//
// Q1^T Q0^T | -X | = | R |
// | I | | 0 |
//
// using an inlined Householder QR factorization of [-X; I].
//
const Real& chi00 = X[0+0*XLDim];
const Real& chi01 = X[0+1*XLDim];
const Real& chi10 = X[1+0*XLDim];
const Real& chi11 = X[1+1*XLDim];
Real v0[3];
v0[0] = -chi00;
v0[1] = -chi10;
v0[2] = scale;
Real phi0 = Reflector( 3, v0[0], &v0[1], 1 );
v0[0] = 1;
innerProd = -phi0*(chi01+v0[1]*chi11);
Real v1[3];
v1[0] = -innerProd*v0[1] - chi11;
v1[1] = -innerProd*v0[2];
v1[2] = scale;
Real phi1 = Reflector( 3, v1[0], &v1[1], 1 );
v1[0] = 1;
if( testAccuracy )
{
// Perform the candidate rotation out-of-place on D
// ------------------------------------------------
// Apply the first rotation from the left,
// D := (I - phi0 v0 v0') D = D - v0 (phi0 v0' D)
ApplyReflector( true, 3, 4, v0, 1, phi0, D, nSum, work );
// Apply the first rotation from the right,
// D := D (I - phi0 v0 v0') = D - (phi0 D v0) v0'
ApplyReflector( false, 4, 3, v0, 1, phi0, D, nSum, work );
// Apply the second rotation from the left,
// D := (I - phi1 v1 v1') D = D - v1 (phi1 v1' D)
ApplyReflector
( true, 3, 4, v1, 1, phi1, &D[1+0*nSum], nSum, work );
// Apply the second rotation from the right,
// D := D (I - phi1 v1 v1') = D - (phi1 D v1) v1'
ApplyReflector
( false, 4, 3, v1, 1, phi1, &D[0+1*nSum], nSum, work );
// Throw an exception if the rotation would be too inaccurate.
Real errMeasure = Max( Abs(D[2+0*4]), Abs(D[2+1*4]) );
errMeasure = Max( errMeasure, Abs(D[3+0*4]) );
errMeasure = Max( errMeasure, Abs(D[3+1*4]) );
if( errMeasure > thresh )
RuntimeError
("Unacceptable Schur block swap: errMeasure, ",errMeasure,
" was greater than ",thresh);
}
// Perform the rotation on T
// -------------------------
// Apply the first rotation from the left,
// T := (I - phi0 v0 v0') T = T - v0 (phi0 v0' T)
ApplyReflector
( true, 3, n-j1, v0, 1, phi0, &T[j1+j1*TLDim], TLDim, work );
// Apply the first rotation from the right,
// T := T (I - phi0 v0 v0') = T - (phi0 T v0) v0'
ApplyReflector
( false, j1+4, 3, v0, 1, phi0, &T[j1*TLDim], TLDim, work );
// Apply the second rotation from the left,
// T := (I - phi1 v1 v1') T = T - v1 (phi1 v1' T)
ApplyReflector
( true, 3, n-j1, v1, 1, phi1, &T[(j1+1)+j1*TLDim], TLDim, work );
// Apply the second rotation from the right,
// T := T (I - phi1 v1 v1') = T - (phi1 T v1) v1'
ApplyReflector
( false, j1+4, 3, v1, 1, phi1, &T[(j1+1)*TLDim], TLDim, work );
// Force our a priori knowledge that T is block upper-triangular
T[(j1+2)+ j1 *TLDim] = zero;
T[(j1+2)+(j1+1)*TLDim] = zero;
T[(j1+3)+ j1 *TLDim] = zero;
T[(j1+3)+(j1+1)*TLDim] = zero;
if( wantSchurVecs )
{
// Apply the rotations from the right,
// Q := Q (I - phi v v') = Q - (phi Q v) v'
ApplyReflector
( false, n, 3, v0, 1, phi0, &Q[j1*QLDim], QLDim, work );
ApplyReflector
( false, n, 3, v1, 1, phi1, &Q[(j1+1)*QLDim], QLDim, work );
}
}
// Clean up
if( n1 == 2 )
{
// Force the rotated T11 into standard form
Real c, s;
Complex<Real> lambda0, lambda1;
const Int j3 = j1+n2;
const Int j4 = j3+1;
schur::TwoByTwo
( T[j3+j3*TLDim], T[j3+j4*TLDim],
T[j4+j3*TLDim], T[j4+j4*TLDim], lambda0, lambda1, c, s );
if( j3+2 < n )
{
blas::Rot
( n-(j3+2),
&T[j3+(j3+2)*TLDim], TLDim,
&T[j4+(j3+2)*TLDim], TLDim, c, s );
}
blas::Rot
( j3,
&T[j3*TLDim], 1,
&T[j4*TLDim], 1, c, s );
if( wantSchurVecs )
{
blas::Rot
( n,
&Q[j3*QLDim], 1,
&Q[j4*QLDim], 1, c, s );
}
}
if( n2 == 2 )
{
// Force the rotated T22 into standard form
Real c, s;
Complex<Real> lambda0, lambda1;
const Int j2 = j1+1;
schur::TwoByTwo
( T[j1+j1*TLDim], T[j1+j2*TLDim],
T[j2+j1*TLDim], T[j2+j2*TLDim], lambda0, lambda1, c, s );
blas::Rot
( n-(j1+2),
&T[j1+(j1+2)*TLDim], TLDim,
&T[j2+(j1+2)*TLDim], TLDim, c, s );
blas::Rot
( j1,
&T[j1*TLDim], 1,
&T[j2*TLDim], 1, c, s );
if( wantSchurVecs )
{
blas::Rot
( n,
&Q[j1*QLDim], 1,
&Q[j2*QLDim], 1, c, s );
}
}
}
}
} // namespace adjacent_schur
template<typename Real>
void AdjacentSchurExchange
( BlasInt n,
Real* T, BlasInt TLDim,
BlasInt j1,
BlasInt n1,
BlasInt n2,
Real* work,
bool testAccuracy )
{
EL_DEBUG_CSE
bool wantSchurVecs = false;
Real* Q=nullptr;
BlasInt QLDim = 1;
adjacent_schur::Helper
( wantSchurVecs, n, T, TLDim, Q, QLDim, j1, n1, n2, work, testAccuracy );
}
template<typename Real>
void AdjacentSchurExchange
( BlasInt n,
Real* T, BlasInt TLDim,
Real* Q, BlasInt QLDim,
BlasInt j1,
BlasInt n1,
BlasInt n2,
Real* work,
bool testAccuracy )
{
EL_DEBUG_CSE
bool wantSchurVecs = true;
adjacent_schur::Helper
( wantSchurVecs, n, T, TLDim, Q, QLDim, j1, n1, n2, work, testAccuracy );
}
template void AdjacentSchurExchange
( BlasInt n,
float* T, BlasInt TLDim,
BlasInt j1,
BlasInt n1,
BlasInt n2,
float* work,
bool testAccuracy );
template void AdjacentSchurExchange
( BlasInt n,
float* T, BlasInt TLDim,
float* Q, BlasInt QLDim,
BlasInt j1,
BlasInt n1,
BlasInt n2,
float* work,
bool testAccuracy );
template void AdjacentSchurExchange
( BlasInt n,
double* T, BlasInt TLDim,
BlasInt j1,
BlasInt n1,
BlasInt n2,
double* work,
bool testAccuracy );
template void AdjacentSchurExchange
( BlasInt n,
double* T, BlasInt TLDim,
double* Q, BlasInt QLDim,
BlasInt j1,
BlasInt n1,
BlasInt n2,
double* work,
bool testAccuracy );
#ifdef EL_HAVE_QUAD
template void AdjacentSchurExchange
( BlasInt n,
Quad* T, BlasInt TLDim,
BlasInt j1,
BlasInt n1,
BlasInt n2,
Quad* work,
bool testAccuracy );
template void AdjacentSchurExchange
( BlasInt n,
Quad* T, BlasInt TLDim,
Quad* Q, BlasInt QLDim,
BlasInt j1,
BlasInt n1,
BlasInt n2,
Quad* work,
bool testAccuracy );
#endif
#ifdef EL_HAVE_QD
template void AdjacentSchurExchange
( BlasInt n,
DoubleDouble* T, BlasInt TLDim,
BlasInt j1,
BlasInt n1,
BlasInt n2,
DoubleDouble* work,
bool testAccuracy );
template void AdjacentSchurExchange
( BlasInt n,
DoubleDouble* T, BlasInt TLDim,
DoubleDouble* Q, BlasInt QLDim,
BlasInt j1,
BlasInt n1,
BlasInt n2,
DoubleDouble* work,
bool testAccuracy );
template void AdjacentSchurExchange
( BlasInt n,
QuadDouble* T, BlasInt TLDim,
BlasInt j1,
BlasInt n1,
BlasInt n2,
QuadDouble* work,
bool testAccuracy );
template void AdjacentSchurExchange
( BlasInt n,
QuadDouble* T, BlasInt TLDim,
QuadDouble* Q, BlasInt QLDim,
BlasInt j1,
BlasInt n1,
BlasInt n2,
QuadDouble* work,
bool testAccuracy );
#endif
#ifdef EL_HAVE_MPC
template void AdjacentSchurExchange
( BlasInt n,
BigFloat* T, BlasInt TLDim,
BlasInt j1,
BlasInt n1,
BlasInt n2,
BigFloat* work,
bool testAccuracy );
template void AdjacentSchurExchange
( BlasInt n,
BigFloat* T, BlasInt TLDim,
BigFloat* Q, BlasInt QLDim,
BlasInt j1,
BlasInt n1,
BlasInt n2,
BigFloat* work,
bool testAccuracy );
#endif
// Exchange two blocks of a real Schur decomposition
// =================================================
namespace schur_exchange {
// This following technique is an analogue of LAPACK's {s,d}trexc
template<typename Real,typename=EnableIf<IsReal<Real>>>
void Helper
( bool wantSchurVecs,
BlasInt n,
Real* T, BlasInt TLDim,
Real* Q, BlasInt QLDim,
BlasInt j1,
BlasInt j2,
Real* work,
bool testAccuracy )
{
EL_DEBUG_CSE
const Real zero(0);
if( n <= 1 )
return;
if( j1 > 0 && T[j1+(j1-1)*TLDim] != zero )
--j1;
const bool doubleFirst = ( j1 < n-1 && T[(j1+1)+j1*TLDim] != zero );
const Int nb = ( doubleFirst ? 2 : 1 );
if( j2 > 0 && T[j2+(j2-1)*TLDim] != zero )
--j2;
const bool doubleSecond = ( j1 < n-1 && T[(j1+1)+j1*TLDim] != zero );
if( j1 == j2 )
return;
bool splitDouble = false;
if( j1 < j2 )
{
// We will translate down the j1 block, one swap at a time
if( doubleFirst && !doubleSecond )
--j2;
if( !doubleFirst && doubleSecond )
++j2;
for( Int j=j1; j<j2; )
{
if( !splitDouble )
{
bool doubleNext =
( j+nb+1 < n && T[(j+nb+1)+(j+nb)*TLDim] != zero );
Int nbNext = ( doubleNext ? 2 : 1 );
adjacent_schur::Helper
( wantSchurVecs, n,
T, TLDim,
Q, QLDim,
j, nb, nbNext,
work, testAccuracy );
j += nbNext;
if( nb==2 && T[(j+1)+j*TLDim] == zero )
{
// The 2x2 just split (this should be very rare)
splitDouble = true;
}
}
else
{
bool doubleNext = ( j+3<n && T[(j+3)+(j+2)*TLDim] != zero );
Int nbNext = ( doubleNext ? 2 : 1 );
adjacent_schur::Helper
( wantSchurVecs, n,
T, TLDim,
Q, QLDim,
j+1, 1, nbNext,
work, testAccuracy );
if( nbNext == 1 )
{
adjacent_schur::Helper
( wantSchurVecs, n,
T, TLDim,
Q, QLDim,
j, 1, nbNext,
work, testAccuracy );
}
else
{
if( T[(j+2)+(j+1)*TLDim] != zero )
{
adjacent_schur::Helper
( wantSchurVecs, n,
T, TLDim,
Q, QLDim,
j, 1, 2,
work, testAccuracy );
}
else
{
// The 2x2 just split (this should be very rare)
adjacent_schur::Helper
( wantSchurVecs, n,
T, TLDim,
Q, QLDim,
j, 1, 1,
work, testAccuracy );
adjacent_schur::Helper
( wantSchurVecs, n,
T, TLDim,
Q, QLDim,
j+1, 1, 1,
work, testAccuracy );
}
}
j += nbNext;
}
}
}
else
{
// We will translate up the j1 block, one swap at a time
for( Int j=j1; j>j2; )
{
if( !splitDouble )
{
bool doubleNext = ( j>=2 && T[(j-1)+(j-2)*TLDim] != zero );
Int nbNext = ( doubleNext ? 2 : 1 );
adjacent_schur::Helper
( wantSchurVecs, n,
T, TLDim,
Q, QLDim,
j-nbNext, nbNext, nb,
work, testAccuracy );
j -= nbNext;
if( nb==2 && T[(j+1)+j*TLDim] == zero )
splitDouble = true;
}
else
{
// The 2x2 has split (this is very rare)
bool doubleNext = ( j>=2 && T[(j-1)+(j-2)*TLDim] != zero );
Int nbNext = ( doubleNext ? 2 : 1 );
adjacent_schur::Helper
( wantSchurVecs, n,
T, TLDim,
Q, QLDim,
j-nbNext, nbNext, 1,
work, testAccuracy );
if( nbNext == 1 )
{
adjacent_schur::Helper
( wantSchurVecs, n,
T, TLDim,
Q, QLDim,
j, nbNext, 1,
work, testAccuracy );
}
else
{
if( T[j+(j-1)*TLDim] != zero )
{
adjacent_schur::Helper
( wantSchurVecs, n,
T, TLDim,
Q, QLDim,
j-1, 2, 1,
work, testAccuracy );
}
else
{
// The 2x2 has just split (this is very rare)
adjacent_schur::Helper
( wantSchurVecs, n,
T, TLDim,
Q, QLDim,
j, 1, 1,
work, testAccuracy );
adjacent_schur::Helper
( wantSchurVecs, n,
T, TLDim,
Q, QLDim,
j-1, 1, 1,
work, testAccuracy );
}
}
j -= nbNext;
}
}
}
}
template<typename Real>
void Helper
( bool wantSchurVecs,
BlasInt n,
Complex<Real>* T, BlasInt TLDim,
Complex<Real>* Q, BlasInt QLDim,
BlasInt j1,
BlasInt j2 )
{
EL_DEBUG_CSE
if( n <= 1 || j1 == j2 )
return;
const Int jBeg = ( j1<j2 ? j1 : j1-1 );
const Int jEnd = ( j1<j2 ? j2 : j2-1 );
const Int stride = ( j1<j2 ? 1 : -1 );
for( Int j=jBeg; j!=jEnd; j+=stride )
{
// Save the j'th and (j+1)'th diagonal entries
Complex<Real> tau00 = T[j+j*TLDim];
Complex<Real> tau11 = T[(j+1)+(j+1)*TLDim];
// Find the Givens rotation for swapping said diagonal entries
Real c;
Complex<Real> s;
Givens( T[j+(j+1)*TLDim], tau11-tau00, c, s );
// Apply the Givens rotation from the left
if( j+2 < n )
blas::Rot
( n-(j+2), &T[j +(j+2)*TLDim], TLDim,
&T[(j+1)+(j+2)*TLDim], TLDim, c, s );
// Apply the Givens rotation from the right
if( j > 0 )
blas::Rot( j, &T[j*TLDim], 1, &T[(j+1)*TLDim], 1, c, Conj(s) );
if( wantSchurVecs )
blas::Rot( n, &Q[j*QLDim], 1, &Q[(j+1)*QLDim], 1, c, Conj(s) );
T[ j + j *TLDim] = tau11;
T[(j+1)+(j+1)*TLDim] = tau00;
}
}
} // namespace schur_exchange
template<typename Real>
void SchurExchange
( BlasInt n,
Real* T, BlasInt TLDim,
BlasInt j1,
BlasInt j2,
Real* work,
bool testAccuracy )
{
EL_DEBUG_CSE
bool wantSchurVecs = false;
Real* Q=nullptr;
BlasInt QLDim = 1;
schur_exchange::Helper
( wantSchurVecs, n, T, TLDim, Q, QLDim, j1, j2, work, testAccuracy );
}
template<typename Real>
void SchurExchange
( BlasInt n,
Complex<Real>* T, BlasInt TLDim,
BlasInt j1,
BlasInt j2 )
{
EL_DEBUG_CSE
bool wantSchurVecs = false;
Complex<Real>* Q=nullptr;
BlasInt QLDim = 1;
schur_exchange::Helper( wantSchurVecs, n, T, TLDim, Q, QLDim, j1, j2 );
}
template<typename Real>
void SchurExchange
( BlasInt n,
Real* T, BlasInt TLDim,
Real* Q, BlasInt QLDim,
BlasInt j1,
BlasInt j2,
Real* work,
bool testAccuracy )
{
EL_DEBUG_CSE
bool wantSchurVecs = true;
schur_exchange::Helper
( wantSchurVecs, n, T, TLDim, Q, QLDim, j1, j2, work, testAccuracy );
}
template<typename Real>
void SchurExchange
( BlasInt n,
Complex<Real>* T, BlasInt TLDim,
Complex<Real>* Q, BlasInt QLDim,
BlasInt j1,
BlasInt j2 )
{
EL_DEBUG_CSE
bool wantSchurVecs = true;
schur_exchange::Helper
( wantSchurVecs, n, T, TLDim, Q, QLDim, j1, j2 );
}
template void SchurExchange
( BlasInt n,
float* T, BlasInt TLDim,
BlasInt j1,
BlasInt j2,
float* work,
bool testAccuracy );
template void SchurExchange
( BlasInt n,
float* T, BlasInt TLDim,
float* Q, BlasInt QLDim,
BlasInt j1,
BlasInt j2,
float* work,
bool testAccuracy );
template void SchurExchange
( BlasInt n,
Complex<float>* T, BlasInt TLDim,
BlasInt j1,
BlasInt j2 );
template void SchurExchange
( BlasInt n,
Complex<float>* T, BlasInt TLDim,
Complex<float>* Q, BlasInt QLDim,
BlasInt j1,
BlasInt j2 );
template void SchurExchange
( BlasInt n,
double* T, BlasInt TLDim,
BlasInt j1,
BlasInt j2,
double* work,
bool testAccuracy );
template void SchurExchange
( BlasInt n,
double* T, BlasInt TLDim,
double* Q, BlasInt QLDim,
BlasInt j1,
BlasInt j2,
double* work,
bool testAccuracy );
template void SchurExchange
( BlasInt n,
Complex<double>* T, BlasInt TLDim,
BlasInt j1,
BlasInt j2 );
template void SchurExchange
( BlasInt n,
Complex<double>* T, BlasInt TLDim,
Complex<double>* Q, BlasInt QLDim,
BlasInt j1,
BlasInt j2 );
#ifdef EL_HAVE_QUAD
template void SchurExchange
( BlasInt n,
Quad* T, BlasInt TLDim,
BlasInt j1,
BlasInt j2,
Quad* work,
bool testAccuracy );
template void SchurExchange
( BlasInt n,
Quad* T, BlasInt TLDim,
Quad* Q, BlasInt QLDim,
BlasInt j1,
BlasInt j2,
Quad* work,
bool testAccuracy );
template void SchurExchange
( BlasInt n,
Complex<Quad>* T, BlasInt TLDim,
BlasInt j1,
BlasInt j2 );
template void SchurExchange
( BlasInt n,
Complex<Quad>* T, BlasInt TLDim,
Complex<Quad>* Q, BlasInt QLDim,
BlasInt j1,
BlasInt j2 );
#endif
#ifdef EL_HAVE_QD
template void SchurExchange
( BlasInt n,
DoubleDouble* T, BlasInt TLDim,
BlasInt j1,
BlasInt j2,
DoubleDouble* work,
bool testAccuracy );
template void SchurExchange
( BlasInt n,
DoubleDouble* T, BlasInt TLDim,
DoubleDouble* Q, BlasInt QLDim,
BlasInt j1,
BlasInt j2,
DoubleDouble* work,
bool testAccuracy );
template void SchurExchange
( BlasInt n,
Complex<DoubleDouble>* T, BlasInt TLDim,
BlasInt j1,
BlasInt j2 );
template void SchurExchange
( BlasInt n,
Complex<DoubleDouble>* T, BlasInt TLDim,
Complex<DoubleDouble>* Q, BlasInt QLDim,
BlasInt j1,
BlasInt j2 );
template void SchurExchange
( BlasInt n,
QuadDouble* T, BlasInt TLDim,
BlasInt j1,
BlasInt j2,
QuadDouble* work,
bool testAccuracy );
template void SchurExchange
( BlasInt n,
QuadDouble* T, BlasInt TLDim,
QuadDouble* Q, BlasInt QLDim,
BlasInt j1,
BlasInt j2,
QuadDouble* work,
bool testAccuracy );
template void SchurExchange
( BlasInt n,
Complex<QuadDouble>* T, BlasInt TLDim,
BlasInt j1,
BlasInt j2 );
template void SchurExchange
( BlasInt n,
Complex<QuadDouble>* T, BlasInt TLDim,
Complex<QuadDouble>* Q, BlasInt QLDim,
BlasInt j1,
BlasInt j2 );
#endif
#ifdef EL_HAVE_MPC
template void SchurExchange
( BlasInt n,
BigFloat* T, BlasInt TLDim,
BlasInt j1,
BlasInt j2,
BigFloat* work,
bool testAccuracy );
template void SchurExchange
( BlasInt n,
BigFloat* T, BlasInt TLDim,
BigFloat* Q, BlasInt QLDim,
BlasInt j1,
BlasInt j2,
BigFloat* work,
bool testAccuracy );
template void SchurExchange
( BlasInt n,
Complex<BigFloat>* T, BlasInt TLDim,
BlasInt j1,
BlasInt j2 );
template void SchurExchange
( BlasInt n,
Complex<BigFloat>* T, BlasInt TLDim,
Complex<BigFloat>* Q, BlasInt QLDim,
BlasInt j1,
BlasInt j2 );
#endif
// Compute the Schur decomposition of an upper Hessenberg matrix
// =============================================================
void HessenbergSchur
( BlasInt n,
float* H, BlasInt ldH,
scomplex* w,
bool fullTriangle,
bool useAED )
{
EL_DEBUG_CSE
if( n == 0 )
return;
BlasInt info;
BlasInt ilo=1, ihi=n;
BlasInt fakeLDim=1;
vector<float> wr( n ), wi( n );
if( useAED )
{
const char job=(fullTriangle ? 'S' : 'E'), compZ='N';
BlasInt workSize=-1;
float workDummy;
EL_LAPACK(shseqr)
( &job, &compZ, &n, &ilo, &ihi, H, &ldH, wr.data(), wi.data(),
0, &fakeLDim, &workDummy, &workSize, &info );
workSize = workDummy;
vector<float> work(workSize);
EL_LAPACK(shseqr)
( &job, &compZ, &n, &ilo, &ihi, H, &ldH, wr.data(), wi.data(),
0, &fakeLDim, work.data(), &workSize, &info );
if( info < 0 )
RuntimeError("Argument ",-info," had an illegal value");
else if( info > 0 )
RuntimeError("shseqr failed to compute all eigenvalues");
}
else
{
FortranLogical wantT=(fullTriangle ? FORTRAN_TRUE : FORTRAN_FALSE),
wantZ=FORTRAN_FALSE;
EL_LAPACK(slahqr)
( &wantT, &wantZ, &n, &ilo, &ihi, H, &ldH, wr.data(), wi.data(),
&ilo, &ihi, 0, &fakeLDim, &info );
if( info < 0 )
RuntimeError("Argument ",-info," had an illegal value");
else if( info > 0 )
RuntimeError("slahqr failed to compute all eigenvalues");
}
for( BlasInt i=0; i<n; ++i )
w[i] = Complex<float>(wr[i],wi[i]);
}
void HessenbergSchur
( BlasInt n,
double* H, BlasInt ldH,
dcomplex* w,
bool fullTriangle,
bool useAED )
{
EL_DEBUG_CSE
if( n == 0 )
return;
BlasInt info;
BlasInt ilo=1, ihi=n;
BlasInt fakeLDim=1;
vector<double> wr( n ), wi( n );
if( useAED )
{
const char job=(fullTriangle ? 'S' : 'E'), compZ='N';
BlasInt workSize=-1;
double workDummy;
EL_LAPACK(dhseqr)
( &job, &compZ, &n, &ilo, &ihi, H, &ldH, wr.data(), wi.data(),
0, &fakeLDim, &workDummy, &workSize, &info );
workSize = workDummy;
vector<double> work(workSize);
EL_LAPACK(dhseqr)
( &job, &compZ, &n, &ilo, &ihi, H, &ldH, wr.data(), wi.data(),
0, &fakeLDim, work.data(), &workSize, &info );
if( info < 0 )
RuntimeError("Argument ",-info," had an illegal value");
else if( info > 0 )
RuntimeError("dhseqr failed to compute all eigenvalues");
}
else
{
FortranLogical wantT=(fullTriangle ? FORTRAN_TRUE : FORTRAN_FALSE),
wantZ=FORTRAN_FALSE;
EL_LAPACK(dlahqr)
( &wantT, &wantZ, &n, &ilo, &ihi, H, &ldH, wr.data(), wi.data(),
&ilo, &ihi, 0, &fakeLDim, &info );
if( info < 0 )
RuntimeError("Argument ",-info," had an illegal value");
else if( info > 0 )
RuntimeError("dlahqr failed to compute all eigenvalues");
}
for( BlasInt i=0; i<n; ++i )
w[i] = Complex<double>(wr[i],wi[i]);
}
void HessenbergSchur
( BlasInt n,
scomplex* H, BlasInt ldH,
scomplex* w,
bool fullTriangle,
bool useAED )
{
EL_DEBUG_CSE
if( n == 0 )
return;
BlasInt info;
BlasInt ilo=1, ihi=n;
BlasInt fakeLDim=1;
if( useAED )
{
const char job=(fullTriangle ? 'S' : 'E'), compZ='N';
BlasInt workSize=-1;
scomplex workDummy;
EL_LAPACK(chseqr)
( &job, &compZ, &n, &ilo, &ihi, H, &ldH, w, 0, &fakeLDim,
&workDummy, &workSize, &info );
workSize = workDummy.real();
vector<scomplex> work(workSize);
EL_LAPACK(chseqr)
( &job, &compZ, &n, &ilo, &ihi, H, &ldH, w, 0, &fakeLDim,
work.data(), &workSize, &info );
if( info < 0 )
RuntimeError("Argument ",-info," had an illegal value");
else if( info > 0 )
RuntimeError("chseqr failed to compute all eigenvalues");
}
else
{
FortranLogical wantT=(fullTriangle ? FORTRAN_TRUE : FORTRAN_FALSE),
wantZ=FORTRAN_FALSE;
EL_LAPACK(clahqr)
( &wantT, &wantZ, &n, &ilo, &ihi, H, &ldH, w,
&ilo, &ihi, 0, &fakeLDim, &info );
if( info < 0 )
RuntimeError("Argument ",-info," had an illegal value");
else if( info > 0 )
RuntimeError("clahqr failed to compute all eigenvalues");
}
}
void HessenbergSchur
( BlasInt n,
dcomplex* H, BlasInt ldH,
dcomplex* w,
bool fullTriangle,
bool useAED )
{
EL_DEBUG_CSE
if( n == 0 )
return;
BlasInt info;
BlasInt ilo=1, ihi=n;
BlasInt fakeLDim=1;
if( useAED )
{
const char job=(fullTriangle ? 'S' : 'E'), compZ='N';
BlasInt workSize=-1;
dcomplex workDummy;
EL_LAPACK(zhseqr)
( &job, &compZ, &n, &ilo, &ihi, H, &ldH, w, 0, &fakeLDim,
&workDummy, &workSize, &info );
workSize = workDummy.real();
vector<dcomplex> work(workSize);
EL_LAPACK(zhseqr)
( &job, &compZ, &n, &ilo, &ihi, H, &ldH, w, 0, &fakeLDim,
work.data(), &workSize, &info );
if( info < 0 )
RuntimeError("Argument ",-info," had an illegal value");
else if( info > 0 )
RuntimeError("zhseqr failed to compute all eigenvalues");
}
else
{
FortranLogical wantT=(fullTriangle ? FORTRAN_TRUE : FORTRAN_FALSE),
wantZ=FORTRAN_FALSE;
EL_LAPACK(zlahqr)
( &wantT, &wantZ, &n, &ilo, &ihi, H, &ldH, w,
&ilo, &ihi, 0, &fakeLDim, &info );
if( info < 0 )
RuntimeError("Argument ",-info," had an illegal value");
else if( info > 0 )
RuntimeError("zlahqr failed to compute all eigenvalues");
}
}
void HessenbergSchur
( BlasInt n,
float* H, BlasInt ldH,
scomplex* w,
float* Q, BlasInt ldQ,
bool fullTriangle,
bool multiplyQ,
bool useAED )
{
EL_DEBUG_CSE
if( n == 0 )
return;
BlasInt info;
BlasInt ilo=1, ihi=n;
vector<float> wr( n ), wi( n );
if( useAED )
{
const char job=(fullTriangle ? 'S' : 'E'),
compZ=(multiplyQ ? 'V' : 'I');
BlasInt workSize=-1;
float workDummy;
EL_LAPACK(shseqr)
( &job, &compZ, &n, &ilo, &ihi, H, &ldH, wr.data(), wi.data(), Q, &ldQ,
&workDummy, &workSize, &info );
workSize = workDummy;
vector<float> work(workSize);
EL_LAPACK(shseqr)
( &job, &compZ, &n, &ilo, &ihi, H, &ldH, wr.data(), wi.data(), Q, &ldQ,
work.data(), &workSize, &info );
if( info < 0 )
RuntimeError("Argument ",-info," had an illegal value");
else if( info > 0 )
RuntimeError("shseqr failed to compute all eigenvalues");
}
else
{
FortranLogical wantT=(fullTriangle ? FORTRAN_TRUE : FORTRAN_FALSE),
wantZ=FORTRAN_TRUE;
EL_LAPACK(slahqr)
( &wantT, &wantZ, &n, &ilo, &ihi, H, &ldH, wr.data(), wi.data(),
&ilo, &ihi, Q, &ldQ, &info );
if( info < 0 )
RuntimeError("Argument ",-info," had an illegal value");
else if( info > 0 )
RuntimeError("slahqr failed to compute all eigenvalues");
}
for( BlasInt i=0; i<n; ++i )
w[i] = Complex<float>(wr[i],wi[i]);
}
void HessenbergSchur
( BlasInt n,
double* H, BlasInt ldH,
dcomplex* w,
double* Q, BlasInt ldQ,
bool fullTriangle,
bool multiplyQ,
bool useAED )
{
EL_DEBUG_CSE
if( n == 0 )
return;
BlasInt info;
BlasInt ilo=1, ihi=n;
vector<double> wr( n ), wi( n );
if( useAED )
{
const char job=(fullTriangle ? 'S' : 'E'),
compZ=(multiplyQ ? 'V' : 'I');
BlasInt workSize=-1;
double workDummy;
EL_LAPACK(dhseqr)
( &job, &compZ, &n, &ilo, &ihi, H, &ldH, wr.data(), wi.data(), Q, &ldQ,
&workDummy, &workSize, &info );
workSize = workDummy;
vector<double> work(workSize);
EL_LAPACK(dhseqr)
( &job, &compZ, &n, &ilo, &ihi, H, &ldH, wr.data(), wi.data(), Q, &ldQ,
work.data(), &workSize, &info );
if( info < 0 )
RuntimeError("Argument ",-info," had an illegal value");
else if( info > 0 )
RuntimeError("dhseqr failed to compute all eigenvalues");
}
else
{
FortranLogical wantT=(fullTriangle ? FORTRAN_TRUE : FORTRAN_FALSE),
wantZ=FORTRAN_TRUE;
EL_LAPACK(dlahqr)
( &wantT, &wantZ, &n, &ilo, &ihi, H, &ldH, wr.data(), wi.data(),
&ilo, &ihi, Q, &ldQ, &info );
if( info < 0 )
RuntimeError("Argument ",-info," had an illegal value");
else if( info > 0 )
RuntimeError("dlahqr failed to compute all eigenvalues");
}
for( BlasInt i=0; i<n; ++i )
w[i] = Complex<double>(wr[i],wi[i]);
}
void HessenbergSchur
( BlasInt n,
scomplex* H, BlasInt ldH,
scomplex* w,
scomplex* Q, BlasInt ldQ,
bool fullTriangle,
bool multiplyQ,
bool useAED )
{
EL_DEBUG_CSE
if( n == 0 )
return;
BlasInt info;
BlasInt ilo=1, ihi=n;
if( useAED )
{
const char job=(fullTriangle ? 'S' : 'E'),
compZ=(multiplyQ ? 'V' : 'I');
BlasInt workSize=-1;
scomplex workDummy;
EL_LAPACK(chseqr)
( &job, &compZ, &n, &ilo, &ihi, H, &ldH, w, Q, &ldQ,
&workDummy, &workSize, &info );
workSize = workDummy.real();
vector<scomplex> work(workSize);
EL_LAPACK(chseqr)
( &job, &compZ, &n, &ilo, &ihi, H, &ldH, w, Q, &ldQ,
work.data(), &workSize, &info );
if( info < 0 )
RuntimeError("Argument ",-info," had an illegal value");
else if( info > 0 )
RuntimeError("chseqr failed to compute all eigenvalues");
}
else
{
FortranLogical wantT=(fullTriangle ? FORTRAN_TRUE : FORTRAN_FALSE),
wantZ=FORTRAN_TRUE;
EL_LAPACK(clahqr)
( &wantT, &wantZ, &n, &ilo, &ihi, H, &ldH, w,
&ilo, &ihi, Q, &ldQ, &info );
if( info < 0 )
RuntimeError("Argument ",-info," had an illegal value");
else if( info > 0 )
RuntimeError("clahqr failed to compute all eigenvalues");
}
}
void HessenbergSchur
( BlasInt n,
dcomplex* H, BlasInt ldH,
dcomplex* w,
dcomplex* Q, BlasInt ldQ,
bool fullTriangle,
bool multiplyQ,
bool useAED )
{
EL_DEBUG_CSE
if( n == 0 )
return;
BlasInt info;
BlasInt ilo=1, ihi=n;
if( useAED )
{
const char job=(fullTriangle ? 'S' : 'E'),
compZ=(multiplyQ ? 'V' : 'I');
BlasInt workSize=-1;
dcomplex workDummy;
EL_LAPACK(zhseqr)
( &job, &compZ, &n, &ilo, &ihi, H, &ldH, w, Q, &ldQ,
&workDummy, &workSize, &info );
workSize = workDummy.real();
vector<dcomplex> work(workSize);
EL_LAPACK(zhseqr)
( &job, &compZ, &n, &ilo, &ihi, H, &ldH, w, Q, &ldQ,
work.data(), &workSize, &info );
if( info < 0 )
RuntimeError("Argument ",-info," had an illegal value");
else if( info > 0 )
RuntimeError("zhseqr failed to compute all eigenvalues");
}
else
{
FortranLogical wantT=(fullTriangle ? FORTRAN_TRUE : FORTRAN_FALSE),
wantZ=FORTRAN_TRUE;
EL_LAPACK(zlahqr)
( &wantT, &wantZ, &n, &ilo, &ihi, H, &ldH, w,
&ilo, &ihi, Q, &ldQ, &info );
if( info < 0 )
RuntimeError("Argument ",-info," had an illegal value");
else if( info > 0 )
RuntimeError("zlahqr failed to compute all eigenvalues");
}
}
// Compute eigenvalues/pairs of an upper Hessenberg matrix
// =======================================================
void HessenbergEig( BlasInt n, float* H, BlasInt ldH, scomplex* w )
{
EL_DEBUG_CSE
HessenbergSchur( n, H, ldH, w, false );
}
void HessenbergEig( BlasInt n, double* H, BlasInt ldH, dcomplex* w )
{
EL_DEBUG_CSE
HessenbergSchur( n, H, ldH, w, false );
}
void HessenbergEig( BlasInt n, scomplex* H, BlasInt ldH, scomplex* w )
{
EL_DEBUG_CSE
HessenbergSchur( n, H, ldH, w, false );
}
void HessenbergEig( BlasInt n, dcomplex* H, BlasInt ldH, dcomplex* w )
{
EL_DEBUG_CSE
HessenbergSchur( n, H, ldH, w, false );
}
// TODO: Compute eigenpairs
// Compute the Schur decomposition of a square matrix
// ==================================================
// TODO: Add timing of components
void Schur
( BlasInt n,
float* A, BlasInt ldA,
scomplex* w,
bool fullTriangle,
bool time )
{
EL_DEBUG_CSE
if( n == 0 )
return;
// Query the reduction to Hessenberg form workspace size
BlasInt ilo=1, ihi=n, workSize=-1, info;
float workDummy;
vector<float> tau( n );
EL_LAPACK(sgehrd)
( &n, &ilo, &ihi, A, &ldA, tau.data(), &workDummy, &workSize, &info );
workSize = workDummy;
// Query the QR algorithm workspace size
const char job = ( fullTriangle ? 'S' : 'E' ), compZ='N';
BlasInt fakeLDim=1, negOne=-1;
vector<float> wr( n ), wi( n );
EL_LAPACK(shseqr)
( &job, &compZ, &n, &ilo, &ihi, A, &ldA, wr.data(), wi.data(), 0, &fakeLDim,
&workDummy, &negOne, &info );
workSize = Max( BlasInt(workDummy), workSize );
// Reduce to Hessenberg form
vector<float> work( workSize );
EL_LAPACK(sgehrd)
( &n, &ilo, &ihi, A, &ldA, tau.data(), work.data(), &workSize, &info );
if( info < 0 )
RuntimeError("Argument ",-info," of reduction had an illegal value");
// Compute the eigenvalues
EL_LAPACK(shseqr)
( &job, &compZ, &n, &ilo, &ihi, A, &ldA, wr.data(), wi.data(), 0, &fakeLDim,
work.data(), &workSize, &info );
if( info < 0 )
RuntimeError("Argument ",-info," of QR alg had an illegal value");
else if( info > 0 )
RuntimeError("shseqr's failed to compute all eigenvalues");
// Return the complex eigenvalues
for( BlasInt i=0; i<n; ++i )
w[i] = Complex<float>(wr[i],wi[i]);
}
void Schur
( BlasInt n,
double* A, BlasInt ldA,
dcomplex* w,
bool fullTriangle,
bool time )
{
EL_DEBUG_CSE
if( n == 0 )
return;
// Query the reduction to Hessenberg form workspace size
BlasInt ilo=1, ihi=n, workSize=-1, info;
double workDummy;
vector<double> tau( n );
EL_LAPACK(dgehrd)
( &n, &ilo, &ihi, A, &ldA, tau.data(), &workDummy, &workSize, &info );
workSize = workDummy;
// Query the QR algorithm workspace size
const char job = ( fullTriangle ? 'S' : 'E' ), compZ='N';
BlasInt fakeLDim=1, negOne=-1;
vector<double> wr( n ), wi( n );
EL_LAPACK(dhseqr)
( &job, &compZ, &n, &ilo, &ihi, A, &ldA, wr.data(), wi.data(), 0, &fakeLDim,
&workDummy, &negOne, &info );
workSize = Max( BlasInt(workDummy), workSize );
// Reduce to Hessenberg form
vector<double> work( workSize );
EL_LAPACK(dgehrd)
( &n, &ilo, &ihi, A, &ldA, tau.data(), work.data(), &workSize, &info );
if( info < 0 )
RuntimeError("Argument ",-info," of reduction had an illegal value");
// Compute the eigenvalues
EL_LAPACK(dhseqr)
( &job, &compZ, &n, &ilo, &ihi, A, &ldA, wr.data(), wi.data(), 0, &fakeLDim,
work.data(), &workSize, &info );
if( info < 0 )
RuntimeError("Argument ",-info," of QR alg had an illegal value");
else if( info > 0 )
RuntimeError("dhseqr's failed to compute all eigenvalues");
// Return the complex eigenvalues
for( BlasInt i=0; i<n; ++i )
w[i] = Complex<double>(wr[i],wi[i]);
}
void Schur
( BlasInt n,
scomplex* A, BlasInt ldA,
scomplex* w,
bool fullTriangle,
bool time )
{
EL_DEBUG_CSE
if( n == 0 )
return;
// Query the reduction to Hessenberg form workspace size
BlasInt ilo=1, ihi=n, workSize=-1, info;
scomplex workDummy;
vector<scomplex> tau( n );
EL_LAPACK(cgehrd)
( &n, &ilo, &ihi, A, &ldA, tau.data(), &workDummy, &workSize, &info );
workSize = workDummy.real();
// Query the QR algorithm workspace size
const char job = ( fullTriangle ? 'S' : 'E' ), compZ='N';
BlasInt fakeLDim=1, negOne=-1;
EL_LAPACK(chseqr)
( &job, &compZ, &n, &ilo, &ihi, A, &ldA, w, 0, &fakeLDim,
&workDummy, &negOne, &info );
workSize = Max( BlasInt(workDummy.real()), workSize );
// Reduce to Hessenberg form
vector<scomplex> work( workSize );
EL_LAPACK(cgehrd)
( &n, &ilo, &ihi, A, &ldA, tau.data(), work.data(), &workSize, &info );
if( info < 0 )
RuntimeError("Argument ",-info," of reduction had an illegal value");
// Compute the eigenvalues
EL_LAPACK(chseqr)
( &job, &compZ, &n, &ilo, &ihi, A, &ldA, w, 0, &fakeLDim,
work.data(), &workSize, &info );
if( info < 0 )
RuntimeError("Argument ",-info," of QR alg had an illegal value");
else if( info > 0 )
RuntimeError("chseqr's failed to compute all eigenvalues");
}
void Schur
( BlasInt n,
dcomplex* A, BlasInt ldA,
dcomplex* w,
bool fullTriangle,
bool time )
{
EL_DEBUG_CSE
if( n == 0 )
return;
// Query the reduction to Hessenberg form workspace size
BlasInt ilo=1, ihi=n, workSize=-1, info;
dcomplex workDummy;
vector<dcomplex> tau( n );
EL_LAPACK(zgehrd)
( &n, &ilo, &ihi, A, &ldA, tau.data(), &workDummy, &workSize, &info );
workSize = workDummy.real();
// Query the QR algorithm workspace size
const char job = ( fullTriangle ? 'S' : 'E' ), compZ='N';
BlasInt fakeLDim=1, negOne=-1;
EL_LAPACK(zhseqr)
( &job, &compZ, &n, &ilo, &ihi, A, &ldA, w, 0, &fakeLDim,
&workDummy, &negOne, &info );
workSize = Max( BlasInt(workDummy.real()), workSize );
// Reduce to Hessenberg form
vector<dcomplex> work( workSize );
EL_LAPACK(zgehrd)
( &n, &ilo, &ihi, A, &ldA, tau.data(), work.data(), &workSize, &info );
if( info < 0 )
RuntimeError("Argument ",-info," of reduction had an illegal value");
// Compute the eigenvalues
EL_LAPACK(zhseqr)
( &job, &compZ, &n, &ilo, &ihi, A, &ldA, w, 0, &fakeLDim,
work.data(), &workSize, &info );
if( info < 0 )
RuntimeError("Argument ",-info," of QR alg had an illegal value");
else if( info > 0 )
RuntimeError("zhseqr's failed to compute all eigenvalues");
}
void Schur
( BlasInt n,
float* A, BlasInt ldA,
scomplex* w,
float* Q, BlasInt ldQ,
bool fullTriangle,
bool time )
{
EL_DEBUG_CSE
if( n == 0 )
return;
// Query the reduction to Hessenberg form workspace size
BlasInt ilo=1, ihi=n, workSize=-1, info;
float workDummy;
vector<float> tau( n );
EL_LAPACK(sgehrd)
( &n, &ilo, &ihi, A, &ldA, tau.data(), &workDummy, &workSize, &info );
workSize = workDummy;
// Query the explicit Q formation workspace
BlasInt negOne=-1;
EL_LAPACK(sorghr)
( &n, &ilo, &ihi, Q, &ldQ, tau.data(), &workDummy, &negOne, &info );
workSize = Max( BlasInt(workDummy), workSize );
// Query the QR algorithm workspace size
const char job = ( fullTriangle ? 'S' : 'E' ), compZ='V';
vector<float> wr( n ), wi( n );
EL_LAPACK(shseqr)
( &job, &compZ, &n, &ilo, &ihi, A, &ldA, wr.data(), wi.data(), Q, &ldQ,
&workDummy, &negOne, &info );
workSize = Max( BlasInt(workDummy), workSize );
// Reduce to Hessenberg form
vector<float> work( workSize );
EL_LAPACK(sgehrd)
( &n, &ilo, &ihi, A, &ldA, tau.data(), work.data(), &workSize, &info );
if( info < 0 )
RuntimeError("Argument ",-info," of reduction had an illegal value");
// Copy the Householder vectors over
for( BlasInt j=0; j<n; ++j )
MemCopy( &Q[j*ldQ], &A[j*ldA], n );
// Form the orthogonal matrix in place
EL_LAPACK(sorghr)
( &n, &ilo, &ihi, Q, &ldQ, tau.data(), work.data(), &workSize, &info );
if( info < 0 )
RuntimeError("Argument ",-info," of formation had an illegal value");
// Compute the Schur decomposition
EL_LAPACK(shseqr)
( &job, &compZ, &n, &ilo, &ihi, A, &ldA, wr.data(), wi.data(), Q, &ldQ,
work.data(), &workSize, &info );
if( info < 0 )
RuntimeError("Argument ",-info," of QR alg had an illegal value");
else if( info > 0 )
RuntimeError("shseqr's failed to compute all eigenvalues");
// Return the complex eigenvalues
for( BlasInt i=0; i<n; ++i )
w[i] = Complex<float>(wr[i],wi[i]);
}
void Schur
( BlasInt n,
double* A, BlasInt ldA,
dcomplex* w,
double* Q, BlasInt ldQ,
bool fullTriangle,
bool time )
{
EL_DEBUG_CSE
if( n == 0 )
return;
// Query the reduction to Hessenberg form workspace size
BlasInt ilo=1, ihi=n, workSize=-1, info;
double workDummy;
vector<double> tau( n );
EL_LAPACK(dgehrd)
( &n, &ilo, &ihi, A, &ldA, tau.data(), &workDummy, &workSize, &info );
workSize = workDummy;
// Query the explicit Q formation workspace
BlasInt negOne=-1;
EL_LAPACK(dorghr)
( &n, &ilo, &ihi, Q, &ldQ, tau.data(), &workDummy, &negOne, &info );
workSize = Max( BlasInt(workDummy), workSize );
// Query the QR algorithm workspace size
const char job = ( fullTriangle ? 'S' : 'E' ), compZ='V';
vector<double> wr( n ), wi( n );
EL_LAPACK(dhseqr)
( &job, &compZ, &n, &ilo, &ihi, A, &ldA, wr.data(), wi.data(), Q, &ldQ,
&workDummy, &negOne, &info );
workSize = Max( BlasInt(workDummy), workSize );
// Reduce to Hessenberg form
vector<double> work( workSize );
EL_LAPACK(dgehrd)
( &n, &ilo, &ihi, A, &ldA, tau.data(), work.data(), &workSize, &info );
if( info < 0 )
RuntimeError("Argument ",-info," of reduction had an illegal value");
// Copy the Householder vectors over
for( BlasInt j=0; j<n; ++j )
MemCopy( &Q[j*ldQ], &A[j*ldA], n );
// Form the orthogonal matrix in place
EL_LAPACK(dorghr)
( &n, &ilo, &ihi, Q, &ldQ, tau.data(), work.data(), &workSize, &info );
if( info < 0 )
RuntimeError("Argument ",-info," of formation had an illegal value");
// Compute the Schur decomposition
EL_LAPACK(dhseqr)
( &job, &compZ, &n, &ilo, &ihi, A, &ldA, wr.data(), wi.data(), Q, &ldQ,
work.data(), &workSize, &info );
if( info < 0 )
RuntimeError("Argument ",-info," of QR alg had an illegal value");
else if( info > 0 )
RuntimeError("dhseqr's failed to compute all eigenvalues");
// Return the complex eigenvalues
for( BlasInt i=0; i<n; ++i )
w[i] = Complex<double>(wr[i],wi[i]);
}
void Schur
( BlasInt n,
scomplex* A, BlasInt ldA,
scomplex* w,
scomplex* Q, BlasInt ldQ,
bool fullTriangle,
bool time )
{
EL_DEBUG_CSE
if( n == 0 )
return;
// Query the reduction to Hessenberg form workspace size
BlasInt ilo=1, ihi=n, workSize=-1, info;
scomplex workDummy;
vector<scomplex> tau( n );
EL_LAPACK(cgehrd)
( &n, &ilo, &ihi, A, &ldA, tau.data(), &workDummy, &workSize, &info );
workSize = workDummy.real();
// Query the explicit Q formation workspace
BlasInt negOne=-1;
EL_LAPACK(cunghr)
( &n, &ilo, &ihi, Q, &ldQ, tau.data(), &workDummy, &negOne, &info );
workSize = Max( BlasInt(workDummy.real()), workSize );
// Query the QR algorithm workspace size
const char job = ( fullTriangle ? 'S' : 'E' ), compZ='V';
EL_LAPACK(chseqr)
( &job, &compZ, &n, &ilo, &ihi, A, &ldA, w, Q, &ldQ,
&workDummy, &negOne, &info );
workSize = Max( BlasInt(workDummy.real()), workSize );
// Reduce to Hessenberg form
vector<scomplex> work( workSize );
EL_LAPACK(cgehrd)
( &n, &ilo, &ihi, A, &ldA, tau.data(), work.data(), &workSize, &info );
if( info < 0 )
RuntimeError("Argument ",-info," of reduction had an illegal value");
// Copy the Householder vectors over
for( BlasInt j=0; j<n; ++j )
MemCopy( &Q[j*ldQ], &A[j*ldA], n );
// Form the orthogonal matrix in place
EL_LAPACK(cunghr)
( &n, &ilo, &ihi, Q, &ldQ, tau.data(), work.data(), &workSize, &info );
if( info < 0 )
RuntimeError("Argument ",-info," of formation had an illegal value");
// Compute the Schur decomposition
EL_LAPACK(chseqr)
( &job, &compZ, &n, &ilo, &ihi, A, &ldA, w, Q, &ldQ, work.data(), &workSize,
&info );
if( info < 0 )
RuntimeError("Argument ",-info," of QR alg had an illegal value");
else if( info > 0 )
RuntimeError("chseqr's failed to compute all eigenvalues");
}
void Schur
( BlasInt n,
dcomplex* A, BlasInt ldA,
dcomplex* w,
dcomplex* Q, BlasInt ldQ,
bool fullTriangle,
bool time )
{
EL_DEBUG_CSE
if( n == 0 )
return;
// Query the reduction to Hessenberg form workspace size
BlasInt ilo=1, ihi=n, workSize=-1, info;
dcomplex workDummy;
vector<dcomplex> tau( n );
EL_LAPACK(zgehrd)
( &n, &ilo, &ihi, A, &ldA, tau.data(), &workDummy, &workSize, &info );
workSize = workDummy.real();
// Query the explicit Q formation workspace
BlasInt negOne=-1;
EL_LAPACK(zunghr)
( &n, &ilo, &ihi, Q, &ldQ, tau.data(), &workDummy, &negOne, &info );
workSize = Max( BlasInt(workDummy.real()), workSize );
// Query the QR algorithm workspace size
const char job = ( fullTriangle ? 'S' : 'E' ), compZ='V';
EL_LAPACK(zhseqr)
( &job, &compZ, &n, &ilo, &ihi, A, &ldA, w, Q, &ldQ,
&workDummy, &negOne, &info );
workSize = Max( BlasInt(workDummy.real()), workSize );
// Reduce to Hessenberg form
vector<dcomplex> work( workSize );
EL_LAPACK(zgehrd)
( &n, &ilo, &ihi, A, &ldA, tau.data(), work.data(), &workSize, &info );
if( info < 0 )
RuntimeError("Argument ",-info," of reduction had an illegal value");
// Copy the Householder vectors over
for( BlasInt j=0; j<n; ++j )
MemCopy( &Q[j*ldQ], &A[j*ldA], n );
// Form the orthogonal matrix in place
EL_LAPACK(zunghr)
( &n, &ilo, &ihi, Q, &ldQ, tau.data(), work.data(), &workSize, &info );
if( info < 0 )
RuntimeError("Argument ",-info," of formation had an illegal value");
// Compute the Schur decomposition
EL_LAPACK(zhseqr)
( &job, &compZ, &n, &ilo, &ihi, A, &ldA, w, Q, &ldQ, work.data(), &workSize,
&info );
if( info < 0 )
RuntimeError("Argument ",-info," of QR alg had an illegal value");
else if( info > 0 )
RuntimeError("chseqr's failed to compute all eigenvalues");
}
} // namespace lapack
} // namespace El
#include "./lapack/TriangEig.hpp"
#include "./lapack/Schur.hpp"
| 67,500 |
3,193 | #include <cstddef>
using f_ptr = unsigned int();
extern unsigned int regression_1000();
extern unsigned int regression_1008();
extern unsigned int regression_1067();
extern unsigned int regression_1072();
extern unsigned int regression_1087();
extern unsigned int regression_1095();
extern unsigned int regression_1096();
extern unsigned int regression_1149();
extern unsigned int regression_1192();
static f_ptr* const regression_tests_regressions[]
= { ®ression_1008, ®ression_1000, ®ression_1067, ®ression_1072, ®ression_1087, ®ression_1095, ®ression_1096, ®ression_1149, ®ression_1192 };
static const int regression_tests_sizeof_regressions = sizeof(regression_tests_regressions) / sizeof(regression_tests_regressions[0]);
int trampoline(f_ptr* f) {
try {
return f();
}
catch (...) {
}
return 1;
}
int main(int, char*[]) {
int r = 0;
for (std::size_t i = 0; i < regression_tests_sizeof_regressions; ++i) {
f_ptr* f = regression_tests_regressions[i];
r += static_cast<int>(trampoline(f) != 0u);
}
return r;
}
| 376 |
5,133 | /*
* Copyright MapStruct Authors.
*
* Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package org.mapstruct.ap.internal.util;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.TypeElement;
import javax.lang.model.util.Elements;
public class EclipseElementUtilsDecorator extends AbstractElementUtilsDecorator {
private final Elements delegate;
EclipseElementUtilsDecorator(ProcessingEnvironment processingEnv) {
super( processingEnv );
this.delegate = processingEnv.getElementUtils();
}
/**
* When running during Eclipse Incremental Compilation, we might get a TypeElement that has an UnresolvedTypeBinding
* and which is not automatically resolved. In that case, getEnclosedElements returns an empty list. We take that as
* a hint to check if the TypeElement resolved by FQN might have any enclosed elements and, if so, return the
* resolved element.
*
* @param element the original element
* @return the element freshly resolved using the qualified name, if the original element did not return any
* enclosed elements, whereas the resolved element does return enclosed elements.
*/
protected TypeElement replaceTypeElementIfNecessary(TypeElement element) {
if ( element.getEnclosedElements().isEmpty() ) {
TypeElement resolvedByName = delegate.getTypeElement( element.getQualifiedName() );
if ( resolvedByName != null && !resolvedByName.getEnclosedElements().isEmpty() ) {
return resolvedByName;
}
}
return element;
}
}
| 549 |
772 | <reponame>ryansloan/code-dot-or
{
"continue": "بەردەوام بە",
"doCode": "بكە",
"elseCode": "یان",
"endGame": "یارییەکە تەواو بکە",
"endGameTooltip": "یارییەکە تەواو دەکات.",
"flap": "بازدان",
"flapRandom": "بازدانی بڕێکی هەرەمەکی",
"flapVerySmall": "بازدانی بڕێکی زۆر کەم",
"flapSmall": "بازدانی بڕێکی کەم",
"flapNormal": "بازدانی بڕێکی ئاسایی",
"flapLarge": "بازدانی بڕێکی گەورە",
"flapVeryLarge": "بازدانی بڕێکی زۆر گەورە",
"flapTooltip": "فڕینی فلاپی بۆ سەرەوە.",
"flappySpecificFail": "کۆدەکانت باش دەردەکەون - ئەوە لەگەڵ هەر کرتەیەک بازدەدات. بەڵام تۆ پێویستتە زۆر جار کرتە بکەیت بۆ ئەوەی باز بدات بۆ ئامانجەکە.",
"incrementPlayerScore": "خاڵێک وەربگرە",
"incrementPlayerScoreTooltip": "خالێک بۆ خاڵەکانی یاریزانی ئێستا زیاد بکە.",
"playSoundRandom": "دەنکێکی هەرەمەکی لێبدە",
"playSoundBounce": "دەنگی هەڵبەزینەوە ئیش پێ بکە",
"playSoundDie": "دەنگی غەمگینی بەکار بهێنە",
"playSoundHit": "دەنگی شکان لێبدە",
"playSoundPoint": "دەنگی خاڵ لێبدە",
"playSoundSwoosh": "دەنگی خشەخش لێبدە",
"soundRandom": "هەڕەمەکی"
}
| 956 |
3,269 | // Time: O(max(r, c) * w)
// Space: O(w)
class Solution {
public:
bool hasPath(vector<vector<int>>& maze, vector<int>& start, vector<int>& destination) {
static const vector<vector<int>> dirs = {{-1, 0}, {0, 1}, {0, -1}, {1, 0}};
queue<node> q;
unordered_set<int> visited;
q.emplace(0, start);
while (!q.empty()) {
int dist = 0;
vector<int> node;
tie(dist, node) = q.front();
q.pop();
if (visited.count(hash(maze, node))) {
continue;
}
if (node[0] == destination[0] &&
node[1] == destination[1]) {
return true;
}
visited.emplace(hash(maze, node));
for (const auto& dir : dirs) {
int neighbor_dist = 0;
vector<int> neighbor;
tie(neighbor_dist, neighbor) = findNeighbor(maze, node, dir);
q.emplace(dist + neighbor_dist, neighbor);
}
}
return false;
}
private:
using node = pair<int, vector<int>>;
node findNeighbor(const vector<vector<int>>& maze,
const vector<int>& node, const vector<int>& dir) {
vector<int> cur_node = node;
int dist = 0;
while (0 <= cur_node[0] + dir[0] && cur_node[0] + dir[0] < maze.size() &&
0 <= cur_node[1] + dir[1] && cur_node[1] + dir[1] < maze[0].size() &&
!maze[cur_node[0] + dir[0]][cur_node[1] + dir[1]]) {
cur_node[0] += dir[0];
cur_node[1] += dir[1];
++dist;
}
return {dist, cur_node};
}
int hash(const vector<vector<int>>& maze, const vector<int>& node) {
return node[0] * maze[0].size() + node[1];
}
};
| 981 |
5,169 | {
"name": "DIYCamera",
"version": "1.0.0",
"summary": "custom camera",
"description": "A custom Camera Demo,",
"homepage": "https://github.com/onelibra/DIYCamera",
"license": "MIT",
"authors": {
"yangbo": "<EMAIL>"
},
"platforms": {
"ios": "5.0"
},
"source": {
"git": "https://github.com/onelibra/DIYCamera.git",
"tag": "1.0.0"
},
"source_files": [
"CamerDemo",
"CamerDemo/Camera/*.{h,m}"
],
"resources": "CamerDemo/Camera/*.{png,xib,nib,storyboard}",
"frameworks": [
"AVFoundation",
"CoreMotion",
"UIKit"
],
"dependencies": {
"NYXImagesKit": [
],
"Masonry": [
]
}
}
| 307 |
5,169 | <gh_stars>1000+
{
"name": "DDCycleScrollView",
"version": "2.0.0",
"summary": "简单易用的图片无限轮播器.",
"homepage": "https://github.com/Faithlight/DDCycleScrollView.git",
"license": "MIT",
"authors": {
"Faithlight": "<EMAIL>"
},
"platforms": {
"ios": "9.0"
},
"source": {
"git": "https://github.com/Faithlight/DDCycleScrollView.git",
"tag": "2.0.0"
},
"source_files": "DDCycleScrollView/DDCycleScrollView/**/*.{h,m}",
"requires_arc": true
}
| 230 |
903 | <reponame>dyzmapl/BumpTop<gh_stars>100-1000
#include "../../../src/gui/kernel/qshortcutmap_p.h"
| 45 |
410 | <filename>Source/ThirdParty/LuaCpp/ObjFunc.h
#pragma once
namespace LuaCpp {
template <int N, typename Ret, typename... Args>
class ObjFunc : public BaseFunc {
using _func_type = std::function<Ret(Args...)>;
public:
ObjFunc(lua_State *l, const std::string &name, Ret(*func)(Args...))
: ObjFunc(l, name, _func_type(func)) {}
// Set function field of metatable of object
ObjFunc(lua_State *l, const std::string &name, _func_type func)
: _name(name), _func(func) {
// NOTE: Assume that metatable of object is already pushed on top
lua_pushlightuserdata(l, (void *)static_cast<BaseFunc *>(this));
lua_pushcclosure(l, &detail::_lua_dispatcher, 1);
// Add a closure function with name
lua_setfield(l, -2, name.c_str());
}
// Each application of a function receives a new Lua context so this argument is necessary.
virtual int Invoke(lua_State *l) override {
// Read all arguments from the stack and pack it into a tuple
std::tuple<Args...> args = detail::_get_args<Args...>(l);
// Call the function '_func' with those arguments by converting the tuple back into a parameter pack.
// Push the returned value(s) onto the stack.
detail::_push(l, detail::_lift(_func, args));
// Return the number of values returned so Lua knows how many values to pop on its end.
return N;
}
private:
_func_type _func;
std::string _name;
};
template <typename... Args>
class ObjFunc<0, void, Args...> : public BaseFunc {
using _func_type = std::function<void(Args...)>;
public:
ObjFunc(lua_State *l, const std::string &name, void(*func)(Args...))
: ObjFunc(l, name, _func_type(func)) {}
// Set function field of metatable of object
ObjFunc(lua_State *l, const std::string &name, _func_type func)
: _name(name), _func(func) {
// NOTE: Assume that metatable of object is already pushed on top
lua_pushlightuserdata(l, (void *)static_cast<BaseFunc *>(this));
lua_pushcclosure(l, &detail::_lua_dispatcher, 1);
// Add a closure function with name
lua_setfield(l, -2, name.c_str());
}
// Each application of a function receives a new Lua context so this argument is necessary.
virtual int Invoke(lua_State *l) override {
// Read all arguments from the stack and pack it into a tuple
std::tuple<Args...> args = detail::_get_args<Args...>(l);
// Call the function '_func' with those arguments by converting the tuple back into a parameter pack.
detail::_lift(_func, args);
// There are no return values
return 0;
}
private:
_func_type _func;
std::string _name;
};
}
| 1,054 |
475 | <filename>net/src/main/java/com/zfoo/net/router/route/PacketBus.java
/*
* Copyright (C) 2020 The zfoo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and limitations under the License.
*/
package com.zfoo.net.router.route;
import com.zfoo.event.model.event.IEvent;
import com.zfoo.net.packet.service.PacketService;
import com.zfoo.net.router.attachment.GatewayAttachment;
import com.zfoo.net.router.attachment.HttpAttachment;
import com.zfoo.net.router.attachment.IAttachment;
import com.zfoo.net.router.attachment.UdpAttachment;
import com.zfoo.net.router.receiver.EnhanceUtils;
import com.zfoo.net.router.receiver.IPacketReceiver;
import com.zfoo.net.router.receiver.PacketReceiver;
import com.zfoo.net.router.receiver.PacketReceiverDefinition;
import com.zfoo.net.session.model.Session;
import com.zfoo.protocol.IPacket;
import com.zfoo.protocol.ProtocolManager;
import com.zfoo.protocol.collection.ArrayUtils;
import com.zfoo.protocol.exception.RunException;
import com.zfoo.protocol.registration.IProtocolRegistration;
import com.zfoo.protocol.util.AssertionUtils;
import com.zfoo.protocol.util.ReflectionUtils;
import com.zfoo.protocol.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Modifier;
/**
* 包的接收路线,服务器收到packet调用对应的Receiver
*
* @author jaysunxiao
* @version 3.0
*/
public abstract class PacketBus {
private static final Logger logger = LoggerFactory.getLogger(PacketBus.class);
/**
* 客户端和服务端都有接受packet的方法,packetReceiverList对应的就是包的接收方法,将receiver注册到IProtocolRegistration
*/
public static final IProtocolRegistration[] packetReceiverList = ProtocolManager.protocols;
/**
* 正常消息的接收
* <p>
* 发送者同时能发送多个包
* 接收者同时只能处理一个session的一个包,同一个发送者发送过来的包排队处理
*/
public static void submit(Session session, IPacket packet, IAttachment attachment) {
var packetReceiver = (IPacketReceiver) packetReceiverList[packet.protocolId()].receiver();
if (packetReceiver == null) {
throw new RuntimeException(StringUtils.format("no any packetReceiverDefinition found for this [packet:{}]", packet.getClass().getName()));
}
// 调用PacketReceiver
packetReceiver.invoke(session, packet, attachment);
}
public static void registerPacketReceiverDefinition(Object bean) {
var clazz = bean.getClass();
var methods = ReflectionUtils.getMethodsByAnnoInPOJOClass(clazz, PacketReceiver.class);
if (ArrayUtils.isEmpty(methods)) {
return;
}
if (!ReflectionUtils.isPojoClass(clazz)) {
logger.warn("消息注册类[{}]不是POJO类,父类的消息接收不会被扫描到", clazz);
}
for (var method : methods) {
var paramClazzs = method.getParameterTypes();
AssertionUtils.isTrue(paramClazzs.length == 2 || paramClazzs.length == 3
, "[class:{}] [method:{}] must have two or three parameter!", bean.getClass().getName(), method.getName());
AssertionUtils.isTrue(Session.class.isAssignableFrom(paramClazzs[0])
, "[class:{}] [method:{}],the first parameter must be Session type parameter Exception.", bean.getClass().getName(), method.getName());
AssertionUtils.isTrue(IPacket.class.isAssignableFrom(paramClazzs[1])
, "[class:{}] [method:{}],the second parameter must be IPacket type parameter Exception.", bean.getClass().getName(), method.getName());
AssertionUtils.isTrue(paramClazzs.length != 3 || IAttachment.class.isAssignableFrom(paramClazzs[2])
, "[class:{}] [method:{}],the third parameter must be IAttachment type parameter Exception.", bean.getClass().getName(), method.getName());
var packetClazz = (Class<? extends IEvent>) paramClazzs[1];
var attachmentClazz = paramClazzs.length == 3 ? paramClazzs[2] : null;
var packetName = packetClazz.getCanonicalName();
var methodName = method.getName();
AssertionUtils.isTrue(Modifier.isPublic(method.getModifiers())
, "[class:{}] [method:{}] [packet:{}] must use 'public' as modifier!", bean.getClass().getName(), methodName, packetName);
AssertionUtils.isTrue(!Modifier.isStatic(method.getModifiers())
, "[class:{}] [method:{}] [packet:{}] can not use 'static' as modifier!", bean.getClass().getName(), methodName, packetName);
var expectedMethodName = StringUtils.format("at{}", packetClazz.getSimpleName());
AssertionUtils.isTrue(methodName.equals(expectedMethodName)
, "[class:{}] [method:{}] [packet:{}] expects '{}' as method name!", bean.getClass().getName(), methodName, packetName, expectedMethodName);
// 如果以Request结尾的请求,那么attachment应该为GatewayAttachment
// 如果以Ask结尾的请求,那么attachment不能为GatewayAttachment
if (attachmentClazz != null) {
if (packetName.endsWith(PacketService.NET_REQUEST_SUFFIX)) {
AssertionUtils.isTrue(attachmentClazz.equals(GatewayAttachment.class) || attachmentClazz.equals(UdpAttachment.class) || attachmentClazz.equals(HttpAttachment.class)
, "[class:{}] [method:{}] [packet:{}] must use [attachment:{}]!", bean.getClass().getName(), methodName, packetName, GatewayAttachment.class.getCanonicalName());
} else if (packetName.endsWith(PacketService.NET_ASK_SUFFIX)) {
AssertionUtils.isTrue(!attachmentClazz.equals(GatewayAttachment.class)
, "[class:{}] [method:{}] [packet:{}] can not match with [attachment:{}]!", bean.getClass().getName(), methodName, packetName, GatewayAttachment.class.getCanonicalName());
}
}
try {
var protocolIdField = packetClazz.getDeclaredField(ProtocolManager.PROTOCOL_ID);
ReflectionUtils.makeAccessible(protocolIdField);
var protocolId = (short) protocolIdField.get(null);
var receiverDefinition = new PacketReceiverDefinition(bean, method, packetClazz, attachmentClazz);
var enhanceReceiverDefinition = EnhanceUtils.createPacketReceiver(receiverDefinition);
// 将receiver注册到IProtocolRegistration
var protocolRegistration = packetReceiverList[protocolId];
AssertionUtils.notNull(protocolRegistration, "协议类[class:{}][protocolId:{}]没有注册", packetClazz.getSimpleName(), protocolId);
var receiverField = ReflectionUtils.getFieldByNameInPOJOClass(protocolRegistration.getClass(), "receiver");
ReflectionUtils.makeAccessible(receiverField);
ReflectionUtils.setField(receiverField, protocolRegistration, enhanceReceiverDefinition);
} catch (Throwable t) {
throw new RunException(t, "解析协议类[class:{}]未知异常", packetClazz.getSimpleName());
}
}
}
}
| 3,239 |
1,850 | <gh_stars>1000+
package com.alibaba.jvm.sandbox.repeater.plugin.domain;
import java.util.Map;
/**
* {@link HttpInvocation} http请求调用比较独立
* <p>
*
* @author zhaoyb1990
*/
public class HttpInvocation extends Invocation implements java.io.Serializable {
/**
* 请求的URL
*/
private String requestURL;
/**
* 请求的URI
*/
private String requestURI;
/**
* 本地端口号
*/
private int port;
/**
* 请求方法
*/
private String method;
/**
* 内容类型
*/
private String contentType;
/**
* 请求headers
*/
private Map<String, String> headers;
/**
* 请求参数 - 没有拦截post body方式提交;没有同步序列化,导致被更改,只能使用request里面的参数
*/
private Map<String, String[]> paramsMap;
/**
* POST请求的BODY
*/
private String body;
/**
* 异步调用
*/
private volatile boolean async;
/**
* 是否已初始化
*/
private transient boolean init;
public String getRequestURL() {
return requestURL;
}
public void setRequestURL(String requestURL) {
this.requestURL = requestURL;
}
public String getRequestURI() {
return requestURI;
}
public void setRequestURI(String requestURI) {
this.requestURI = requestURI;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
public Map<String, String> getHeaders() {
return headers;
}
public void setHeaders(Map<String, String> headers) {
this.headers = headers;
}
public Map<String, String[]> getParamsMap() {
return paramsMap;
}
public void setParamsMap(Map<String, String[]> paramsMap) {
this.paramsMap = paramsMap;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public boolean isAsync() {
return async;
}
public void setAsync(boolean async) {
this.async = async;
}
public boolean isInit() {
return init;
}
public void setInit(boolean init) {
this.init = init;
}
}
| 1,180 |
1,006 | <filename>libs/libc/pthread/pthread_keydelete.c
/****************************************************************************
* libs/libc/pthread/pthread_keydelete.c
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. The
* ASF licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#include <pthread.h>
#include <nuttx/tls.h>
/****************************************************************************
* Public Functions
****************************************************************************/
/****************************************************************************
* Name: pthread_key_delete
*
* Description:
* This POSIX function deletes a thread-specific data key
* previously returned by pthread_key_create().
*
* Input Parameters:
* key - the key to delete
*
* Returned Value:
* Returns zero (OK) on success. EINVAL may be returned if an invalid
* key is received.
*
* POSIX Compatibility:
*
****************************************************************************/
int pthread_key_delete(pthread_key_t key)
{
/* Free the TLS index */
int ret = tls_free((int)key);
return ret < 0 ? -ret : 0;
}
| 483 |
1,459 | <reponame>gioannides/OpenSeq2Seq
import os
import sys
import argparse
import librosa
parser = argparse.ArgumentParser(description='Conversion parameters')
parser.add_argument("--source_dir", required=False, type=str, default="calibration/sound_files/",
help="Path to source of flac LibriSpeech files")
parser.add_argument("--target_dir", required=False, type=str, default="calibration/sound_files_wav/",
help="Path to source of flac LibriSpeech files")
parser.add_argument("--sample_rate", required=False, type=int, default=16000,
help="Output sample rate")
args = parser.parse_args()
source_dir = args.source_dir
sample_rate = args.sample_rate
target_dir = args.target_dir
def getListOfFiles(dirName):
"""create a list of file and sub directories
names in the given directory
"""
listOfFile = os.listdir(dirName)
allFiles = list()
# Iterate over all the entries
for entry in listOfFile:
# Create full path
fullPath = os.path.join(dirName, entry)
# If entry is a directory then get the list of files in this directory
if os.path.isdir(fullPath):
allFiles = allFiles + getListOfFiles(fullPath)
else:
if fullPath[-3:] == "wav" or fullPath[-4:] == "flac":
allFiles.append(fullPath)
return allFiles
def convert_to_wav(flac_files,sample_rate,target_dir):
"""This function converts flac input to wav output of given sample rate"""
for sound_file in flac_files:
dir_tree = sound_file.split("/")[-4:]
save_path = '/'.join(dir_tree[:-1])
name = dir_tree[-1][:-4] + "wav"
if not os.path.isdir(save_path):
os.makedirs(save_path)
sig, sr = librosa.load(sound_file, sample_rate)
output_dir = target_dir+save_path
if not os.path.isdir(output_dir):
os.makedirs(output_dir)
librosa.output.write_wav(output_dir + "/" + name, sig, sample_rate)
flac_files = getListOfFiles(source_dir)
convert_to_wav(flac_files,sample_rate,target_dir)
| 757 |
583 | <reponame>dzliangjing/KSYMediaPlayer_iOS<gh_stars>100-1000
//
// VideoListShowController.h
// KSYPlayerDemo
//
// Created by devcdl on 2017/9/11.
// Copyright © 2017年 kingsoft. All rights reserved.
//
#import "BaseViewController.h"
#import "Constant.h"
@interface VideoListShowController : BaseViewController
@property (nonatomic, assign) BOOL hasSuspendView;
@property (nonatomic, assign) VideoListShowType showType;
@end
| 150 |
575 | <gh_stars>100-1000
// Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/public/common/widget/visual_properties.h"
#include "base/ranges/algorithm.h"
namespace blink {
VisualProperties::VisualProperties() = default;
VisualProperties::VisualProperties(const VisualProperties& other) = default;
VisualProperties::~VisualProperties() = default;
VisualProperties& VisualProperties::operator=(const VisualProperties& other) =
default;
bool VisualProperties::operator==(const VisualProperties& other) const {
return screen_infos == other.screen_infos &&
auto_resize_enabled == other.auto_resize_enabled &&
min_size_for_auto_resize == other.min_size_for_auto_resize &&
max_size_for_auto_resize == other.max_size_for_auto_resize &&
new_size == other.new_size &&
visible_viewport_size == other.visible_viewport_size &&
compositor_viewport_pixel_rect ==
other.compositor_viewport_pixel_rect &&
browser_controls_params == other.browser_controls_params &&
scroll_focused_node_into_view == other.scroll_focused_node_into_view &&
local_surface_id == other.local_surface_id &&
is_fullscreen_granted == other.is_fullscreen_granted &&
display_mode == other.display_mode &&
capture_sequence_number == other.capture_sequence_number &&
zoom_level == other.zoom_level &&
page_scale_factor == other.page_scale_factor &&
compositing_scale_factor == other.compositing_scale_factor &&
root_widget_window_segments == other.root_widget_window_segments &&
is_pinch_gesture_active == other.is_pinch_gesture_active;
}
bool VisualProperties::operator!=(const VisualProperties& other) const {
return !operator==(other);
}
} // namespace blink
| 696 |
453 | /******************************************************************************
* Author: <NAME> <<EMAIL>>
*
* Copyright (C) 2014-2016 <NAME> <<EMAIL>>
*
* Licensed according to the included 'LICENSE' document
*
* This file is part of lua-lluv library.
******************************************************************************/
#include "lluv.h"
#include "lluv_handle.h"
#include "lluv_timer.h"
#include "lluv_loop.h"
#include "lluv_error.h"
#include <assert.h>
#define LLUV_TIMER_NAME LLUV_PREFIX" Timer"
static const char *LLUV_TIMER = LLUV_TIMER_NAME;
LLUV_INTERNAL int lluv_timer_index(lua_State *L){
return lluv__index(L, LLUV_TIMER, lluv_handle_index);
}
LLUV_IMPL_SAFE(lluv_timer_create){
lluv_loop_t *loop = lluv_opt_loop_ex(L, 1, LLUV_FLAG_OPEN);
lluv_handle_t *handle = lluv_handle_create(L, UV_TIMER, safe_flag | INHERITE_FLAGS(loop));
int err = uv_timer_init(loop->handle, LLUV_H(handle, uv_timer_t));
if(err < 0){
lluv_handle_cleanup(L, handle, -1);
return lluv_fail(L, safe_flag | loop->flags, LLUV_ERR_UV, (uv_errno_t)err, NULL);
}
return 1;
}
static lluv_handle_t* lluv_check_timer(lua_State *L, int idx, lluv_flags_t flags){
lluv_handle_t *handle = lluv_check_handle(L, idx, flags);
luaL_argcheck (L, LLUV_H(handle, uv_handle_t)->type == UV_TIMER, idx, LLUV_TIMER_NAME" expected");
return handle;
}
static void lluv_on_timer_start(uv_timer_t *arg){
uv_handle_t *h = (uv_handle_t*)arg;
if(!uv_is_active(h)){
lluv_handle_t *handle = lluv_handle_byptr(h);
lua_State *L = LLUV_HCALLBACK_L(handle);
lluv_handle_unlock(L, handle, LLUV_LOCK_START);
}
lluv_on_handle_start(h);
}
static int lluv_timer_start(lua_State *L){
lluv_handle_t *handle = lluv_check_timer(L, 1, LLUV_FLAG_OPEN);
uint64_t timeout, repeat;
int err;
lluv_check_args_with_cb(L, 4);
LLUV_START_CB(handle) = luaL_ref(L, LLUV_LUA_REGISTRY);
if(lua_gettop(L) > 1){
timeout = lutil_checkint64(L, 2);
if(lua_gettop(L) > 2)
repeat = lutil_checkint64(L, 3);
else
repeat = 0;
}
else{
timeout = 0;
repeat = 0;
}
err = uv_timer_start(LLUV_H(handle, uv_timer_t), lluv_on_timer_start, timeout, repeat);
if(err >= 0) lluv_handle_lock(L, handle, LLUV_LOCK_START);
return lluv_return(L, handle, LLUV_START_CB(handle), err);
}
static int lluv_timer_stop(lua_State *L){
lluv_handle_t *handle = lluv_check_timer(L, 1, LLUV_FLAG_OPEN);
int err = uv_timer_stop(LLUV_H(handle, uv_timer_t));
if(err < 0){
return lluv_fail(L, handle->flags, LLUV_ERR_UV, err, NULL);
}
lluv_handle_lock(L, handle, LLUV_LOCK_START);
lua_settop(L, 1);
return 1;
}
static int lluv_timer_again(lua_State *L){
lluv_handle_t *handle = lluv_check_timer(L, 1, LLUV_FLAG_OPEN);
int err;
if(lua_isnumber(L, 2)){
uint64_t repeat = lutil_optint64(L, 2, 0);
uv_timer_set_repeat(LLUV_H(handle, uv_timer_t), repeat);
}
err = uv_timer_again(LLUV_H(handle, uv_timer_t));
if(err < 0){
return lluv_fail(L, handle->flags, LLUV_ERR_UV, err, NULL);
}
lluv_handle_lock(L, handle, LLUV_LOCK_START);
lua_settop(L, 1);
return 1;
}
static int lluv_timer_set_repeat(lua_State *L){
lluv_handle_t *handle = lluv_check_timer(L, 1, LLUV_FLAG_OPEN);
uint64_t repeat = lutil_optint64(L, 2, 0);
uv_timer_set_repeat(LLUV_H(handle, uv_timer_t), repeat);
lua_settop(L, 1);
return 1;
}
static int lluv_timer_get_repeat(lua_State *L){
lluv_handle_t *handle = lluv_check_timer(L, 1, LLUV_FLAG_OPEN);
uint64_t repeat = uv_timer_get_repeat(LLUV_H(handle, uv_timer_t));
lutil_pushint64(L, repeat);
return 1;
}
static const struct luaL_Reg lluv_timer_methods[] = {
{ "start", lluv_timer_start },
{ "stop", lluv_timer_stop },
{ "again", lluv_timer_again },
{ "set_repeat", lluv_timer_set_repeat },
{ "get_repeat", lluv_timer_get_repeat },
{NULL,NULL}
};
#define LLUV_FUNCTIONS(F) \
{"timer", lluv_timer_create_##F}, \
static const struct luaL_Reg lluv_functions[][2] = {
{
LLUV_FUNCTIONS(unsafe)
{NULL,NULL}
},
{
LLUV_FUNCTIONS(safe)
{NULL,NULL}
},
};
LLUV_INTERNAL void lluv_timer_initlib(lua_State *L, int nup, int safe){
lutil_pushnvalues(L, nup);
if(!lutil_createmetap(L, LLUV_TIMER, lluv_timer_methods, nup))
lua_pop(L, nup);
lua_pop(L, 1);
luaL_setfuncs(L, lluv_functions[safe], nup);
}
| 1,964 |
384 | <reponame>baidu/Jprotobuf-rpc-socket
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.baidu.jprotobuf.pbrpc.utils;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.util.Enumeration;
import java.util.Random;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Utiltiy class for net.
*
* @author xiemalin
* @since 2.27
*/
public class NetUtils {
/** The Constant logger. */
private static final Logger logger = LoggerFactory.getLogger(NetUtils.class.getName());
/** The Constant LOCALHOST. */
public static final String LOCALHOST = "127.0.0.1";
/** The Constant ANYHOST. */
public static final String ANYHOST = "0.0.0.0";
/** The Constant RND_PORT_START. */
private static final int RND_PORT_START = 30000;
/** The Constant RND_PORT_RANGE. */
private static final int RND_PORT_RANGE = 10000;
/** The Constant RANDOM. */
private static final Random RANDOM = new Random(System.currentTimeMillis());
/** The local address. */
private static volatile InetAddress LOCAL_ADDRESS = null;
/**
* Gets the random port.
*
* @return the random port
*/
public static int getRandomPort() {
return RND_PORT_START + RANDOM.nextInt(RND_PORT_RANGE);
}
/**
* Gets the available port.
*
* @return the available port
*/
public static int getAvailablePort() {
ServerSocket ss = null;
try {
ss = new ServerSocket();
ss.bind(null);
return ss.getLocalPort();
} catch (IOException e) {
return getRandomPort();
} finally {
if (ss != null) {
try {
ss.close();
} catch (IOException e) {
if (logger.isDebugEnabled()) {
logger.debug(e.getMessage(), e);
}
}
}
}
}
/**
* Gets the available port.
*
* @param port the port
* @return the available port
*/
public static int getAvailablePort(int port) {
if (port <= 0) {
return getAvailablePort();
}
for (int i = port; i < MAX_PORT; i++) {
ServerSocket ss = null;
try {
ss = new ServerSocket(i);
return i;
} catch (IOException e) {
// continue
} finally {
if (ss != null) {
try {
ss.close();
} catch (IOException e) {
if (logger.isDebugEnabled()) {
logger.debug(e.getMessage(), e);
}
}
}
}
}
return port;
}
/** The Constant MIN_PORT. */
private static final int MIN_PORT = 0;
/** The Constant MAX_PORT. */
private static final int MAX_PORT = 65535;
/**
* Checks if is invalid port.
*
* @param port the port
* @return true, if is invalid port
*/
public static boolean isInvalidPort(int port) {
return !isValidPort(port);
}
/**
* Checks if is valid port.
*
* @param port the port
* @return true, if is valid port
*/
public static boolean isValidPort(int port) {
return port > MIN_PORT && port <= MAX_PORT;
}
/** The Constant ADDRESS_PATTERN. */
private static final Pattern ADDRESS_PATTERN = Pattern.compile("^\\d{1,3}(\\.\\d{1,3}){3}\\:\\d{1,5}$");
/**
* Checks if is valid address.
*
* @param address the address
* @return true, if is valid address
*/
public static boolean isValidAddress(String address) {
return ADDRESS_PATTERN.matcher(address).matches();
}
/** The Constant LOCAL_IP_PATTERN. */
private static final Pattern LOCAL_IP_PATTERN = Pattern.compile("127(\\.\\d{1,3}){3}$");
/**
* Checks if is local host.
*
* @param host the host
* @return true, if is local host
*/
public static boolean isLocalHost(String host) {
return host != null && (LOCAL_IP_PATTERN.matcher(host).matches() || host.equalsIgnoreCase("localhost"));
}
/**
* Checks if is any host.
*
* @param host the host
* @return true, if is any host
*/
public static boolean isAnyHost(String host) {
return "0.0.0.0".equals(host);
}
/**
* Checks if is invalid local host.
*
* @param host the host
* @return true, if is invalid local host
*/
public static boolean isInvalidLocalHost(String host) {
return host == null || host.length() == 0 || host.equalsIgnoreCase("localhost") || host.equals("0.0.0.0")
|| (LOCAL_IP_PATTERN.matcher(host).matches());
}
/**
* Checks if is valid local host.
*
* @param host the host
* @return true, if is valid local host
*/
public static boolean isValidLocalHost(String host) {
return !isInvalidLocalHost(host);
}
/**
* Gets the local socket address.
*
* @param host the host
* @param port the port
* @return the local socket address
*/
public static InetSocketAddress getLocalSocketAddress(String host, int port) {
return isInvalidLocalHost(host) ? new InetSocketAddress(port) : new InetSocketAddress(host, port);
}
/** The Constant IP_PATTERN. */
private static final Pattern IP_PATTERN = Pattern.compile("\\d{1,3}(\\.\\d{1,3}){3,5}$");
/**
* Checks if is valid address.
*
* @param address the address
* @return true, if is valid address
*/
private static boolean isValidAddress(InetAddress address) {
if (address == null || address.isLoopbackAddress()) {
return false;
}
String name = address.getHostAddress();
return (name != null && !ANYHOST.equals(name) && !LOCALHOST.equals(name) && IP_PATTERN.matcher(name).matches());
}
/**
* Gets the local address.
*
* @return the local address
*/
public static InetAddress getLocalAddress() {
if (LOCAL_ADDRESS != null) {
return LOCAL_ADDRESS;
}
InetAddress localAddress = getLocalAddress0();
LOCAL_ADDRESS = localAddress;
return localAddress;
}
/**
* Gets the log host.
*
* @return the log host
*/
public static String getLogHost() {
InetAddress address = LOCAL_ADDRESS;
return address == null ? LOCALHOST : address.getHostAddress();
}
/**
* Gets the local address0.
*
* @return the local address0
*/
private static InetAddress getLocalAddress0() {
InetAddress localAddress = null;
try {
localAddress = InetAddress.getLocalHost();
if (isValidAddress(localAddress)) {
return localAddress;
}
} catch (Throwable e) {
logger.warn("Failed to retriving ip address, " + e.getMessage(), e);
}
try {
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
if (interfaces != null) {
while (interfaces.hasMoreElements()) {
try {
NetworkInterface network = interfaces.nextElement();
Enumeration<InetAddress> addresses = network.getInetAddresses();
if (addresses != null) {
while (addresses.hasMoreElements()) {
try {
InetAddress address = addresses.nextElement();
if (isValidAddress(address)) {
return address;
}
} catch (Throwable e) {
logger.warn("Failed to retriving ip address, " + e.getMessage(), e);
}
}
}
} catch (Throwable e) {
logger.warn("Failed to retriving ip address, " + e.getMessage(), e);
}
}
}
} catch (Throwable e) {
logger.warn("Failed to retriving ip address, " + e.getMessage(), e);
}
logger.error("Could not get local host ip address, will use 127.0.0.1 instead.");
return localAddress;
}
}
| 4,237 |
348 | {"nom":"Preux-au-Sart","circ":"12ème circonscription","dpt":"Nord","inscrits":213,"abs":130,"votants":83,"blancs":4,"nuls":3,"exp":76,"res":[{"nuance":"REM","nom":"<NAME>","voix":53},{"nuance":"FN","nom":"<NAME>","voix":23}]} | 92 |
1,431 | /* ====================================================================
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.poi.hslf.usermodel;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import org.apache.poi.POIDataSamples;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* Tests that SlideShow returns MetaSheets which have the right text in them
*/
public final class TestNotesText {
// SlideShow primed on the test data
private HSLFSlideShow ss;
@BeforeEach
void setup() throws Exception {
POIDataSamples slTests = POIDataSamples.getSlideShowInstance();
HSLFSlideShowImpl hss = new HSLFSlideShowImpl(slTests.openResourceAsStream("basic_test_ppt_file.ppt"));
ss = new HSLFSlideShow(hss);
}
@Test
void testNotesOne() {
HSLFNotes notes = ss.getNotes().get(0);
String[] expectText = {"These are the notes for page 1"};
assertArrayEquals(expectText, toStrings(notes));
}
@Test
void testNotesTwo() {
HSLFNotes notes = ss.getNotes().get(1);
String[] expectText = {"These are the notes on page two, again lacking formatting"};
assertArrayEquals(expectText, toStrings(notes));
}
private static String[] toStrings(HSLFNotes notes) {
return notes.getTextParagraphs().stream().map(HSLFTextParagraph::getRawText).toArray(String[]::new);
}
}
| 714 |
45,293 | public @interface Ann {
}
| 8 |
2,748 | <gh_stars>1000+
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alipay.sofa.startup.stage.healthcheck;
import com.alipay.sofa.boot.startup.BaseStat;
import com.alipay.sofa.healthcheck.AfterReadinessCheckCallbackProcessor;
import com.alipay.sofa.healthcheck.HealthCheckProperties;
import com.alipay.sofa.healthcheck.HealthCheckerProcessor;
import com.alipay.sofa.healthcheck.HealthIndicatorProcessor;
import com.alipay.sofa.healthcheck.ReadinessCheckListener;
import com.alipay.sofa.runtime.configure.SofaRuntimeConfigurationProperties;
import com.alipay.sofa.startup.StartupReporter;
import org.springframework.core.env.Environment;
import static com.alipay.sofa.boot.startup.BootStageConstants.HEALTH_CHECK_STAGE;
/**
* @author huzijie
* @version StartupReadinessCheckListener.java, v 0.1 2020年12月31日 4:39 下午 huzijie Exp $
*/
public class StartupReadinessCheckListener extends ReadinessCheckListener {
private final StartupReporter startupReporter;
public StartupReadinessCheckListener(Environment environment,
HealthCheckerProcessor healthCheckerProcessor,
HealthIndicatorProcessor healthIndicatorProcessor,
AfterReadinessCheckCallbackProcessor afterReadinessCheckCallbackProcessor,
SofaRuntimeConfigurationProperties sofaRuntimeConfigurationProperties,
HealthCheckProperties healthCheckProperties,
StartupReporter startupReporter) {
super(environment, healthCheckerProcessor, healthIndicatorProcessor,
afterReadinessCheckCallbackProcessor, sofaRuntimeConfigurationProperties,
healthCheckProperties);
this.startupReporter = startupReporter;
}
@Override
public void readinessHealthCheck() {
BaseStat stat = new BaseStat();
stat.setName(HEALTH_CHECK_STAGE);
stat.setStartTime(System.currentTimeMillis());
super.readinessHealthCheck();
stat.setEndTime(System.currentTimeMillis());
startupReporter.addCommonStartupStat(stat);
}
}
| 1,060 |
527 | // INPUT:abc
struct production
{
static constexpr auto rule = LEXY_LIT("a") / LEXY_LIT("abc") / LEXY_LIT("bc");
};
| 52 |
501 | import django.core.validators
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
class UserenaAuthenticationBackend(ModelBackend):
"""
Custom backend because the user must be able to supply a ``email`` or
``username`` to the login form.
"""
def authenticate(self, identification, password=None, check_password=True):
"""
Authenticates a user through the combination email/username with
password.
:param identification:
A string containing the username or e-mail of the user that is
trying to authenticate.
:password:
Optional string containing the password for the user.
:param check_password:
Boolean that defines if the password should be checked for this
user. Always keep this ``True``. This is only used by userena at
activation when a user opens a page with a secret hash.
:return: The signed in :class:`User`.
"""
User = get_user_model()
try:
django.core.validators.validate_email(identification)
try: user = User.objects.get(email__iexact=identification)
except User.DoesNotExist: return None
except django.core.validators.ValidationError:
try: user = User.objects.get(username__iexact=identification)
except User.DoesNotExist: return None
if check_password:
if user.check_password(password):
return user
return None
else: return user
def get_user(self, user_id):
User = get_user_model()
try: return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
| 708 |
4,124 | /**
* 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 storm.trident.planner.processor;
import backtype.storm.task.TopologyContext;
import backtype.storm.tuple.Fields;
import java.util.Map;
import storm.trident.planner.ProcessorContext;
import storm.trident.planner.TridentProcessor;
import storm.trident.planner.TupleReceiver;
import storm.trident.tuple.TridentTuple;
import storm.trident.tuple.TridentTuple.Factory;
import storm.trident.tuple.TridentTupleView.ProjectionFactory;
public class ProjectedProcessor implements TridentProcessor {
Fields _projectFields;
ProjectionFactory _factory;
TridentContext _context;
public ProjectedProcessor(Fields projectFields) {
_projectFields = projectFields;
}
@Override
public void prepare(Map conf, TopologyContext context, TridentContext tridentContext) {
if (tridentContext.getParentTupleFactories().size() != 1) {
throw new RuntimeException("Projection processor can only have one parent");
}
_context = tridentContext;
_factory = new ProjectionFactory(tridentContext.getParentTupleFactories().get(0), _projectFields);
}
@Override
public void cleanup() {
}
@Override
public void startBatch(ProcessorContext processorContext) {
}
@Override
public void execute(ProcessorContext processorContext, String streamId, TridentTuple tuple) {
TridentTuple toEmit = _factory.create(tuple);
for (TupleReceiver r : _context.getReceivers()) {
r.execute(processorContext, _context.getOutStreamId(), toEmit);
}
}
@Override
public void finishBatch(ProcessorContext processorContext) {
}
@Override
public Factory getOutputFactory() {
return _factory;
}
}
| 801 |
3,372 | /*
* Copyright 2016-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.mediatailor.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/mediatailor-2018-04-23/CreateProgram" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class CreateProgramRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* The ad break configuration settings.
* </p>
*/
private java.util.List<AdBreak> adBreaks;
/**
* <p>
* The identifier for the channel you are working on.
* </p>
*/
private String channelName;
/**
* <p>
* The identifier for the program you are working on.
* </p>
*/
private String programName;
/**
* <p>
* The schedule configuration settings.
* </p>
*/
private ScheduleConfiguration scheduleConfiguration;
/**
* <p>
* The name of the source location.
* </p>
*/
private String sourceLocationName;
/**
* <p>
* The name that's used to refer to a VOD source.
* </p>
*/
private String vodSourceName;
/**
* <p>
* The ad break configuration settings.
* </p>
*
* @return The ad break configuration settings.
*/
public java.util.List<AdBreak> getAdBreaks() {
return adBreaks;
}
/**
* <p>
* The ad break configuration settings.
* </p>
*
* @param adBreaks
* The ad break configuration settings.
*/
public void setAdBreaks(java.util.Collection<AdBreak> adBreaks) {
if (adBreaks == null) {
this.adBreaks = null;
return;
}
this.adBreaks = new java.util.ArrayList<AdBreak>(adBreaks);
}
/**
* <p>
* The ad break configuration settings.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setAdBreaks(java.util.Collection)} or {@link #withAdBreaks(java.util.Collection)} if you want to override
* the existing values.
* </p>
*
* @param adBreaks
* The ad break configuration settings.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateProgramRequest withAdBreaks(AdBreak... adBreaks) {
if (this.adBreaks == null) {
setAdBreaks(new java.util.ArrayList<AdBreak>(adBreaks.length));
}
for (AdBreak ele : adBreaks) {
this.adBreaks.add(ele);
}
return this;
}
/**
* <p>
* The ad break configuration settings.
* </p>
*
* @param adBreaks
* The ad break configuration settings.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateProgramRequest withAdBreaks(java.util.Collection<AdBreak> adBreaks) {
setAdBreaks(adBreaks);
return this;
}
/**
* <p>
* The identifier for the channel you are working on.
* </p>
*
* @param channelName
* The identifier for the channel you are working on.
*/
public void setChannelName(String channelName) {
this.channelName = channelName;
}
/**
* <p>
* The identifier for the channel you are working on.
* </p>
*
* @return The identifier for the channel you are working on.
*/
public String getChannelName() {
return this.channelName;
}
/**
* <p>
* The identifier for the channel you are working on.
* </p>
*
* @param channelName
* The identifier for the channel you are working on.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateProgramRequest withChannelName(String channelName) {
setChannelName(channelName);
return this;
}
/**
* <p>
* The identifier for the program you are working on.
* </p>
*
* @param programName
* The identifier for the program you are working on.
*/
public void setProgramName(String programName) {
this.programName = programName;
}
/**
* <p>
* The identifier for the program you are working on.
* </p>
*
* @return The identifier for the program you are working on.
*/
public String getProgramName() {
return this.programName;
}
/**
* <p>
* The identifier for the program you are working on.
* </p>
*
* @param programName
* The identifier for the program you are working on.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateProgramRequest withProgramName(String programName) {
setProgramName(programName);
return this;
}
/**
* <p>
* The schedule configuration settings.
* </p>
*
* @param scheduleConfiguration
* The schedule configuration settings.
*/
public void setScheduleConfiguration(ScheduleConfiguration scheduleConfiguration) {
this.scheduleConfiguration = scheduleConfiguration;
}
/**
* <p>
* The schedule configuration settings.
* </p>
*
* @return The schedule configuration settings.
*/
public ScheduleConfiguration getScheduleConfiguration() {
return this.scheduleConfiguration;
}
/**
* <p>
* The schedule configuration settings.
* </p>
*
* @param scheduleConfiguration
* The schedule configuration settings.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateProgramRequest withScheduleConfiguration(ScheduleConfiguration scheduleConfiguration) {
setScheduleConfiguration(scheduleConfiguration);
return this;
}
/**
* <p>
* The name of the source location.
* </p>
*
* @param sourceLocationName
* The name of the source location.
*/
public void setSourceLocationName(String sourceLocationName) {
this.sourceLocationName = sourceLocationName;
}
/**
* <p>
* The name of the source location.
* </p>
*
* @return The name of the source location.
*/
public String getSourceLocationName() {
return this.sourceLocationName;
}
/**
* <p>
* The name of the source location.
* </p>
*
* @param sourceLocationName
* The name of the source location.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateProgramRequest withSourceLocationName(String sourceLocationName) {
setSourceLocationName(sourceLocationName);
return this;
}
/**
* <p>
* The name that's used to refer to a VOD source.
* </p>
*
* @param vodSourceName
* The name that's used to refer to a VOD source.
*/
public void setVodSourceName(String vodSourceName) {
this.vodSourceName = vodSourceName;
}
/**
* <p>
* The name that's used to refer to a VOD source.
* </p>
*
* @return The name that's used to refer to a VOD source.
*/
public String getVodSourceName() {
return this.vodSourceName;
}
/**
* <p>
* The name that's used to refer to a VOD source.
* </p>
*
* @param vodSourceName
* The name that's used to refer to a VOD source.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateProgramRequest withVodSourceName(String vodSourceName) {
setVodSourceName(vodSourceName);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getAdBreaks() != null)
sb.append("AdBreaks: ").append(getAdBreaks()).append(",");
if (getChannelName() != null)
sb.append("ChannelName: ").append(getChannelName()).append(",");
if (getProgramName() != null)
sb.append("ProgramName: ").append(getProgramName()).append(",");
if (getScheduleConfiguration() != null)
sb.append("ScheduleConfiguration: ").append(getScheduleConfiguration()).append(",");
if (getSourceLocationName() != null)
sb.append("SourceLocationName: ").append(getSourceLocationName()).append(",");
if (getVodSourceName() != null)
sb.append("VodSourceName: ").append(getVodSourceName());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof CreateProgramRequest == false)
return false;
CreateProgramRequest other = (CreateProgramRequest) obj;
if (other.getAdBreaks() == null ^ this.getAdBreaks() == null)
return false;
if (other.getAdBreaks() != null && other.getAdBreaks().equals(this.getAdBreaks()) == false)
return false;
if (other.getChannelName() == null ^ this.getChannelName() == null)
return false;
if (other.getChannelName() != null && other.getChannelName().equals(this.getChannelName()) == false)
return false;
if (other.getProgramName() == null ^ this.getProgramName() == null)
return false;
if (other.getProgramName() != null && other.getProgramName().equals(this.getProgramName()) == false)
return false;
if (other.getScheduleConfiguration() == null ^ this.getScheduleConfiguration() == null)
return false;
if (other.getScheduleConfiguration() != null && other.getScheduleConfiguration().equals(this.getScheduleConfiguration()) == false)
return false;
if (other.getSourceLocationName() == null ^ this.getSourceLocationName() == null)
return false;
if (other.getSourceLocationName() != null && other.getSourceLocationName().equals(this.getSourceLocationName()) == false)
return false;
if (other.getVodSourceName() == null ^ this.getVodSourceName() == null)
return false;
if (other.getVodSourceName() != null && other.getVodSourceName().equals(this.getVodSourceName()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getAdBreaks() == null) ? 0 : getAdBreaks().hashCode());
hashCode = prime * hashCode + ((getChannelName() == null) ? 0 : getChannelName().hashCode());
hashCode = prime * hashCode + ((getProgramName() == null) ? 0 : getProgramName().hashCode());
hashCode = prime * hashCode + ((getScheduleConfiguration() == null) ? 0 : getScheduleConfiguration().hashCode());
hashCode = prime * hashCode + ((getSourceLocationName() == null) ? 0 : getSourceLocationName().hashCode());
hashCode = prime * hashCode + ((getVodSourceName() == null) ? 0 : getVodSourceName().hashCode());
return hashCode;
}
@Override
public CreateProgramRequest clone() {
return (CreateProgramRequest) super.clone();
}
}
| 4,898 |
665 | //
// Copyright(c) 2015 <NAME>.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
#pragma once
#include "details/log_msg.h"
namespace spdlog
{
namespace details
{
class flag_formatter;
}
class formatter
{
public:
virtual ~formatter() {}
virtual void format(details::log_msg& msg) = 0;
};
class pattern_formatter : public formatter
{
public:
explicit pattern_formatter(const std::string& pattern);
pattern_formatter(const pattern_formatter&) = delete;
pattern_formatter& operator=(const pattern_formatter&) = delete;
void format(details::log_msg& msg) override;
private:
const std::string _pattern;
std::vector<std::unique_ptr<details::flag_formatter>> _formatters;
void handle_flag(char flag);
void compile_pattern(const std::string& pattern);
};
}
#include "details/pattern_formatter_impl.h"
| 297 |
3,227 | #ifdef BENCH
# define NDEBUG
#endif
#define CGAL_MESH_3_DEBUG_BEFORE_CONFLICTS 0
#define CGAL_MESH_3_DEBUG_AFTER_NO_INSERTION 0
#define CGAL_MESH_3_DEBUG_AFTER_INSERTION 0
#define CGAL_MESH_3_DEBUG_DOUBLE_MAP 0
// #define CGAL_MESHES_NO_OUTPUT
// #define CGAL_SURFACE_MESHER_EDGES_DEBUG_INTERSECTION
// #define CGAL_SURFACE_MESHER_DEBUG_POLYHEDRAL_SURFACE_CONSTRUCTION
// #define CGAL_SURFACE_MESHER_VERBOSE
// #define CGAL_POLYHEDRAL_SURFACE_VERBOSE_CONSTRUCTION
// #define CGAL_SURFACE_MESHER_EDGES_DEBUG_INSERTIONS
// #define CGAL_MESHES_DEBUG_REFINEMENT_POINTS
// #define CGAL_DEBUG_OCTREE_CONSTRUCTION
//#define CGAL_MESH_3_VERBOSE
//#define CGAL_MESH_3_IO_VERBOSE
// #define OPTIMIZE_INTERSECTION
| 336 |
809 | /**
* @file
* @brief Header file for AT91 LCD Controller.
*
* @date 11.10.10
* @author <NAME>
* @author <NAME>
*/
#ifndef NXT_LCD_H_
#define NXT_LCD_H_
#include <stdint.h>
#define NXT_LCD_DEPTH 8
#define NXT_LCD_WIDTH 100
#define N_CHARS 128
#define FONT_WIDTH 5
#define CELL_WIDTH (FONT_WIDTH + 1)
#define DISPLAY_CHAR_WIDTH (NXT_LCD_WIDTH/(CELL_WIDTH))
#define DISPLAY_CHAR_DEPTH (NXT_LCD_DEPTH)
extern void display_char(int c);
extern void display_string(const char *str);
extern void nxt_lcd_force_update(void);
extern void display_clear_screen(void);
extern int lcd_init(void);
extern int display_draw(uint8_t x, uint8_t y,
uint8_t width, uint8_t height, uint8_t *buff);
extern int display_fill(uint8_t x, uint8_t y,
uint8_t width, uint8_t height, uint8_t q);
extern void tab_display(const char *str);
#endif /* NXT_LCD_H_ */
| 395 |
1,350 | <reponame>Shashi-rk/azure-sdk-for-java
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.azurestack.models;
import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
/** Link with additional information about a product. */
@Fluent
public final class ProductLink {
@JsonIgnore private final ClientLogger logger = new ClientLogger(ProductLink.class);
/*
* The description of the link.
*/
@JsonProperty(value = "displayName")
private String displayName;
/*
* The URI corresponding to the link.
*/
@JsonProperty(value = "uri")
private String uri;
/**
* Get the displayName property: The description of the link.
*
* @return the displayName value.
*/
public String displayName() {
return this.displayName;
}
/**
* Set the displayName property: The description of the link.
*
* @param displayName the displayName value to set.
* @return the ProductLink object itself.
*/
public ProductLink withDisplayName(String displayName) {
this.displayName = displayName;
return this;
}
/**
* Get the uri property: The URI corresponding to the link.
*
* @return the uri value.
*/
public String uri() {
return this.uri;
}
/**
* Set the uri property: The URI corresponding to the link.
*
* @param uri the uri value to set.
* @return the ProductLink object itself.
*/
public ProductLink withUri(String uri) {
this.uri = uri;
return this;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
}
}
| 734 |
1,647 | <reponame>davidbrochart/pythran
#ifndef PYTHONIC_NUMPY_BITWISE_XOR_HPP
#define PYTHONIC_NUMPY_BITWISE_XOR_HPP
#include "pythonic/include/numpy/bitwise_xor.hpp"
#include "pythonic/utils/functor.hpp"
#include "pythonic/types/ndarray.hpp"
#include "pythonic/types/numpy_broadcast.hpp"
#include "pythonic/utils/numpy_traits.hpp"
#include "pythonic/operator_/xor_.hpp"
PYTHONIC_NS_BEGIN
namespace numpy
{
#define NUMPY_NARY_FUNC_NAME bitwise_xor
#define NUMPY_NARY_FUNC_SYM pythonic::operator_::xor_
#include "pythonic/types/numpy_nary_expr.hpp"
}
PYTHONIC_NS_END
#endif
| 265 |
747 | <reponame>andreicovaliov/incubator-sedona
/*
* 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.sedona.core.spatialOperator;
import org.apache.sedona.core.knnJudgement.GeometryDistanceComparator;
import org.apache.sedona.core.knnJudgement.KnnJudgement;
import org.apache.sedona.core.knnJudgement.KnnJudgementUsingIndex;
import org.apache.sedona.core.spatialRDD.SpatialRDD;
import org.apache.sedona.core.utils.CRSTransformation;
import org.apache.spark.api.java.JavaRDD;
import org.locationtech.jts.geom.Geometry;
import java.io.Serializable;
import java.util.List;
// TODO: Auto-generated Javadoc
/**
* The Class KNNQuery.
*/
public class KNNQuery
implements Serializable
{
/**
* Spatial knn query.
*
* @param spatialRDD the spatial RDD
* @param originalQueryPoint the original query window
* @param k the k
* @param useIndex the use index
* @return the list
*/
public static <U extends Geometry, T extends Geometry> List<T> SpatialKnnQuery(SpatialRDD<T> spatialRDD, U originalQueryPoint, Integer k, boolean useIndex)
{
U queryCenter = originalQueryPoint;
if (spatialRDD.getCRStransformation()) {
queryCenter = CRSTransformation.Transform(spatialRDD.getSourceEpsgCode(), spatialRDD.getTargetEpgsgCode(), originalQueryPoint);
}
if (useIndex) {
if (spatialRDD.indexedRawRDD == null) {
throw new NullPointerException("Need to invoke buildIndex() first, indexedRDDNoId is null");
}
JavaRDD<T> tmp = spatialRDD.indexedRawRDD.mapPartitions(new KnnJudgementUsingIndex(queryCenter, k));
List<T> result = tmp.takeOrdered(k, new GeometryDistanceComparator(queryCenter, true));
// Take the top k
return result;
}
else {
JavaRDD<T> tmp = spatialRDD.getRawSpatialRDD().mapPartitions(new KnnJudgement(queryCenter, k));
List<T> result = tmp.takeOrdered(k, new GeometryDistanceComparator(queryCenter, true));
// Take the top k
return result;
}
}
}
| 1,038 |
325 | {
"data": [
{
"quote": "Music doesn’t lie. If there is something to be changed in this world, then it can only happen through music.",
"author": "<NAME>"
},
{
"quote": "When all the original blues guys are gone, you start to realize that someone has to tend to the tradition. I recognize that I have some responsibility to keep the music alive, and it’s a pretty honorable position to be in.",
"author": "<NAME>"
},
{
"quote": "A guitar is like an old friend that is there with me.",
"author": "<NAME>"
},
{
"quote": "To achieve great things, two things are needed; a plan, and not quite enough time.",
"author": "<NAME>"
},
{
"quote": "I am hitting my head against the walls, but the walls are giving way.",
"author": "<NAME>"
},
{
"quote": "I can't understand why people are frightened of new ideas. I'm frightened of the old ones.",
"author": "<NAME>"
},
{
"quote": "Imagination creates reality.",
"author": "<NAME>"
},
{
"quote": "Please, no matter how we advance technologically, please don't abandon the book. There is nothing in our material world more beautiful than the book.",
"author": "<NAME>"
},
{
"quote": "Music is my religion.",
"author": " <NAME>"
},
{
"quote": "There is nothing permanent except change.",
"author": "Heraclitus"
},
{
"quote": "Nothing exists except atoms and empty space; everything else is just opinion.",
"author": "Democritus"
},
{
"quote": "I've missed more than 9000 shots in my career. I've lost almost 300 games. 26 times, I've been trusted to take the game winning shot and missed. I've failed over and over and over again in my life. And that is why I succeed.",
"author": "<NAME>"
},
{
"quote": "Fear is not evil. It tells you what weakness is. And once you know your weakness, you can become stronger as well as kinder.",
"author": "Unknown"
},
{
"quote": "Yesterday is gone. Tomorrow has not yet come. We have only today. Let us begin.",
"author": "<NAME>"
},
{
"quote": "Time is a created thing. To say 'I don't have time,' is like saying, 'I don't want to'.",
"author": "<NAME>"
},
{
"quote": "Life is really simple, but we insist on making it complicated.",
"author": "Confucius"
},
{
"quote": "Simplicity is a great virtue but it requires hard work to achieve it and education to appreciate it. And to make matters worse: complexity sells better.",
"author": "<NAME>"
},
{
"quote": "Happiness in intelligent people is the rarest thing I know.",
"author": " <NAME>"
},
{
"quote": "Happiness is when what you think, what you say, and what you do are in harmony.",
"author": "<NAME>"
},
{
"quote": "Every man has his secret sorrows which the world knows not; and often times we call a man cold when he is only sad.",
"author": "<NAME>"
}
]
} | 1,503 |
472 | <gh_stars>100-1000
""" Implementation of Bubble Sort algorithm
"""
def bubble(array):
""" Bubble sort is a simple sorting algorithm that repeatedly steps
through the list to be sorted, compares each pair of adjacent items and
swaps them if they are in the wrong order. The pass through the list is
repeated until no swaps are needed, which indicates that the list is
sorted.
:param array: list of elements that needs to be sorted
:type array: list
"""
length = len(array)
swapped = True
while swapped:
swapped = False
for i in range(length - 1):
if array[i] > array[i+1]:
array[i], array[i+1] = array[i+1], array[i]
swapped = True
def main():
""" operational function """
arr = [34, 56, 23, 67, 3, 68]
print(f"unsorted array: {arr}")
bubble(arr)
print(f" sorted array: {arr}")
if __name__ == "__main__":
main()
| 353 |
5,169 | <filename>Specs/4/b/4/SmartPenSDK/1.0.0/SmartPenSDK.podspec.json
{
"name": "SmartPenSDK",
"version": "1.0.0",
"summary": "智能手写笔ios ipad Mac 通用SDK",
"description": "SmartPenSDK for gama games developer.SmartPenSDK for gama games developer.",
"homepage": "https://github.com/xiao0227/SmartPenSDK",
"license": {
"type": "MIT",
"file": "LICENSE"
},
"authors": {
"yy": "<EMAIL>"
},
"platforms": {
"ios": "9.0"
},
"source": {
"git": "https://github.com/xiao0227/SmartPenSDK.git",
"tag": "1.0.0"
},
"ios": {
"vendored_frameworks": "SmartPenSDK.framework"
},
"frameworks": "CoreBluetooth",
"requires_arc": true,
"pod_target_xcconfig": {
"VALID_ARCHS": "x86_64 armv7 arm64"
}
}
| 348 |
409 | <gh_stars>100-1000
// Arduino.h includes our String overrides.
#include <Arduino.h>
| 29 |
326 | from .._pydp._partition_selection import (
create_truncated_geometric_partition_strategy, # type: ignore
create_laplace_partition_strategy, # type: ignore
create_gaussian_partition_strategy, # type: ignore
)
__all__ = [
"PartitionSelectionStrategy",
"create_partition_strategy",
"create_truncated_geometric_partition_strategy",
"create_laplace_partition_strategy",
"create_gaussian_partition_strategy",
]
class PartitionSelectionStrategy:
"""
Base class for all (Ɛ, 𝛿)-differenially private partition selection strategies.
"""
def should_keep(self, num_users: int) -> bool:
"""
Decides whether or not to keep a partition with `num_users` based on differential privacy parameters and strategy.
"""
...
def create_partition_strategy(
strategy: str, epsilon: float, delta: float, max_partitions_contributed: int
) -> "PartitionSelectionStrategy":
"""
Creates a :class:`~PartitionSelectionStrategy` instance.
Parameters
--------------
strategy:
One of:
* **'truncated_geomteric'**: creates a `Truncated Geometric <https://arxiv.org/pdf/2006.03684.pdf>`_ Partition Strategy.
* **'laplace'**: creates a private partition strategy with Laplace mechanism.
* **'gaussian'**: creates a private partition strategy with Gaussian mechanism.
epsilon:
The :math:`\\varepsilon` of the partition mechanism
delta:
The :math:`\\delta` of the partition mechanism
max_partitions_contributed:
The maximum amount of partitions contributed by the strategy.
"""
if strategy.lower() == "truncated_geometric":
return create_truncated_geometric_partition_strategy(
epsilon, delta, max_partitions_contributed
)
if strategy.lower() == "laplace":
return create_laplace_partition_strategy(
epsilon, delta, max_partitions_contributed
)
if strategy.lower() == "gaussian":
return create_gaussian_partition_strategy(
epsilon, delta, max_partitions_contributed
)
raise ValueError(f"Strategy '{strategy}' is not supported.")
| 837 |
935 | /*
* Copyright 2019 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.cloud.dataflow.server.config.cloudfoundry;
import java.util.HashMap;
import java.util.Map;
import org.cloudfoundry.reactor.ConnectionContext;
import org.cloudfoundry.reactor.DefaultConnectionContext;
import org.springframework.cloud.deployer.spi.cloudfoundry.CloudFoundryConnectionProperties;
/**
* @author <NAME>ki
**/
public class CloudFoundryPlatformConnectionContextProvider {
private Map<String, ConnectionContext> connectionContexts = new HashMap<>();
private final CloudFoundryPlatformProperties platformProperties;
public CloudFoundryPlatformConnectionContextProvider(
CloudFoundryPlatformProperties platformProperties) {
this.platformProperties = platformProperties;
}
public ConnectionContext connectionContext(String account) {
CloudFoundryConnectionProperties connectionProperties =
this.platformProperties.accountProperties(account).getConnection();
this.connectionContexts.putIfAbsent(account, DefaultConnectionContext.builder()
.apiHost(connectionProperties.getUrl().getHost())
.skipSslValidation(connectionProperties.isSkipSslValidation())
.build());
return connectionContexts.get(account);
}
}
| 484 |
405 | <reponame>zishuimuyu/jeewx<filename>jeewx/src/main/java/weixin/guanjia/core/entity/common/ProgramButton.java
package weixin.guanjia.core.entity.common;
import weixin.guanjia.menu.entity.MenuEntity;
/**
* 小程序button
* @author taoYan
* @since 2018年3月12日
*/
public class ProgramButton extends Button{
private String type;
private String url;
private String appid;
private String pagepath;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getAppid() {
return appid;
}
public void setAppid(String appid) {
this.appid = appid;
}
public String getPagepath() {
return pagepath;
}
public void setPagepath(String pagepath) {
this.pagepath = pagepath;
}
public ProgramButton() {
}
/**
* 构造器
* @param entity
*/
public ProgramButton(MenuEntity entity) {
this.type = entity.getType();
this.url = entity.getUrl();
this.appid = entity.getAppid();
this.pagepath = entity.getPagepath();
setName(entity.getName());
}
}
| 448 |
892 | {
"schema_version": "1.2.0",
"id": "GHSA-jh9h-c6xc-wp2c",
"modified": "2022-05-01T23:40:04Z",
"published": "2022-05-01T23:40:04Z",
"aliases": [
"CVE-2008-1432"
],
"details": "Cross-site scripting (XSS) vulnerability in SolutionSearch.do in ManageEngine SupportCenter Plus 7.0.0 allows remote attackers to inject arbitrary web script or HTML via the searchText parameter, a related issue to CVE-2008-1299. NOTE: the provenance of this information is unknown; the details are obtained solely from third party information.",
"severity": [
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2008-1432"
},
{
"type": "WEB",
"url": "http://secunia.com/advisories/29441"
}
],
"database_specific": {
"cwe_ids": [
"CWE-79"
],
"severity": "MODERATE",
"github_reviewed": false
}
} | 378 |
777 | <gh_stars>100-1000
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CONTENT_RENDERER_MOJO_THREAD_SAFE_ASSOCIATED_INTERFACE_PTR_PROVIDER_H_
#define CONTENT_RENDERER_MOJO_THREAD_SAFE_ASSOCIATED_INTERFACE_PTR_PROVIDER_H_
#include "base/bind.h"
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "ipc/ipc_channel_proxy.h"
#include "mojo/public/cpp/bindings/thread_safe_interface_ptr.h"
namespace content {
// This class provides a way to create ThreadSafeAssociatedInterfacePtr's from
// the main thread that can be used right away (even though the backing
// AssociatedInterfacePtr is created on the IO thread and the channel may not be
// connected yet).
class ThreadSafeAssociatedInterfacePtrProvider {
public:
// Note that this does not take ownership of |channel_proxy|. It's the
// caller responsibility to ensure |channel_proxy| outlives this object.
explicit ThreadSafeAssociatedInterfacePtrProvider(
IPC::ChannelProxy* channel_proxy)
: channel_proxy_(channel_proxy) {}
template <typename Interface>
scoped_refptr<mojo::ThreadSafeAssociatedInterfacePtr<Interface>>
CreateInterfacePtr() {
scoped_refptr<mojo::ThreadSafeAssociatedInterfacePtr<Interface>> ptr =
mojo::ThreadSafeAssociatedInterfacePtr<Interface>::CreateUnbound(
channel_proxy_->ipc_task_runner());
channel_proxy_->RetrieveAssociatedInterfaceOnIOThread<Interface>(base::Bind(
&ThreadSafeAssociatedInterfacePtrProvider::BindInterfacePtr<Interface>,
ptr));
return ptr;
}
private:
template <typename Interface>
static void BindInterfacePtr(
const scoped_refptr<mojo::ThreadSafeAssociatedInterfacePtr<Interface>>&
ptr,
mojo::AssociatedInterfacePtr<Interface> interface_ptr) {
bool success = ptr->Bind(std::move(interface_ptr));
DCHECK(success);
}
IPC::ChannelProxy* channel_proxy_;
DISALLOW_COPY_AND_ASSIGN(ThreadSafeAssociatedInterfacePtrProvider);
};
} // namespace content
#endif // CONTENT_RENDERER_MOJO_THREAD_SAFE_ASSOCIATED_INTERFACE_PTR_PROVIDER_H_ | 715 |
1,616 | import unittest
from pypika import Query, Table
from pypika.pseudocolumns import (
ColumnValue,
ObjectID,
ObjectValue,
RowID,
RowNum,
SysDate,
)
from pypika.terms import PseudoColumn
class PseudoColumnsTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
super(PseudoColumnsTest, cls).setUpClass()
cls.table1 = Table("table1")
def test_column_value(self):
self.assertEqual("COLUMN_VALUE", ColumnValue)
def test_object_id(self):
self.assertEqual("OBJECT_ID", ObjectID)
def test_object_value(self):
self.assertEqual("OBJECT_VALUE", ObjectValue)
def test_row_id(self):
self.assertEqual("ROWID", RowID)
def test_row_num(self):
self.assertEqual("ROWNUM", RowNum)
def test_sys_date(self):
self.assertEqual("SYSDATE", SysDate)
def test_can_be_used_in_a_select_statement(self):
query = Query.from_(self.table1).where(self.table1.is_active == 1).select(PseudoColumn("abcde"))
self.assertEqual(str(query), 'SELECT abcde FROM "table1" WHERE "is_active"=1')
def test_can_be_used_in_a_where_clause(self):
query = Query.from_(self.table1).where(PseudoColumn("abcde") > 1).select(self.table1.is_active)
self.assertEqual(str(query), 'SELECT "is_active" FROM "table1" WHERE abcde>1')
def test_can_be_used_in_orderby(self):
query = Query.from_(self.table1).select(self.table1.abcde.as_("some_name")).orderby(PseudoColumn("some_name"))
self.assertEqual(str(query), 'SELECT "abcde" "some_name" FROM "table1" ORDER BY some_name')
| 686 |
3,301 | package com.alibaba.alink.operator.stream.feature.aggfunc;
import org.apache.flink.table.functions.AggregateFunction;
import com.alibaba.alink.common.sql.builtin.agg.BaseSummaryUdaf.SummaryData;
import com.alibaba.alink.common.sql.builtin.agg.CountUdaf;
import org.junit.Before;
import java.util.ArrayList;
import java.util.List;
public class CountWithExcludeLastTest extends AggFunctionTestBase <Object[], Object, SummaryData> {
@Before
public void init() {
multiInput = true;
}
@Override
protected List <List <Object[]>> getInputValueSets() {
List <List <Object[]>> res = new ArrayList <>();
ArrayList <Object[]> data1 = new ArrayList <>();
res.add((List <Object[]>) data1.clone());
data1.add(new Object[] {1});
res.add((List <Object[]>) data1.clone());
data1.add(new Object[] {4});
res.add(data1);
return res;
}
@Override
protected List <Object> getExpectedResults() {
List <Object> res = new ArrayList <>();
res.add(0L);
res.add(0L);
res.add(1L);
return res;
}
@Override
protected AggregateFunction <Object, SummaryData> getAggregator() {
return new CountUdaf(true);
}
@Override
protected Class <?> getAccClass() {
return SummaryData.class;
}
}
| 441 |
575 | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/modules/webcodecs/gpu_factories_retriever.h"
#include "media/video/gpu_video_accelerator_factories.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread.h"
#include "third_party/blink/renderer/platform/wtf/cross_thread_functional.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"
namespace blink {
namespace {
media::GpuVideoAcceleratorFactories* GetGpuFactoriesOnMainThread() {
DCHECK(IsMainThread());
return Platform::Current()->GetGpuFactories();
}
void RetrieveGpuFactories(OutputCB result_callback) {
if (IsMainThread()) {
std::move(result_callback).Run(GetGpuFactoriesOnMainThread());
return;
}
Thread::MainThread()->GetTaskRunner()->PostTaskAndReplyWithResult(
FROM_HERE,
ConvertToBaseOnceCallback(
CrossThreadBindOnce(&GetGpuFactoriesOnMainThread)),
ConvertToBaseOnceCallback(std::move(result_callback)));
}
void OnSupportKnown(OutputCB result_cb,
media::GpuVideoAcceleratorFactories* factories) {
std::move(result_cb).Run(factories);
}
} // namespace
void RetrieveGpuFactoriesWithKnownEncoderSupport(OutputCB callback) {
auto on_factories_received =
[](OutputCB result_cb, media::GpuVideoAcceleratorFactories* factories) {
if (!factories || factories->IsEncoderSupportKnown()) {
std::move(result_cb).Run(factories);
} else {
factories->NotifyEncoderSupportKnown(ConvertToBaseOnceCallback(
CrossThreadBindOnce(OnSupportKnown, std::move(result_cb),
CrossThreadUnretained(factories))));
}
};
auto factories_callback =
CrossThreadBindOnce(on_factories_received, std::move(callback));
RetrieveGpuFactories(std::move(factories_callback));
}
} // namespace blink
| 757 |
316 | <gh_stars>100-1000
/************************************************************************/
/* */
/* Copyright 2007 by <NAME>, <NAME>, <NAME> */
/* */
/* This file is part of the VIGRA computer vision library. */
/* The VIGRA Website is */
/* http://hci.iwr.uni-heidelberg.de/vigra/ */
/* Please direct questions, bug reports, and contributions to */
/* <EMAIL> or */
/* <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 <iostream>
#include <functional>
#include <cmath>
#include <list>
#include <vigra/unittest.hxx>
#include <vigra/multi_distance.hxx>
#include <vigra/distancetransform.hxx>
#include <vigra/eccentricitytransform.hxx>
#include <vigra/impex.hxx>
#include <vigra/vector_distance.hxx>
#include <vigra/skeleton.hxx>
#include <vigra/timing.hxx>
#include "test_data.hxx"
using namespace vigra;
struct MultiDistanceTest
{
typedef vigra::MultiArray<3,int> IntVolume;
typedef vigra::MultiArray<3,double> DoubleVolume;
typedef vigra::MultiArray<2,double> Double2DArray;
typedef vigra::DImage Image;
typedef vigra::MultiArrayView<2,Image::value_type> ImageView;
typedef vigra::TinyVector<int,3> IntVec;
typedef vigra::MultiArray<3,vigra::TinyVector<int,3> > IntVecVolume;
typedef vigra::MultiArray<3,vigra::TinyVector<double,3> > DoubleVecVolume;
typedef vigra::MultiArray<2,vigra::TinyVector<double,2> > DoubleVecImage;
#if 1
enum { WIDTH = 15, //
HEIGHT = 15, // Volume-Dimensionen
DEPTH = 15}; //
#else
enum { WIDTH = 4, //
HEIGHT = 4, // Volume-Dimensionen
DEPTH = 1}; //
#endif
std::vector<std::vector<IntVec> > pointslists;
std::vector<Image> images;
Double2DArray img2;
DoubleVolume volume;
IntVolume shouldVol;
MultiDistanceTest()
: images(3, Image(7,7)), img2(Double2DArray::difference_type(7,1)),
volume(IntVolume::difference_type(WIDTH,HEIGHT,DEPTH)),
shouldVol(IntVolume::difference_type(WIDTH,HEIGHT,DEPTH))
{
std::vector<IntVec> temp;
temp.push_back(IntVec( 0, 0, 0));
temp.push_back(IntVec(WIDTH-1, 0, 0));
temp.push_back(IntVec( 0, HEIGHT-1, 0));
temp.push_back(IntVec(WIDTH-1, HEIGHT-1, 0));
temp.push_back(IntVec( 0, 0, DEPTH-1));
temp.push_back(IntVec(WIDTH-1, 0, DEPTH-1));
temp.push_back(IntVec( 0, HEIGHT-1, DEPTH-1));
temp.push_back(IntVec(WIDTH-1, HEIGHT-1, DEPTH-1));
pointslists.push_back(temp);
temp.clear();
temp.push_back(IntVec( 0, HEIGHT/2, DEPTH/2));
temp.push_back(IntVec(WIDTH/2, HEIGHT/2, 0));
temp.push_back(IntVec(WIDTH/2, 0, DEPTH/2));
temp.push_back(IntVec(WIDTH-1, HEIGHT/2, DEPTH/2));
temp.push_back(IntVec(WIDTH/2, HEIGHT/2, DEPTH-1));
temp.push_back(IntVec(WIDTH/2, HEIGHT-1, DEPTH/2));
pointslists.push_back(temp);
static const double in[] = {
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
{
Image::ScanOrderIterator i = images[0].begin();
Image::ScanOrderIterator end = images[0].end();
Image::Accessor acc = images[0].accessor();
const double * p = in;
for(; i != end; ++i, ++p)
{
acc.set(*p, i);
}
}
static const unsigned char in2[] = {
1, 0, 0, 0, 0, 0, 1,
1, 0, 0, 0, 0, 0, 1,
1, 0, 0, 0, 0, 0, 1,
1, 0, 0, 0, 0, 0, 1,
1, 0, 0, 0, 0, 0, 1,
1, 0, 0, 0, 0, 0, 1,
1, 0, 0, 0, 0, 0, 1};
{
Image::ScanOrderIterator i = images[1].begin();
Image::ScanOrderIterator end = images[1].end();
Image::Accessor acc = images[1].accessor();
const unsigned char * p = in2;
for(; i != end; ++i, ++p)
{
acc.set(*p, i);
}
}
static const unsigned char in3[] = {
1, 1, 1, 1, 1, 1, 1,
1, 0, 0, 0, 0, 0, 1,
1, 0, 0, 0, 0, 0, 1,
1, 0, 0, 0, 0, 0, 1,
1, 0, 0, 0, 0, 0, 1,
1, 0, 0, 0, 0, 0, 1,
1, 1, 1, 1, 1, 1, 1};
{
Image::ScanOrderIterator i = images[2].begin();
Image::ScanOrderIterator end = images[2].end();
Image::Accessor acc = images[2].accessor();
const unsigned char * p = in3;
for(; i != end; ++i, ++p)
{
acc.set(*p, i);
}
}
static const double in2d[] = {0, 0, 0, 1, 0, 0, 0};
const double * p=in2d;
for(Double2DArray::iterator iter=img2.begin(); iter!=img2.end(); ++iter, ++p){
*iter=*p;
}
}
void testDistanceVolumes()
{
DoubleVolume dt(volume.shape()), desired(volume.shape());
DoubleVecVolume vecDesired(volume.shape());
for(unsigned k = 0; k<pointslists.size(); ++k)
{
DoubleVolume::iterator i = desired.begin();
for(; i.isValid(); ++i)
{
UInt64 minDist = NumericTraits<UInt64>::max();
int nearest = -1;
for(unsigned j=0; j<pointslists[k].size(); ++j)
{
UInt64 dist = squaredNorm(pointslists[k][j] - i.point());
if(dist < minDist)
{
minDist = dist;
nearest = j;
}
}
*i = minDist;
vecDesired[i.point()] = pointslists[k][nearest] - i.point();
}
volume = 0.0;
for(unsigned j=0; j<pointslists[k].size(); ++j)
volume[pointslists[k][j]] = 1;
separableMultiDistSquared(volume, dt, true);
shouldEqualSequence(dt.begin(), dt.end(), desired.begin());
{
//test vectorial distance
using functor::Arg1;
DoubleVecVolume vecVolume(volume.shape());
separableVectorDistance(volume, vecVolume, true);
DoubleVolume distVolume(volume.shape());
transformMultiArray(vecVolume, distVolume, squaredNorm(Arg1()));
shouldEqualSequence(distVolume.begin(), distVolume.end(), desired.begin());
// FIXME: this test fails because the nearest point may be ambiguous
//shouldEqualSequence(vecVolume.begin(), vecVolume.end(), vecDesired.begin());
}
}
typedef MultiArrayShape<3>::type Shape;
MultiArrayView<3, double> vol(Shape(12,10,35), volume_data);
MultiArray<3, double> res(vol.shape());
separableMultiDistSquared(vol, res, false);
shouldEqualSequence(res.data(), res.data()+res.elementCount(), ref_dist2);
{
//test vectorial distance
using functor::Arg1;
DoubleVecVolume vecVolume(vol.shape());
separableVectorDistance(vol, vecVolume, false);
DoubleVolume distVolume(vol.shape());
transformMultiArray(vecVolume, distVolume, squaredNorm(Arg1()));
shouldEqualSequence(distVolume.begin(), distVolume.end(), ref_dist2);
}
}
void testDistanceAxesPermutation()
{
using namespace vigra::functor;
typedef MultiArrayShape<3>::type Shape;
MultiArrayView<3, double> vol(Shape(12,10,35), volume_data);
MultiArray<3, double> res1(vol.shape()), res2(vol.shape());
DoubleVecVolume vecVolume(reverse(vol.shape()));
separableMultiDistSquared(vol, res1, true);
separableMultiDistSquared(vol.transpose(), res2.transpose(), true);
shouldEqualSequence(res1.data(), res1.data()+res1.elementCount(), res2.data());
res2 = 0.0;
separableVectorDistance(vol.transpose(), vecVolume, true);
transformMultiArray(vecVolume, res2.transpose(), squaredNorm(Arg1()));
shouldEqualSequence(res1.data(), res1.data()+res1.elementCount(), res2.data());
separableMultiDistSquared(vol, res1, false);
separableMultiDistSquared(vol.transpose(), res2.transpose(), false);
shouldEqualSequence(res1.data(), res1.data()+res1.elementCount(), res2.data());
res2 = 0.0;
separableVectorDistance(vol.transpose(), vecVolume, false);
transformMultiArray(vecVolume, res2.transpose(), squaredNorm(Arg1()));
shouldEqualSequence(res1.data(), res1.data()+res1.elementCount(), res2.data());
}
void testVectorDistanceBug()
{
MultiArray<3, int> data(Shape3(9,10,2));
data.subarray(Shape3(5,5,1), Shape3(7,7,2)) = 1;
MultiArray<3, TinyVector<int, 3> > res(data.shape());
separableVectorDistance(data, res);
int ref[] = { 5, 4, 3, 2, 1, 0, 0, -1, -2, -3 };
for(MultiCoordinateIterator<3> it(data.shape()); it.isValid(); ++it)
{
shouldEqual(res[*it][0], ref[(*it)[0]]);
shouldEqual(res[*it][1], ref[(*it)[1]]);
shouldEqual(res[*it][2], 1-(*it)[2]);
}
}
void testDistanceVolumesAnisotropic()
{
double epsilon = 1e-14;
TinyVector<double, 3> pixelPitch(1.2, 1.0, 2.4);
DoubleVolume res(volume.shape()), desired(volume.shape());
for(unsigned k = 0; k<pointslists.size(); ++k)
{
DoubleVolume::iterator i = desired.begin();
for(; i.isValid(); ++i)
{
double minDist = NumericTraits<double>::max();
//int nearest = -1;
for(unsigned j=0; j<pointslists[k].size(); ++j)
{
double dist = squaredNorm(pixelPitch*(pointslists[k][j] - i.point()));
if(dist < minDist)
{
minDist = dist;
//nearest = j;
}
}
*i = minDist;
//vecDesired[i.point()] = pointslists[k][nearest] - i.point();
}
volume = 0.0;
for(unsigned j=0; j<pointslists[k].size(); ++j)
volume[pointslists[k][j]] = 1;
separableMultiDistSquared(volume, res, true, pixelPitch);
shouldEqualSequenceTolerance(res.begin(), res.end(), desired.begin(), epsilon);
{
//test vectorial distance
using namespace functor;
DoubleVecVolume vecVolume(volume.shape());
separableVectorDistance(volume, vecVolume, true, pixelPitch);
DoubleVolume distVolume(volume.shape());
transformMultiArray(vecVolume, distVolume, squaredNorm(Param(pixelPitch)*Arg1()));
shouldEqualSequenceTolerance(distVolume.begin(), distVolume.end(), desired.begin(), epsilon);
}
}
}
void distanceTransform2DCompare()
{
for(unsigned int k=0; k<images.size(); ++k)
{
Image res_old(images[k]);
ImageView img_array(Shape2(images[k].width(), images[k].height()), &images[k](0,0));
MultiArray<2, Image::value_type> res_new(img_array.shape());
distanceTransform(srcImageRange(images[k]), destImage(res_old), 0.0, 2);
separableMultiDistance(img_array, res_new, true);
shouldEqualSequenceTolerance(res_new.begin(), res_new.end(), res_old.data(), 1e-7);
DoubleVecImage vec_image(img_array.shape());
separableVectorDistance(img_array, vec_image, true);
MultiArray<2, double> img_array_dist(img_array.shape());
using namespace functor;
transformMultiArray(vec_image, img_array_dist, norm(Arg1()));
shouldEqualSequenceTolerance(img_array_dist.begin(), img_array_dist.end(), res_old.data(), 1e-7);
}
}
void distanceTest1D()
{
vigra::MultiArray<2,double> res(img2);
static const int desired[] = {3, 2, 1, 0, 1, 2, 3};
separableMultiDistance(img2, res, true);
shouldEqualSequence(res.begin(), res.end(), desired);
}
};
struct BoundaryMultiDistanceTest
{
typedef vigra::MultiArray<3,int> IntVolume;
typedef vigra::MultiArray<3,double> DoubleVolume;
typedef vigra::MultiArray<2,double> Double2DArray;
typedef vigra::MultiArray<1,double> Double1DArray;
typedef vigra::DImage Image;
typedef vigra::MultiArrayView<2,Image::value_type> ImageView;
typedef vigra::TinyVector<int,3> IntVec;
#if 1
enum { WIDTH = 50, //
HEIGHT = 50, // Volume-Dimensionen
DEPTH = 1}; //
#else
enum { WIDTH = 4, //
HEIGHT = 4, // Volume-Dimensionen
DEPTH = 1}; //
#endif
std::vector<std::vector<IntVec> > pointslists;
std::vector<Image> images;
Double1DArray img2;
DoubleVolume volume;
IntVolume shouldVol;
BoundaryMultiDistanceTest()
: images(3, Image(7,7)), img2(Shape1(7)),
volume(IntVolume::difference_type(WIDTH,HEIGHT,DEPTH)),
shouldVol(IntVolume::difference_type(WIDTH,HEIGHT,DEPTH))
{
std::vector<IntVec> temp;
temp.push_back(IntVec( 0, 0, 0));
temp.push_back(IntVec(WIDTH-1, 0, 0));
temp.push_back(IntVec( 0, HEIGHT-1, 0));
temp.push_back(IntVec(WIDTH-1, HEIGHT-1, 0));
temp.push_back(IntVec( 0, 0, DEPTH-1));
temp.push_back(IntVec(WIDTH-1, 0, DEPTH-1));
temp.push_back(IntVec( 0, HEIGHT-1, DEPTH-1));
temp.push_back(IntVec(WIDTH-1, HEIGHT-1, DEPTH-1));
pointslists.push_back(temp);
temp.clear();
temp.push_back(IntVec( 0, HEIGHT/2, DEPTH/2));
temp.push_back(IntVec(WIDTH/2, HEIGHT/2, 0));
temp.push_back(IntVec(WIDTH/2, 0, DEPTH/2));
temp.push_back(IntVec(WIDTH-1, HEIGHT/2, DEPTH/2));
temp.push_back(IntVec(WIDTH/2, HEIGHT/2, DEPTH-1));
temp.push_back(IntVec(WIDTH/2, HEIGHT-1, DEPTH/2));
pointslists.push_back(temp);
static const double in[] = {
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
{
Image::ScanOrderIterator i = images[0].begin();
Image::ScanOrderIterator end = images[0].end();
Image::Accessor acc = images[0].accessor();
const double * p = in;
for(; i != end; ++i, ++p)
{
acc.set(*p, i);
}
}
static const unsigned char in2[] = {
1, 0, 0, 0, 0, 0, 1,
1, 0, 0, 0, 0, 0, 1,
1, 0, 0, 0, 0, 0, 1,
1, 0, 0, 0, 0, 0, 1,
1, 0, 0, 0, 0, 0, 1,
1, 0, 0, 0, 0, 0, 1,
1, 0, 0, 0, 0, 0, 1};
{
Image::ScanOrderIterator i = images[1].begin();
Image::ScanOrderIterator end = images[1].end();
Image::Accessor acc = images[1].accessor();
const unsigned char * p = in2;
for(; i != end; ++i, ++p)
{
acc.set(*p, i);
}
}
static const unsigned char in3[] = {
1, 1, 1, 1, 1, 1, 1,
1, 0, 0, 0, 0, 0, 1,
1, 0, 0, 0, 0, 0, 1,
1, 0, 0, 0, 0, 0, 1,
1, 0, 0, 0, 0, 0, 1,
1, 0, 0, 0, 0, 0, 1,
1, 1, 1, 1, 1, 1, 1};
{
Image::ScanOrderIterator i = images[2].begin();
Image::ScanOrderIterator end = images[2].end();
Image::Accessor acc = images[2].accessor();
const unsigned char * p = in3;
for(; i != end; ++i, ++p)
{
acc.set(*p, i);
}
}
static const double in2d[] = {0, 0, 0, 1, 0, 0, 0};
const double * p=in2d;
for(Double1DArray::iterator iter=img2.begin(); iter!=img2.end(); ++iter, ++p){
*iter=*p;
}
}
void testDistanceVolumes()
{
using namespace multi_math;
MultiArrayView<2, double> vol(Shape2(50,50), bndMltDst_data);
MultiArray<2, double> res(vol.shape());
boundaryMultiDistance(vol, res);
shouldEqualSequenceTolerance(res.begin(), res.end(), bndMltDst_ref, 1e-6);
boundaryMultiDistance(vol, res, true);
shouldEqualSequenceTolerance(res.begin(), res.end(), bndMltDstArrayBorder_ref, 1e-6);
MultiArray<2, double> res2(vol.shape());
MultiArray<2, TinyVector<double, 2> > res_vec(vol.shape());
boundaryMultiDistance(vol, res, false, InterpixelBoundary);
boundaryVectorDistance(vol, res_vec, false, InterpixelBoundary);
res2 = norm(res_vec);
shouldEqualSequenceTolerance(res.begin(), res.end(), res2.begin(), 0.25); // FIXME: check this -- 0.25 is a lot
boundaryMultiDistance(vol, res, false, OuterBoundary);
boundaryVectorDistance(vol, res_vec, false, OuterBoundary);
res2 = norm(res_vec);
shouldEqualSequenceTolerance(res.begin(), res.end(), res2.begin(), 1e-15);
boundaryMultiDistance(vol, res, false, InnerBoundary);
boundaryVectorDistance(vol, res_vec, false, InnerBoundary);
res2 = norm(res_vec);
shouldEqualSequenceTolerance(res.begin(), res.end(), res2.begin(), 1e-15);
boundaryMultiDistance(vol, res, true, InterpixelBoundary);
boundaryVectorDistance(vol, res_vec, true, InterpixelBoundary);
res2 = norm(res_vec);
shouldEqualSequenceTolerance(res.begin(), res.end(), res2.begin(), 0.25); // FIXME: check this -- 0.25 is a lot
boundaryMultiDistance(vol, res, true, OuterBoundary);
boundaryVectorDistance(vol, res_vec, true, OuterBoundary);
res2 = norm(res_vec);
shouldEqualSequenceTolerance(res.begin(), res.end(), res2.begin(), 1e-15);
boundaryMultiDistance(vol, res, true, InnerBoundary);
boundaryVectorDistance(vol, res_vec, true, InnerBoundary);
res2 = norm(res_vec);
shouldEqualSequenceTolerance(res.begin(), res.end(), res2.begin(), 1e-15);
// FIXME: add tests for alternative boundary definitions
}
void distanceTest1D()
{
{
// OuterBoundary
Double1DArray res(img2.shape());
static const float desired[] = {3, 2, 1, 1, 1, 2, 3};
boundaryMultiDistance(img2, res, false, OuterBoundary);
shouldEqualSequence(res.begin(), res.end(), desired);
}
{
//InterpixelBoundary
Double1DArray res(img2.shape());
static const float desired[] = {2.5, 1.5, 0.5, 0.5, 0.5, 1.5, 2.5};
boundaryMultiDistance(img2, res);
shouldEqualSequence(res.begin(), res.end(), desired);
}
{
// InnerBoundary
Double1DArray res(img2.shape());
static const float desired[] = {2, 1, 0, 0, 0, 1, 2};
boundaryMultiDistance(img2, res, false, InnerBoundary);
shouldEqualSequence(res.begin(), res.end(), desired);
}
{
//OuterBoundary and image border
Double1DArray res(img2.shape());
static const float desired[] = {1, 2, 1, 1, 1, 2, 1};
boundaryMultiDistance(img2, res, true, OuterBoundary);
shouldEqualSequence(res.begin(), res.end(), desired);
}
{
//InterpixelBoundary and image border
Double1DArray res(img2.shape());
static const float desired[] = {0.5, 1.5, 0.5, 0.5, 0.5, 1.5, 0.5};
boundaryMultiDistance(img2, res, true);
shouldEqualSequence(res.begin(), res.end(), desired);
}
{
//InnerBoundary and image border
Double1DArray res(img2.shape());
static const float desired[] = {0, 1, 0, 0, 0, 1, 0};
boundaryMultiDistance(img2, res, true, InnerBoundary);
shouldEqualSequence(res.begin(), res.end(), desired);
}
}
void vectorDistanceTest1D()
{
typedef TinyVector<double, 1> P;
{
// OuterBoundary
MultiArray<1, P> res(img2.shape());
static const P desired[] = {P(3), P(2), P(1), P(1), P(-1), P(-2), P(-3) };
boundaryVectorDistance(img2, res, false, OuterBoundary);
//for(int k=0; k<7; ++k)
// std::cerr << res[k] << " ";
//std::cerr << "\n";
shouldEqualSequence(res.begin(), res.end(), desired);
}
{
//InterpixelBoundary
MultiArray<1, P> res(img2.shape());
static const P desired[] = {P(2.5), P(1.5), P(0.5), P(-0.5), P(-0.5), P(-1.5), P(-2.5) };
boundaryVectorDistance(img2, res, false, InterpixelBoundary);
shouldEqualSequence(res.begin(), res.end(), desired);
}
{
// InnerBoundary
MultiArray<1, P> res(img2.shape());
static const P desired[] = {P(2), P(1), P(0), P(0), P(0), P(-1), P(-2)};
boundaryVectorDistance(img2, res, false, InnerBoundary);
shouldEqualSequence(res.begin(), res.end(), desired);
}
{
//OuterBoundary and image border
MultiArray<1, P> res(img2.shape());
static const P desired[] = {P(-1), P(2), P(1), P(1), P(-1), P(2), P(1) };
boundaryVectorDistance(img2, res, true, OuterBoundary);
shouldEqualSequence(res.begin(), res.end(), desired);
}
{
//InterpixelBoundary and image border
MultiArray<1, P> res(img2.shape());
static const P desired[] = {P(-0.5), P(1.5), P(0.5), P(-0.5), P(-0.5), P(1.5), P(0.5)};
boundaryVectorDistance(img2, res, true, InterpixelBoundary);
shouldEqualSequence(res.begin(), res.end(), desired);
}
{
//InnerBoundary and image border
MultiArray<1, P> res(img2.shape());
static const P desired[] = {P(0), P(1), P(0), P(0), P(0), P(1), P(0) };
boundaryVectorDistance(img2, res, true, InnerBoundary);
shouldEqualSequence(res.begin(), res.end(), desired);
}
}
};
struct EccentricityTest
{
void testEccentricityCenters()
{
typedef Shape2 Point;
typedef Shape3 Point3;
{
MultiArray<2, int> labels(Shape2(4,2), 1);
labels.subarray(Shape2(2,0), Shape2(4,2)) = 2;
ArrayVector<Point> centers;
MultiArray<2, float> distances(labels.shape());
eccentricityTransformOnLabels(labels, distances, centers);
shouldEqual(centers.size(), 3);
shouldEqual(centers[1], Point(1,1));
shouldEqual(centers[2], Point(3,1));
float ref[] = {1.41421f, 1, 1.41421f, 1, 1, 0, 1, 0 };
shouldEqualSequenceTolerance(distances.begin(), distances.end(), ref, 1e-5f);
}
{
int image_data_small[100] = {
1, 2, 3, 3, 3, 3, 2, 2, 4, 4,
2, 2, 2, 3, 3, 3, 2, 2, 2, 4,
5, 2, 2, 2, 2, 2, 2, 6, 2, 2,
5, 5, 2, 2, 2, 2, 6, 6, 2, 2,
5, 5, 5, 5, 6, 2, 6, 2, 2, 2,
5, 5, 5, 5, 6, 6, 6, 2, 2, 7,
5, 5, 2, 2, 6, 6, 2, 2, 2, 7,
5, 5, 2, 2, 2, 2, 2, 2, 2, 7,
5, 5, 2, 2, 2, 2, 2, 7, 7, 7,
5, 5, 2, 2, 7, 7, 7, 7, 7, 7
};
MultiArrayView<2, int> labels(Shape2(10,10), image_data_small);
ArrayVector<Point> centers;
MultiArray<2, float> distances(labels.shape());
eccentricityTransformOnLabels(labels, distances, centers);
shouldEqual(centers.size(), 8);
Point centers_ref[] = {
Point(0, 0),
Point(8, 2),
Point(3, 1),
Point(9, 1),
Point(1, 5),
Point(6, 4),
Point(8, 8)
};
shouldEqualSequence(centers.begin()+1, centers.end(), centers_ref);
float dist_ref[] = {
0.000000f, 8.656855f, 1.414214f, 1.000000f, 1.414214f, 2.414214f, 2.828427f, 2.414214f, 1.414214f, 1.000000f,
9.242640f, 8.242640f, 7.242641f, 0.000000f, 1.000000f, 2.000000f, 2.414214f, 1.414214f, 1.000000f, 0.000000f,
3.414214f, 7.828427f, 6.828427f, 5.828427f, 4.828427f, 3.828427f, 2.828427f, 2.414214f, 0.000000f, 1.000000f,
2.414214f, 2.000000f, 7.242640f, 6.242640f, 5.242640f, 4.242640f, 1.000000f, 1.414214f, 1.000000f, 1.414214f,
1.414214f, 1.000000f, 1.414214f, 2.414214f, 2.828427f, 5.242640f, 0.000000f, 2.414214f, 2.000000f, 2.414214f,
1.000000f, 0.000000f, 1.000000f, 2.000000f, 2.414214f, 1.414214f, 1.000000f, 3.414214f, 3.000000f, 3.414214f,
1.414214f, 1.000000f, 9.656855f, 8.656855f, 2.828427f, 2.414214f, 4.828427f, 4.414214f, 4.000000f, 2.414214f,
2.414214f, 2.000000f, 9.242641f, 8.242641f, 7.242641f, 6.242641f, 5.828427f, 5.414214f, 5.000000f, 1.414214f,
3.414214f, 3.000000f, 9.656855f, 8.656855f, 7.656855f, 7.242641f, 6.828427f, 1.000000f, 0.000000f, 1.000000f,
4.414214f, 4.000000f, 10.071068f, 9.071068f, 4.414214f, 3.414214f, 2.414214f, 1.414214f, 1.000000f, 1.414214f,
};
shouldEqualSequenceTolerance(distances.begin(), distances.end(), dist_ref, 1e-5f);
}
{
MultiArrayView<2, unsigned int> labels(Shape2(100, 100), eccTrafo_data);
ArrayVector<Point> centers;
MultiArray<2, float> distances(labels.shape());
eccentricityTransformOnLabels(labels, distances, centers);
shouldEqual(centers.size(), 98);
Point centers_ref[98];
for (int i=0; i<98; ++i) {
centers_ref[i] = Point(eccTrafo_centers[2*i], eccTrafo_centers[2*i+1]);
}
shouldEqualSequence(centers.begin(), centers.end(), centers_ref);
shouldEqualSequenceTolerance(distances.begin(), distances.end(), eccTrafo_ref, 1e-5f);
}
{
MultiArrayView<3, unsigned int> labels(Shape3(40, 40, 40), eccTrafo_volume);
ArrayVector<Point3> centers;
MultiArray<3, float> distances(labels.shape());
eccentricityTransformOnLabels(labels, distances, centers);
shouldEqual(centers.size(), 221);
Point3 centers_ref[221];
for (int i=0; i<221; ++i) {
centers_ref[i] = Point3(eccTrafo_volume_centers[3*i], eccTrafo_volume_centers[3*i+1], eccTrafo_volume_centers[3*i+2]);
}
shouldEqualSequence(centers.begin(), centers.end(), centers_ref);
shouldEqualSequenceTolerance(distances.begin(), distances.end(), eccTrafo_volume_ref, 1e-5f);
}
}
};
struct SkeletonTest
{
void testSkeleton()
{
MultiArray<2, UInt8> data;
importImage("blatt.xv", data);
MultiArray<2, UInt8> skel(data.shape());
MultiArray<2, float> desired(data.shape());
//USETICTOC;
{
//TIC;
skeletonizeImage(data, skel,
SkeletonOptions().dontPrune());
//TOC;
//exportImage(skel, "raw_skeleton.tif");
importImage("raw_skeleton.xv", desired);
should(skel == desired);
}
{
MultiArray<2, float> skel(data.shape());
skeletonizeImage(data, skel,
SkeletonOptions().returnLength());
//exportImage(skel, "skeleton_length.tif");
importImage("skeleton_length.xv", desired);
should(skel == desired);
}
{
skeletonizeImage(data, skel,
SkeletonOptions().pruneLength(100.0));
//exportImage(skel, "skeleton_length_greater_100.tif");
importImage("skeleton_length_greater_100.xv", desired);
should(skel == desired);
}
{
skeletonizeImage(data, skel,
SkeletonOptions().pruneLengthRelative(0.5));
//exportImage(skel, "skeleton_length_greater_50_percent.tif");
importImage("skeleton_length_greater_50_percent.xv", desired);
should(skel == desired);
}
{
MultiArray<2, float> skel(data.shape());
skeletonizeImage(data, skel,
SkeletonOptions().returnSalience());
//exportImage(skel, "skeleton_salience.tif");
importImage("skeleton_salience.xv", desired);
should(skel == desired);
}
{
skeletonizeImage(data, skel,
SkeletonOptions().pruneSalience(10.0));
//exportImage(skel, "skeleton_salience_greater_10.tif");
importImage("skeleton_salience_greater_10.xv", desired);
should(skel == desired);
}
{
skeletonizeImage(data, skel,
SkeletonOptions().pruneSalienceRelative(0.6));
//exportImage(skel, "skeleton_salience_greater_60_percent.tif");
importImage("skeleton_salience_greater_60_percent.xv", desired);
should(skel == desired);
}
{
skeletonizeImage(data, skel,
SkeletonOptions().pruneTopology());
//exportImage(skel, "skeleton_topology.tif");
importImage("skeleton_topology.xv", desired);
should(skel == desired);
}
{
skeletonizeImage(data, skel,
SkeletonOptions().pruneTopology(false));
//exportImage(skel, "skeleton_topology_without_center.tif");
importImage("skeleton_topology_without_center.xv", desired);
should(skel == desired);
}
}
void testSkeletonFeatures()
{
MultiArray<2, UInt8> data;
importImage("blatt.xv", data);
ArrayVector<SkeletonFeatures> features;
{
extractSkeletonFeatures(data, features);
int label=255;
shouldEqual(features[label].center, Shape2(255, 255));
shouldEqualTolerance(features[label].diameter, 545.4823227814104, 1e-15);
shouldEqualTolerance(features[label].euclidean_diameter, 501.86551983574248, 1e-15);
shouldEqualTolerance(features[label].total_length, 1650.0012254892786, 1e-15);
shouldEqualTolerance(features[label].average_length, 268.45282570696946, 1e-15);
shouldEqual(features[label].branch_count, 6);
shouldEqual(features[label].hole_count, 1);
shouldEqual(features[label].terminal1, Shape2(133, 472));
shouldEqual(features[label].terminal2, Shape2(378, 34));
}
}
};
struct DistanceTransformTestSuite
: public vigra::test_suite
{
DistanceTransformTestSuite()
: vigra::test_suite("DistanceTransformTestSuite")
{
add( testCase( &MultiDistanceTest::testDistanceVolumes));
add( testCase( &MultiDistanceTest::testVectorDistanceBug));
add( testCase( &MultiDistanceTest::testDistanceAxesPermutation));
add( testCase( &MultiDistanceTest::testDistanceVolumesAnisotropic));
add( testCase( &MultiDistanceTest::distanceTransform2DCompare));
add( testCase( &MultiDistanceTest::distanceTest1D));
add( testCase( &BoundaryMultiDistanceTest::distanceTest1D));
add( testCase( &BoundaryMultiDistanceTest::testDistanceVolumes));
add( testCase( &BoundaryMultiDistanceTest::vectorDistanceTest1D));
add( testCase( &EccentricityTest::testEccentricityCenters));
add( testCase( &SkeletonTest::testSkeleton));
add( testCase( &SkeletonTest::testSkeletonFeatures));
}
};
int main(int argc, char ** argv)
{
DistanceTransformTestSuite test;
int failed = test.run(vigra::testsToBeExecuted(argc, argv));
std::cout << test.report() << std::endl;
return (failed != 0);
}
| 18,330 |
890 | // Copyright (C) <2019> Intel Corporation
//
// SPDX-License-Identifier: Apache-2.0
#include <string>
#include "InternalQuic.h"
using namespace v8;
// Class InternalQuicIn
Persistent<Function> InternalQuicIn::constructor;
InternalQuicIn::InternalQuicIn() {};
InternalQuicIn::~InternalQuicIn() {};
void InternalQuicIn::Init(v8::Local<v8::Object> exports) {
Isolate* isolate = Isolate::GetCurrent();
// Prepare constructor template
Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);
tpl->SetClassName(String::NewFromUtf8(isolate, "InternalQuicIn"));
tpl->InstanceTemplate()->SetInternalFieldCount(1);
// Prototype
NODE_SET_PROTOTYPE_METHOD(tpl, "close", close);
NODE_SET_PROTOTYPE_METHOD(tpl, "getListeningPort", getListeningPort);
NODE_SET_PROTOTYPE_METHOD(tpl, "addDestination", addDestination);
NODE_SET_PROTOTYPE_METHOD(tpl, "removeDestination", removeDestination);
constructor.Reset(isolate, tpl->GetFunction());
exports->Set(String::NewFromUtf8(isolate, "in"), tpl->GetFunction());
}
void InternalQuicIn::New(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
String::Utf8Value param0(args[0]->ToString());
std::string cert_file = std::string(*param0);
String::Utf8Value param1(args[1]->ToString());
std::string key_file = std::string(*param1);
InternalQuicIn* obj = new InternalQuicIn();
obj->me = new QuicIn(cert_file, key_file);
obj->src = obj->me;
obj->Wrap(args.This());
args.GetReturnValue().Set(args.This());
}
void InternalQuicIn::close(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
InternalQuicIn* obj = ObjectWrap::Unwrap<InternalQuicIn>(args.Holder());
delete obj->me;
obj->me = nullptr;
obj->src = nullptr;
obj->src = nullptr;
}
void InternalQuicIn::getListeningPort(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
InternalQuicIn* obj = ObjectWrap::Unwrap<InternalQuicIn>(args.This());
QuicIn* me = obj->me;
uint32_t port = me->getListeningPort();
args.GetReturnValue().Set(Number::New(isolate, port));
}
void InternalQuicIn::addDestination(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
InternalQuicIn* obj = ObjectWrap::Unwrap<InternalQuicIn>(args.Holder());
QuicIn* me = obj->me;
String::Utf8Value param0(args[0]->ToString());
std::string track = std::string(*param0);
FrameDestination* param = ObjectWrap::Unwrap<FrameDestination>(args[1]->ToObject());
owt_base::FrameDestination* dest = param->dest;
if (track == "audio") {
me->addAudioDestination(dest);
} else if (track == "video") {
me->addVideoDestination(dest);
}
}
void InternalQuicIn::removeDestination(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
InternalQuicIn* obj = ObjectWrap::Unwrap<InternalQuicIn>(args.Holder());
QuicIn* me = obj->me;
String::Utf8Value param0(args[0]->ToString());
std::string track = std::string(*param0);
FrameDestination* param = ObjectWrap::Unwrap<FrameDestination>(args[1]->ToObject());
owt_base::FrameDestination* dest = param->dest;
if (track == "audio") {
me->removeAudioDestination(dest);
} else if (track == "video") {
me->removeVideoDestination(dest);
}
}
// Class InternalQuicOut
Persistent<Function> InternalQuicOut::constructor;
InternalQuicOut::InternalQuicOut() {};
InternalQuicOut::~InternalQuicOut() {};
void InternalQuicOut::Init(v8::Local<v8::Object> exports) {
Isolate* isolate = Isolate::GetCurrent();
// Prepare constructor template
Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);
tpl->SetClassName(String::NewFromUtf8(isolate, "InternalQuicOut"));
tpl->InstanceTemplate()->SetInternalFieldCount(1);
// Prototype
NODE_SET_PROTOTYPE_METHOD(tpl, "close", close);
constructor.Reset(isolate, tpl->GetFunction());
exports->Set(String::NewFromUtf8(isolate, "out"), tpl->GetFunction());
}
void InternalQuicOut::New(const v8::FunctionCallbackInfo<v8::Value>& args) {
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
String::Utf8Value param0(args[0]->ToString());
std::string ip = std::string(*param0);
int port = args[1]->Uint32Value();
InternalQuicOut* obj = new InternalQuicOut();
obj->me = new QuicOut(ip, port);
obj->dest = obj->me;
obj->Wrap(args.This());
args.GetReturnValue().Set(args.This());
}
void InternalQuicOut::close(const v8::FunctionCallbackInfo<v8::Value>& args) {
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
InternalQuicOut* obj = ObjectWrap::Unwrap<InternalQuicOut>(args.Holder());
delete obj->me;
obj->me = nullptr;
obj->dest = nullptr;
}
| 1,685 |
852 | import FWCore.ParameterSet.Config as cms
Cascade2Parameters = cms.PSet(
parameterSets = cms.vstring('CascadeSettings'),
CascadeSettings = cms.vstring('NCB = 50000 ! number of calls per iteration for bases',
'ACC1 = 1.0 ! relative precision for grid optimisation',
'ACC2 = 0.5 ! relative precision for integration',
'KE = 2212 ! flavour code of beam1',
'IRES(1) = 1 ! direct or resolved particle 1',
'KP = 2212 ! flavour code of beam2',
'IRES(2) = 1 ! direct or resolved particle 2',
'NFLAV = 5 ! number of active flavors',
'IPRO = 10 ! hard subprocess number',
'IRPA = 1 ! IPRO = 10, switch to select QCD process g* g* -> q qbar',
'IRPB = 1 ! IPRO = 10, switch to select QCD process g* g -> g g',
'IRPC = 1 ! IPRO = 10, switch to select QCD process g* q -> g q',
'IHFLA = 4 ! flavor of heavy quark produced (IPRO = 11, 504, 514)',
# 'I23S = 0 ! select vector meson state (0 = 1S, 2 = 2S, 3 = 3S from version 2.2.03 on)',
'IPSIPOL = 0 ! use matrix element including J/psi (Upsilon) polarisation (1 = on, 0 = off)',
'PT2CUT = 0.0 ! pt2 cut in ME for massless partons'
'NFRAG = 1 ! switch for fragmentation (1 = on, 0 = off)',
'IFPS = 3 ! switch for parton shower: (0 = off - 1 = initial - 2 = final - 3 = initial & final)',
'ITIMSHR = 1 ! switch for time like parton shower in intial state (0 = off,1 = on)',
'ICCFM = 1 ! select CCFM or DGLAP evolution (CCFM = 1, DGLAP = 0)'
'IFINAL = 1 ! scale switch for final state parton shower',
'SCALFAF = 1.0 ! scale factor for final state parton shower',
'IRspl = 4 ! switch for proton remnant treatment',
'IPST = 0 ! keep track of intermediate state in parton shower ',
'INTER = 0 ! mode of interaction for ep (photon exchange, Z-echange (not implemented))',
'IRUNAEM = 1 ! switch for running alphaem (0 = off,1 = on)',
'IRUNA = 1 ! switch for running alphas (0 = off,1 = on)',
'IQ2 = 3 ! scale in alphas',
'SCALFA = 1.0 ! scale factor for scale in alphas',
'IGLU = 1010 ! select uPDF'))
| 1,756 |
3,603 | <reponame>WeDoSoftware/trino
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.trino.operator.aggregation;
import com.google.common.collect.ImmutableList;
import io.trino.spi.type.LongTimestamp;
import io.trino.spi.type.TimestampType;
import io.trino.spi.type.Type;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
public class TestApproximateSetGenericLongTimestamp
extends AbstractTestApproximateSetGeneric
{
@Override
protected Type getValueType()
{
return TimestampType.createTimestampType(9);
}
@Override
protected Object randomValue()
{
return new LongTimestamp(ThreadLocalRandom.current().nextLong(), ThreadLocalRandom.current().nextInt(1000));
}
@Override
protected List<Object> getResultStabilityTestSample()
{
return ImmutableList.of(
new LongTimestamp(0, 0),
new LongTimestamp(1000, 4434),
new LongTimestamp(3323232332L, 343443),
new LongTimestamp(43434, 4343),
new LongTimestamp(2, 10),
new LongTimestamp(60, 545));
}
@Override
protected String getResultStabilityExpected()
{
// This value should not be changed; it is used to test result stability for $approx_set
// Result stability is important because a produced value can be persisted by a connector.
return "020C060026000000C0FB0651C2B3EE6640E0727B0138E2D1034E9CF2";
}
}
| 722 |
418 | <gh_stars>100-1000
/*
* Copyright (c) 2015 <NAME> (gfx).
*
* 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.github.gfx.android.orma;
import com.github.gfx.android.orma.annotation.OnConflict;
import com.github.gfx.android.orma.core.Database;
import com.github.gfx.android.orma.core.DatabaseStatement;
import com.github.gfx.android.orma.event.DataSetChangedEvent;
import com.github.gfx.android.orma.exception.InsertionFailureException;
import androidx.annotation.NonNull;
import java.io.Closeable;
import java.util.concurrent.Callable;
/**
* Represents a prepared statement to insert models in batch.
*/
public class Inserter<Model> implements Closeable {
final OrmaConnection conn;
final Schema<Model> schema;
final boolean withoutAutoId;
final DatabaseStatement statement;
final String sql;
public Inserter(OrmaConnection conn, Schema<Model> schema, @OnConflict int onConflictAlgorithm, boolean withoutAutoId) {
Database db = conn.getWritableDatabase();
this.conn = conn;
this.schema = schema;
this.withoutAutoId = withoutAutoId;
sql = schema.getInsertStatement(onConflictAlgorithm, withoutAutoId);
statement = db.compileStatement(sql);
}
public Inserter(OrmaConnection conn, Schema<Model> schema) {
this(conn, schema, OnConflict.NONE, true);
}
/**
* <p>Inserts {@code model} into a table. This method does not modify the {@code model} even if a new row id is given to
* it.</p>
*
* @param model a model object to insert
* @return The last inserted row id. {@code -1} for failure (e.g. constraint violations).
*/
public long execute(@NonNull Model model) {
if (conn.trace) {
conn.trace(sql, schema.convertToArgs(conn, model, withoutAutoId));
}
schema.bindArgs(conn, statement, model, withoutAutoId);
long rowId = statement.executeInsert();
conn.trigger(DataSetChangedEvent.Type.INSERT, schema);
return rowId;
}
/**
* @param modelFactory A mode factory to create a model object to insert
* @return The last inserted row id
*/
public long execute(@NonNull Callable<Model> modelFactory) {
try {
return execute(modelFactory.call());
} catch (Exception e) {
throw new InsertionFailureException(e);
}
}
public void executeAll(@NonNull Iterable<Model> models) {
for (Model model : models) {
execute(model);
}
}
/**
* Does {@link #execute(Object)} and then does {@link #close()} immediately
*
* @param model A model to insert
* @return A last-inserted row id
*/
public long executeAndClose(@NonNull Model model) {
try {
return execute(model);
} finally {
close();
}
}
@Override
public void close() {
statement.close();
}
}
| 1,259 |
1,615 | /**
* Created by MomoLuaNative.
* Copyright (c) 2020, Momo Group. All rights reserved.
*
* This source code is licensed under the MIT.
* For the full copyright and license information,please view the LICENSE file in the root directory of this source tree.
*/
//
// Created by Generator on 2020-10-16
//
#include <jni.h>
#include "lauxlib.h"
#include "cache.h"
#include "statistics.h"
#include "jinfo.h"
#include "jtable.h"
#include "juserdata.h"
#include "m_mem.h"
#define PRE if (!lua_isuserdata(L, 1)) { \
lua_pushstring(L, "use ':' instead of '.' to call method!!");\
lua_error(L); \
return 1; \
} \
JNIEnv *env; \
getEnv(&env); \
UDjavaobject ud = (UDjavaobject) lua_touserdata(L, 1); \
jobject jobj = getUserdata(env, L, ud); \
if (!jobj) { \
lua_pushfstring(L, "get java object from java failed, id: %d", ud->id); \
lua_error(L); \
return 1; \
}
#define REMOVE_TOP(L) while (lua_gettop(L) > 0 && lua_isnil(L, -1)) lua_pop(L, 1);
static inline void push_number(lua_State *L, jdouble num) {
lua_Integer li1 = (lua_Integer) num;
if (li1 == num) {
lua_pushinteger(L, li1);
} else {
lua_pushnumber(L, num);
}
}
static inline void push_string(JNIEnv *env, lua_State *L, jstring s) {
const char *str = GetString(env, s);
if (str)
lua_pushstring(L, str);
else
lua_pushnil(L);
ReleaseChar(env, s, str);
}
static inline void dumpParams(lua_State *L, int from) {
const int SIZE = 100;
const int MAX = SIZE - 4;
char type[SIZE] = {0};
int top = lua_gettop(L);
int i;
int idx = 0;
for (i = from; i <= top; ++i) {
const char *n = lua_typename(L, lua_type(L, i));
size_t len = strlen(n);
if (len + idx >= MAX) {
memcpy(type + idx, "...", 3);
break;
}
if (i != from) {
type[idx ++] = ',';
}
memcpy(type + idx, n, len);
idx += len;
}
lua_pushstring(L, type);
}
#ifdef STATISTIC_PERFORMANCE
#include <time.h>
#define _get_milli_second(t) ((t)->tv_sec*1000.0 + (t)->tv_usec / 1000.0)
#endif
#define LUA_CLASS_NAME "InteractiveBehavior"
#define META_NAME METATABLE_PREFIX "" LUA_CLASS_NAME
static jclass _globalClass;
static jmethodID _constructor0;
//<editor-fold desc="method definition">
static jmethodID setDirectionID;
static jmethodID getDirectionID;
static int _direction(lua_State *L);
static jmethodID setEndDistanceID;
static jmethodID getEndDistanceID;
static int _endDistance(lua_State *L);
static jmethodID setOverBoundaryID;
static jmethodID isOverBoundaryID;
static int _overBoundary(lua_State *L);
static jmethodID setEnableID;
static jmethodID isEnableID;
static int _enable(lua_State *L);
static jmethodID setFollowEnableID;
static jmethodID isFollowEnableID;
static int _followEnable(lua_State *L);
static jmethodID touchBlockID;
static int _touchBlock(lua_State *L);
static jmethodID targetViewID;
static int _targetView(lua_State *L);
//</editor-fold>
/**
* -1: metatable
*/
static void fillUDMetatable(lua_State *L, const char *parentMeta) {
static const luaL_Reg _methohds[] = {
{"direction", _direction},
{"endDistance", _endDistance},
{"overBoundary", _overBoundary},
{"enable", _enable},
{"followEnable", _followEnable},
{"touchBlock", _touchBlock},
{"targetView", _targetView},
{NULL, NULL}
};
const luaL_Reg *lib = _methohds;
for (; lib->func; lib++) {
lua_pushstring(L, lib->name);
lua_pushcfunction(L, lib->func);
lua_rawset(L, -3);
}
if (parentMeta) {
JNIEnv *env;
getEnv(&env);
setParentMetatable(env, L, parentMeta);
}
}
static int _execute_new_ud(lua_State *L);
static int _new_java_obj(JNIEnv *env, lua_State *L);
//<editor-fold desc="JNI methods">
#define JNIMETHODDEFILE(s) Java_com_immomo_mmui_ud_anim_InteractiveBehavior_ ## s
/**
* java层需要初始化的class静态调用
* 初始化各种jmethodID
*/
JNIEXPORT void JNICALL JNIMETHODDEFILE(_1init)
(JNIEnv *env, jclass clz) {
_globalClass = GLOBAL(env, clz);
_constructor0 = (*env)->GetMethodID(env, clz, JAVA_CONSTRUCTOR, "(J)V");
setDirectionID = (*env)->GetMethodID(env, clz, "setDirection", "(I)V");
getDirectionID = (*env)->GetMethodID(env, clz, "getDirection", "()I");
setEndDistanceID = (*env)->GetMethodID(env, clz, "setEndDistance", "(D)V");
getEndDistanceID = (*env)->GetMethodID(env, clz, "getEndDistance", "()D");
setOverBoundaryID = (*env)->GetMethodID(env, clz, "setOverBoundary", "(Z)V");
isOverBoundaryID = (*env)->GetMethodID(env, clz, "isOverBoundary", "()Z");
setEnableID = (*env)->GetMethodID(env, clz, "setEnable", "(Z)V");
isEnableID = (*env)->GetMethodID(env, clz, "isEnable", "()Z");
setFollowEnableID = (*env)->GetMethodID(env, clz, "setFollowEnable", "(Z)V");
isFollowEnableID = (*env)->GetMethodID(env, clz, "isFollowEnable", "()Z");
touchBlockID = (*env)->GetMethodID(env, clz, "touchBlock", "(J)V");
targetViewID = (*env)->GetMethodID(env, clz, "targetView", "(Lcom/immomo/mmui/ud/UDView;)V");
}
/**
* java层需要将此ud注册到虚拟机里
* @param l 虚拟机
* @param parent 父类,可为空
*/
JNIEXPORT void JNICALL JNIMETHODDEFILE(_1register)
(JNIEnv *env, jclass o, jlong l, jstring parent) {
lua_State *L = (lua_State *)l;
u_newmetatable(L, META_NAME);
/// get metatable.__index
lua_pushstring(L, LUA_INDEX);
lua_rawget(L, -2);
/// 未初始化过,创建并设置metatable.__index
if (!lua_istable(L, -1)) {
lua_pop(L, 1);
lua_pushvalue(L, -1);
lua_pushstring(L, LUA_INDEX);
lua_pushvalue(L, -2);
/// -1:nt -2:__index -3:nt -4:mt
/// mt.__index=nt
lua_rawset(L, -4);
}
/// -1:nt -2: metatable
const char *luaParent = GetString(env, parent);
if (luaParent) {
char *parentMeta = getUDMetaname(luaParent);
fillUDMetatable(L, parentMeta);
#if defined(J_API_INFO)
m_malloc(parentMeta, (strlen(parentMeta) + 1) * sizeof(char), 0);
#else
free(parentMeta);
#endif
ReleaseChar(env, parent, luaParent);
} else {
fillUDMetatable(L, NULL);
}
jclass clz = _globalClass;
/// 设置gc方法
pushUserdataGcClosure(env, L, clz);
/// 设置需要返回bool的方法,比如__eq
pushUserdataBoolClosure(env, L, clz);
/// 设置__tostring
pushUserdataTostringClosure(env, L, clz);
lua_pop(L, 2);
lua_pushcfunction(L, _execute_new_ud);
lua_setglobal(L, LUA_CLASS_NAME);
}
//</editor-fold>
//<editor-fold desc="lua method implementation">
/**
* int getDirection()
* void setDirection(int)
*/
static int _direction(lua_State *L) {
#ifdef STATISTIC_PERFORMANCE
struct timeval start = {0};
struct timeval end = {0};
gettimeofday(&start, NULL);
#endif
PRE
if (lua_gettop(L) == 1) {
jint ret = (*env)->CallIntMethod(env, jobj, getDirectionID);
if (catchJavaException(env, L, LUA_CLASS_NAME ".getDirection")) {
return lua_error(L);
}
lua_pushinteger(L, (lua_Integer) ret);
#ifdef STATISTIC_PERFORMANCE
gettimeofday(&end, NULL);
userdataMethodCall(ud->name + strlen(METATABLE_PREFIX), "getDirection", _get_milli_second(&end) - _get_milli_second(&start));
#endif
return 1;
}
lua_Integer p1 = luaL_checkinteger(L, 2);
(*env)->CallVoidMethod(env, jobj, setDirectionID, (jint)p1);
if (catchJavaException(env, L, LUA_CLASS_NAME ".setDirection")) {
return lua_error(L);
}
lua_settop(L, 1);
#ifdef STATISTIC_PERFORMANCE
gettimeofday(&end, NULL);
userdataMethodCall(ud->name + strlen(METATABLE_PREFIX), "setDirection", _get_milli_second(&end) - _get_milli_second(&start));
#endif
return 1;
}
/**
* double getEndDistance()
* void setEndDistance(double)
*/
static int _endDistance(lua_State *L) {
#ifdef STATISTIC_PERFORMANCE
struct timeval start = {0};
struct timeval end = {0};
gettimeofday(&start, NULL);
#endif
PRE
if (lua_gettop(L) == 1) {
jdouble ret = (*env)->CallDoubleMethod(env, jobj, getEndDistanceID);
if (catchJavaException(env, L, LUA_CLASS_NAME ".getEndDistance")) {
return lua_error(L);
}
push_number(L, (jdouble) ret);
#ifdef STATISTIC_PERFORMANCE
gettimeofday(&end, NULL);
userdataMethodCall(ud->name + strlen(METATABLE_PREFIX), "getEndDistance", _get_milli_second(&end) - _get_milli_second(&start));
#endif
return 1;
}
lua_Number p1 = luaL_checknumber(L, 2);
(*env)->CallVoidMethod(env, jobj, setEndDistanceID, (jdouble)p1);
if (catchJavaException(env, L, LUA_CLASS_NAME ".setEndDistance")) {
return lua_error(L);
}
lua_settop(L, 1);
#ifdef STATISTIC_PERFORMANCE
gettimeofday(&end, NULL);
userdataMethodCall(ud->name + strlen(METATABLE_PREFIX), "setEndDistance", _get_milli_second(&end) - _get_milli_second(&start));
#endif
return 1;
}
/**
* boolean isOverBoundary()
* void setOverBoundary(boolean)
*/
static int _overBoundary(lua_State *L) {
#ifdef STATISTIC_PERFORMANCE
struct timeval start = {0};
struct timeval end = {0};
gettimeofday(&start, NULL);
#endif
PRE
if (lua_gettop(L) == 1) {
jboolean ret = (*env)->CallBooleanMethod(env, jobj, isOverBoundaryID);
if (catchJavaException(env, L, LUA_CLASS_NAME ".isOverBoundary")) {
return lua_error(L);
}
lua_pushboolean(L, (int) ret);
#ifdef STATISTIC_PERFORMANCE
gettimeofday(&end, NULL);
userdataMethodCall(ud->name + strlen(METATABLE_PREFIX), "isOverBoundary", _get_milli_second(&end) - _get_milli_second(&start));
#endif
return 1;
}
int p1 = lua_toboolean(L, 2);
(*env)->CallVoidMethod(env, jobj, setOverBoundaryID, (jboolean)p1);
if (catchJavaException(env, L, LUA_CLASS_NAME ".setOverBoundary")) {
return lua_error(L);
}
lua_settop(L, 1);
#ifdef STATISTIC_PERFORMANCE
gettimeofday(&end, NULL);
userdataMethodCall(ud->name + strlen(METATABLE_PREFIX), "setOverBoundary", _get_milli_second(&end) - _get_milli_second(&start));
#endif
return 1;
}
/**
* boolean isEnable()
* void setEnable(boolean)
*/
static int _enable(lua_State *L) {
#ifdef STATISTIC_PERFORMANCE
struct timeval start = {0};
struct timeval end = {0};
gettimeofday(&start, NULL);
#endif
PRE
if (lua_gettop(L) == 1) {
jboolean ret = (*env)->CallBooleanMethod(env, jobj, isEnableID);
if (catchJavaException(env, L, LUA_CLASS_NAME ".isEnable")) {
return lua_error(L);
}
lua_pushboolean(L, (int) ret);
#ifdef STATISTIC_PERFORMANCE
gettimeofday(&end, NULL);
userdataMethodCall(ud->name + strlen(METATABLE_PREFIX), "isEnable", _get_milli_second(&end) - _get_milli_second(&start));
#endif
return 1;
}
int p1 = lua_toboolean(L, 2);
(*env)->CallVoidMethod(env, jobj, setEnableID, (jboolean)p1);
if (catchJavaException(env, L, LUA_CLASS_NAME ".setEnable")) {
return lua_error(L);
}
lua_settop(L, 1);
#ifdef STATISTIC_PERFORMANCE
gettimeofday(&end, NULL);
userdataMethodCall(ud->name + strlen(METATABLE_PREFIX), "setEnable", _get_milli_second(&end) - _get_milli_second(&start));
#endif
return 1;
}
/**
* boolean isFollowEnable()
* void setFollowEnable(boolean)
*/
static int _followEnable(lua_State *L) {
#ifdef STATISTIC_PERFORMANCE
struct timeval start = {0};
struct timeval end = {0};
gettimeofday(&start, NULL);
#endif
PRE
if (lua_gettop(L) == 1) {
jboolean ret = (*env)->CallBooleanMethod(env, jobj, isFollowEnableID);
if (catchJavaException(env, L, LUA_CLASS_NAME ".isFollowEnable")) {
return lua_error(L);
}
lua_pushboolean(L, (int) ret);
#ifdef STATISTIC_PERFORMANCE
gettimeofday(&end, NULL);
userdataMethodCall(ud->name + strlen(METATABLE_PREFIX), "isFollowEnable", _get_milli_second(&end) - _get_milli_second(&start));
#endif
return 1;
}
int p1 = lua_toboolean(L, 2);
(*env)->CallVoidMethod(env, jobj, setFollowEnableID, (jboolean)p1);
if (catchJavaException(env, L, LUA_CLASS_NAME ".setFollowEnable")) {
return lua_error(L);
}
lua_settop(L, 1);
#ifdef STATISTIC_PERFORMANCE
gettimeofday(&end, NULL);
userdataMethodCall(ud->name + strlen(METATABLE_PREFIX), "setFollowEnable", _get_milli_second(&end) - _get_milli_second(&start));
#endif
return 1;
}
/**
* void touchBlock(long)
*/
static int _touchBlock(lua_State *L) {
#ifdef STATISTIC_PERFORMANCE
struct timeval start = {0};
struct timeval end = {0};
gettimeofday(&start, NULL);
#endif
PRE
luaL_checktype(L, 2, LUA_TFUNCTION);
jlong p1 = (jlong) copyValueToGNV(L, 2);
(*env)->CallVoidMethod(env, jobj, touchBlockID, p1);
if (catchJavaException(env, L, LUA_CLASS_NAME ".touchBlock")) {
return lua_error(L);
}
lua_settop(L, 1);
#ifdef STATISTIC_PERFORMANCE
gettimeofday(&end, NULL);
userdataMethodCall(ud->name + strlen(METATABLE_PREFIX), "touchBlock", _get_milli_second(&end) - _get_milli_second(&start));
#endif
return 1;
}
/**
* void targetView(com.immomo.mmui.ud.UDView)
*/
static int _targetView(lua_State *L) {
#ifdef STATISTIC_PERFORMANCE
struct timeval start = {0};
struct timeval end = {0};
gettimeofday(&start, NULL);
#endif
PRE
jobject p1 = lua_isnil(L, 2) ? NULL : toJavaValue(env, L, 2);
(*env)->CallVoidMethod(env, jobj, targetViewID, p1);
if (catchJavaException(env, L, LUA_CLASS_NAME ".targetView")) {
FREE(env, p1);
return lua_error(L);
}
FREE(env, p1);
lua_settop(L, 1);
#ifdef STATISTIC_PERFORMANCE
gettimeofday(&end, NULL);
userdataMethodCall(ud->name + strlen(METATABLE_PREFIX), "targetView", _get_milli_second(&end) - _get_milli_second(&start));
#endif
return 1;
}
//</editor-fold>
static int _execute_new_ud(lua_State *L) {
#ifdef STATISTIC_PERFORMANCE
struct timeval start = {0};
struct timeval end = {0};
gettimeofday(&start, NULL);
#endif
JNIEnv *env;
int need = getEnv(&env);
if (_new_java_obj(env, L)) {
if (need) detachEnv();
lua_error(L);
return 1;
}
luaL_getmetatable(L, META_NAME);
lua_setmetatable(L, -2);
if (need) detachEnv();
#ifdef STATISTIC_PERFORMANCE
gettimeofday(&end, NULL);
double offset = _get_milli_second(&end) - _get_milli_second(&start);
userdataMethodCall(LUA_CLASS_NAME, InitMethodName, offset);
#endif
return 1;
}
static int _new_java_obj(JNIEnv *env, lua_State *L) {
jobject javaObj = NULL;
javaObj = (*env)->NewObject(env, _globalClass, _constructor0, (jlong) L);
char *info = joinstr(LUA_CLASS_NAME, InitMethodName);
if (catchJavaException(env, L, info)) {
if (info)
m_malloc(info, sizeof(char) * (1 + strlen(info)), 0);
FREE(env, javaObj);
return 1;
}
if (info)
m_malloc(info, sizeof(char) * (1 + strlen(info)), 0);
UDjavaobject ud = (UDjavaobject) lua_newuserdata(L, sizeof(javaUserdata));
ud->id = getUserdataId(env, javaObj);
if (isStrongUserdata(env, _globalClass)) {
setUDFlag(ud, JUD_FLAG_STRONG);
copyUDToGNV(env, L, ud, -1, javaObj);
}
FREE(env, javaObj);
ud->refCount = 0;
ud->name = lua_pushstring(L, META_NAME);
lua_pop(L, 1);
return 0;
} | 7,515 |
777 | <reponame>google-ar/chromium<filename>content/browser/media/capture/window_activity_tracker_aura.h
// Copyright (c) 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CONTENT_BROWSER_MEDIA_CAPTURE_WINDOW_ACTIVITY_TRACKER_AURA_H_
#define CONTENT_BROWSER_MEDIA_CAPTURE_WINDOW_ACTIVITY_TRACKER_AURA_H_
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "base/memory/weak_ptr.h"
#include "content/browser/media/capture/window_activity_tracker.h"
#include "content/common/content_export.h"
#include "ui/aura/window.h"
#include "ui/events/event_handler.h"
namespace content {
// Tracks UI events and makes a decision on whether the user has been
// actively interacting with a specified window.
class CONTENT_EXPORT WindowActivityTrackerAura : public WindowActivityTracker,
public ui::EventHandler,
public aura::WindowObserver {
public:
explicit WindowActivityTrackerAura(aura::Window* window);
~WindowActivityTrackerAura() final;
base::WeakPtr<WindowActivityTracker> GetWeakPtr() final;
private:
// ui::EventHandler overrides.
void OnEvent(ui::Event* event) final;
// aura::WindowObserver overrides.
void OnWindowDestroying(aura::Window* window) final;
aura::Window* window_;
base::WeakPtrFactory<WindowActivityTrackerAura> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(WindowActivityTrackerAura);
};
} // namespace content
#endif // CONTENT_BROWSER_MEDIA_CAPTURE_WINDOW_ACTIVITY_TRACKER_AURA_H_
| 607 |
4,047 | #!/usr/bin/env python3
import shutil, sys
if __name__ == '__main__':
shutil.copyfile(sys.argv[1], sys.argv[2])
| 53 |
416 | /*
* Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencentcloudapi.cwp.v20180228.models;
import com.tencentcloudapi.common.AbstractModel;
import com.google.gson.annotations.SerializedName;
import com.google.gson.annotations.Expose;
import java.util.HashMap;
public class ProtectDirRelatedServer extends AbstractModel{
/**
* 唯一ID
*/
@SerializedName("Id")
@Expose
private String Id;
/**
* 服务器名称
*/
@SerializedName("HostName")
@Expose
private String HostName;
/**
* 服务器IP
*/
@SerializedName("HostIp")
@Expose
private String HostIp;
/**
* 服务器系统
*/
@SerializedName("MachineOs")
@Expose
private String MachineOs;
/**
* 关联目录数
*/
@SerializedName("RelateDirNum")
@Expose
private Long RelateDirNum;
/**
* 防护状态
*/
@SerializedName("ProtectStatus")
@Expose
private Long ProtectStatus;
/**
* 防护开关
*/
@SerializedName("ProtectSwitch")
@Expose
private Long ProtectSwitch;
/**
* 自动恢复开关
*/
@SerializedName("AutoRestoreSwitchStatus")
@Expose
private Long AutoRestoreSwitchStatus;
/**
* 服务器唯一ID
*/
@SerializedName("Quuid")
@Expose
private String Quuid;
/**
* 是否已经授权
*/
@SerializedName("Authorization")
@Expose
private Boolean Authorization;
/**
* 异常状态
*/
@SerializedName("Exception")
@Expose
private Long Exception;
/**
* 过渡进度
*/
@SerializedName("Progress")
@Expose
private Long Progress;
/**
* 异常信息
*/
@SerializedName("ExceptionMessage")
@Expose
private String ExceptionMessage;
/**
* Get 唯一ID
* @return Id 唯一ID
*/
public String getId() {
return this.Id;
}
/**
* Set 唯一ID
* @param Id 唯一ID
*/
public void setId(String Id) {
this.Id = Id;
}
/**
* Get 服务器名称
* @return HostName 服务器名称
*/
public String getHostName() {
return this.HostName;
}
/**
* Set 服务器名称
* @param HostName 服务器名称
*/
public void setHostName(String HostName) {
this.HostName = HostName;
}
/**
* Get 服务器IP
* @return HostIp 服务器IP
*/
public String getHostIp() {
return this.HostIp;
}
/**
* Set 服务器IP
* @param HostIp 服务器IP
*/
public void setHostIp(String HostIp) {
this.HostIp = HostIp;
}
/**
* Get 服务器系统
* @return MachineOs 服务器系统
*/
public String getMachineOs() {
return this.MachineOs;
}
/**
* Set 服务器系统
* @param MachineOs 服务器系统
*/
public void setMachineOs(String MachineOs) {
this.MachineOs = MachineOs;
}
/**
* Get 关联目录数
* @return RelateDirNum 关联目录数
*/
public Long getRelateDirNum() {
return this.RelateDirNum;
}
/**
* Set 关联目录数
* @param RelateDirNum 关联目录数
*/
public void setRelateDirNum(Long RelateDirNum) {
this.RelateDirNum = RelateDirNum;
}
/**
* Get 防护状态
* @return ProtectStatus 防护状态
*/
public Long getProtectStatus() {
return this.ProtectStatus;
}
/**
* Set 防护状态
* @param ProtectStatus 防护状态
*/
public void setProtectStatus(Long ProtectStatus) {
this.ProtectStatus = ProtectStatus;
}
/**
* Get 防护开关
* @return ProtectSwitch 防护开关
*/
public Long getProtectSwitch() {
return this.ProtectSwitch;
}
/**
* Set 防护开关
* @param ProtectSwitch 防护开关
*/
public void setProtectSwitch(Long ProtectSwitch) {
this.ProtectSwitch = ProtectSwitch;
}
/**
* Get 自动恢复开关
* @return AutoRestoreSwitchStatus 自动恢复开关
*/
public Long getAutoRestoreSwitchStatus() {
return this.AutoRestoreSwitchStatus;
}
/**
* Set 自动恢复开关
* @param AutoRestoreSwitchStatus 自动恢复开关
*/
public void setAutoRestoreSwitchStatus(Long AutoRestoreSwitchStatus) {
this.AutoRestoreSwitchStatus = AutoRestoreSwitchStatus;
}
/**
* Get 服务器唯一ID
* @return Quuid 服务器唯一ID
*/
public String getQuuid() {
return this.Quuid;
}
/**
* Set 服务器唯一ID
* @param Quuid 服务器唯一ID
*/
public void setQuuid(String Quuid) {
this.Quuid = Quuid;
}
/**
* Get 是否已经授权
* @return Authorization 是否已经授权
*/
public Boolean getAuthorization() {
return this.Authorization;
}
/**
* Set 是否已经授权
* @param Authorization 是否已经授权
*/
public void setAuthorization(Boolean Authorization) {
this.Authorization = Authorization;
}
/**
* Get 异常状态
* @return Exception 异常状态
*/
public Long getException() {
return this.Exception;
}
/**
* Set 异常状态
* @param Exception 异常状态
*/
public void setException(Long Exception) {
this.Exception = Exception;
}
/**
* Get 过渡进度
* @return Progress 过渡进度
*/
public Long getProgress() {
return this.Progress;
}
/**
* Set 过渡进度
* @param Progress 过渡进度
*/
public void setProgress(Long Progress) {
this.Progress = Progress;
}
/**
* Get 异常信息
* @return ExceptionMessage 异常信息
*/
public String getExceptionMessage() {
return this.ExceptionMessage;
}
/**
* Set 异常信息
* @param ExceptionMessage 异常信息
*/
public void setExceptionMessage(String ExceptionMessage) {
this.ExceptionMessage = ExceptionMessage;
}
public ProtectDirRelatedServer() {
}
/**
* NOTE: Any ambiguous key set via .set("AnyKey", "value") will be a shallow copy,
* and any explicit key, i.e Foo, set via .setFoo("value") will be a deep copy.
*/
public ProtectDirRelatedServer(ProtectDirRelatedServer source) {
if (source.Id != null) {
this.Id = new String(source.Id);
}
if (source.HostName != null) {
this.HostName = new String(source.HostName);
}
if (source.HostIp != null) {
this.HostIp = new String(source.HostIp);
}
if (source.MachineOs != null) {
this.MachineOs = new String(source.MachineOs);
}
if (source.RelateDirNum != null) {
this.RelateDirNum = new Long(source.RelateDirNum);
}
if (source.ProtectStatus != null) {
this.ProtectStatus = new Long(source.ProtectStatus);
}
if (source.ProtectSwitch != null) {
this.ProtectSwitch = new Long(source.ProtectSwitch);
}
if (source.AutoRestoreSwitchStatus != null) {
this.AutoRestoreSwitchStatus = new Long(source.AutoRestoreSwitchStatus);
}
if (source.Quuid != null) {
this.Quuid = new String(source.Quuid);
}
if (source.Authorization != null) {
this.Authorization = new Boolean(source.Authorization);
}
if (source.Exception != null) {
this.Exception = new Long(source.Exception);
}
if (source.Progress != null) {
this.Progress = new Long(source.Progress);
}
if (source.ExceptionMessage != null) {
this.ExceptionMessage = new String(source.ExceptionMessage);
}
}
/**
* Internal implementation, normal users should not use it.
*/
public void toMap(HashMap<String, String> map, String prefix) {
this.setParamSimple(map, prefix + "Id", this.Id);
this.setParamSimple(map, prefix + "HostName", this.HostName);
this.setParamSimple(map, prefix + "HostIp", this.HostIp);
this.setParamSimple(map, prefix + "MachineOs", this.MachineOs);
this.setParamSimple(map, prefix + "RelateDirNum", this.RelateDirNum);
this.setParamSimple(map, prefix + "ProtectStatus", this.ProtectStatus);
this.setParamSimple(map, prefix + "ProtectSwitch", this.ProtectSwitch);
this.setParamSimple(map, prefix + "AutoRestoreSwitchStatus", this.AutoRestoreSwitchStatus);
this.setParamSimple(map, prefix + "Quuid", this.Quuid);
this.setParamSimple(map, prefix + "Authorization", this.Authorization);
this.setParamSimple(map, prefix + "Exception", this.Exception);
this.setParamSimple(map, prefix + "Progress", this.Progress);
this.setParamSimple(map, prefix + "ExceptionMessage", this.ExceptionMessage);
}
}
| 4,362 |
857 | #ifndef __CONSOLE_DISPLAY_H__
#define __CONSOLE_DISPLAY_H__ 1
#define CONDIS_LINE_MAX_LEN (125)
#define CONDIS_MAX_HISTORY (256)
struct condis_line
{
const char *color_str;
char line[CONDIS_LINE_MAX_LEN];
};
typedef struct
{
int fd;
struct condis_line cdl[CONDIS_MAX_HISTORY]; // Ring Buffer
int entries; // scrolling if less than MAX entries
int pos_add; // idx of next used entry
int pos_display;
int rows; // Number of rows. Normally 3
int y; // starting top ROW (y-cordinate).
int max_char; // Max displayeable characters. Normally 79.
int is_redraw_needed;
} GS_CONDIS;
int GS_condis_init(GS_CONDIS *cd, int fd, int rows);
void GS_condis_add(GS_CONDIS *cd, int color, const char *str);
void GS_condis_printf(GS_CONDIS *cd, int color, const char *fmt, ...);
void GS_condis_log(GS_CONDIS *cd, int color, const char *str);
void GS_condis_pos(GS_CONDIS *cd, int y, int maxlen);
void GS_condis_draw(GS_CONDIS *cd, int force);
void GS_condis_up(GS_CONDIS *cd);
void GS_condis_down(GS_CONDIS *cd);
void GS_condis_clear(GS_CONDIS *cd);
// enum condis_type = {}
#endif /* !__CONSOLE_DISPLAY_H__ */
| 474 |
4,262 | <filename>components/camel-azure/camel-azure-storage-queue/src/main/java/org/apache/camel/component/azure/storage/queue/operations/QueueOperationResponse.java<gh_stars>1000+
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.azure.storage.queue.operations;
import java.util.HashMap;
import java.util.Map;
import com.azure.core.http.rest.Response;
import com.azure.storage.queue.models.SendMessageResult;
import org.apache.camel.component.azure.storage.queue.QueueExchangeHeaders;
public final class QueueOperationResponse {
private Object body;
private Map<String, Object> headers = new HashMap<>();
public QueueOperationResponse(final Object body, final Map<String, Object> headers) {
this.body = body;
this.headers = headers;
}
private QueueOperationResponse(final Object body) {
setBody(body);
}
public static QueueOperationResponse create(final Object body) {
return new QueueOperationResponse(body);
}
public static QueueOperationResponse create(final Object body, final Map<String, Object> headers) {
return new QueueOperationResponse(body, headers);
}
@SuppressWarnings("rawtypes")
public static QueueOperationResponse create(final Response response) {
return buildResponse(response, false);
}
public static QueueOperationResponse createWithEmptyBody(final Map<String, Object> headers) {
return new QueueOperationResponse(true, headers);
}
public static QueueOperationResponse createWithEmptyBody() {
return new QueueOperationResponse(true);
}
@SuppressWarnings("rawtypes")
public static QueueOperationResponse createWithEmptyBody(final Response response) {
return buildResponse(response, true);
}
@SuppressWarnings("rawtypes")
private static QueueOperationResponse buildResponse(final Response response, final boolean emptyBody) {
final Object body = emptyBody ? true : response.getValue();
QueueExchangeHeaders exchangeHeaders;
if (response.getValue() instanceof SendMessageResult) {
exchangeHeaders = QueueExchangeHeaders
.createQueueExchangeHeadersFromSendMessageResult((SendMessageResult) response.getValue());
} else {
exchangeHeaders = new QueueExchangeHeaders();
}
exchangeHeaders.httpHeaders(response.getHeaders());
return new QueueOperationResponse(body, exchangeHeaders.toMap());
}
public Object getBody() {
return body;
}
private void setBody(Object body) {
this.body = body;
}
public Map<String, Object> getHeaders() {
return headers;
}
private void setHeaders(final Map<String, Object> headers) {
this.headers = headers;
}
}
| 1,147 |
656 | import multiprocessing
import os
import logging
logger = logging.getLogger('inventree')
workers = os.environ.get('INVENTREE_GUNICORN_WORKERS', None)
if workers is not None:
try:
workers = int(workers)
except ValueError:
workers = None
if workers is None:
workers = multiprocessing.cpu_count() * 2 + 1
logger.info(f"Starting gunicorn server with {workers} workers")
max_requests = 1000
max_requests_jitter = 50
| 164 |
1,767 | package com.annimon.stream;
import com.annimon.stream.function.*;
import com.annimon.stream.internal.Compose;
import com.annimon.stream.internal.Operators;
import com.annimon.stream.internal.Params;
import com.annimon.stream.internal.SpinedBuffer;
import com.annimon.stream.iterator.PrimitiveIndexedIterator;
import com.annimon.stream.iterator.PrimitiveIterator;
import com.annimon.stream.operator.*;
import java.io.Closeable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.NoSuchElementException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* A sequence of {@code double}-valued elements supporting aggregate operations.
*
* @since 1.1.4
* @see Stream
*/
public final class DoubleStream implements Closeable {
/**
* Single instance for empty stream. It is safe for multi-thread environment because it has no content.
*/
private static final DoubleStream EMPTY = new DoubleStream(new PrimitiveIterator.OfDouble() {
@Override
public boolean hasNext() {
return false;
}
@Override
public double nextDouble() {
return 0d;
}
});
/**
* Returns an empty stream.
*
* @return the empty stream
*/
@NotNull
public static DoubleStream empty() {
return EMPTY;
}
/**
* Creates a {@code DoubleStream} from {@code PrimitiveIterator.OfDouble}.
*
* @param iterator the iterator with elements to be passed to stream
* @return the new {@code DoubleStream}
* @throws NullPointerException if {@code iterator} is null
*/
@NotNull
public static DoubleStream of(@NotNull PrimitiveIterator.OfDouble iterator) {
Objects.requireNonNull(iterator);
return new DoubleStream(iterator);
}
/**
* Creates a {@code DoubleStream} from the specified values.
*
* @param values the elements of the new stream
* @return the new stream
* @throws NullPointerException if {@code values} is null
*/
@NotNull
public static DoubleStream of(@NotNull final double... values) {
Objects.requireNonNull(values);
if (values.length == 0) {
return DoubleStream.empty();
}
return new DoubleStream(new DoubleArray(values));
}
/**
* Returns stream which contains single element passed as param
*
* @param t element of the stream
* @return the new stream
*/
@NotNull
public static DoubleStream of(final double t) {
return new DoubleStream(new DoubleArray(new double[] { t }));
}
/**
* Creates a {@code DoubleStream} by elements that generated by {@code DoubleSupplier}.
*
* @param s the {@code DoubleSupplier} for generated elements
* @return a new infinite sequential {@code DoubleStream}
* @throws NullPointerException if {@code s} is null
*/
@NotNull
public static DoubleStream generate(@NotNull final DoubleSupplier s) {
Objects.requireNonNull(s);
return new DoubleStream(new DoubleGenerate(s));
}
/**
* Creates a {@code DoubleStream} by iterative application {@code DoubleUnaryOperator} function
* to an initial element {@code seed}. Produces {@code DoubleStream} consisting of
* {@code seed}, {@code f(seed)}, {@code f(f(seed))}, etc.
*
* <p> The first element (position {@code 0}) in the {@code DoubleStream} will be
* the provided {@code seed}. For {@code n > 0}, the element at position
* {@code n}, will be the result of applying the function {@code f} to the
* element at position {@code n - 1}.
*
* <p>Example:
* <pre>
* seed: 1
* f: (a) -> a + 5
* result: [1, 6, 11, 16, ...]
* </pre>
*
* @param seed the initial element
* @param f a function to be applied to the previous element to produce a new element
* @return a new sequential {@code DoubleStream}
* @throws NullPointerException if {@code f} is null
*/
@NotNull
public static DoubleStream iterate(final double seed,
@NotNull final DoubleUnaryOperator f) {
Objects.requireNonNull(f);
return new DoubleStream(new DoubleIterate(seed, f));
}
/**
* Creates an {@code DoubleStream} by iterative application {@code DoubleUnaryOperator} function
* to an initial element {@code seed}, conditioned on satisfying the supplied predicate.
*
* <p>Example:
* <pre>
* seed: 0.0
* predicate: (a) -> a < 0.2
* f: (a) -> a + 0.05
* result: [0.0, 0.05, 0.1, 0.15]
* </pre>
*
* @param seed the initial value
* @param predicate a predicate to determine when the stream must terminate
* @param op operator to produce new element by previous one
* @return the new stream
* @throws NullPointerException if {@code op} is null
* @since 1.1.5
*/
@NotNull
public static DoubleStream iterate(
final double seed,
@NotNull final DoublePredicate predicate,
@NotNull final DoubleUnaryOperator op) {
Objects.requireNonNull(predicate);
return iterate(seed, op).takeWhile(predicate);
}
/**
* Lazily concatenates two streams.
*
* <p>Example:
* <pre>
* stream a: [1, 2, 3, 4]
* stream b: [5, 6]
* result: [1, 2, 3, 4, 5, 6]
* </pre>
*
* @param a the first stream
* @param b the second stream
* @return the new concatenated stream
* @throws NullPointerException if {@code a} or {@code b} is null
*/
@NotNull
public static DoubleStream concat(
@NotNull final DoubleStream a,
@NotNull final DoubleStream b) {
Objects.requireNonNull(a);
Objects.requireNonNull(b);
DoubleStream result = new DoubleStream(new DoubleConcat(a.iterator, b.iterator));
return result.onClose(Compose.closeables(a, b));
}
/**
* Lazily concatenates three or more streams.
*
* <p>Example:
* <pre>
* stream a: [1, 2, 3, 4]
* stream b: [5, 6]
* stream c: [7]
* stream d: [8, 9, 10]
* result: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
* </pre>
*
* @param a the first stream
* @param b the second stream
* @param rest the rest of streams
* @return the new concatenated stream
* @throws NullPointerException if {@code a} or {@code b}
* or {@code rest} is null
* @since 1.2.2
*/
@NotNull
public static DoubleStream concat(
@NotNull final DoubleStream a,
@NotNull final DoubleStream b,
@NotNull final DoubleStream... rest) {
Objects.requireNonNull(a);
Objects.requireNonNull(b);
Objects.requireNonNull(rest);
final List<PrimitiveIterator.OfDouble> iterators =
new ArrayList<PrimitiveIterator.OfDouble>(rest.length + 2);
final List<Closeable> closeables =
new ArrayList<Closeable>(rest.length + 2);
Collections.addAll(iterators, a.iterator, b.iterator);
Collections.addAll(closeables, a, b);
for (final DoubleStream stream : rest) {
iterators.add(stream.iterator);
closeables.add(stream);
}
DoubleStream result = new DoubleStream(new DoubleConcat(iterators));
return result.onClose(Compose.closeables(closeables));
}
private final PrimitiveIterator.OfDouble iterator;
private final Params params;
private DoubleStream(PrimitiveIterator.OfDouble iterator) {
this(null, iterator);
}
DoubleStream(Params params, PrimitiveIterator.OfDouble iterator) {
this.params = params;
this.iterator = iterator;
}
/**
* Returns internal {@code DoubleStream} iterator.
*
* @return internal {@code DoubleStream} iterator.
*/
public PrimitiveIterator.OfDouble iterator() {
return iterator;
}
/**
* Applies custom operator on stream.
*
* Transforming function can return {@code DoubleStream} for intermediate operations,
* or any value for terminal operation.
*
* <p>Operator examples:
* <pre><code>
* // Intermediate operator
* public class Zip implements Function<DoubleStream, DoubleStream> {
*
* private final DoubleStream secondStream;
* private final DoubleBinaryOperator combiner;
*
* public Zip(DoubleStream secondStream, DoubleBinaryOperator combiner) {
* this.secondStream = secondStream;
* this.combiner = combiner;
* }
*
* @Override
* public DoubleStream apply(DoubleStream firstStream) {
* final PrimitiveIterator.OfDouble it1 = firstStream.iterator();
* final PrimitiveIterator.OfDouble it2 = secondStream.iterator();
* return DoubleStream.of(new PrimitiveIterator.OfDouble() {
* @Override
* public boolean hasNext() {
* return it1.hasNext() && it2.hasNext();
* }
*
* @Override
* public double nextDouble() {
* return combiner.applyAsDouble(it1.nextDouble(), it2.nextDouble());
* }
* });
* }
* }
*
* // Intermediate operator based on existing stream operators
* public class SkipAndLimit implements UnaryOperator<DoubleStream> {
*
* private final int skip, limit;
*
* public SkipAndLimit(int skip, int limit) {
* this.skip = skip;
* this.limit = limit;
* }
*
* @Override
* public DoubleStream apply(DoubleStream stream) {
* return stream.skip(skip).limit(limit);
* }
* }
*
* // Terminal operator
* public class DoubleSummaryStatistics implements Function<DoubleStream, double[]> {
* @Override
* public double[] apply(DoubleStream stream) {
* long count = 0;
* double sum = 0;
* final PrimitiveIterator.OfDouble it = stream.iterator();
* while (it.hasNext()) {
* count++;
* sum += it.nextDouble();
* }
* double average = (count == 0) ? 0 : (sum / (double) count);
* return new double[] {count, sum, average};
* }
* }
* </code></pre>
*
* @param <R> the type of the result
* @param function a transforming function
* @return a result of the transforming function
* @see Stream#custom(com.annimon.stream.function.Function)
* @throws NullPointerException if {@code function} is null
*/
@Nullable
public <R> R custom(@NotNull final Function<DoubleStream, R> function) {
Objects.requireNonNull(function);
return function.apply(this);
}
/**
* Returns a {@code Stream} consisting of the elements of this stream,
* each boxed to an {@code Double}.
*
* <p>This is an lazy intermediate operation.
*
* @return a {@code Stream} consistent of the elements of this stream,
* each boxed to an {@code Double}
*/
@NotNull
public Stream<Double> boxed() {
return new Stream<Double>(params, iterator);
}
/**
* Prepends given {@code DoubleStream} to current and returns a new stream.
*
* This is similar to {@code DoubleStream.concat(stream, this)}
*
* <p>Example:
* <pre>
* current: [1, 2, 3]
* stream: [4, 5, 6]
* result: [4, 5, 6, 1, 2, 3]
* </pre>
*
* @param stream the stream to prepend
* @return the new stream
* @since 1.2.2
* @see #concat(DoubleStream, DoubleStream)
*/
@NotNull
public DoubleStream prepend(@NotNull DoubleStream stream) {
return DoubleStream.concat(stream, this);
}
/**
* Appends given {@code DoubleStream} to current and returns a new stream.
*
* This is similar to {@code DoubleStream.concat(this, stream)}
*
* <p>Example:
* <pre>
* current: [1, 2, 3]
* stream: [4, 5, 6]
* result: [1, 2, 3, 4, 5, 6]
* </pre>
*
* @param stream the stream to append
* @return the new stream
* @since 1.2.2
* @see #concat(DoubleStream, DoubleStream)
*/
@NotNull
public DoubleStream append(@NotNull DoubleStream stream) {
return DoubleStream.concat(this, stream);
}
/**
* Returns {@code DoubleStream} with elements that satisfy the given predicate.
*
* <p> This is an intermediate operation.
*
* <p>Example:
* <pre>
* predicate: (a) -> a > 2
* stream: [1, 2, 3, 4, -8, 0, 11]
* result: [3, 4, 11]
* </pre>
*
* @param predicate the predicate used to filter elements
* @return the new stream
*/
@NotNull
public DoubleStream filter(@NotNull final DoublePredicate predicate) {
return new DoubleStream(params, new DoubleFilter(iterator, predicate));
}
/**
* Returns a {@code DoubleStream} with elements that satisfy the given {@code IndexedDoublePredicate}.
*
* <p>This is an intermediate operation.
*
* <p>Example:
* <pre>
* predicate: (index, value) -> (index + value) > 6
* stream: [1, 2, 3, 4, 0, 11]
* index: [0, 1, 2, 3, 4, 5]
* sum: [1, 3, 5, 7, 4, 16]
* filter: [ 7, 16]
* result: [4, 11]
* </pre>
*
* @param predicate the {@code IndexedDoublePredicate} used to filter elements
* @return the new stream
* @since 1.2.1
*/
@NotNull
public DoubleStream filterIndexed(@NotNull IndexedDoublePredicate predicate) {
return filterIndexed(0, 1, predicate);
}
/**
* Returns a {@code DoubleStream} with elements that satisfy the given {@code IndexedDoublePredicate}.
*
* <p>This is an intermediate operation.
*
* <p>Example:
* <pre>
* from: 4
* step: 3
* predicate: (index, value) -> (index + value) > 15
* stream: [1, 2, 3, 4, 0, 11]
* index: [4, 7, 10, 13, 16, 19]
* sum: [5, 9, 13, 17, 16, 30]
* filter: [ 17, 16, 30]
* result: [4, 0, 11]
* </pre>
*
* @param from the initial value of the index (inclusive)
* @param step the step of the index
* @param predicate the {@code IndexedDoublePredicate} used to filter elements
* @return the new stream
* @since 1.2.1
*/
@NotNull
public DoubleStream filterIndexed(int from, int step,
@NotNull IndexedDoublePredicate predicate) {
return new DoubleStream(params, new DoubleFilterIndexed(
new PrimitiveIndexedIterator.OfDouble(from, step, iterator),
predicate));
}
/**
* Returns {@code DoubleStream} with elements that does not satisfy the given predicate.
*
* <p> This is an intermediate operation.
*
* @param predicate the predicate used to filter elements
* @return the new stream
*/
@NotNull
public DoubleStream filterNot(@NotNull final DoublePredicate predicate) {
return filter(DoublePredicate.Util.negate(predicate));
}
/**
* Returns an {@code DoubleStream} consisting of the results of applying the given
* function to the elements of this stream.
*
* <p> This is an intermediate operation.
*
* <p>Example:
* <pre>
* mapper: (a) -> a + 5
* stream: [1, 2, 3, 4]
* result: [6, 7, 8, 9]
* </pre>
*
* @param mapper the mapper function used to apply to each element
* @return the new stream
* @see Stream#map(com.annimon.stream.function.Function)
*/
@NotNull
public DoubleStream map(@NotNull final DoubleUnaryOperator mapper) {
return new DoubleStream(params, new DoubleMap(iterator, mapper));
}
/**
* Returns a {@code DoubleStream} with elements that obtained
* by applying the given {@code IndexedDoubleUnaryOperator}.
*
* <p>This is an intermediate operation.
*
* <p>Example:
* <pre>
* mapper: (index, value) -> (index * value)
* stream: [1, 2, 3, 4]
* index: [0, 1, 2, 3]
* result: [0, 2, 6, 12]
* </pre>
*
* @param mapper the mapper function used to apply to each element
* @return the new stream
* @since 1.2.1
*/
@NotNull
public DoubleStream mapIndexed(@NotNull IndexedDoubleUnaryOperator mapper) {
return mapIndexed(0, 1, mapper);
}
/**
* Returns a {@code DoubleStream} with elements that obtained
* by applying the given {@code IndexedDoubleUnaryOperator}.
*
* <p>This is an intermediate operation.
*
* <p>Example:
* <pre>
* from: -2
* step: 2
* mapper: (index, value) -> (index * value)
* stream: [ 1, 2, 3, 4]
* index: [-2, 0, 2, 4]
* result: [-2, 0, 6, 16]
* </pre>
*
* @param from the initial value of the index (inclusive)
* @param step the step of the index
* @param mapper the mapper function used to apply to each element
* @return the new stream
* @since 1.2.1
*/
@NotNull
public DoubleStream mapIndexed(int from, int step,
@NotNull IndexedDoubleUnaryOperator mapper) {
return new DoubleStream(params, new DoubleMapIndexed(
new PrimitiveIndexedIterator.OfDouble(from, step, iterator),
mapper));
}
/**
* Returns a {@code Stream} consisting of the results of applying the given
* function to the elements of this stream.
*
* <p> This is an intermediate operation.
*
* @param <R> the type result
* @param mapper the mapper function used to apply to each element
* @return the new {@code Stream}
*/
@NotNull
public <R> Stream<R> mapToObj(@NotNull final DoubleFunction<? extends R> mapper) {
return new Stream<R>(params, new DoubleMapToObj<R>(iterator, mapper));
}
/**
* Returns an {@code IntStream} consisting of the results of applying the given
* function to the elements of this stream.
*
* <p> This is an intermediate operation.
*
* @param mapper the mapper function used to apply to each element
* @return the new {@code IntStream}
*/
@NotNull
public IntStream mapToInt(@NotNull final DoubleToIntFunction mapper) {
return new IntStream(params, new DoubleMapToInt(iterator, mapper));
}
/**
* Returns an {@code LongStream} consisting of the results of applying the given
* function to the elements of this stream.
*
* <p> This is an intermediate operation.
*
* @param mapper the mapper function used to apply to each element
* @return the new {@code LongStream}
*/
@NotNull
public LongStream mapToLong(@NotNull final DoubleToLongFunction mapper) {
return new LongStream(params, new DoubleMapToLong(iterator, mapper));
}
/**
* Returns a stream consisting of the results of replacing each element of
* this stream with the contents of a mapped stream produced by applying
* the provided mapping function to each element.
*
* <p>This is an intermediate operation.
*
* <p>Example:
* <pre>
* mapper: (a) -> [a, a + 5]
* stream: [1, 2, 3, 4]
* result: [1, 6, 2, 7, 3, 8, 4, 9]
* </pre>
*
* @param mapper the mapper function used to apply to each element
* @return the new stream
* @see Stream#flatMap(com.annimon.stream.function.Function)
*/
@NotNull
public DoubleStream flatMap(@NotNull final DoubleFunction<? extends DoubleStream> mapper) {
return new DoubleStream(params, new DoubleFlatMap(iterator, mapper));
}
/**
* Returns a stream consisting of the results of replacing each element of
* this stream with the contents of a mapped stream produced by applying
* the provided mapping function to each element.
*
* <p>This is an intermediate operation.
*
* @param mapper the mapper function used to apply to each element for producing replacing elements
* @return the new stream
* @since 1.2.2
* @see Stream#mapMulti(com.annimon.stream.function.BiConsumer)
* @see DoubleStream#flatMap(com.annimon.stream.function.DoubleFunction)
*/
@NotNull
public DoubleStream mapMulti(@NotNull final DoubleMapMultiConsumer mapper) {
return flatMap(new DoubleFunction<DoubleStream>() {
@Override
public DoubleStream apply(double value) {
SpinedBuffer.OfDouble buffer = new SpinedBuffer.OfDouble();
mapper.accept(value, buffer);
return DoubleStream.of(buffer.iterator());
}
});
}
/**
* Represents an operation on two input arguments.
*
* @since 1.2.2
* @see #mapMulti(com.annimon.stream.DoubleStream.DoubleMapMultiConsumer)
*/
public interface DoubleMapMultiConsumer {
/**
* Replaces the given {@code value} with zero or more values
* by feeding the mapped values to the {@code consumer} consumer.
*
* @param value the double value coming from upstream
* @param consumer a {@code DoubleConsumer} accepting the mapped values
*/
void accept(double value, DoubleConsumer consumer);
}
/**
* Returns a stream consisting of the distinct elements of this stream.
*
* <p>This is a stateful intermediate operation.
*
* <p>Example:
* <pre>
* stream: [1, 4, 2, 3, 3, 4, 1]
* result: [1, 4, 2, 3]
* </pre>
*
* @return the new stream
*/
@NotNull
public DoubleStream distinct() {
return boxed().distinct().mapToDouble(UNBOX_FUNCTION);
}
/**
* Returns a stream consisting of the elements of this stream in sorted order.
*
* <p>This is a stateful intermediate operation.
*
* <p>Example:
* <pre>
* stream: [3, 4, 1, 2]
* result: [1, 2, 3, 4]
* </pre>
*
* @return the new stream
*/
@NotNull
public DoubleStream sorted() {
return new DoubleStream(params, new DoubleSorted(iterator));
}
/**
* Returns a stream consisting of the elements of this stream
* in sorted order as determinated by provided {@code Comparator}.
*
* <p>This is a stateful intermediate operation.
*
* <p>Example:
* <pre>
* comparator: (a, b) -> -a.compareTo(b)
* stream: [1, 2, 3, 4]
* result: [4, 3, 2, 1]
* </pre>
*
* @param comparator the {@code Comparator} to compare elements
* @return the new {@code DoubleStream}
*/
@NotNull
public DoubleStream sorted(@Nullable Comparator<Double> comparator) {
return boxed().sorted(comparator).mapToDouble(UNBOX_FUNCTION);
}
/**
* Samples the {@code DoubleStream} by emitting every n-th element.
*
* <p>This is an intermediate operation.
*
* <p>Example:
* <pre>
* stepWidth: 3
* stream: [1, 2, 3, 4, 5, 6, 7, 8]
* result: [1, 4, 7]
* </pre>
*
* @param stepWidth step width
* @return the new {@code DoubleStream}
* @throws IllegalArgumentException if {@code stepWidth} is zero or negative
* @see Stream#sample(int)
*/
@NotNull
public DoubleStream sample(final int stepWidth) {
if (stepWidth <= 0) throw new IllegalArgumentException("stepWidth cannot be zero or negative");
if (stepWidth == 1) return this;
return new DoubleStream(params, new DoubleSample(iterator, stepWidth));
}
/**
* Performs provided action on each element.
*
* <p>This is an intermediate operation.
*
* @param action the action to be performed on each element
* @return the new stream
*/
@NotNull
public DoubleStream peek(@NotNull final DoubleConsumer action) {
return new DoubleStream(params, new DoublePeek(iterator, action));
}
/**
* Returns a {@code DoubleStream} produced by iterative application of a accumulation function
* to reduction value and next element of the current stream.
* Produces a {@code DoubleStream} consisting of {@code value1}, {@code acc(value1, value2)},
* {@code acc(acc(value1, value2), value3)}, etc.
*
* <p>This is an intermediate operation.
*
* <p>Example:
* <pre>
* accumulator: (a, b) -> a + b
* stream: [1, 2, 3, 4, 5]
* result: [1, 3, 6, 10, 15]
* </pre>
*
* @param accumulator the accumulation function
* @return the new stream
* @throws NullPointerException if {@code accumulator} is null
* @since 1.1.6
*/
@NotNull
public DoubleStream scan(@NotNull final DoubleBinaryOperator accumulator) {
Objects.requireNonNull(accumulator);
return new DoubleStream(params, new DoubleScan(iterator, accumulator));
}
/**
* Returns a {@code DoubleStream} produced by iterative application of a accumulation function
* to an initial element {@code identity} and next element of the current stream.
* Produces a {@code DoubleStream} consisting of {@code identity}, {@code acc(identity, value1)},
* {@code acc(acc(identity, value1), value2)}, etc.
*
* <p>This is an intermediate operation.
*
* <p>Example:
* <pre>
* identity: 0
* accumulator: (a, b) -> a + b
* stream: [1, 2, 3, 4, 5]
* result: [0, 1, 3, 6, 10, 15]
* </pre>
*
* @param identity the initial value
* @param accumulator the accumulation function
* @return the new stream
* @throws NullPointerException if {@code accumulator} is null
* @since 1.1.6
*/
@NotNull
public DoubleStream scan(final double identity,
@NotNull final DoubleBinaryOperator accumulator) {
Objects.requireNonNull(accumulator);
return new DoubleStream(params, new DoubleScanIdentity(iterator, identity, accumulator));
}
/**
* Takes elements while the predicate returns {@code true}.
*
* <p>This is an intermediate operation.
*
* <p>Example:
* <pre>
* predicate: (a) -> a < 3
* stream: [1, 2, 3, 4, 1, 2, 3, 4]
* result: [1, 2]
* </pre>
*
* @param predicate the predicate used to take elements
* @return the new {@code DoubleStream}
*/
@NotNull
public DoubleStream takeWhile(@NotNull final DoublePredicate predicate) {
return new DoubleStream(params, new DoubleTakeWhile(iterator, predicate));
}
/**
* Takes elements while the predicate returns {@code false}.
* Once predicate condition is satisfied by an element, the stream
* finishes with this element.
*
* <p>This is an intermediate operation.
*
* <p>Example:
* <pre>
* stopPredicate: (a) -> a > 2
* stream: [1, 2, 3, 4, 1, 2, 3, 4]
* result: [1, 2, 3]
* </pre>
*
* @param stopPredicate the predicate used to take elements
* @return the new {@code DoubleStream}
* @since 1.1.6
*/
@NotNull
public DoubleStream takeUntil(@NotNull final DoublePredicate stopPredicate) {
return new DoubleStream(params, new DoubleTakeUntil(iterator, stopPredicate));
}
/**
* Drops elements while the predicate is true and returns the rest.
*
* <p>This is an intermediate operation.
*
* <p>Example:
* <pre>
* predicate: (a) -> a < 3
* stream: [1, 2, 3, 4, 1, 2, 3, 4]
* result: [3, 4, 1, 2, 3, 4]
* </pre>
*
* @param predicate the predicate used to drop elements
* @return the new {@code DoubleStream}
*/
@NotNull
public DoubleStream dropWhile(@NotNull final DoublePredicate predicate) {
return new DoubleStream(params, new DoubleDropWhile(iterator, predicate));
}
/**
* Returns a stream consisting of the elements of this stream, truncated
* to be no longer than {@code maxSize} in length.
*
* <p> This is a short-circuiting stateful intermediate operation.
*
* <p>Example:
* <pre>
* maxSize: 3
* stream: [1, 2, 3, 4, 5]
* result: [1, 2, 3]
*
* maxSize: 10
* stream: [1, 2]
* result: [1, 2]
* </pre>
*
* @param maxSize the number of elements the stream should be limited to
* @return the new stream
* @throws IllegalArgumentException if {@code maxSize} is negative
*/
@NotNull
public DoubleStream limit(final long maxSize) {
if (maxSize < 0) throw new IllegalArgumentException("maxSize cannot be negative");
if (maxSize == 0) return DoubleStream.empty();
return new DoubleStream(params, new DoubleLimit(iterator, maxSize));
}
/**
* Skips first {@code n} elements and returns {@code DoubleStream} with remaining elements.
* If this stream contains fewer than {@code n} elements, then an
* empty stream will be returned.
*
* <p>This is a stateful intermediate operation.
*
* <p>Example:
* <pre>
* n: 3
* stream: [1, 2, 3, 4, 5]
* result: [4, 5]
*
* n: 10
* stream: [1, 2]
* result: []
* </pre>
*
* @param n the number of elements to skip
* @return the new stream
* @throws IllegalArgumentException if {@code n} is negative
*/
@NotNull
public DoubleStream skip(final long n) {
if (n < 0) throw new IllegalArgumentException("n cannot be negative");
if (n == 0) return this;
return new DoubleStream(params, new DoubleSkip(iterator, n));
}
/**
* Performs an action for each element of this stream.
*
* <p>This is a terminal operation.
*
* @param action the action to be performed on each element
*/
public void forEach(@NotNull DoubleConsumer action) {
while (iterator.hasNext()) {
action.accept(iterator.nextDouble());
}
}
/**
* Performs the given indexed action on each element.
*
* <p>This is a terminal operation.
*
* @param action the action to be performed on each element
* @since 1.2.1
*/
public void forEachIndexed(@NotNull IndexedDoubleConsumer action) {
forEachIndexed(0, 1, action);
}
/**
* Performs the given indexed action on each element.
*
* <p>This is a terminal operation.
*
* @param from the initial value of the index (inclusive)
* @param step the step of the index
* @param action the action to be performed on each element
* @since 1.2.1
*/
public void forEachIndexed(int from, int step,
@NotNull IndexedDoubleConsumer action) {
int index = from;
while (iterator.hasNext()) {
action.accept(index, iterator.nextDouble());
index += step;
}
}
/**
* Performs a reduction on the elements of this stream, using the provided
* identity value and an associative accumulation function, and returns the
* reduced value.
*
* <p>The {@code identity} value must be an identity for the accumulator
* function. This means that for all {@code x},
* {@code accumulator.apply(identity, x)} is equal to {@code x}.
* The {@code accumulator} function must be an associative function.
*
* <p>This is a terminal operation.
*
* <p>Example:
* <pre>
* identity: 0
* accumulator: (a, b) -> a + b
* stream: [1, 2, 3, 4, 5]
* result: 15
* </pre>
*
* @param identity the identity value for the accumulating function
* @param accumulator the accumulation function
* @return the result of the reduction
* @see #sum()
* @see #min()
* @see #max()
*/
public double reduce(double identity, @NotNull DoubleBinaryOperator accumulator) {
double result = identity;
while (iterator.hasNext()) {
final double value = iterator.nextDouble();
result = accumulator.applyAsDouble(result, value);
}
return result;
}
/**
* Performs a reduction on the elements of this stream, using an
* associative accumulation function, and returns an {@code OptionalDouble}
* describing the reduced value, if any.
*
* <p>The {@code accumulator} function must be an associative function.
*
* <p>This is a terminal operation.
*
* @param accumulator the accumulation function
* @return the result of the reduction
* @see #reduce(com.annimon.stream.function.DoubleBinaryOperator)
*/
@NotNull
public OptionalDouble reduce(@NotNull DoubleBinaryOperator accumulator) {
boolean foundAny = false;
double result = 0;
while (iterator.hasNext()) {
final double value = iterator.nextDouble();
if (!foundAny) {
foundAny = true;
result = value;
} else {
result = accumulator.applyAsDouble(result, value);
}
}
return foundAny ? OptionalDouble.of(result) : OptionalDouble.empty();
}
/**
* Returns an array containing the elements of this stream.
*
* <p>This is a terminal operation.
*
* @return an array containing the elements of this stream
*/
@NotNull
public double[] toArray() {
return Operators.toDoubleArray(iterator);
}
/**
* Collects elements to {@code supplier} provided container by applying the given accumulation function.
*
* <p>This is a terminal operation.
*
* @param <R> the type of the result
* @param supplier the supplier function that provides container
* @param accumulator the accumulation function
* @return the result of collect elements
* @see Stream#collect(com.annimon.stream.function.Supplier, com.annimon.stream.function.BiConsumer)
*/
@Nullable
public <R> R collect(@NotNull Supplier<R> supplier,
@NotNull ObjDoubleConsumer<R> accumulator) {
final R result = supplier.get();
while (iterator.hasNext()) {
final double value = iterator.nextDouble();
accumulator.accept(result, value);
}
return result;
}
/**
* Returns the sum of elements in this stream.
*
* @return the sum of elements in this stream
*/
public double sum() {
double sum = 0;
while (iterator.hasNext()) {
sum += iterator.nextDouble();
}
return sum;
}
/**
* Returns an {@code OptionalDouble} describing the minimum element of this
* stream, or an empty optional if this stream is empty.
*
* <p>This is a terminal operation.
*
* @return the minimum element
*/
@NotNull
public OptionalDouble min() {
return reduce(new DoubleBinaryOperator() {
@Override
public double applyAsDouble(double left, double right) {
return Math.min(left, right);
}
});
}
/**
* Returns an {@code OptionalDouble} describing the maximum element of this
* stream, or an empty optional if this stream is empty.
*
* <p>This is a terminal operation.
*
* @return the maximum element
*/
@NotNull
public OptionalDouble max() {
return reduce(new DoubleBinaryOperator() {
@Override
public double applyAsDouble(double left, double right) {
return Math.max(left, right);
}
});
}
/**
* Returns the count of elements in this stream.
*
* <p>This is a terminal operation.
*
* @return the count of elements in this stream
*/
public long count() {
long count = 0;
while (iterator.hasNext()) {
iterator.nextDouble();
count++;
}
return count;
}
/**
* Returns the average of elements in this stream.
*
* <p>This is a terminal operation.
*
* @return the average of elements in this stream
*/
@NotNull
public OptionalDouble average() {
long count = 0;
double sum = 0d;
while (iterator.hasNext()) {
sum += iterator.nextDouble();
count++;
}
if (count == 0) return OptionalDouble.empty();
return OptionalDouble.of(sum / (double) count);
}
/**
* Tests whether all elements match the given predicate.
* May not evaluate the predicate on all elements if not necessary
* for determining the result. If the stream is empty then
* {@code false} is returned and the predicate is not evaluated.
*
* <p>This is a short-circuiting terminal operation.
*
* <p>Example:
* <pre>
* predicate: (a) -> a == 5
* stream: [1, 2, 3, 4, 5]
* result: true
*
* predicate: (a) -> a == 5
* stream: [5, 5, 5]
* result: true
* </pre>
*
* @param predicate the predicate used to match elements
* @return {@code true} if any elements of the stream match the provided
* predicate, otherwise {@code false}
*/
public boolean anyMatch(@NotNull DoublePredicate predicate) {
while (iterator.hasNext()) {
if (predicate.test(iterator.nextDouble()))
return true;
}
return false;
}
/**
* Tests whether all elements match the given predicate.
* May not evaluate the predicate on all elements if not necessary for
* determining the result. If the stream is empty then {@code true} is
* returned and the predicate is not evaluated.
*
* <p>This is a short-circuiting terminal operation.
*
* <p>Example:
* <pre>
* predicate: (a) -> a == 5
* stream: [1, 2, 3, 4, 5]
* result: false
*
* predicate: (a) -> a == 5
* stream: [5, 5, 5]
* result: true
* </pre>
*
* @param predicate the predicate used to match elements
* @return {@code true} if either all elements of the stream match the
* provided predicate or the stream is empty, otherwise {@code false}
*/
public boolean allMatch(@NotNull DoublePredicate predicate) {
while (iterator.hasNext()) {
if (!predicate.test(iterator.nextDouble()))
return false;
}
return true;
}
/**
* Tests whether no elements match the given predicate.
* May not evaluate the predicate on all elements if not necessary for
* determining the result. If the stream is empty then {@code true} is
* returned and the predicate is not evaluated.
*
* <p>This is a short-circuiting terminal operation.
*
* <p>Example:
* <pre>
* predicate: (a) -> a == 5
* stream: [1, 2, 3, 4, 5]
* result: false
*
* predicate: (a) -> a == 5
* stream: [1, 2, 3]
* result: true
* </pre>
*
* @param predicate the predicate used to match elements
* @return {@code true} if either no elements of the stream match the
* provided predicate or the stream is empty, otherwise {@code false}
*/
public boolean noneMatch(@NotNull DoublePredicate predicate) {
while (iterator.hasNext()) {
if (predicate.test(iterator.nextDouble()))
return false;
}
return true;
}
/**
* Returns the first element wrapped by {@code OptionalDouble} class.
* If stream is empty, returns {@code OptionalDouble.empty()}.
*
* <p>This is a short-circuiting terminal operation.
*
* @return an {@code OptionalDouble} with first element
* or {@code OptionalDouble.empty()} if stream is empty
*/
@NotNull
public OptionalDouble findFirst() {
if (iterator.hasNext()) {
return OptionalDouble.of(iterator.nextDouble());
}
return OptionalDouble.empty();
}
/**
* Returns the first element if stream is not empty,
* otherwise returns {@code other}.
*
* <p>This is a short-circuiting terminal operation.
*
* @param other the value to be returned if stream is empty
* @return first element or {@code other} if stream is empty
* @since 1.2.2
*/
public double findFirstOrElse(double other) {
if (iterator.hasNext()) {
return iterator.nextDouble();
} else {
return other;
}
}
/**
* Returns the last element wrapped by {@code OptionalDouble} class.
* If stream is empty, returns {@code OptionalDouble.empty()}.
*
* <p>This is a short-circuiting terminal operation.
*
* @return an {@code OptionalDouble} with the last element
* or {@code OptionalDouble.empty()} if the stream is empty
* @since 1.1.8
*/
@NotNull
public OptionalDouble findLast() {
return reduce(new DoubleBinaryOperator() {
@Override
public double applyAsDouble(double left, double right) {
return right;
}
});
}
/**
* Returns the single element of stream.
* If stream is empty, throws {@code NoSuchElementException}.
* If stream contains more than one element, throws {@code IllegalStateException}.
*
* <p>This is a short-circuiting terminal operation.
*
* <p>Example:
* <pre>
* stream: []
* result: NoSuchElementException
*
* stream: [1]
* result: 1
*
* stream: [1, 2, 3]
* result: IllegalStateException
* </pre>
*
* @return single element of stream
* @throws NoSuchElementException if stream is empty
* @throws IllegalStateException if stream contains more than one element
*/
public double single() {
if (!iterator.hasNext()) {
throw new NoSuchElementException("DoubleStream contains no element");
}
final double singleCandidate = iterator.nextDouble();
if (iterator.hasNext()) {
throw new IllegalStateException("DoubleStream contains more than one element");
}
return singleCandidate;
}
/**
* Returns the single element wrapped by {@code OptionalDouble} class.
* If stream is empty, returns {@code OptionalDouble.empty()}.
* If stream contains more than one element, throws {@code IllegalStateException}.
*
* <p>This is a short-circuiting terminal operation.
*
* <p>Example:
* <pre>
* stream: []
* result: OptionalDouble.empty()
*
* stream: [1]
* result: OptionalDouble.of(1)
*
* stream: [1, 2, 3]
* result: IllegalStateException
* </pre>
*
* @return an {@code OptionalDouble} with single element
* or {@code OptionalDouble.empty()} if stream is empty
* @throws IllegalStateException if stream contains more than one element
*/
@NotNull
public OptionalDouble findSingle() {
if (!iterator.hasNext()) {
return OptionalDouble.empty();
}
final double singleCandidate = iterator.nextDouble();
if (iterator.hasNext()) {
throw new IllegalStateException("DoubleStream contains more than one element");
}
return OptionalDouble.of(singleCandidate);
}
/**
* Adds close handler to the current stream.
*
* <p>This is an intermediate operation.
*
* @param closeHandler an action to execute when the stream is closed
* @return the new stream with the close handler
* @since 1.1.8
*/
@NotNull
public DoubleStream onClose(@NotNull final Runnable closeHandler) {
Objects.requireNonNull(closeHandler);
final Params newParams = Params.wrapWithCloseHandler(params, closeHandler);
return new DoubleStream(newParams, iterator);
}
/**
* Causes close handler to be invoked if it exists.
* Since most of the stream providers are lists or arrays,
* it is not necessary to close the stream.
*
* @since 1.1.8
*/
@Override
public void close() {
if (params != null && params.closeHandler != null) {
params.closeHandler.run();
params.closeHandler = null;
}
}
private static final ToDoubleFunction<Double> UNBOX_FUNCTION = new ToDoubleFunction<Double>() {
@Override
public double applyAsDouble(Double t) {
return t;
}
};
}
| 18,484 |
629 | # -*- coding: UTF-8 -*-
class Base(object):
def list(self):
raise NotImplementedError
def add(self, data):
raise NotImplementedError
def update(self, data):
raise NotImplementedError
def delete(self, data):
raise NotImplementedError
def handler(self):
raise NotImplementedError
| 140 |
2,073 | /**
* 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.mahout.vectorizer.term;
import com.google.common.collect.Lists;
import com.google.common.io.Closeables;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.filecache.DistributedCache;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.lucene.analysis.shingle.ShingleFilter;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.mahout.common.HadoopUtil;
import org.apache.mahout.common.Pair;
import org.apache.mahout.common.StringTuple;
import org.apache.mahout.common.iterator.sequencefile.SequenceFileIterable;
import org.apache.mahout.common.lucene.IteratorTokenStream;
import org.apache.mahout.math.NamedVector;
import org.apache.mahout.math.RandomAccessSparseVector;
import org.apache.mahout.math.SequentialAccessSparseVector;
import org.apache.mahout.math.Vector;
import org.apache.mahout.math.VectorWritable;
import org.apache.mahout.math.map.OpenObjectIntHashMap;
import org.apache.mahout.vectorizer.DictionaryVectorizer;
import org.apache.mahout.vectorizer.common.PartialVectorMerger;
import java.io.IOException;
import java.net.URI;
import java.util.Iterator;
import java.util.List;
/**
* Converts a document in to a sparse vector
*/
public class TFPartialVectorReducer extends Reducer<Text, StringTuple, Text, VectorWritable> {
private final OpenObjectIntHashMap<String> dictionary = new OpenObjectIntHashMap<>();
private int dimension;
private boolean sequentialAccess;
private boolean namedVector;
private int maxNGramSize = 1;
@Override
protected void reduce(Text key, Iterable<StringTuple> values, Context context)
throws IOException, InterruptedException {
Iterator<StringTuple> it = values.iterator();
if (!it.hasNext()) {
return;
}
List<String> value = Lists.newArrayList();
while (it.hasNext()) {
value.addAll(it.next().getEntries());
}
Vector vector = new RandomAccessSparseVector(dimension, value.size()); // guess at initial size
if (maxNGramSize >= 2) {
ShingleFilter sf = new ShingleFilter(new IteratorTokenStream(value.iterator()), maxNGramSize);
sf.reset();
try {
do {
String term = sf.getAttribute(CharTermAttribute.class).toString();
if (!term.isEmpty() && dictionary.containsKey(term)) { // ngram
int termId = dictionary.get(term);
vector.setQuick(termId, vector.getQuick(termId) + 1);
}
} while (sf.incrementToken());
sf.end();
} finally {
Closeables.close(sf, true);
}
} else {
for (String term : value) {
if (!term.isEmpty() && dictionary.containsKey(term)) { // unigram
int termId = dictionary.get(term);
vector.setQuick(termId, vector.getQuick(termId) + 1);
}
}
}
if (sequentialAccess) {
vector = new SequentialAccessSparseVector(vector);
}
if (namedVector) {
vector = new NamedVector(vector, key.toString());
}
// if the vector has no nonZero entries (nothing in the dictionary), let's not waste space sending it to disk.
if (vector.getNumNondefaultElements() > 0) {
VectorWritable vectorWritable = new VectorWritable(vector);
context.write(key, vectorWritable);
} else {
context.getCounter("TFPartialVectorReducer", "emptyVectorCount").increment(1);
}
}
@Override
protected void setup(Context context) throws IOException, InterruptedException {
super.setup(context);
Configuration conf = context.getConfiguration();
dimension = conf.getInt(PartialVectorMerger.DIMENSION, Integer.MAX_VALUE);
sequentialAccess = conf.getBoolean(PartialVectorMerger.SEQUENTIAL_ACCESS, false);
namedVector = conf.getBoolean(PartialVectorMerger.NAMED_VECTOR, false);
maxNGramSize = conf.getInt(DictionaryVectorizer.MAX_NGRAMS, maxNGramSize);
URI[] localFiles = DistributedCache.getCacheFiles(conf);
Path dictionaryFile = HadoopUtil.findInCacheByPartOfFilename(DictionaryVectorizer.DICTIONARY_FILE, localFiles);
// key is word value is id
for (Pair<Writable, IntWritable> record
: new SequenceFileIterable<Writable, IntWritable>(dictionaryFile, true, conf)) {
dictionary.put(record.getFirst().toString(), record.getSecond().get());
}
}
}
| 1,799 |
348 | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class ShinyServer(CMakePackage):
"""Shiny server lets you put shiny web applications and interactive
documents online. Take your shiny apps and share them with your
organization or the world."""
#
# HEADS UP:
# 1. The shiny server installation step will download various node
# and npm bits from the net. They seem to have them well
# constrained ("npm shrinkwrap"?), but this package is not
# "air gappable".
# 2. Docs say that it requires 'gcc'. depends_on() won't do the
# right thing, it's Up To You.
#
homepage = "https://www.rstudio.com/products/shiny/shiny-server/"
url = "https://github.com/rstudio/shiny-server/archive/v1.5.3.838.tar.gz"
version('1.5.3.838', sha256='6fd1b12cd1cbe5c64cacbec4accefe955353f9c675e5feff809c0e911a382141', deprecated=True)
depends_on('python@:2.8') # docs say: "Really. 3.x will not work"
depends_on('[email protected]:', type='build')
depends_on('git')
depends_on('r+X')
depends_on('openssl')
def cmake_args(self):
spec = self.spec
options = []
options.append("-DPYTHON=%s" % spec['python'].command.path)
return options
# Recompile the npm modules included in the project
@run_after('build')
def build_node(self):
bash = which('bash')
mkdirp('build')
bash('-c', 'bin/npm --python="$PYTHON" install')
bash('-c', 'bin/node ./ext/node/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js --python="$PYTHON" rebuild') # noqa: E501
def setup_run_environment(self, env):
env.prepend_path('PATH', join_path(self.prefix, 'shiny-server', 'bin'))
# shiny comes with its own pandoc; hook it up...
env.prepend_path('PATH', join_path(
self.prefix, 'shiny-server', 'ext', 'pandoc', 'static'))
| 834 |
719 | version https://git-lfs.github.com/spec/v1
oid sha256:a4a0a2711f5667c839fd78a78ab8a0cdb7f58c85b0cc035e3d29789edc95533e
size 34907
| 70 |
5,169 | {
"name": "CodeField",
"version": "0.1.0",
"summary": "Custom UITextField to input code.",
"description": "CodeField is custom view extends UIView. Using CodeField you can type the code like secret codes.",
"homepage": "https://github.com/brownsoo/CodeField",
"license": {
"type": "MIT",
"file": "LICENSE"
},
"authors": {
"brownsoo": "<EMAIL>"
},
"source": {
"git": "https://github.com/brownsoo/CodeField.git",
"tag": "0.1.0"
},
"social_media_url": "https://twitter.com/hansoolabs",
"platforms": {
"ios": "9.0"
},
"source_files": "CodeField/Classes/**/*",
"frameworks": "UIKit"
}
| 256 |
571 | /*
* Copyright (c) 2021
* <NAME> <EMAIL>
* Licensed under the Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) license
*/
#ifndef FR_MODEL_3D_ITEMS_TITLE_FLAG_H
#define FR_MODEL_3D_ITEMS_TITLE_FLAG_H
#include "fr_model_3d_item.h"
namespace fr::model_3d_items
{
constexpr inline vertex_3d title_flag_vertices[] = {
vertex_3d(-12.5, 0.0, 83.33),
vertex_3d(-4.17, 0.0, 83.33),
vertex_3d(4.17, 0.0, 83.33),
vertex_3d(12.5, 0.0, 83.33),
vertex_3d(-20.83, 0.0, 75.0),
vertex_3d(-12.5, 0.0, 75.0),
vertex_3d(-4.17, 0.0, 75.0),
vertex_3d(4.17, 0.0, 75.0),
vertex_3d(12.5, 0.0, 75.0),
vertex_3d(20.83, 0.0, 75.0),
vertex_3d(-20.83, 0.0, 66.67),
vertex_3d(-12.5, 0.0, 66.67),
vertex_3d(-4.17, 0.0, 66.67),
vertex_3d(4.17, 0.0, 66.67),
vertex_3d(12.5, 0.0, 66.67),
vertex_3d(20.83, 0.0, 66.67),
vertex_3d(-20.83, 0.0, 58.33),
vertex_3d(-12.5, 0.0, 58.33),
vertex_3d(-4.17, 0.0, 58.33),
vertex_3d(4.17, 0.0, 58.33),
vertex_3d(12.5, 0.0, 58.33),
vertex_3d(20.83, 0.0, 58.33),
vertex_3d(-20.83, 0.0, 50.0),
vertex_3d(-12.5, 0.0, 50.0),
vertex_3d(-4.17, 0.0, 50.0),
vertex_3d(4.17, 0.0, 50.0),
vertex_3d(12.5, 0.0, 50.0),
vertex_3d(20.83, 0.0, 50.0),
vertex_3d(-20.83, 0.0, 41.67),
vertex_3d(-12.5, 0.0, 41.67),
vertex_3d(-4.17, 0.0, 41.67),
vertex_3d(4.17, 0.0, 41.67),
vertex_3d(12.5, 0.0, 41.67),
vertex_3d(20.83, 0.0, 41.67),
vertex_3d(-20.83, 0.0, 33.33),
vertex_3d(-12.5, 0.0, 33.33),
vertex_3d(-4.17, 0.0, 33.33),
vertex_3d(4.17, 0.0, 33.33),
vertex_3d(12.5, 0.0, 33.33),
vertex_3d(20.83, 0.0, 33.33),
vertex_3d(-20.83, 0.0, 25.0),
vertex_3d(-12.5, 0.0, 25.0),
vertex_3d(-4.17, 0.0, 25.0),
vertex_3d(4.17, 0.0, 25.0),
vertex_3d(12.5, 0.0, 25.0),
vertex_3d(20.83, 0.0, 25.0),
vertex_3d(-20.83, 0.0, 16.67),
vertex_3d(-12.5, 0.0, 16.67),
vertex_3d(-4.17, 0.0, 16.67),
vertex_3d(4.17, 0.0, 16.67),
vertex_3d(12.5, 0.0, 16.67),
vertex_3d(20.83, 0.0, 16.67),
vertex_3d(-20.83, 0.0, 8.33),
vertex_3d(-12.5, 0.0, 8.33),
vertex_3d(-4.17, 0.0, 8.33),
vertex_3d(4.17, 0.0, 8.33),
vertex_3d(12.5, 0.0, 8.33),
vertex_3d(20.83, 0.0, 8.33),
vertex_3d(-20.83, 0.0, 0.0),
vertex_3d(-12.5, 0.0, 0.0),
vertex_3d(-4.17, 0.0, 0.0),
vertex_3d(4.17, 0.0, 0.0),
vertex_3d(12.5, 0.0, 0.0),
vertex_3d(20.83, 0.0, 0.0),
};
constexpr inline int title_flag_white_color = 0;
constexpr inline int title_flag_white_shading = -1;
constexpr inline face_3d title_flag_faces[] = {
face_3d(title_flag_vertices, vertex_3d(0.0, 1.0, -0.0), 0, 1, 6, 5, title_flag_white_color, title_flag_white_shading),
face_3d(title_flag_vertices, vertex_3d(0.0, 1.0, -0.0), 2, 3, 8, 7, title_flag_white_color, title_flag_white_shading),
face_3d(title_flag_vertices, vertex_3d(0.0, 1.0, -0.0), 4, 5, 11, 10, title_flag_white_color, title_flag_white_shading),
face_3d(title_flag_vertices, vertex_3d(0.0, 1.0, -0.0), 6, 7, 13, 12, title_flag_white_color, title_flag_white_shading),
face_3d(title_flag_vertices, vertex_3d(0.0, 1.0, -0.0), 8, 9, 15, 14, title_flag_white_color, title_flag_white_shading),
face_3d(title_flag_vertices, vertex_3d(0.0, 1.0, -0.0), 11, 12, 18, 17, title_flag_white_color, title_flag_white_shading),
face_3d(title_flag_vertices, vertex_3d(0.0, 1.0, -0.0), 13, 14, 20, 19, title_flag_white_color, title_flag_white_shading),
face_3d(title_flag_vertices, vertex_3d(0.0, 1.0, -0.0), 16, 17, 23, 22, title_flag_white_color, title_flag_white_shading),
face_3d(title_flag_vertices, vertex_3d(0.0, 1.0, 0.0), 19, 25, 24, 18, title_flag_white_color, title_flag_white_shading),
face_3d(title_flag_vertices, vertex_3d(0.0, 1.0, -0.0), 23, 24, 30, 29, title_flag_white_color, title_flag_white_shading),
face_3d(title_flag_vertices, vertex_3d(0.0, 1.0, -0.0), 25, 26, 32, 31, title_flag_white_color, title_flag_white_shading),
face_3d(title_flag_vertices, vertex_3d(0.0, 1.0, 0.0), 27, 26, 20, 21, title_flag_white_color, title_flag_white_shading),
face_3d(title_flag_vertices, vertex_3d(0.0, 1.0, -0.0), 28, 29, 35, 34, title_flag_white_color, title_flag_white_shading),
face_3d(title_flag_vertices, vertex_3d(0.0, 1.0, -0.0), 30, 31, 37, 36, title_flag_white_color, title_flag_white_shading),
face_3d(title_flag_vertices, vertex_3d(0.0, 1.0, -0.0), 32, 33, 39, 38, title_flag_white_color, title_flag_white_shading),
face_3d(title_flag_vertices, vertex_3d(0.0, 1.0, -0.0), 35, 36, 42, 41, title_flag_white_color, title_flag_white_shading),
face_3d(title_flag_vertices, vertex_3d(0.0, 1.0, -0.0), 37, 38, 44, 43, title_flag_white_color, title_flag_white_shading),
face_3d(title_flag_vertices, vertex_3d(0.0, 1.0, -0.0), 40, 41, 47, 46, title_flag_white_color, title_flag_white_shading),
face_3d(title_flag_vertices, vertex_3d(0.0, 1.0, -0.0), 42, 43, 49, 48, title_flag_white_color, title_flag_white_shading),
face_3d(title_flag_vertices, vertex_3d(0.0, 1.0, -0.0), 44, 45, 51, 50, title_flag_white_color, title_flag_white_shading),
face_3d(title_flag_vertices, vertex_3d(0.0, 1.0, -0.0), 47, 48, 54, 53, title_flag_white_color, title_flag_white_shading),
face_3d(title_flag_vertices, vertex_3d(0.0, 1.0, -0.0), 49, 50, 56, 55, title_flag_white_color, title_flag_white_shading),
face_3d(title_flag_vertices, vertex_3d(0.0, 1.0, -0.0), 52, 53, 59, 58, title_flag_white_color, title_flag_white_shading),
face_3d(title_flag_vertices, vertex_3d(0.0, 1.0, -0.0), 54, 55, 61, 60, title_flag_white_color, title_flag_white_shading),
face_3d(title_flag_vertices, vertex_3d(0.0, 1.0, -0.0), 56, 57, 63, 62, title_flag_white_color, title_flag_white_shading),
};
constexpr inline model_3d_item title_flag(title_flag_vertices, title_flag_faces);
}
#endif
| 3,538 |
651 | package com.squareup.subzero;
import org.junit.Test;
import static org.assertj.core.api.Java6Assertions.assertThat;
public class SystemShutdownTest {
@Test
public void testSystemShutdown(){
if (System.getProperty("os.name").contains("Linux")) {
try {
SystemShutdown.systemShutdown();
assertThat(false);
} catch (Exception e) {
//should throw exception as shutdown now as non root user on Linux should fail.
assertThat(true);
}
} else {
try {
//NOP
SystemShutdown.systemShutdown();
assertThat(true);
} catch (Exception e){
//should not throw an exception.
assertThat(false);
}
}
}
}
| 415 |
7,158 | /*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, <NAME> Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of the copyright holders may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/
#include "precomp.hpp"
#if !defined HAVE_CUDA || defined(CUDA_DISABLER)
cv::Ptr<cv::cuda::OpticalFlowDual_TVL1> cv::cuda::OpticalFlowDual_TVL1::create(double, double, double, int, int, double, int, double, double, bool)
{
throw_no_cuda();
return Ptr<cv::cuda::OpticalFlowDual_TVL1>();
}
#else
using namespace cv;
using namespace cv::cuda;
namespace tvl1flow
{
void centeredGradient(PtrStepSzf src, PtrStepSzf dx, PtrStepSzf dy, cudaStream_t stream);
void warpBackward(PtrStepSzf I0, PtrStepSzf I1, PtrStepSzf I1x, PtrStepSzf I1y,
PtrStepSzf u1, PtrStepSzf u2,
PtrStepSzf I1w, PtrStepSzf I1wx, PtrStepSzf I1wy,
PtrStepSzf grad, PtrStepSzf rho,
cudaStream_t stream);
void estimateU(PtrStepSzf I1wx, PtrStepSzf I1wy,
PtrStepSzf grad, PtrStepSzf rho_c,
PtrStepSzf p11, PtrStepSzf p12, PtrStepSzf p21, PtrStepSzf p22, PtrStepSzf p31, PtrStepSzf p32,
PtrStepSzf u1, PtrStepSzf u2, PtrStepSzf u3, PtrStepSzf error,
float l_t, float theta, float gamma, bool calcError,
cudaStream_t stream);
void estimateDualVariables(PtrStepSzf u1, PtrStepSzf u2, PtrStepSzf u3,
PtrStepSzf p11, PtrStepSzf p12, PtrStepSzf p21, PtrStepSzf p22, PtrStepSzf p31, PtrStepSzf p32,
float taut, float gamma,
cudaStream_t stream);
}
namespace
{
class OpticalFlowDual_TVL1_Impl : public OpticalFlowDual_TVL1
{
public:
OpticalFlowDual_TVL1_Impl(double tau, double lambda, double theta, int nscales, int warps, double epsilon,
int iterations, double scaleStep, double gamma, bool useInitialFlow) :
tau_(tau), lambda_(lambda), gamma_(gamma), theta_(theta), nscales_(nscales), warps_(warps),
epsilon_(epsilon), iterations_(iterations), scaleStep_(scaleStep), useInitialFlow_(useInitialFlow)
{
}
virtual double getTau() const { return tau_; }
virtual void setTau(double tau) { tau_ = tau; }
virtual double getLambda() const { return lambda_; }
virtual void setLambda(double lambda) { lambda_ = lambda; }
virtual double getGamma() const { return gamma_; }
virtual void setGamma(double gamma) { gamma_ = gamma; }
virtual double getTheta() const { return theta_; }
virtual void setTheta(double theta) { theta_ = theta; }
virtual int getNumScales() const { return nscales_; }
virtual void setNumScales(int nscales) { nscales_ = nscales; }
virtual int getNumWarps() const { return warps_; }
virtual void setNumWarps(int warps) { warps_ = warps; }
virtual double getEpsilon() const { return epsilon_; }
virtual void setEpsilon(double epsilon) { epsilon_ = epsilon; }
virtual int getNumIterations() const { return iterations_; }
virtual void setNumIterations(int iterations) { iterations_ = iterations; }
virtual double getScaleStep() const { return scaleStep_; }
virtual void setScaleStep(double scaleStep) { scaleStep_ = scaleStep; }
virtual bool getUseInitialFlow() const { return useInitialFlow_; }
virtual void setUseInitialFlow(bool useInitialFlow) { useInitialFlow_ = useInitialFlow; }
virtual void calc(InputArray I0, InputArray I1, InputOutputArray flow, Stream& stream);
virtual String getDefaultName() const { return "DenseOpticalFlow.OpticalFlowDual_TVL1"; }
private:
double tau_;
double lambda_;
double gamma_;
double theta_;
int nscales_;
int warps_;
double epsilon_;
int iterations_;
double scaleStep_;
bool useInitialFlow_;
private:
void calcImpl(const GpuMat& I0, const GpuMat& I1, GpuMat& flowx, GpuMat& flowy, Stream& stream);
void procOneScale(const GpuMat& I0, const GpuMat& I1, GpuMat& u1, GpuMat& u2, GpuMat& u3, Stream& stream);
std::vector<GpuMat> I0s;
std::vector<GpuMat> I1s;
std::vector<GpuMat> u1s;
std::vector<GpuMat> u2s;
std::vector<GpuMat> u3s;
GpuMat I1x_buf;
GpuMat I1y_buf;
GpuMat I1w_buf;
GpuMat I1wx_buf;
GpuMat I1wy_buf;
GpuMat grad_buf;
GpuMat rho_c_buf;
GpuMat p11_buf;
GpuMat p12_buf;
GpuMat p21_buf;
GpuMat p22_buf;
GpuMat p31_buf;
GpuMat p32_buf;
GpuMat diff_buf;
GpuMat diff_sum_dev;
Mat diff_sum_host;
};
void OpticalFlowDual_TVL1_Impl::calc(InputArray _frame0, InputArray _frame1, InputOutputArray _flow, Stream& stream)
{
const GpuMat frame0 = _frame0.getGpuMat();
const GpuMat frame1 = _frame1.getGpuMat();
BufferPool pool(stream);
GpuMat flowx = pool.getBuffer(frame0.size(), CV_32FC1);
GpuMat flowy = pool.getBuffer(frame0.size(), CV_32FC1);
calcImpl(frame0, frame1, flowx, flowy, stream);
GpuMat flows[] = {flowx, flowy};
cuda::merge(flows, 2, _flow, stream);
}
void OpticalFlowDual_TVL1_Impl::calcImpl(const GpuMat& I0, const GpuMat& I1, GpuMat& flowx, GpuMat& flowy, Stream& stream)
{
CV_Assert( I0.type() == CV_8UC1 || I0.type() == CV_32FC1 );
CV_Assert( I0.size() == I1.size() );
CV_Assert( I0.type() == I1.type() );
CV_Assert( !useInitialFlow_ || (flowx.size() == I0.size() && flowx.type() == CV_32FC1 && flowy.size() == flowx.size() && flowy.type() == flowx.type()) );
CV_Assert( nscales_ > 0 );
// allocate memory for the pyramid structure
I0s.resize(nscales_);
I1s.resize(nscales_);
u1s.resize(nscales_);
u2s.resize(nscales_);
u3s.resize(nscales_);
I0.convertTo(I0s[0], CV_32F, I0.depth() == CV_8U ? 1.0 : 255.0, stream);
I1.convertTo(I1s[0], CV_32F, I1.depth() == CV_8U ? 1.0 : 255.0, stream);
if (!useInitialFlow_)
{
flowx.create(I0.size(), CV_32FC1);
flowy.create(I0.size(), CV_32FC1);
}
u1s[0] = flowx;
u2s[0] = flowy;
if (gamma_)
{
u3s[0].create(I0.size(), CV_32FC1);
}
I1x_buf.create(I0.size(), CV_32FC1);
I1y_buf.create(I0.size(), CV_32FC1);
I1w_buf.create(I0.size(), CV_32FC1);
I1wx_buf.create(I0.size(), CV_32FC1);
I1wy_buf.create(I0.size(), CV_32FC1);
grad_buf.create(I0.size(), CV_32FC1);
rho_c_buf.create(I0.size(), CV_32FC1);
p11_buf.create(I0.size(), CV_32FC1);
p12_buf.create(I0.size(), CV_32FC1);
p21_buf.create(I0.size(), CV_32FC1);
p22_buf.create(I0.size(), CV_32FC1);
if (gamma_)
{
p31_buf.create(I0.size(), CV_32FC1);
p32_buf.create(I0.size(), CV_32FC1);
}
diff_buf.create(I0.size(), CV_32FC1);
// create the scales
for (int s = 1; s < nscales_; ++s)
{
cuda::resize(I0s[s-1], I0s[s], Size(), scaleStep_, scaleStep_, INTER_LINEAR, stream);
cuda::resize(I1s[s-1], I1s[s], Size(), scaleStep_, scaleStep_, INTER_LINEAR, stream);
if (I0s[s].cols < 16 || I0s[s].rows < 16)
{
nscales_ = s;
break;
}
if (useInitialFlow_)
{
cuda::resize(u1s[s-1], u1s[s], Size(), scaleStep_, scaleStep_, INTER_LINEAR, stream);
cuda::resize(u2s[s-1], u2s[s], Size(), scaleStep_, scaleStep_, INTER_LINEAR, stream);
cuda::multiply(u1s[s], Scalar::all(scaleStep_), u1s[s], 1, -1, stream);
cuda::multiply(u2s[s], Scalar::all(scaleStep_), u2s[s], 1, -1, stream);
}
else
{
u1s[s].create(I0s[s].size(), CV_32FC1);
u2s[s].create(I0s[s].size(), CV_32FC1);
}
if (gamma_)
{
u3s[s].create(I0s[s].size(), CV_32FC1);
}
}
if (!useInitialFlow_)
{
u1s[nscales_-1].setTo(Scalar::all(0), stream);
u2s[nscales_-1].setTo(Scalar::all(0), stream);
}
if (gamma_)
{
u3s[nscales_ - 1].setTo(Scalar::all(0), stream);
}
// pyramidal structure for computing the optical flow
for (int s = nscales_ - 1; s >= 0; --s)
{
// compute the optical flow at the current scale
procOneScale(I0s[s], I1s[s], u1s[s], u2s[s], u3s[s], stream);
// if this was the last scale, finish now
if (s == 0)
break;
// otherwise, upsample the optical flow
// zoom the optical flow for the next finer scale
cuda::resize(u1s[s], u1s[s - 1], I0s[s - 1].size(), 0, 0, INTER_LINEAR, stream);
cuda::resize(u2s[s], u2s[s - 1], I0s[s - 1].size(), 0, 0, INTER_LINEAR, stream);
if (gamma_)
{
cuda::resize(u3s[s], u3s[s - 1], I0s[s - 1].size(), 0, 0, INTER_LINEAR, stream);
}
// scale the optical flow with the appropriate zoom factor
cuda::multiply(u1s[s - 1], Scalar::all(1/scaleStep_), u1s[s - 1], 1, -1, stream);
cuda::multiply(u2s[s - 1], Scalar::all(1/scaleStep_), u2s[s - 1], 1, -1, stream);
}
}
void OpticalFlowDual_TVL1_Impl::procOneScale(const GpuMat& I0, const GpuMat& I1, GpuMat& u1, GpuMat& u2, GpuMat& u3, Stream& _stream)
{
using namespace tvl1flow;
cudaStream_t stream = StreamAccessor::getStream(_stream);
const double scaledEpsilon = epsilon_ * epsilon_ * I0.size().area();
CV_DbgAssert( I1.size() == I0.size() );
CV_DbgAssert( I1.type() == I0.type() );
CV_DbgAssert( u1.size() == I0.size() );
CV_DbgAssert( u2.size() == u1.size() );
GpuMat I1x = I1x_buf(Rect(0, 0, I0.cols, I0.rows));
GpuMat I1y = I1y_buf(Rect(0, 0, I0.cols, I0.rows));
centeredGradient(I1, I1x, I1y, stream);
GpuMat I1w = I1w_buf(Rect(0, 0, I0.cols, I0.rows));
GpuMat I1wx = I1wx_buf(Rect(0, 0, I0.cols, I0.rows));
GpuMat I1wy = I1wy_buf(Rect(0, 0, I0.cols, I0.rows));
GpuMat grad = grad_buf(Rect(0, 0, I0.cols, I0.rows));
GpuMat rho_c = rho_c_buf(Rect(0, 0, I0.cols, I0.rows));
GpuMat p11 = p11_buf(Rect(0, 0, I0.cols, I0.rows));
GpuMat p12 = p12_buf(Rect(0, 0, I0.cols, I0.rows));
GpuMat p21 = p21_buf(Rect(0, 0, I0.cols, I0.rows));
GpuMat p22 = p22_buf(Rect(0, 0, I0.cols, I0.rows));
GpuMat p31, p32;
if (gamma_)
{
p31 = p31_buf(Rect(0, 0, I0.cols, I0.rows));
p32 = p32_buf(Rect(0, 0, I0.cols, I0.rows));
}
p11.setTo(Scalar::all(0), _stream);
p12.setTo(Scalar::all(0), _stream);
p21.setTo(Scalar::all(0), _stream);
p22.setTo(Scalar::all(0), _stream);
if (gamma_)
{
p31.setTo(Scalar::all(0), _stream);
p32.setTo(Scalar::all(0), _stream);
}
GpuMat diff = diff_buf(Rect(0, 0, I0.cols, I0.rows));
const float l_t = static_cast<float>(lambda_ * theta_);
const float taut = static_cast<float>(tau_ / theta_);
for (int warpings = 0; warpings < warps_; ++warpings)
{
warpBackward(I0, I1, I1x, I1y, u1, u2, I1w, I1wx, I1wy, grad, rho_c, stream);
double error = std::numeric_limits<double>::max();
double prevError = 0.0;
for (int n = 0; error > scaledEpsilon && n < iterations_; ++n)
{
// some tweaks to make sum operation less frequently
bool calcError = (epsilon_ > 0) && (n & 0x1) && (prevError < scaledEpsilon);
estimateU(I1wx, I1wy, grad, rho_c, p11, p12, p21, p22, p31, p32, u1, u2, u3, diff, l_t, static_cast<float>(theta_), gamma_, calcError, stream);
if (calcError)
{
cuda::calcSum(diff, diff_sum_dev, cv::noArray(), _stream);
diff_sum_dev.download(diff_sum_host, _stream);
_stream.waitForCompletion();
error = diff_sum_host.at<double>(0,0);
prevError = error;
}
else
{
error = std::numeric_limits<double>::max();
prevError -= scaledEpsilon;
}
estimateDualVariables(u1, u2, u3, p11, p12, p21, p22, p31, p32, taut, gamma_, stream);
}
}
}
}
Ptr<OpticalFlowDual_TVL1> cv::cuda::OpticalFlowDual_TVL1::create(
double tau, double lambda, double theta, int nscales, int warps,
double epsilon, int iterations, double scaleStep, double gamma, bool useInitialFlow)
{
return makePtr<OpticalFlowDual_TVL1_Impl>(tau, lambda, theta, nscales, warps,
epsilon, iterations, scaleStep, gamma, useInitialFlow);
}
#endif // !defined HAVE_CUDA || defined(CUDA_DISABLER)
| 7,574 |
314 | import fs
import logging
from django.conf import settings
from django.apps import AppConfig
logger = logging.getLogger(__name__)
class BakeryConfig(AppConfig):
name = 'bakery'
verbose_name = "Bakery"
filesystem_name = getattr(settings, 'BAKERY_FILESYSTEM', "osfs:///")
filesystem = fs.open_fs(filesystem_name)
| 116 |
11,356 | <reponame>Bpowers4/turicreate
/* Copyright © 2017 Apple Inc. All rights reserved.
*
* Use of this source code is governed by a BSD-3-clause license that can
* be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
*/
#ifndef TURI_SERIALIZE_VECTOR_HPP
#define TURI_SERIALIZE_VECTOR_HPP
#include <vector>
#include <core/storage/serialization/iarchive.hpp>
#include <core/storage/serialization/oarchive.hpp>
#include <core/storage/serialization/iterator.hpp>
namespace turi {
namespace archive_detail {
/**
* We re-dispatch vectors because based on the contained type,
* it is actually possible to serialize them like a POD
*/
template <typename OutArcType, typename ValueType, bool IsPOD>
struct vector_serialize_impl {
static void exec(OutArcType& oarc, const ValueType& vec) {
// really this is an assert false. But the static assert
// must depend on a template parameter
BOOST_STATIC_ASSERT(sizeof(OutArcType) == 0);
assert(false);
};
};
/**
* We re-dispatch vectors because based on the contained type,
* it is actually possible to deserialize them like iarc POD
*/
template <typename InArcType, typename ValueType, bool IsPOD>
struct vector_deserialize_impl {
static void exec(InArcType& iarc, ValueType& vec) {
// really this is an assert false. But the static assert
// must depend on a template parameter
BOOST_STATIC_ASSERT(sizeof(InArcType) == 0);
assert(false);
};
};
/// If contained type is not a POD use the standard serializer
template <typename OutArcType, typename ValueType>
struct vector_serialize_impl<OutArcType, ValueType, false > {
static void exec(OutArcType& oarc, const std::vector<ValueType>& vec) {
oarc << size_t(vec.size());
for (size_t i = 0;i < vec.size(); ++i) {
oarc << vec[i];
}
}
};
/// Fast vector serialization if contained type is a POD
template <typename OutArcType, typename ValueType>
struct vector_serialize_impl<OutArcType, ValueType, true > {
static void exec(OutArcType& oarc, const std::vector<ValueType>& vec) {
oarc << size_t(vec.size());
serialize(oarc, vec.data(),sizeof(ValueType)*vec.size());
}
};
/// If contained type is not a POD use the standard deserializer
template <typename InArcType, typename ValueType>
struct vector_deserialize_impl<InArcType, ValueType, false > {
static void exec(InArcType& iarc, std::vector<ValueType>& vec){
size_t len;
iarc >> len;
vec.clear(); vec.resize(len);
for (size_t i = 0;i < len; ++i) {
iarc >> vec[i];
}
}
};
/// Fast vector deserialization if contained type is a POD
template <typename InArcType, typename ValueType>
struct vector_deserialize_impl<InArcType, ValueType, true > {
static void exec(InArcType& iarc, std::vector<ValueType>& vec){
size_t len;
iarc >> len;
vec.clear(); vec.resize(len);
deserialize(iarc, vec.data(), sizeof(ValueType)*vec.size());
}
};
/**
Serializes a vector */
template <typename OutArcType, typename ValueType>
struct serialize_impl<OutArcType, std::vector<ValueType>, false > {
static void exec(OutArcType& oarc, const std::vector<ValueType>& vec) {
vector_serialize_impl<OutArcType, ValueType,
gl_is_pod_or_scaler<ValueType>::value >::exec(oarc, vec);
}
};
/**
deserializes a vector */
template <typename InArcType, typename ValueType>
struct deserialize_impl<InArcType, std::vector<ValueType>, false > {
static void exec(InArcType& iarc, std::vector<ValueType>& vec){
vector_deserialize_impl<InArcType, ValueType,
gl_is_pod_or_scaler<ValueType>::value >::exec(iarc, vec);
}
};
} // archive_detail
} // namespace turi
#endif
| 1,587 |
14,668 | <filename>chrome/browser/ui/commander/fuzzy_finder.cc
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/commander/fuzzy_finder.h"
#include "base/i18n/case_conversion.h"
#include "base/i18n/char_iterator.h"
#include "base/ranges/algorithm.h"
#include "base/strings/string_util.h"
#include "third_party/icu/source/common/unicode/uchar.h"
#include "third_party/icu/source/common/unicode/ustring.h"
namespace {
// Used only for exact matches.
static const double kMaxScore = 1.0;
// When needle is a prefix of haystack.
static const double kPrefixScore = .99;
// When a heuristic determines that the match should score highly,
// but it is *not* an exact match or prefix.
static const double kVeryHighScore = .95;
// Max haystack size in UTF-16 units for the dynamic programming algorithm.
// Haystacks longer than this are scored by ConsecutiveMatchWithGaps.
static constexpr size_t kMaxHaystack = 1024;
// Max needle size in UTF-16 units for the dynamic programming algorithm.
// Needles longer than this are scored by ConsecutiveMatchWithGaps
static constexpr size_t kMaxNeedle = 16;
struct MatchRecord {
MatchRecord(int start, int end, int length, bool is_boundary, int gap_before)
: range(start, end),
length(length),
gap_before(gap_before),
is_boundary(is_boundary) {}
gfx::Range range;
// This can't be inferred from `range` since range is in code units for
// display, but `length` is in code points.
int length;
int gap_before;
bool is_boundary;
};
// Scores matches identified by ConsecutiveMatchWithGaps(). See that comment
// for details.
double ScoreForMatches(const std::vector<MatchRecord>& matches,
size_t needle_size,
size_t haystack_size) {
// |base_score| is the maximum per match, so total should not exceed 1.0.
const double base_score = 1.0 / needle_size;
const double gap_penalty = 1.0 / haystack_size;
static const double kRegularMultiplier = .5;
static const double kWordBoundaryMultiplier = .8;
static const double kInitialMultiplier = 1.0;
double score = 0;
for (size_t i = 0; i < matches.size(); i++) {
MatchRecord match = matches[i];
// The first character of the match is special; it gets a relative bonus
// if it is on a boundary. Otherwise, it is penalized by the distance
// between it and the previous match.
if (match.is_boundary) {
score +=
base_score * (i == 0 ? kInitialMultiplier : kWordBoundaryMultiplier);
} else {
double penalty_multiplier = 1 - (gap_penalty * match.gap_before);
DCHECK_GT(penalty_multiplier, 0);
score += base_score * kRegularMultiplier * penalty_multiplier;
}
// ...then the rest of a contiguous match.
score += (match.length - 1) * base_score * kRegularMultiplier;
}
DCHECK(score <= 1.0);
return score;
}
size_t LengthInCodePoints(const std::u16string& str) {
return u_countChar32(str.data(), str.size());
}
// Returns a positive score if every code point in |needle| is present in
// |haystack| in the same order. The match *need not* be contiguous. Matches in
// special positions are given extra weight, and noncontiguous matches are
// penalized based on the size of the gaps between.
// This is not guaranteed to return the best possible match; for example, given
// needle = "orange" and haystack = "William of Orange", this function will
// match as "William [o]f O[range]" rather than "William of [Orange]". It's main
// use is to filter nonmatches before a more comprehensive algorithm, and as a
// fallback for when the inputs are too high for a more comprehensive algorithm
// to be performant.
double ConsecutiveMatchWithGaps(const std::u16string& needle,
const std::u16string& haystack,
std::vector<gfx::Range>* matched_ranges) {
DCHECK(needle == base::i18n::FoldCase(needle));
DCHECK(haystack == base::i18n::FoldCase(haystack));
DCHECK(matched_ranges->empty());
// Special case for prefix.
if (base::StartsWith(haystack, needle)) {
matched_ranges->emplace_back(0, needle.size());
return kPrefixScore;
}
base::i18n::UTF16CharIterator n_iter(needle);
base::i18n::UTF16CharIterator h_iter(haystack);
std::vector<MatchRecord> matches;
int gap_size_before_match = 0;
int match_began_on_boundary = true;
int match_start = -1;
int match_length = 0;
// Find matching ranges.
while (!n_iter.end() && !h_iter.end()) {
if (n_iter.get() == h_iter.get()) {
// There's a match.
if (match_length == 0) {
// Match start.
match_start = h_iter.array_pos();
match_began_on_boundary =
h_iter.start() || u_isUWhiteSpace(h_iter.PreviousCodePoint());
}
++match_length;
h_iter.Advance();
n_iter.Advance();
} else {
if (match_length > 0) {
DCHECK(match_start != -1);
match_length = 0;
matches.emplace_back(match_start, h_iter.array_pos(), match_length,
match_began_on_boundary, gap_size_before_match);
gap_size_before_match = 1;
match_start = -1;
} else {
gap_size_before_match++;
}
h_iter.Advance();
}
}
if (!n_iter.end()) {
// Didn't match all of |needle|.
matched_ranges->clear();
return 0;
}
if (match_length > 0) {
DCHECK(match_start != -1);
matches.emplace_back(match_start, h_iter.array_pos(), match_length,
match_began_on_boundary, gap_size_before_match);
}
for (const MatchRecord& match : matches) {
matched_ranges->push_back(match.range);
}
double score = ScoreForMatches(matches, LengthInCodePoints(needle),
LengthInCodePoints(haystack));
score *= kPrefixScore; // Normalize so that a prefix always wins.
return score;
}
// Converts a list of indices in `positions` into contiguous ranges and fills
// `matched_ranges` with the result.
// For example: [0, 1, 4, 7, 8, 9] -> [{0, 2}, {4, 1}, {7, 3}].
void ConvertPositionsToRanges(const std::vector<size_t>& positions,
std::vector<gfx::Range>* matched_ranges) {
size_t n = positions.size();
DCHECK(n > 0);
size_t start = positions.front();
size_t length = 1;
for (size_t i = 0; i < n - 1; ++i) {
if (positions.at(i) + 1 < positions.at(i + 1)) {
// Noncontiguous positions -> close out the range.
matched_ranges->emplace_back(start, start + length);
start = positions.at(i + 1);
length = 1;
} else {
++length;
}
}
matched_ranges->emplace_back(start, start + length);
}
// Returns the maximum score for the given matrix, then backtracks to fill in
// `matched_ranges`. See fuzzy_finder.md for extended discussion.
int ScoreForMatrix(const std::vector<int> score_matrix,
size_t width,
size_t height,
const std::vector<size_t> codepoint_to_offset,
std::vector<gfx::Range>* matched_ranges) {
// Find winning score and its index.
size_t max_index = 0;
int max_score = 0;
for (size_t i = 0; i < width; i++) {
int score = score_matrix[(height - 1) * width + i];
if (score > max_score) {
max_score = score;
max_index = i;
}
}
// Backtrack through the matrix to find matching positions.
std::vector<size_t> positions = {codepoint_to_offset[max_index]};
size_t cur_i = max_index;
size_t cur_j = height - 1;
while (cur_j > 0) {
// Move diagonally...
--cur_i;
--cur_j;
// ...then scan left until the score stops increasing.
int current = score_matrix[cur_j * width + cur_i];
int left = cur_i == 0 ? 0 : score_matrix[cur_j * width + cur_i - 1];
while (current < left) {
cur_i -= 1;
if (cur_i == 0)
break;
current = left;
left = score_matrix[cur_j * width + cur_i - 1];
}
positions.push_back(codepoint_to_offset[cur_i]);
}
base::ranges::reverse(positions);
ConvertPositionsToRanges(positions, matched_ranges);
return max_score;
}
} // namespace
namespace commander {
FuzzyFinder::FuzzyFinder(const std::u16string& needle)
: needle_(base::i18n::FoldCase(needle)) {
if (needle_.size() <= kMaxNeedle) {
score_matrix_.reserve(needle_.size() * kMaxHaystack);
consecutive_matrix_.reserve(needle_.size() * kMaxHaystack);
}
}
FuzzyFinder::~FuzzyFinder() = default;
double FuzzyFinder::Find(const std::u16string& haystack,
std::vector<gfx::Range>* matched_ranges) {
matched_ranges->clear();
if (needle_.size() == 0)
return 0;
const std::u16string& folded = base::i18n::FoldCase(haystack);
size_t m = needle_.size();
size_t n = folded.size();
// Special case 0: M > N. We don't allow skipping anything in |needle|, so
// no match possible.
if (m > n) {
return 0;
}
// Special case 1: M == N. It must be either an exact match,
// or a non-match.
if (m == n) {
if (folded == needle_) {
matched_ranges->emplace_back(0, needle_.length());
return kMaxScore;
} else {
return 0;
}
}
// Special case 2: needle is a prefix of haystack
if (base::StartsWith(folded, needle_)) {
matched_ranges->emplace_back(0, needle_.length());
return kPrefixScore;
}
// Special case 3: M == 1. Scan through all matches, and return:
// no match ->
// 0
// prefix match ->
// kPrefixScore (but should have been handled above)
// word boundary match (e.g. needle: j, haystack "Orange [J]uice") ->
// kVeryHighScore
// any other match ->
// Scored based on how far into haystack needle is found, normalized by
// haystack length.
if (m == 1) {
size_t substring_position = folded.find(needle_);
while (substring_position != std::string::npos) {
if (substring_position == 0) {
// Prefix match.
matched_ranges->emplace_back(0, 1);
return kPrefixScore;
} else {
wchar_t previous = folded.at(substring_position - 1);
if (base::IsUnicodeWhitespace(previous)) {
// Word boundary. Since we've eliminated prefix by now, this is as
// good as we're going to get, so we can return.
matched_ranges->clear();
matched_ranges->emplace_back(substring_position,
substring_position + 1);
return kVeryHighScore;
// Internal match. If |matched_ranges| is already populated, we've
// seen another internal match previously, so ignore this one.
} else if (matched_ranges->empty()) {
matched_ranges->emplace_back(substring_position,
substring_position + 1);
}
}
substring_position = folded.find(needle_, substring_position + 1);
}
if (matched_ranges->empty()) {
return 0;
} else {
// First internal match.
DCHECK_EQ(matched_ranges->size(), 1u);
double position = static_cast<double>(matched_ranges->back().start());
return std::min(1 - position / folded.length(), 0.01);
}
}
// This has two purposes:
// 1. If there's no match here, we should bail instead of wasting time on the
// full O(mn) matching algorithm.
// 2. If m * n is too big, we will use this result instead of doing the full
// full O(mn) matching algorithm.
double score = ConsecutiveMatchWithGaps(needle_, folded, matched_ranges);
if (score == 0) {
matched_ranges->clear();
return 0;
} else if (n > kMaxHaystack || m > kMaxNeedle) {
return score;
}
matched_ranges->clear();
return MatrixMatch(needle_, folded, matched_ranges);
}
double FuzzyFinder::MatrixMatch(const std::u16string& needle_string,
const std::u16string& haystack_string,
std::vector<gfx::Range>* matched_ranges) {
static constexpr int kMatchScore = 16;
static constexpr int kBoundaryBonus = 8;
static constexpr int kConsecutiveBonus = 4;
static constexpr int kInitialBonus = kBoundaryBonus * 2;
static constexpr int kGapStart = 3;
static constexpr int kGapExtension = 1;
const size_t m = LengthInCodePoints(needle_string);
const size_t n = LengthInCodePoints(haystack_string);
DCHECK_LE(m, kMaxNeedle);
DCHECK_LE(n, kMaxHaystack);
score_matrix_.assign(m * n, 0);
consecutive_matrix_.assign(m * n, 0);
word_boundaries_.assign(n, false);
codepoint_to_offset_.assign(n, 0);
base::i18n::UTF16CharIterator needle(needle_string);
base::i18n::UTF16CharIterator haystack(haystack_string);
// Fill in first row and word boundaries.
bool in_gap = false;
int32_t needle_code_point = needle.get();
int32_t haystack_code_point;
word_boundaries_[0] = true;
while (!haystack.end()) {
haystack_code_point = haystack.get();
size_t i = haystack.char_offset();
codepoint_to_offset_[i] = haystack.array_pos();
if (i < n - 1)
word_boundaries_[i + 1] = u_isUWhiteSpace(haystack_code_point);
int bonus = word_boundaries_[i] ? kInitialBonus : 0;
if (needle_code_point == haystack_code_point) {
consecutive_matrix_[i] = 1;
score_matrix_[i] = kMatchScore + bonus;
in_gap = false;
} else {
int penalty = in_gap ? kGapExtension : kGapStart;
int left_score = i > 0 ? score_matrix_[i - 1] : 0;
score_matrix_[i] = std::max(left_score - penalty, 0);
in_gap = true;
}
haystack.Advance();
}
while (!haystack.start())
haystack.Rewind();
needle.Advance();
// Fill in rows 1 through n -1:
while (!needle.end()) {
in_gap = false;
while (!haystack.end()) {
size_t j = needle.char_offset();
size_t i = haystack.char_offset();
size_t idx = i + (j * n);
if (i < j) {
// Since all of needle must match, by the time we've gotten to the nth
// character of needle, at least n - 1 characters of haystack have been
// consumed.
haystack.Advance();
continue;
}
// If we choose `left_score`, we're either creating or extending a gap.
int left_score = i > 0 ? score_matrix_[idx - 1] : 0;
int penalty = in_gap ? kGapExtension : kGapStart;
left_score -= penalty;
// If we choose `diagonal_score`, we're extending a match.
int diagonal_score = 0;
int consecutive = 0;
if (needle.get() == haystack.get()) {
DCHECK_GT(j, 0u);
DCHECK_GE(i, j);
// DCHECKs above show that this index is valid.
size_t diagonal_index = idx - n - 1;
diagonal_score = score_matrix_[diagonal_index] + kMatchScore;
if (word_boundaries_[j]) {
diagonal_score += kBoundaryBonus;
// If we're giving a boundary bonus, it implies that this position
// is an "acronym" type match rather than a "consecutive string"
// type match, so reset consecutive to not double dip.
consecutive = 1;
} else {
consecutive = consecutive_matrix_[idx] + 1;
if (consecutive > 1) {
// Find the beginning of this consecutive run.
size_t run_start = i - consecutive;
diagonal_score += word_boundaries_[run_start] ? kBoundaryBonus
: kConsecutiveBonus;
}
}
}
in_gap = left_score > diagonal_score;
consecutive_matrix_[idx] = in_gap ? 0 : consecutive;
score_matrix_[idx] = std::max(0, std::max(left_score, diagonal_score));
haystack.Advance();
}
while (!haystack.start())
haystack.Rewind();
needle.Advance();
}
const int raw_score =
ScoreForMatrix(score_matrix_, n, m, codepoint_to_offset_, matched_ranges);
const int max_possible_score =
kInitialBonus + kMatchScore + (kBoundaryBonus + kMatchScore) * (m - 1);
// But that said, in most cases, good matches will score well below this, so
// let's saturate a little.
constexpr float kScoreBias = 0.25;
const double score =
kScoreBias +
(static_cast<double>(raw_score) / max_possible_score) * (1 - kScoreBias);
DCHECK_LE(score, 1.0);
// Make sure it scores below exact matches and prefixes.
return score * kVeryHighScore;
}
} // namespace commander
| 6,590 |
422 | #pragma once
namespace vuda
{
namespace detail
{
class thrdcmdpool
{
//friend class logical_device;
public:
/*
For each thread that sets/uses the device a single command pool is created
- this pool have m_queueComputeCount command buffers allocated.
This way,
- VkCommandBuffers are allocated from a "parent" VkCommandPool
- VkCommandBuffers written to in different threads must come from different pools
=======================================================
command buffers \ threads : 0 1 2 3 4 ... #n
0
1
.
.
.
m_queueComputeCount
=======================================================
*/
thrdcmdpool(const vk::UniqueDevice& device, const uint32_t queueFamilyIndex, const uint32_t queueComputeCount) :
m_commandPool(device->createCommandPoolUnique(vk::CommandPoolCreateInfo(vk::CommandPoolCreateFlags(vk::CommandPoolCreateFlagBits::eResetCommandBuffer), queueFamilyIndex))),
m_commandBuffers(device->allocateCommandBuffersUnique(vk::CommandBufferAllocateInfo(m_commandPool.get(), vk::CommandBufferLevel::ePrimary, queueComputeCount))),
m_commandBufferState(queueComputeCount, cbReset),
m_queryPool(device->createQueryPoolUnique(vk::QueryPoolCreateInfo(vk::QueryPoolCreateFlags(), vk::QueryType::eTimestamp, VUDA_MAX_QUERY_COUNT, vk::QueryPipelineStatisticFlags()))),
m_queryIndex(0)
{
//
// create unique mutexes
/*m_mtxCommandBuffers.resize(queueComputeCount);
for(unsigned int i = 0; i < queueComputeCount; ++i)
m_mtxCommandBuffers[i] = std::make_unique<std::mutex>();*/
//
// create fences
m_ufences.reserve(queueComputeCount);
for(unsigned int i = 0; i < queueComputeCount; ++i)
m_ufences.push_back(device->createFenceUnique(vk::FenceCreateFlags()));
}
/*
public synchronized interface
*/
void SetEvent(const vk::UniqueDevice& device, const event_t event, const stream_t stream) const
{
//
// lock access to the streams commandbuffer
//std::lock_guard<std::mutex> lck(*m_mtxCommandBuffers[stream]);
//
//
CheckStateAndBeginCommandBuffer(device, stream);
//
//
m_commandBuffers[stream]->setEvent(event, vk::PipelineStageFlagBits::eBottomOfPipe);
}
uint32_t GetQueryID(void) const
{
assert(m_queryIndex != VUDA_MAX_QUERY_COUNT);
return m_queryIndex++;
}
void WriteTimeStamp(const vk::UniqueDevice& device, const uint32_t queryID, const stream_t stream) const
{
//
// lock access to the streams commandbuffer
//std::lock_guard<std::mutex> lck(*m_mtxCommandBuffers[stream]);
//
// submit write time stamp command
CheckStateAndBeginCommandBuffer(device, stream);
// reset
m_commandBuffers[stream]->resetQueryPool(m_queryPool.get(), queryID, 1);
// write
m_commandBuffers[stream]->writeTimestamp(vk::PipelineStageFlagBits::eBottomOfPipe, m_queryPool.get(), queryID);
}
uint64_t GetQueryPoolResults(const vk::UniqueDevice& device, const uint32_t queryID) const
{
// vkGetQueryPoolResults(sync)
// vkCmdCopyQueryPoolResults(async)
const uint32_t numQueries = 1; // VUDA_MAX_QUERY_COUNT;
uint64_t result[numQueries];
size_t stride = sizeof(uint64_t);
size_t size = numQueries * stride;
//
// vkGetQueryPoolResults will wait for the results to be available when VK_QUERY_RESULT_WAIT_BIT is specified
vk::Result res =
device->getQueryPoolResults(m_queryPool.get(), queryID, numQueries, size, &result[0], stride, vk::QueryResultFlagBits::e64 | vk::QueryResultFlagBits::eWait);
assert(res == vk::Result::eSuccess);
return result[0];
}
/*void ResetQueryPool(const vk::UniqueDevice& device, const uint32_t queryID, const stream_t stream) const
{
//
// lock access to the streams commandbuffer
std::lock_guard<std::mutex> lck(*m_mtxCommandBuffers[stream]);
//
// reset query
CheckStateAndBeginCommandBuffer(device, stream);
m_commandBuffers[stream]->resetQueryPool(m_queryPool.get(), queryID, 1);
}*/
void memcpyDevice(const vk::UniqueDevice& device, const vk::Buffer& bufferDst, const vk::DeviceSize dstOffset, const vk::Buffer& bufferSrc, const vk::DeviceSize srcOffset, const vk::DeviceSize size, const vk::Queue& queue, const stream_t stream) const
{
//
// lock access to the streams commandbuffer
//std::lock_guard<std::mutex> lck(*m_mtxCommandBuffers[stream]);
/*//
// hello
std::ostringstream ostr;
ostr << "thrd: " << std::this_thread::get_id() << ", pooladrr: " << this << ", locked and modifying command buffer: " << stream << std::endl;
std::cout << ostr.str();
ostr.str("");*/
//
// check state of command buffer and see if we should call begin
CheckStateAndBeginCommandBuffer(device, stream);
//
// submit copy buffer call to command buffer
vk::BufferCopy copyRegion = vk::BufferCopy()
.setSrcOffset(srcOffset)
.setDstOffset(dstOffset)
.setSize(size);
//
// the order of src and dst is interchanged compared to memcpy
m_commandBuffers[stream]->copyBuffer(bufferSrc, bufferDst, copyRegion);
//
// hello there
/*std::ostringstream ostr;
ostr << std::this_thread::get_id() << ", commandbuffer: " << &m_commandBuffers[stream] << ", src: " << bufferSrc << ", dst: " << bufferDst << ", copy region: srcOffset: " << copyRegion.srcOffset << ", dstOffset: " << copyRegion.dstOffset << ", size: " << copyRegion.size << std::endl;
std::cout << ostr.str();*/
//
// insert pipeline barrier?
/*vk::BufferMemoryBarrier bmb(vk::AccessFlagBits::eTransferRead, vk::AccessFlagBits::eTransferWrite, VK_QUEUE_FAMILY_IGNORED, VK_QUEUE_FAMILY_IGNORED, bufferDst, dstOffset, size);
m_commandBuffers[stream]->pipelineBarrier(
vk::PipelineStageFlagBits::eTransfer,
vk::PipelineStageFlagBits::eBottomOfPipe,
vk::DependencyFlagBits::eByRegion,
0, nullptr,
1, &bmb,
0, nullptr);*/
//
// execute the command buffer
ExecuteQueue(device, queue, stream);
//ostr << "thrd: " << std::this_thread::get_id() << ", pooladrr: " << this << ", unlocking command buffer: " << stream << std::endl;
//std::cout << ostr.str();
}
template <size_t specializationByteSize, typename... specialTypes, size_t bindingSize>
void UpdateDescriptorAndCommandBuffer(const vk::UniqueDevice& device, const kernelprogram<specializationByteSize>& kernel, const specialization<specialTypes...>& specials, const std::array<vk::DescriptorBufferInfo, bindingSize>& bufferDescriptors, const dim3 blocks, const stream_t stream) const
{
//
// lock access to the streams commandbuffer
//std::lock_guard<std::mutex> lck(*m_mtxCommandBuffers[stream]);
//
// check state of command buffer and see if we should call begin
CheckStateAndBeginCommandBuffer(device, stream);
//
// record command buffer
kernel.UpdateDescriptorAndCommandBuffer(device, m_commandBuffers[stream], bufferDescriptors, specials, blocks);
//
// insert (buffer) memory barrier
// [ memory barriers are created for each resource, it would be better to apply the barriers based on readonly, writeonly information ]
const uint32_t numbuf = (uint32_t)bufferDescriptors.size();
std::vector<vk::BufferMemoryBarrier> bmb(numbuf);
for(uint32_t i=0; i<numbuf; ++i)
{
bmb[i] = vk::BufferMemoryBarrier(
vk::AccessFlagBits::eShaderWrite,
vk::AccessFlagBits::eShaderRead,
VK_QUEUE_FAMILY_IGNORED,
VK_QUEUE_FAMILY_IGNORED,
bufferDescriptors[i].buffer,
bufferDescriptors[i].offset,
bufferDescriptors[i].range);
}
m_commandBuffers[stream]->pipelineBarrier(
vk::PipelineStageFlagBits::eComputeShader,
vk::PipelineStageFlagBits::eComputeShader,
vk::DependencyFlagBits::eByRegion,
0, nullptr,
numbuf, bmb.data(),
0, nullptr);
//
// statistics
/*std::ostringstream ostr;
ostr << "tid: " << std::this_thread::get_id() << ", stream_id: " << stream << ", command buffer addr: " << &m_commandBuffers[stream] << std::endl;
std::cout << ostr.str();*/
/*//
// if the recording failed, it is solely due to the limited amount of descriptor sets
if(ret == false)
{
//
// if we are doing a new recording no need to end and execute
if(newRecording == false)
{
std::ostringstream ostr;
std::thread::id tid = std::this_thread::get_id();
ostr << tid << ": ran out of descriptors! Got to execute now and retry!" << std::endl;
std::cout << ostr.str();
// end recording/execute, wait, begin recording
ExecuteQueue(device, queueFamilyIndex, stream);
WaitAndReset(device, stream);
BeginRecordingCommandBuffer(stream);
}
//
// record
ret = kernel.UpdateDescriptorAndCommandBuffer(device, m_commandBuffers[stream], bufferDescriptors);
assert(ret == true);
}*/
}
void Execute(const vk::UniqueDevice& device, const vk::Queue& queue, const stream_t stream) const
{
//
// lock access to the streams commandbuffer
//std::lock_guard<std::mutex> lck(*m_mtxCommandBuffers[stream]);
ExecuteQueue(device, queue, stream);
}
/*void Wait(const vk::UniqueDevice& device, const vk::Queue& queue, const stream_t stream) const
{
//
// lock access to the streams commandbuffer
std::lock_guard<std::mutex> lck(*m_mtxCommandBuffers[stream]);
WaitAndReset(device, stream);
}*/
void ExecuteAndWait(const vk::UniqueDevice& device, const vk::Queue& queue, const stream_t stream) const
{
//
// lock access to the streams commandbuffer
//std::lock_guard<std::mutex> lck(*m_mtxCommandBuffers[stream]);
ExecuteQueue(device, queue, stream);
WaitAndReset(device, stream);
}
private:
/*
private non-synchronized implementation
- assumes m_mtxCommandBuffers[stream] is locked
*/
void CheckStateAndBeginCommandBuffer(const vk::UniqueDevice& device, const stream_t stream) const
{
//
// assumes m_mtxCommandBuffers[stream] is locked
commandBufferStateFlags state = m_commandBufferState[stream];
if(state == cbReset)
{
// we can begin a new recording
BeginRecordingCommandBuffer(stream);
}
else if(state == cbSubmitted)
{
// wait on completion and start new recording
WaitAndReset(device, stream);
BeginRecordingCommandBuffer(stream);
}
else
{
// this is a continued recording call
//newRecording = false;
}
}
void BeginRecordingCommandBuffer(const stream_t stream) const
{
//
// assumes m_mtxCommandBuffers[stream] is locked
vk::CommandBufferBeginInfo commandBufferBeginInfo = vk::CommandBufferBeginInfo()
.setFlags(vk::CommandBufferUsageFlagBits::eOneTimeSubmit)
.setPInheritanceInfo(nullptr);
m_commandBuffers[stream]->begin(commandBufferBeginInfo);
m_commandBufferState[stream] = cbRecording;
}
void ExecuteQueue(const vk::UniqueDevice& device, const vk::Queue& queue, const stream_t stream) const
{
//
// assumes m_mtxCommandBuffers[stream] is locked
if(m_commandBufferState[stream] == cbRecording)
{
//
// end recording and submit
m_commandBuffers[stream]->end();
//
// submit command buffer to compute queue
/*
https://www.khronos.org/registry/vulkan/specs/1.1-extensions/man/html/vkQueueSubmit.html
Each element of the pCommandBuffers member of each element of pSubmits must have been allocated from a VkCommandPool that was created for the same queue family queue belongs to.
*/
queue.submit(vk::SubmitInfo(0, nullptr, nullptr, 1, &m_commandBuffers[stream].get(), 0, nullptr), m_ufences[stream].get());
m_commandBufferState[stream] = cbSubmitted;
}
}
void WaitAndReset(const vk::UniqueDevice& device, const stream_t stream) const
{
//
// assumes m_mtxCommandBuffers[stream] is locked
if(m_commandBufferState[stream] == cbSubmitted)
{
//
// for now just wait for the queue to become idle
vk::Result res = device->waitForFences(1, &m_ufences[stream].get(), VK_FALSE, (std::numeric_limits<uint64_t>::max)());
assert(res == vk::Result::eSuccess);
device->resetFences(1, &m_ufences[stream].get());
//
// reset command buffer
m_commandBuffers[stream]->reset(vk::CommandBufferResetFlags());
m_commandBufferState[stream] = cbReset;
}
}
/*std::vector<uint32_t> GetStreamList(const void* src)
{
std::lock_guard<std::mutex> lck(*m_mtxResourceDependency);
std::vector<uint32_t> list = m_src2stream[src];
m_src2stream.erase(src);
return list;
}*/
private:
//std::vector<std::unique_ptr<std::mutex>> m_mtxCommandBuffers;
std::vector<vk::UniqueFence> m_ufences;
vk::UniqueCommandPool m_commandPool;
std::vector<vk::UniqueCommandBuffer> m_commandBuffers;
mutable std::vector<commandBufferStateFlags> m_commandBufferState;
//
// time stamp queries
vk::UniqueQueryPool m_queryPool;
mutable std::atomic<uint32_t> m_queryIndex;
//mutable std::array<std::atomic<uint32_t>, VUDA_MAX_QUERY_COUNT> m_querytostream;
//
// resource management
//std::unique_ptr<std::mutex> m_mtxResourceDependency;
//std::unordered_map<const void*, std::vector<uint32_t>> m_src2stream;
};
} //namespace detail
} //namespace vuda | 9,616 |
1,615 | <filename>Tests/image_tests/renderscripts/test_BSDFViewer.py
import sys
sys.path.append('..')
from falcor import *
from helpers import render_frames
exec(open('../../../Source/Mogwai/Data/BSDFViewer.py').read())
# arcade
m.loadScene('Arcade/Arcade.pyscene')
render_frames(m, 'arcade', frames=[16])
# materials
m.loadScene('TestScenes/MaterialTest.pyscene')
render_frames(m, 'materials', frames=[16])
exit()
| 149 |
5,169 | {
"name": "EFInternetIndicator",
"version": "0.1.0",
"summary": "A little Internet status indicator.",
"description": "A little swift Internet error status indicator using ReachabilitySwift.",
"homepage": "https://github.com/ezefranca/EFInternetIndicator",
"screenshots": "https://media.giphy.com/media/3Pumvj8kXlsze/giphy.gif",
"license": {
"type": "MIT",
"file": "LICENSE"
},
"authors": {
"ezefranca": "<EMAIL>"
},
"source": {
"git": "https://github.com/ezefranca/EFInternetIndicator.git",
"tag": "0.1.0"
},
"social_media_url": "https://twitter.com/ezefranca",
"platforms": {
"ios": "9.0"
},
"source_files": "EFInternetIndicator/Classes/**/*.{c,h,hh,m,mm,swift}",
"pushed_with_swift_version": "3.0",
"subspecs": [
{
"name": "Network",
"dependencies": {
"ReachabilitySwift": [
]
}
},
{
"name": "Interface",
"dependencies": {
"SwiftMessages": [
]
}
}
]
}
| 454 |
930 | package com.zone.weixin4j.util;
import com.zone.weixin4j.exception.WeixinException;
import java.io.*;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.net.JarURLConnection;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
/**
* 对class的获取
*
* @className ClassUtil
* @author jinyu(<EMAIL>)
* @date 2014年10月31日
* @since JDK 1.6
* @see
*/
public final class ClassUtil {
private final static String POINT = ".";
private final static String CLASS = ".class";
/**
* 获取某个包下所有的class信息
*
* @param packageName
* 包名
* @return
*/
public static List<Class<?>> getClasses(String packageName)
throws WeixinException {
String packageFileName = packageName.replace(POINT, File.separator);
URL fullPath = getDefaultClassLoader().getResource(packageFileName);
String protocol = fullPath.getProtocol();
if (protocol.equals(ServerToolkits.PROTOCOL_FILE)) {
try {
File dir = new File(fullPath.toURI());
return findClassesByFile(dir, packageName);
} catch (URISyntaxException e) {
throw new WeixinException(e);
}
} else if (protocol.equals(ServerToolkits.PROTOCOL_JAR)) {
try {
return findClassesByJar(
((JarURLConnection) fullPath.openConnection())
.getJarFile(),
packageName);
} catch (IOException e) {
throw new WeixinException(e);
}
}
return null;
}
/**
* 扫描目录下所有的class对象
*
* @param dir
* 文件目录
* @param packageName
* 包的全限类名
* @return
*/
private static List<Class<?>> findClassesByFile(File dir, String packageName) {
List<Class<?>> classes = new ArrayList<Class<?>>();
File[] files = dir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File file, String name) {
return file.isDirectory() || file.getName().endsWith(CLASS);
}
});
if (files != null) {
for (File file : files) {
if (file.isDirectory()) {
classes.addAll(findClassesByFile(file, packageName + POINT
+ file.getName()));
} else {
try {
classes.add(Class.forName(packageName + POINT
+ file.getName().replace(CLASS, "")));
} catch (ClassNotFoundException e) {
;
}
}
}
}
return classes;
}
/**
* 扫描jar包下所有的class对象
*
* @param jar
* jar包对象
* @param packageName
* 包的全限类名
* @return
*/
private static List<Class<?>> findClassesByJar(JarFile jar,
String packageName) {
List<Class<?>> classes = new ArrayList<Class<?>>();
Enumeration<JarEntry> jarEntries = jar.entries();
while (jarEntries.hasMoreElements()) {
JarEntry jarEntry = jarEntries.nextElement();
if (jarEntry.isDirectory()) {
continue;
}
String className = jarEntry.getName()
.replace(File.separator, POINT);
if (!className.startsWith(packageName)
|| !className.endsWith(CLASS)) {
continue;
}
try {
classes.add(Class.forName(className.replace(CLASS, "")));
} catch (ClassNotFoundException e) {
;
}
}
return classes;
}
public static Object deepClone(Object obj) throws WeixinException {
ByteArrayOutputStream bos = null;
ObjectOutputStream oos = null;
ByteArrayInputStream bis = null;
ObjectInputStream ois = null;
try {
bos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
bis = new ByteArrayInputStream(bos.toByteArray());
ois = new ObjectInputStream(bis);
return ois.readObject();
} catch (IOException e) {
throw new WeixinException(e);
} catch (ClassNotFoundException e) {
throw new WeixinException(e);
} finally {
try {
if (bos != null) {
bos.close();
}
if (oos != null) {
oos.close();
}
if (bis != null) {
bis.close();
}
if (ois != null) {
ois.close();
}
} catch (IOException e) {
;// ignore
}
}
}
/**
* 获得泛型类型
*
* @param object
* @return
*/
public static Class<?> getGenericType(Class<?> clazz) {
if(clazz == Object.class){
return null;
}
Type type = clazz.getGenericSuperclass();
if (type instanceof ParameterizedType) {
ParameterizedType ptype = ((ParameterizedType) type);
Type[] args = ptype.getActualTypeArguments();
return (Class<?>) args[0];
}
return getGenericType(clazz.getSuperclass());
}
public static ClassLoader getDefaultClassLoader() {
ClassLoader cl = null;
try {
cl = Thread.currentThread().getContextClassLoader();
} catch (Throwable ex) {
// Cannot access thread context ClassLoader - falling back...
}
if (cl == null) {
// No thread context class loader -> use class loader of this class.
cl = ClassUtil.class.getClassLoader();
if (cl == null) {
// getClassLoader() returning null indicates the bootstrap
// ClassLoader
try {
cl = ClassLoader.getSystemClassLoader();
} catch (Throwable ex) {
// Cannot access system ClassLoader - oh well, maybe the
// caller can live with null...
}
}
}
return cl;
}
public static void main(String[] args) throws WeixinException {
System.err.println(getClasses("com.foxinmy.weixin4j.qy.event"));
}
}
| 2,217 |
401 | <gh_stars>100-1000
package com.almasb.algo.disintegration;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.geometry.Point2D;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
/**
* @author <NAME> (<EMAIL>)
*/
public class Particle {
private DoubleProperty x = new SimpleDoubleProperty();
private DoubleProperty y = new SimpleDoubleProperty();
private Point2D velocity = Point2D.ZERO;
private Color color;
private double life = 1.0;
private boolean active = false;
public Particle(int x, int y, Color color) {
this.x.set(x);
this.y.set(y);
this.color = color;
}
public DoubleProperty xProperty() {
return x;
}
public DoubleProperty yProperty() {
return y;
}
public double getX() {
return x.get();
}
public double getY() {
return y.get();
}
public boolean isDead() {
return life == 0;
}
public boolean isActive() {
return active;
}
public void activate(Point2D velocity) {
active = true;
this.velocity = velocity;
}
public void update() {
if (!active)
return;
life -= 0.017 * 0.75;
if (life < 0)
life = 0;
this.x.set(getX() + velocity.getX());
this.y.set(getY() + velocity.getY());
}
public void draw(GraphicsContext g) {
g.setFill(color);
g.setGlobalAlpha(life);
g.fillOval(getX(), getY(), 1, 1);
}
}
| 682 |
435 | {
"copyright_text": "Standard YouTube License",
"description": "PyData Berlin 2016\n\nPredicting what people like when they choose what to wear is a non-trivial task involving several ingredients. At Mallzee, the data is variegated, large and has to be processed quickly to produce recommendations on products, tailored to each user. We use PySpark to crunch large sets of different data and create models in order to generate robust and meaningful suggestions.\n\nMallzee is a fashion app where people can see products (clothes, shoes and accessories) and decide whether they like them or not. They can also buy products and create feeds of preferred brands and categories of items. We have large amounts of data generated by the users when they scroll and search through products and we use it to understand the user. We want to give everyone meaningful recommendations on the items they might like, hence tailoring the experience to who they are. We build pseudo-intelligent algorithms capable of extracting the style profile of a user and we crunch products data to match items to the user based on a classification model. The model is validated and statistical analyses are performed to determine the tipping point when recommendations are valuable to the user. The talk will go through the steps we implement by showing how the full data stack of Python is used in achieving this goal and how it is interfaced with a Spark cluster through PySpark in order to run Machine Learning algorithms on big data.",
"duration": 2112,
"language": "eng",
"recorded": "2016-06-01",
"related_urls": [],
"speakers": [
"<NAME>"
],
"tags": [
"pyspark"
],
"thumbnail_url": "https://i.ytimg.com/vi/iQ-naTZr8tM/maxresdefault.jpg",
"title": "Spotting trends and tailoring recommendations: PySpark on Big Data in fashion",
"videos": [
{
"type": "youtube",
"url": "https://www.youtube.com/watch?v=iQ-naTZr8tM"
}
]
}
| 508 |
5,903 | /*!
* Copyright 2010 - 2018 <NAME>. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.pentaho.di.purge;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.ByteArrayInputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.repository.ObjectId;
import org.pentaho.di.repository.RepositoryElementInterface;
import org.pentaho.platform.api.repository2.unified.IUnifiedRepository;
import org.pentaho.platform.api.repository2.unified.RepositoryRequest;
import org.pentaho.platform.api.repository2.unified.VersionSummary;
import org.pentaho.platform.repository2.unified.webservices.DefaultUnifiedRepositoryWebService;
import org.pentaho.platform.api.repository2.unified.webservices.RepositoryFileTreeDto;
/**
* Created by tkafalas 7/14/14.
*/
public class UnifiedRepositoryPurgeServiceTest {
private static final String[][] versionData = new String[][] {
{ "100", "1", "01/01/2000", "Bugs Bunny", "original", "1.0" },
{ "101", "1", "01/01/2002", "Bugs Bunny", "1st change", "1.1" },
{ "102", "1", "01/01/2004", "<NAME>", "2nd change", "1.2" },
{ "103", "1", "01/01/2006", "<NAME>", "3rd change", "1.3" },
{ "104", "1", "01/01/2008", "<NAME>", "4th change", "1.4" },
{ "105", "1", "01/01/2010", "<NAME>", "5th change", "1.5" },
{ "200", "2", "01/01/2001", "<NAME>", "original", "1.0" },
{ "201", "2", "01/01/2003", "<NAME>", "1st change", "1.1" },
{ "202", "2", "01/01/2005", "<NAME>", "2nd change", "1.2" },
{ "203", "2", "01/01/2013", "<NAME>", "3rd change", "1.3" }, };
private static final DateFormat DATE_FORMAT = new SimpleDateFormat( "MM/dd/yyyy" );
private static final String treeResponse =
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
+ "<repositoryFileTreeDto><children><children><file><folder>false</folder><hidden>false</hidden><id>1</id><locked>false</locked><name>file1.ktr</name><ownerType>-1</ownerType><path>/home/joe/file1.ktr</path><versionId>1.5</versionId><versioned>true</versioned></file></children>"
+ "<children><children><file><folder>false</folder><hidden>false</hidden><id>2</id><locked>false</locked><name>file2.ktr</name><ownerType>-1</ownerType><path>/home/joe/newdirTest/file2.ktr</path><versionId>1.3</versionId><versioned>true</versioned></file></children>"
+ "</children><file><folder>true</folder><hidden>false</hidden><id>homejoessn</id><locked>false</locked><name>joe</name><ownerType>-1</ownerType><path>/home/joe</path><versioned>false</versioned></file></children>"
+ "<file><folder>true</folder><hidden>false</hidden><id>homessn</id><locked>false</locked><name>home</name><ownerType>-1</ownerType><path>/home</path><versioned>false</versioned></file>"
+ "</repositoryFileTreeDto>";
private static RepositoryElementInterface element1;
static {
// Setup a mocked RepositoryElementInterface so alternate methods can be called for maximum code coverage
element1 = mock( RepositoryElementInterface.class );
ObjectId mockObjectId1 = mock( ObjectId.class );
when( mockObjectId1.getId() ).thenReturn( "1" );
when( element1.getObjectId() ).thenReturn( mockObjectId1 );
}
private HashMap<String, List<VersionSummary>> processVersionMap( IUnifiedRepository mockRepo ) {
// Build versionListMap
final HashMap<String, List<VersionSummary>> versionListMap = new HashMap<String, List<VersionSummary>>();
List<VersionSummary> mockVersionList = new ArrayList<VersionSummary>();
Date d = null;
String fileId = null;
for ( String[] values : versionData ) {
d = getDate( values[2] );
if ( !values[1].equals( fileId ) ) {
if ( fileId != null ) {
versionListMap.put( fileId, mockVersionList );
}
mockVersionList = new ArrayList<VersionSummary>();
}
fileId = values[1];
VersionSummary versionSummary =
new VersionSummary( values[0], fileId, false, d, values[3], values[4], Arrays
.asList( new String[] { values[5] } ) );
mockVersionList.add( versionSummary );
}
versionListMap.put( fileId, mockVersionList );
final ArgumentCaptor<String> fileIdArgument = ArgumentCaptor.forClass( String.class );
when( mockRepo.getVersionSummaries( fileIdArgument.capture() ) ).thenAnswer( new Answer<List<VersionSummary>>() {
public List<VersionSummary> answer( InvocationOnMock invocation ) throws Throwable {
return versionListMap.get( fileIdArgument.getValue() );
}
} );
return versionListMap;
}
@Test
public void deleteAllVersionsTest() throws KettleException {
IUnifiedRepository mockRepo = mock( IUnifiedRepository.class );
final HashMap<String, List<VersionSummary>> versionListMap = processVersionMap( mockRepo );
UnifiedRepositoryPurgeService purgeService = new UnifiedRepositoryPurgeService( mockRepo );
String fileId = "1";
purgeService.deleteAllVersions( element1 );
verifyAllVersionsDeleted( versionListMap, mockRepo, "1" );
verify( mockRepo, never() ).deleteFileAtVersion( eq( "2" ), anyString() );
}
@Test
public void deleteVersionTest() throws KettleException {
IUnifiedRepository mockRepo = mock( IUnifiedRepository.class );
final HashMap<String, List<VersionSummary>> versionListMap = processVersionMap( mockRepo );
UnifiedRepositoryPurgeService purgeService = new UnifiedRepositoryPurgeService( mockRepo );
String fileId = "1";
String versionId = "103";
purgeService.deleteVersion( element1, versionId );
verify( mockRepo, times( 1 ) ).deleteFileAtVersion( fileId, versionId );
verify( mockRepo, never() ).deleteFileAtVersion( eq( "2" ), anyString() );
}
@Test
public void keepNumberOfVersions0Test() throws KettleException {
IUnifiedRepository mockRepo = mock( IUnifiedRepository.class );
final HashMap<String, List<VersionSummary>> versionListMap = processVersionMap( mockRepo );
UnifiedRepositoryPurgeService purgeService = new UnifiedRepositoryPurgeService( mockRepo );
String fileId = "1";
int versionCount = 0;
purgeService.keepNumberOfVersions( element1, versionCount );
verifyVersionCountDeletion( versionListMap, mockRepo, fileId, versionCount );
verify( mockRepo, never() ).deleteFileAtVersion( eq( "2" ), anyString() );
}
@Test
public void keepNumberOfVersionsTest() throws KettleException {
IUnifiedRepository mockRepo = mock( IUnifiedRepository.class );
final HashMap<String, List<VersionSummary>> versionListMap = processVersionMap( mockRepo );
UnifiedRepositoryPurgeService purgeService = new UnifiedRepositoryPurgeService( mockRepo );
String fileId = "1";
int versionCount = 2;
purgeService.keepNumberOfVersions( element1, versionCount );
verifyVersionCountDeletion( versionListMap, mockRepo, fileId, versionCount );
verify( mockRepo, never() ).deleteFileAtVersion( eq( "2" ), anyString() );
}
@Test
public void deleteVersionsBeforeDate() throws KettleException {
IUnifiedRepository mockRepo = mock( IUnifiedRepository.class );
final HashMap<String, List<VersionSummary>> versionListMap = processVersionMap( mockRepo );
UnifiedRepositoryPurgeService purgeService = new UnifiedRepositoryPurgeService( mockRepo );
String fileId = "1";
Date beforeDate = getDate( "01/02/2006" );
purgeService.deleteVersionsBeforeDate( element1, beforeDate );
verifyDateBeforeDeletion( versionListMap, mockRepo, fileId, beforeDate );
verify( mockRepo, never() ).deleteFileAtVersion( eq( "2" ), anyString() );
}
@Test
public void doPurgeUtilPurgeFileTest() throws PurgeDeletionException {
IUnifiedRepository mockRepo = mock( IUnifiedRepository.class );
final HashMap<String, List<VersionSummary>> versionListMap = processVersionMap( mockRepo );
UnifiedRepositoryPurgeService purgeService = getPurgeService( mockRepo );
PurgeUtilitySpecification spec = new PurgeUtilitySpecification();
spec.purgeFiles = true;
spec.setPath( "/" );
purgeService.doDeleteRevisions( spec );
verifyAllVersionsDeleted( versionListMap, mockRepo, "1" );
verifyAllVersionsDeleted( versionListMap, mockRepo, "2" );
verify( UnifiedRepositoryPurgeService.getRepoWs(), times( 1 ) ).deleteFileWithPermanentFlag( eq( "1" ), eq( true ),
anyString() );
verify( UnifiedRepositoryPurgeService.getRepoWs(), times( 1 ) ).deleteFileWithPermanentFlag( eq( "2" ), eq( true ),
anyString() );
}
@Test
public void doPurgeUtilVersionCountTest() throws PurgeDeletionException {
IUnifiedRepository mockRepo = mock( IUnifiedRepository.class );
final HashMap<String, List<VersionSummary>> versionListMap = processVersionMap( mockRepo );
UnifiedRepositoryPurgeService purgeService = getPurgeService( mockRepo );
PurgeUtilitySpecification spec = new PurgeUtilitySpecification();
spec.setVersionCount( 3 );
spec.setPath( "/" );
purgeService.doDeleteRevisions( spec );
verifyVersionCountDeletion( versionListMap, mockRepo, "1", spec.getVersionCount() );
verifyVersionCountDeletion( versionListMap, mockRepo, "2", spec.getVersionCount() );
}
@Test
public void doPurgeUtilDateBeforeTest() throws PurgeDeletionException {
IUnifiedRepository mockRepo = mock( IUnifiedRepository.class );
final HashMap<String, List<VersionSummary>> versionListMap = processVersionMap( mockRepo );
UnifiedRepositoryPurgeService purgeService = getPurgeService( mockRepo );
PurgeUtilitySpecification spec = new PurgeUtilitySpecification();
spec.setBeforeDate( getDate( "01/02/2006" ) );
spec.setPath( "/" );
purgeService.doDeleteRevisions( spec );
verifyDateBeforeDeletion( versionListMap, mockRepo, "1", spec.getBeforeDate() );
verifyDateBeforeDeletion( versionListMap, mockRepo, "2", spec.getBeforeDate() );
}
@Test
public void doPurgeUtilSharedObjectsTest() throws PurgeDeletionException {
IUnifiedRepository mockRepo = mock( IUnifiedRepository.class );
final HashMap<String, List<VersionSummary>> versionListMap = processVersionMap( mockRepo );
UnifiedRepositoryPurgeService purgeService = getPurgeService( mockRepo );
PurgeUtilitySpecification spec = new PurgeUtilitySpecification();
spec.purgeFiles = true;
spec.setSharedObjects( true );
purgeService.doDeleteRevisions( spec );
// Since each tree call delivers the same mock tree, we expect the files to get deleted once per folder.
String fileId = "1";
String fileLastRevision = "105";
List<VersionSummary> list = versionListMap.get( fileId );
for ( VersionSummary sum : list ) {
final int expectedTimes;
if ( !fileLastRevision.equals( sum.getId() ) ) {
expectedTimes = 4;
} else {
expectedTimes = 0;
}
verify( mockRepo, times( expectedTimes ) ).deleteFileAtVersion( fileId, sum.getId() );
verify( UnifiedRepositoryPurgeService.getRepoWs(), times( 4 ) ).deleteFileWithPermanentFlag( eq( fileId ), eq( true ), anyString() );
}
}
// create the necessary mocks for running a full Purge Utility job
private static UnifiedRepositoryPurgeService getPurgeService( IUnifiedRepository mockRepo ) {
UnifiedRepositoryPurgeService purgeService = new UnifiedRepositoryPurgeService( mockRepo );
DefaultUnifiedRepositoryWebService mockRepoWs = mock( DefaultUnifiedRepositoryWebService.class );
UnifiedRepositoryPurgeService.repoWs = mockRepoWs;
// Create a mocked tree to be returned
JAXBContext jc;
RepositoryFileTreeDto tree = null;
try {
jc = JAXBContext.newInstance( RepositoryFileTreeDto.class );
Unmarshaller unmarshaller = jc.createUnmarshaller();
ByteArrayInputStream xml = new ByteArrayInputStream( treeResponse.getBytes() );
tree = (RepositoryFileTreeDto) unmarshaller.unmarshal( xml );
} catch ( JAXBException e ) {
e.printStackTrace();
fail( "Test class has invalid xml representation of tree" );
}
when( mockRepoWs.getTreeFromRequest( any( RepositoryRequest.class ) ) ).thenReturn( tree );
return purgeService;
}
private static void verifyAllVersionsDeleted( HashMap<String, List<VersionSummary>> versionListMap,
IUnifiedRepository mockRepo, String fileId ) {
List<VersionSummary> list = versionListMap.get( fileId );
int i = 1;
for ( VersionSummary sum : list ) {
if ( i < list.size() ) {
verify( mockRepo, times( 1 ) ).deleteFileAtVersion( fileId, sum.getId() );
}
i++;
}
}
private static void verifyVersionCountDeletion( HashMap<String, List<VersionSummary>> versionListMap,
IUnifiedRepository mockRepo, String fileId, int versionCount ) {
List<VersionSummary> list = versionListMap.get( fileId );
int i = 1;
for ( VersionSummary sum : list ) {
if ( i <= list.size() - versionCount ) {
verify( mockRepo, times( 1 ) ).deleteFileAtVersion( fileId, sum.getId() );
}
i++;
}
}
private static void verifyDateBeforeDeletion( HashMap<String, List<VersionSummary>> versionListMap,
IUnifiedRepository mockRepo, String fileId, Date beforeDate ) {
int i = 0;
List<VersionSummary> list = versionListMap.get( fileId );
for ( VersionSummary sum : list ) {
if ( beforeDate.after( sum.getDate() ) && !sum.getId().equals( list.get( list.size() - 1 ).getId() ) ) {
verify( mockRepo, times( 1 ) ).deleteFileAtVersion( fileId, sum.getId() );
} else {
verify( mockRepo, never() ).deleteFileAtVersion( fileId, sum.getId() );
}
}
}
private static Date getDate( String dateString ) {
Date date = null;
try {
date = DATE_FORMAT.parse( dateString );
} catch ( ParseException e ) {
fail( "Bad Date format in test class" );
}
return date;
}
}
| 5,208 |
2,508 | <gh_stars>1000+
extern zend_class_entry *stub_internalinterfaces_ce;
ZEPHIR_INIT_CLASS(Stub_InternalInterfaces);
PHP_METHOD(Stub_InternalInterfaces, count);
ZEND_BEGIN_ARG_INFO_EX(arginfo_stub_internalinterfaces_count, 0, 0, 0)
ZEND_END_ARG_INFO()
ZEPHIR_INIT_FUNCS(stub_internalinterfaces_method_entry) {
#if PHP_VERSION_ID >= 80000
PHP_ME(Stub_InternalInterfaces, count, arginfo_stub_internalinterfaces_count, ZEND_ACC_PUBLIC)
#else
PHP_ME(Stub_InternalInterfaces, count, NULL, ZEND_ACC_PUBLIC)
#endif
PHP_FE_END
};
| 222 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.