<commit_before>/*
 * Force_calling.cpp
 *
 *  Created on: Aug 24, 2017
 *      Author: sedlazec
 */

#include "Force_calling.h"

char assign_type(short type) {

	switch (type) {
	case 0: //DEL
		return DEL;
	case 1: //DUP
		return INV;
	case 2: //INV
		return INV;
	case 3: //TRA
		return TRA;
	case 4: //INS
		return INS;
	case 6:
		return NEST;
	}
	return ' '; //TODO check default. Should not happen!
}
void fill_tree(IntervallTree & final, TNode *& root_final, RefVector ref, std::map<std::string, long>& ref_lens) {
	//prepare lookup:

	long length = 0;
	for (size_t i = 0; i < ref.size(); i++) {
		ref_lens[ref[i].RefName.c_str()] = length;
		length += (long) ref[i].RefLength + (long) Parameter::Instance()->max_dist;
	}

	//sometimes the stop coordinates are off especially for smaller chrs!??

	//parse VCF file
	std::vector<strvcfentry> entries = parse_vcf(Parameter::Instance()->input_vcf, 0);
	std::cout << "\t\t" << entries.size() << " SVs found in input." << std::endl;
	int invalid_svs = 0;
	for (size_t i = 0; i < entries.size(); i++) {
		if (entries[i].type != -1) {
			position_str svs;

			//cout<<"start: "<<entries[i].start.chr << " stop "<<entries[i].start.pos<< " "<<entries[i].type<<endl;
			svs.start.min_pos = (long) entries[i].start.pos + ref_lens[entries[i].start.chr];
			svs.stop.max_pos = (long) entries[i].stop.pos + ref_lens[entries[i].stop.chr];
			read_str read;
			if (ref_lens.find(entries[i].start.chr) == ref_lens.end()) {
				cerr << "Warning undefined CHR in VCF vs. BAM header: " << entries[i].start.chr << endl;
			}
			if (ref_lens.find(entries[i].stop.chr) == ref_lens.end()) {
				cerr << "Warning undefined CHR in VCF vs. BAM header: " << entries[i].stop.chr << endl;
			}
			read.coordinates.first = (long) entries[i].start.pos + ref_lens[entries[i].start.chr];
			read.coordinates.second = (long) entries[i].stop.pos + ref_lens[entries[i].stop.chr];
			if (entries[i].type == 4) { //ins?
				if (entries[i].sv_len == Parameter::Instance()->huge_ins) {
					entries[i].sv_len++; // bad hack!
				}

				svs.stop.max_pos += (long) entries[i].sv_len;
				read.coordinates.second += (long) entries[i].sv_len;
				//	cout << "Parse: " << entries[i].start.pos << " " << entries[i].stop.pos << " " << svs.start.min_pos  <<" "<<svs.stop.max_pos  << endl;
			}

			read.SV = assign_type(entries[i].type);
			read.strand = entries[i].strands;
			read.type = 2; //called
			read.length = entries[i].sv_len; //svs.stop.max_pos-svs.start.min_pos;//try
			svs.support["input"] = read;
		//	cout<<"Submit: "<<entries[i].type <<endl;
			Breakpoint * br = new Breakpoint(svs, (long) entries[i].sv_len, read.SV);
			final.insert(br, root_final);
		} else {
			invalid_svs++;
		}
	}
	cerr << "\tInvalid types found skipping " << invalid_svs << " entries." << endl;
	//std::cout << "Print:" << std::endl;
	//final.print(root_final);
	entries.clear();
	exit(0);
}

void force_calling(std::string bam_file, IPrinter *& printer) {
	cout << "Force calling SVs" << endl;
	//parse reads
	//only process reads overlapping SV
	estimate_parameters(Parameter::Instance()->bam_files[0]);
	BamParser * mapped_file = 0;
	RefVector ref;
	std::string read_filename = Parameter::Instance()->bam_files[0];
	if (read_filename.find("bam") != string::npos) {
		mapped_file = new BamParser(read_filename);
		ref = mapped_file->get_refInfo();
	} else {
		cerr << "File Format not recognized. File must be a sorted .bam file!" << endl;
		exit(0);
	}
	std::cout << "Construct Tree..." << std::endl;

	//construct the tree:
	IntervallTree final;
	TNode * root_final = NULL;
	std::map<std::string, long> ref_lens;
	fill_tree(final, root_final, ref, ref_lens);

	int current_RefID = 0;
	std::cout << "Start parsing: Chr " << ref[current_RefID].RefName << std::endl;

	//FILE * alt_allel_reads;
	FILE * ref_allel_reads;
	if (Parameter::Instance()->genotype) {
		ref_allel_reads = fopen(Parameter::Instance()->tmp_genotyp.c_str(), "wb");
	}
	Alignment * tmp_aln = mapped_file->parseRead(Parameter::Instance()->min_mq);

	long ref_space = ref_lens[ref[tmp_aln->getRefID()].RefName];
	long num_reads = 0;
	while (!tmp_aln->getQueryBases().empty()) {
		if ((tmp_aln->getAlignment()->IsPrimaryAlignment()) && (!(tmp_aln->getAlignment()->AlignmentFlag & 0x800) && tmp_aln->get_is_save())) {
			//change CHR:
			if (current_RefID != tmp_aln->getRefID()) {
				current_RefID = tmp_aln->getRefID();
				ref_space = ref_lens[ref[tmp_aln->getRefID()].RefName];
				std::cout << "\tSwitch Chr " << ref[tmp_aln->getRefID()].RefName << std::endl;				//" " << ref[tmp_aln->getRefID()].RefLength
			}

			//check if overlap with any breakpoint!!
			long read_start_pos = (long) tmp_aln->getPosition() - (long) Parameter::Instance()->max_dist;
			read_start_pos += ref_space;
			long read_stop_pos = read_start_pos + (long) tmp_aln->getAlignment()->Length + (long) Parameter::Instance()->max_dist;	//getRefLength();//(long) tmp_aln->getPosition();

			if (final.overlaps(read_start_pos, read_stop_pos, root_final)) {
				//SCAN read:
				std::vector<str_event> aln_event;
				std::vector<aln_str> split_events;
				if (tmp_aln->getMappingQual() > Parameter::Instance()->min_mq) {
					double score = tmp_aln->get_scrore_ratio();
#pragma omp parallel // starts a new team
					{
#pragma omp sections
						{
							{
								//	clock_t begin = clock();
								if ((score == -1 || score > Parameter::Instance()->score_treshold)) {
									aln_event = tmp_aln->get_events_Aln();
								}
								//	Parameter::Instance()->meassure_time(begin, " Alignment ");
							}
#pragma omp section
							{
								//		clock_t begin_split = clock();
								split_events = tmp_aln->getSA(ref);
								//		Parameter::Instance()->meassure_time(begin_split," Split reads ");
							}
						}
					}
					//tmp_aln->set_supports_SV(aln_event.empty() && split_events.empty());

					//Store reference supporting reads for genotype estimation:
					str_read tmp;
					bool SV_support = !(aln_event.empty() && split_events.empty());
					if ((Parameter::Instance()->genotype && !SV_support) && (score == -1 || score > Parameter::Instance()->score_treshold)) {
						//write read:
						//cout<<"REf: "<<tmp_aln->getName()<<" "<<tmp_aln->getPosition()<<" "<<tmp_aln->getRefLength()<<endl;
						tmp.chr_id = tmp_aln->getRefID();
						tmp.start = tmp_aln->getPosition();
						tmp.length = tmp_aln->getRefLength();
						fwrite(&tmp, sizeof(struct str_read), 1, ref_allel_reads);
					}

					//store the potential SVs:
					if (!aln_event.empty()) {
						add_events(tmp_aln, aln_event, 0, ref_space, final, root_final, num_reads, true);
					}
					if (!split_events.empty()) {
						add_splits(tmp_aln, split_events, 1, ref, final, root_final, num_reads, true);
					}
				}
			}
		}
		//get next read:
		mapped_file->parseReadFast(Parameter::Instance()->min_mq, tmp_aln);

		num_reads++;

		if (num_reads % 10000 == 0) {
			cout << "\t\t# Processed reads: " << num_reads << endl;
		}
	}

	//std::cout << "Print:" << std::endl;
	//final.print(root_final);

	//filter and copy results:
	std::cout << "Finalizing  .." << std::endl;

	if (Parameter::Instance()->genotype) {
		fclose(ref_allel_reads);
	}
	//	sweep->finalyze();

	std::vector<Breakpoint*> points;
	final.get_breakpoints(root_final, points);

	//std::cout<<"fin up"<<std::endl;
	for (size_t i = 0; i < points.size(); i++) {
		points[i]->calc_support();
		points[i]->predict_SV();
		printer->printSV(points[i]); //redo! Ignore min support + STD etc.
	}

}
<commit_msg>Removed debug exit from forcecalling<commit_after>/*
 * Force_calling.cpp
 *
 *  Created on: Aug 24, 2017
 *      Author: sedlazec
 */

#include "Force_calling.h"

char assign_type(short type) {

	switch (type) {
	case 0: //DEL
		return DEL;
	case 1: //DUP
		return INV;
	case 2: //INV
		return INV;
	case 3: //TRA
		return TRA;
	case 4: //INS
		return INS;
	case 6:
		return NEST;
	}
	return ' '; //TODO check default. Should not happen!
}
void fill_tree(IntervallTree & final, TNode *& root_final, RefVector ref, std::map<std::string, long>& ref_lens) {
	//prepare lookup:

	long length = 0;
	for (size_t i = 0; i < ref.size(); i++) {
		ref_lens[ref[i].RefName.c_str()] = length;
		length += (long) ref[i].RefLength + (long) Parameter::Instance()->max_dist;
	}

	//sometimes the stop coordinates are off especially for smaller chrs!??

	//parse VCF file
	std::vector<strvcfentry> entries = parse_vcf(Parameter::Instance()->input_vcf, 0);
	std::cout << "\t\t" << entries.size() << " SVs found in input." << std::endl;
	int invalid_svs = 0;
	for (size_t i = 0; i < entries.size(); i++) {
		if (entries[i].type != -1) {
			position_str svs;

			//cout<<"start: "<<entries[i].start.chr << " stop "<<entries[i].start.pos<< " "<<entries[i].type<<endl;
			svs.start.min_pos = (long) entries[i].start.pos + ref_lens[entries[i].start.chr];
			svs.stop.max_pos = (long) entries[i].stop.pos + ref_lens[entries[i].stop.chr];
			read_str read;
			if (ref_lens.find(entries[i].start.chr) == ref_lens.end()) {
				cerr << "Warning undefined CHR in VCF vs. BAM header: " << entries[i].start.chr << endl;
			}
			if (ref_lens.find(entries[i].stop.chr) == ref_lens.end()) {
				cerr << "Warning undefined CHR in VCF vs. BAM header: " << entries[i].stop.chr << endl;
			}
			read.coordinates.first = (long) entries[i].start.pos + ref_lens[entries[i].start.chr];
			read.coordinates.second = (long) entries[i].stop.pos + ref_lens[entries[i].stop.chr];
			if (entries[i].type == 4) { //ins?
				if (entries[i].sv_len == Parameter::Instance()->huge_ins) {
					entries[i].sv_len++; // bad hack!
				}

				svs.stop.max_pos += (long) entries[i].sv_len;
				read.coordinates.second += (long) entries[i].sv_len;
				//	cout << "Parse: " << entries[i].start.pos << " " << entries[i].stop.pos << " " << svs.start.min_pos  <<" "<<svs.stop.max_pos  << endl;
			}

			read.SV = assign_type(entries[i].type);
			read.strand = entries[i].strands;
			read.type = 2; //called
			read.length = entries[i].sv_len; //svs.stop.max_pos-svs.start.min_pos;//try
			svs.support["input"] = read;
		//	cout<<"Submit: "<<entries[i].type <<endl;
			Breakpoint * br = new Breakpoint(svs, (long) entries[i].sv_len, read.SV);
			final.insert(br, root_final);
		} else {
			invalid_svs++;
		}
	}
	cerr << "\tInvalid types found skipping " << invalid_svs << " entries." << endl;
	//std::cout << "Print:" << std::endl;
	//final.print(root_final);
	entries.clear();
	//exit(0);
}

void force_calling(std::string bam_file, IPrinter *& printer) {
	cout << "Force calling SVs" << endl;
	//parse reads
	//only process reads overlapping SV
	estimate_parameters(Parameter::Instance()->bam_files[0]);
	BamParser * mapped_file = 0;
	RefVector ref;
	std::string read_filename = Parameter::Instance()->bam_files[0];
	if (read_filename.find("bam") != string::npos) {
		mapped_file = new BamParser(read_filename);
		ref = mapped_file->get_refInfo();
	} else {
		cerr << "File Format not recognized. File must be a sorted .bam file!" << endl;
		exit(0);
	}
	std::cout << "Construct Tree..." << std::endl;

	//construct the tree:
	IntervallTree final;
	TNode * root_final = NULL;
	std::map<std::string, long> ref_lens;
	fill_tree(final, root_final, ref, ref_lens);

	int current_RefID = 0;
	std::cout << "Start parsing: Chr " << ref[current_RefID].RefName << std::endl;

	//FILE * alt_allel_reads;
	FILE * ref_allel_reads;
	if (Parameter::Instance()->genotype) {
		ref_allel_reads = fopen(Parameter::Instance()->tmp_genotyp.c_str(), "wb");
	}
	Alignment * tmp_aln = mapped_file->parseRead(Parameter::Instance()->min_mq);

	long ref_space = ref_lens[ref[tmp_aln->getRefID()].RefName];
	long num_reads = 0;
	while (!tmp_aln->getQueryBases().empty()) {
		if ((tmp_aln->getAlignment()->IsPrimaryAlignment()) && (!(tmp_aln->getAlignment()->AlignmentFlag & 0x800) && tmp_aln->get_is_save())) {
			//change CHR:
			if (current_RefID != tmp_aln->getRefID()) {
				current_RefID = tmp_aln->getRefID();
				ref_space = ref_lens[ref[tmp_aln->getRefID()].RefName];
				std::cout << "\tSwitch Chr " << ref[tmp_aln->getRefID()].RefName << std::endl;				//" " << ref[tmp_aln->getRefID()].RefLength
			}

			//check if overlap with any breakpoint!!
			long read_start_pos = (long) tmp_aln->getPosition() - (long) Parameter::Instance()->max_dist;
			read_start_pos += ref_space;
			long read_stop_pos = read_start_pos + (long) tmp_aln->getAlignment()->Length + (long) Parameter::Instance()->max_dist;	//getRefLength();//(long) tmp_aln->getPosition();

			if (final.overlaps(read_start_pos, read_stop_pos, root_final)) {
				//SCAN read:
				std::vector<str_event> aln_event;
				std::vector<aln_str> split_events;
				if (tmp_aln->getMappingQual() > Parameter::Instance()->min_mq) {
					double score = tmp_aln->get_scrore_ratio();
#pragma omp parallel // starts a new team
					{
#pragma omp sections
						{
							{
								//	clock_t begin = clock();
								if ((score == -1 || score > Parameter::Instance()->score_treshold)) {
									aln_event = tmp_aln->get_events_Aln();
								}
								//	Parameter::Instance()->meassure_time(begin, " Alignment ");
							}
#pragma omp section
							{
								//		clock_t begin_split = clock();
								split_events = tmp_aln->getSA(ref);
								//		Parameter::Instance()->meassure_time(begin_split," Split reads ");
							}
						}
					}
					//tmp_aln->set_supports_SV(aln_event.empty() && split_events.empty());

					//Store reference supporting reads for genotype estimation:
					str_read tmp;
					bool SV_support = !(aln_event.empty() && split_events.empty());
					if ((Parameter::Instance()->genotype && !SV_support) && (score == -1 || score > Parameter::Instance()->score_treshold)) {
						//write read:
						//cout<<"REf: "<<tmp_aln->getName()<<" "<<tmp_aln->getPosition()<<" "<<tmp_aln->getRefLength()<<endl;
						tmp.chr_id = tmp_aln->getRefID();
						tmp.start = tmp_aln->getPosition();
						tmp.length = tmp_aln->getRefLength();
						fwrite(&tmp, sizeof(struct str_read), 1, ref_allel_reads);
					}

					//store the potential SVs:
					if (!aln_event.empty()) {
						add_events(tmp_aln, aln_event, 0, ref_space, final, root_final, num_reads, true);
					}
					if (!split_events.empty()) {
						add_splits(tmp_aln, split_events, 1, ref, final, root_final, num_reads, true);
					}
				}
			}
		}
		//get next read:
		mapped_file->parseReadFast(Parameter::Instance()->min_mq, tmp_aln);

		num_reads++;

		if (num_reads % 10000 == 0) {
			cout << "\t\t# Processed reads: " << num_reads << endl;
		}
	}

	//std::cout << "Print:" << std::endl;
	//final.print(root_final);

	//filter and copy results:
	std::cout << "Finalizing  .." << std::endl;

	if (Parameter::Instance()->genotype) {
		fclose(ref_allel_reads);
	}
	//	sweep->finalyze();

	std::vector<Breakpoint*> points;
	final.get_breakpoints(root_final, points);

	//std::cout<<"fin up"<<std::endl;
	for (size_t i = 0; i < points.size(); i++) {
		points[i]->calc_support();
		points[i]->predict_SV();
		printer->printSV(points[i]); //redo! Ignore min support + STD etc.
	}

}
<|endoftext|>


<commit_before>#include <iostream>
#include <sstream>
#include <string>
#include <unordered_set>
#include <unordered_map>
#include <fstream>

#include "clang/AST/AST.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Frontend/ASTConsumers.h"
#include "clang/Frontend/FrontendActions.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "clang/Tooling/Tooling.h"
#include "clang/Rewrite/Core/Rewriter.h"
#include "llvm/Support/raw_ostream.h"
#include "clang/ASTMatchers/ASTMatchers.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "llvm/Support/Format.h"

#include "SMTLIB2.h"

using namespace clang;
using namespace clang::ast_matchers;
using namespace clang::tooling;
using namespace llvm;

bool replaceStr(std::string& str, const std::string& from, const std::string& to) {
  size_t start_pos = str.find(from);
  if(start_pos == std::string::npos)
    return false;
  str.replace(start_pos, from.length(), to);
  return true;
}

class StmtToSMTLIB2 : public StmtVisitor<StmtToSMTLIB2> {
  raw_ostream &OS;
  clang::PrinterHelper* Helper;
  PrintingPolicy Policy;

public:
  StmtToSMTLIB2(raw_ostream &os, PrinterHelper* helper, const PrintingPolicy &Policy):
    OS(os), Helper(helper), Policy(Policy) {}

  void PrintExpr(Expr *E) {
    if (E)
      Visit(E);
    else
      OS << "<null expr>";
  }

  void Visit(Stmt* S) {
    if (Helper && Helper->handledStmt(S, OS))
      return;
    else StmtVisitor<StmtToSMTLIB2>::Visit(S);
  }

  void VisitBinaryOperator(BinaryOperator *Node) {
    std::string opcode_str = BinaryOperator::getOpcodeStr(Node->getOpcode()).lower();
    if (opcode_str == "!=") {
      OS << "(not (= ";
      PrintExpr(Node->getLHS());
      OS << " ";
      PrintExpr(Node->getRHS());
      OS << "))";
      return;
    }

    replaceStr(opcode_str, "==", "=");
    replaceStr(opcode_str, "||", "or");
    replaceStr(opcode_str, "&&", "and");

    OS << "(" << opcode_str << " ";
    PrintExpr(Node->getLHS());
    OS << " ";
    PrintExpr(Node->getRHS());
    OS << ")";
  }

  void VisitUnaryOperator(UnaryOperator *Node) {
    std::string op = UnaryOperator::getOpcodeStr(Node->getOpcode());
    if (op == "!") {
      op = "not";
    }

    OS << "(" << op << " ";
    PrintExpr(Node->getSubExpr());
    OS << ")";
  }

  void VisitImplicitCastExpr(ImplicitCastExpr *Node) {
    PrintExpr(Node->getSubExpr());
  }

  void VisitParenExpr(ParenExpr *Node) {
    PrintExpr(Node->getSubExpr());
  }

  void VisitMemberExpr(MemberExpr *Node) {
    // this is copied from somewhere
    PrintExpr(Node->getBase());

    MemberExpr *ParentMember = dyn_cast<MemberExpr>(Node->getBase());
    FieldDecl  *ParentDecl   = ParentMember
      ? dyn_cast<FieldDecl>(ParentMember->getMemberDecl()) : nullptr;

    if (!ParentDecl || !ParentDecl->isAnonymousStructOrUnion())
      OS << (Node->isArrow() ? "->" : ".");

    if (FieldDecl *FD = dyn_cast<FieldDecl>(Node->getMemberDecl()))
      if (FD->isAnonymousStructOrUnion())
        return;

    if (NestedNameSpecifier *Qualifier = Node->getQualifier())
      Qualifier->print(OS, Policy);
    if (Node->hasTemplateKeyword())
      OS << "template ";
    OS << Node->getMemberNameInfo();
    if (Node->hasExplicitTemplateArgs())
      TemplateSpecializationType::PrintTemplateArgumentList(OS, Node->getTemplateArgs(), Node->getNumTemplateArgs(), Policy);
  }

  void VisitIntegerLiteral(IntegerLiteral *Node) {
    bool isSigned = Node->getType()->isSignedIntegerType();
    OS << Node->getValue().toString(10, isSigned);
  }

  void VisitCharacterLiteral(CharacterLiteral *Node) {
    unsigned value = Node->getValue();

    //TODO: it most likely does not produce valid SMTLIB2:
    switch (value) {
    case '\\':
      OS << "'\\\\'";
      break;
    case '\'':
      OS << "'\\''";
      break;
    case '\a':
      // TODO: K&R: the meaning of '\\a' is different in traditional C
      OS << "'\\a'";
      break;
    case '\b':
      OS << "'\\b'";
      break;
      // Nonstandard escape sequence.
      /*case '\e':
        OS << "'\\e'";
        break;*/
    case '\f':
      OS << "'\\f'";
      break;
    case '\n':
      OS << "'\\n'";
      break;
    case '\r':
      OS << "'\\r'";
      break;
    case '\t':
      OS << "'\\t'";
      break;
    case '\v':
      OS << "'\\v'";
      break;
    default:
      if (value < 256 && isPrintable((unsigned char)value))
        OS << value;
      else if (value < 256)
        OS << "'\\x" << llvm::format("%02x", value) << "'";
      else if (value <= 0xFFFF)
        OS << "'\\u" << llvm::format("%04x", value) << "'";
      else
        OS << "'\\U" << llvm::format("%08x", value) << "'";
    }
  }

  void VisitDeclRefExpr(DeclRefExpr *Node) {
    ValueDecl* decl = Node->getDecl();
    if (isa<EnumConstantDecl>(decl)) {
      EnumConstantDecl* ecdecl = cast<EnumConstantDecl>(decl);
      OS << ecdecl->getInitVal().toString(10);
    } else {
      OS << Node->getNameInfo();
    }
  }

};

std::string toSMTLIB2(const Stmt* stmt) {
    std::string str;
    llvm::raw_string_ostream rso(str);
    PrintingPolicy pp = PrintingPolicy(LangOptions());
    StmtToSMTLIB2 T(rso, nullptr, pp);
    T.Visit(const_cast<Stmt*>(stmt));
    std::string stmtStr = rso.str();
    return stmtStr;
}
<commit_msg>bugfix: negative enum to smt<commit_after>#include <iostream>
#include <sstream>
#include <string>
#include <unordered_set>
#include <unordered_map>
#include <fstream>

#include "clang/AST/AST.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Frontend/ASTConsumers.h"
#include "clang/Frontend/FrontendActions.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "clang/Tooling/Tooling.h"
#include "clang/Rewrite/Core/Rewriter.h"
#include "llvm/Support/raw_ostream.h"
#include "clang/ASTMatchers/ASTMatchers.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "llvm/Support/Format.h"

#include "SMTLIB2.h"

using namespace clang;
using namespace clang::ast_matchers;
using namespace clang::tooling;
using namespace llvm;

bool replaceStr(std::string& str, const std::string& from, const std::string& to) {
  size_t start_pos = str.find(from);
  if(start_pos == std::string::npos)
    return false;
  str.replace(start_pos, from.length(), to);
  return true;
}

class StmtToSMTLIB2 : public StmtVisitor<StmtToSMTLIB2> {
  raw_ostream &OS;
  clang::PrinterHelper* Helper;
  PrintingPolicy Policy;

public:
  StmtToSMTLIB2(raw_ostream &os, PrinterHelper* helper, const PrintingPolicy &Policy):
    OS(os), Helper(helper), Policy(Policy) {}

  void PrintExpr(Expr *E) {
    if (E)
      Visit(E);
    else
      OS << "<null expr>";
  }

  void Visit(Stmt* S) {
    if (Helper && Helper->handledStmt(S, OS))
      return;
    else StmtVisitor<StmtToSMTLIB2>::Visit(S);
  }

  void VisitBinaryOperator(BinaryOperator *Node) {
    std::string opcode_str = BinaryOperator::getOpcodeStr(Node->getOpcode()).lower();
    if (opcode_str == "!=") {
      OS << "(not (= ";
      PrintExpr(Node->getLHS());
      OS << " ";
      PrintExpr(Node->getRHS());
      OS << "))";
      return;
    }

    replaceStr(opcode_str, "==", "=");
    replaceStr(opcode_str, "||", "or");
    replaceStr(opcode_str, "&&", "and");

    OS << "(" << opcode_str << " ";
    PrintExpr(Node->getLHS());
    OS << " ";
    PrintExpr(Node->getRHS());
    OS << ")";
  }

  void VisitUnaryOperator(UnaryOperator *Node) {
    std::string op = UnaryOperator::getOpcodeStr(Node->getOpcode());
    if (op == "!") {
      op = "not";
    }

    OS << "(" << op << " ";
    PrintExpr(Node->getSubExpr());
    OS << ")";
  }

  void VisitImplicitCastExpr(ImplicitCastExpr *Node) {
    PrintExpr(Node->getSubExpr());
  }

  void VisitParenExpr(ParenExpr *Node) {
    PrintExpr(Node->getSubExpr());
  }

  void VisitMemberExpr(MemberExpr *Node) {
    // this is copied from somewhere
    PrintExpr(Node->getBase());

    MemberExpr *ParentMember = dyn_cast<MemberExpr>(Node->getBase());
    FieldDecl  *ParentDecl   = ParentMember
      ? dyn_cast<FieldDecl>(ParentMember->getMemberDecl()) : nullptr;

    if (!ParentDecl || !ParentDecl->isAnonymousStructOrUnion())
      OS << (Node->isArrow() ? "->" : ".");

    if (FieldDecl *FD = dyn_cast<FieldDecl>(Node->getMemberDecl()))
      if (FD->isAnonymousStructOrUnion())
        return;

    if (NestedNameSpecifier *Qualifier = Node->getQualifier())
      Qualifier->print(OS, Policy);
    if (Node->hasTemplateKeyword())
      OS << "template ";
    OS << Node->getMemberNameInfo();
    if (Node->hasExplicitTemplateArgs())
      TemplateSpecializationType::PrintTemplateArgumentList(OS, Node->getTemplateArgs(), Node->getNumTemplateArgs(), Policy);
  }

  void VisitIntegerLiteral(IntegerLiteral *Node) {
    bool isSigned = Node->getType()->isSignedIntegerType();
    OS << Node->getValue().toString(10, isSigned);
  }

  void VisitCharacterLiteral(CharacterLiteral *Node) {
    unsigned value = Node->getValue();

    //TODO: it most likely does not produce valid SMTLIB2:
    switch (value) {
    case '\\':
      OS << "'\\\\'";
      break;
    case '\'':
      OS << "'\\''";
      break;
    case '\a':
      // TODO: K&R: the meaning of '\\a' is different in traditional C
      OS << "'\\a'";
      break;
    case '\b':
      OS << "'\\b'";
      break;
      // Nonstandard escape sequence.
      /*case '\e':
        OS << "'\\e'";
        break;*/
    case '\f':
      OS << "'\\f'";
      break;
    case '\n':
      OS << "'\\n'";
      break;
    case '\r':
      OS << "'\\r'";
      break;
    case '\t':
      OS << "'\\t'";
      break;
    case '\v':
      OS << "'\\v'";
      break;
    default:
      if (value < 256 && isPrintable((unsigned char)value))
        OS << value;
      else if (value < 256)
        OS << "'\\x" << llvm::format("%02x", value) << "'";
      else if (value <= 0xFFFF)
        OS << "'\\u" << llvm::format("%04x", value) << "'";
      else
        OS << "'\\U" << llvm::format("%08x", value) << "'";
    }
  }

  void VisitDeclRefExpr(DeclRefExpr *Node) {
    ValueDecl* decl = Node->getDecl();
    if (isa<EnumConstantDecl>(decl)) {
      EnumConstantDecl* ecdecl = cast<EnumConstantDecl>(decl);
      if (ecdecl->getInitVal() < 0) {
        OS << "(- ";
        OS << (-(ecdecl->getInitVal())).toString(10);
        OS << ")";
      } else {
        OS << ecdecl->getInitVal().toString(10);
      }
    } else {
      OS << Node->getNameInfo();
    }
  }

};

std::string toSMTLIB2(const Stmt* stmt) {
    std::string str;
    llvm::raw_string_ostream rso(str);
    PrintingPolicy pp = PrintingPolicy(LangOptions());
    StmtToSMTLIB2 T(rso, nullptr, pp);
    T.Visit(const_cast<Stmt*>(stmt));
    std::string stmtStr = rso.str();
    return stmtStr;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: indexentrysupplier_default.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: khong $ $Date: 2002-06-18 22:29:26 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include <sal/types.h>
#include <indexentrysupplier_default.hxx>
#include <data/indexdata_unicode.h>

using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::rtl;

namespace com { namespace sun { namespace star { namespace i18n {

IndexEntrySupplier_Unicode::IndexEntrySupplier_Unicode(const Reference < XMultiServiceFactory >& rxMSF) :
    IndexEntrySupplier(rxMSF)
{
    implementationName = "com.sun.star.i18n.IndexEntrySupplier_Unicode";
    collator = new CollatorImpl(rxMSF);
    usePhonetic = sal_False;
}

IndexEntrySupplier_Unicode::~IndexEntrySupplier_Unicode()
{
    delete collator;
}

sal_Bool SAL_CALL IndexEntrySupplier_Unicode::loadAlgorithm( const Locale& rLocale,
    const OUString& SortAlgorithm, sal_Int32 collatorOptions ) throw (RuntimeException)
{
    aSortAlgorithm = SortAlgorithm;
    aLocale = rLocale;
    return collator->loadCollatorAlgorithm(SortAlgorithm, rLocale, collatorOptions) == 0;
}

const OUString& SAL_CALL IndexEntrySupplier_Unicode::getEntry( const OUString& IndexEntry,
    const OUString& PhoneticEntry, const Locale& rLocale ) throw (RuntimeException)
{
    // The condition for using phonetic entry is:
    // usePhonetic is set for the algorithm;
    // rLocale for phonetic entry is same as aLocale for algorithm,
    // which means Chinese phonetic will not be used for Japanese algorithm;
    // phonetic entry is not blank.
    if (usePhonetic && rLocale == aLocale && PhoneticEntry.getLength() > 0)
        return PhoneticEntry;
    else
        return IndexEntry;
}

OUString SAL_CALL IndexEntrySupplier_Unicode::getIndexKey( const OUString& IndexEntry,
    const OUString& PhoneticEntry, const Locale& rLocale ) throw (RuntimeException)
{
    return getIndexCharacter(getEntry(IndexEntry, PhoneticEntry, rLocale), aLocale, OUString());
}

// this method can be overwriten by sub class for better performing key comparison.
sal_Int16 SAL_CALL IndexEntrySupplier_Unicode::compareIndexKey(
    const OUString& IndexEntry1, const OUString& PhoneticEntry1, const Locale& rLocale1,
    const OUString& IndexEntry2, const OUString& PhoneticEntry2, const Locale& rLocale2 )
    throw (RuntimeException)
{
    return collator->compareString( getIndexKey(IndexEntry1, PhoneticEntry1, rLocale1),
                    getIndexKey(IndexEntry2, PhoneticEntry2, rLocale2));
}

sal_Int16 SAL_CALL IndexEntrySupplier_Unicode::compareIndexEntry(
    const OUString& IndexEntry1, const OUString& PhoneticEntry1, const Locale& rLocale1,
    const OUString& IndexEntry2, const OUString& PhoneticEntry2, const Locale& rLocale2 )
    throw (RuntimeException)
{
    sal_Int16 result = compareIndexKey( IndexEntry1, PhoneticEntry1, rLocale1,
                        IndexEntry2, PhoneticEntry2, rLocale2);
    if (result == 0)
        return collator->compareString( getEntry(IndexEntry1, PhoneticEntry1, rLocale1),
                        getEntry(IndexEntry2, PhoneticEntry2, rLocale2));
    return 0;
}

OUString SAL_CALL IndexEntrySupplier_Unicode::getIndexCharacter( const OUString& rIndexEntry,
    const Locale& rLocale, const OUString& rSortAlgorithm ) throw (RuntimeException) {
    sal_uInt16 ch = rIndexEntry.toChar();
    sal_uInt16 address = idx[ch >> 8];
    return OUString((address != 0xFFFF ? &idxStr[address + (ch & 0xFF)] : &ch), 1);
}

} } } }
<commit_msg>#99877# compareIndexEntry always returned 0<commit_after>/*************************************************************************
 *
 *  $RCSfile: indexentrysupplier_default.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: fme $ $Date: 2002-06-26 08:22:03 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include <sal/types.h>
#include <indexentrysupplier_default.hxx>
#include <data/indexdata_unicode.h>

using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::rtl;

namespace com { namespace sun { namespace star { namespace i18n {

IndexEntrySupplier_Unicode::IndexEntrySupplier_Unicode(const Reference < XMultiServiceFactory >& rxMSF) :
    IndexEntrySupplier(rxMSF)
{
    implementationName = "com.sun.star.i18n.IndexEntrySupplier_Unicode";
    collator = new CollatorImpl(rxMSF);
    usePhonetic = sal_False;
}

IndexEntrySupplier_Unicode::~IndexEntrySupplier_Unicode()
{
    delete collator;
}

sal_Bool SAL_CALL IndexEntrySupplier_Unicode::loadAlgorithm( const Locale& rLocale,
    const OUString& SortAlgorithm, sal_Int32 collatorOptions ) throw (RuntimeException)
{
    aSortAlgorithm = SortAlgorithm;
    aLocale = rLocale;
    return collator->loadCollatorAlgorithm(SortAlgorithm, rLocale, collatorOptions) == 0;
}

const OUString& SAL_CALL IndexEntrySupplier_Unicode::getEntry( const OUString& IndexEntry,
    const OUString& PhoneticEntry, const Locale& rLocale ) throw (RuntimeException)
{
    // The condition for using phonetic entry is:
    // usePhonetic is set for the algorithm;
    // rLocale for phonetic entry is same as aLocale for algorithm,
    // which means Chinese phonetic will not be used for Japanese algorithm;
    // phonetic entry is not blank.
    if (usePhonetic && rLocale == aLocale && PhoneticEntry.getLength() > 0)
        return PhoneticEntry;
    else
        return IndexEntry;
}

OUString SAL_CALL IndexEntrySupplier_Unicode::getIndexKey( const OUString& IndexEntry,
    const OUString& PhoneticEntry, const Locale& rLocale ) throw (RuntimeException)
{
    return getIndexCharacter(getEntry(IndexEntry, PhoneticEntry, rLocale), aLocale, OUString());
}

// this method can be overwriten by sub class for better performing key comparison.
sal_Int16 SAL_CALL IndexEntrySupplier_Unicode::compareIndexKey(
    const OUString& IndexEntry1, const OUString& PhoneticEntry1, const Locale& rLocale1,
    const OUString& IndexEntry2, const OUString& PhoneticEntry2, const Locale& rLocale2 )
    throw (RuntimeException)
{
    return collator->compareString( getIndexKey(IndexEntry1, PhoneticEntry1, rLocale1),
                    getIndexKey(IndexEntry2, PhoneticEntry2, rLocale2));
}

sal_Int16 SAL_CALL IndexEntrySupplier_Unicode::compareIndexEntry(
    const OUString& IndexEntry1, const OUString& PhoneticEntry1, const Locale& rLocale1,
    const OUString& IndexEntry2, const OUString& PhoneticEntry2, const Locale& rLocale2 )
    throw (RuntimeException)
{
    sal_Int16 result = compareIndexKey( IndexEntry1, PhoneticEntry1, rLocale1,
                        IndexEntry2, PhoneticEntry2, rLocale2);
    if (result == 0)
        return collator->compareString( getEntry(IndexEntry1, PhoneticEntry1, rLocale1),
                        getEntry(IndexEntry2, PhoneticEntry2, rLocale2));
    return result;
}

OUString SAL_CALL IndexEntrySupplier_Unicode::getIndexCharacter( const OUString& rIndexEntry,
    const Locale& rLocale, const OUString& rSortAlgorithm ) throw (RuntimeException) {
    sal_uInt16 ch = rIndexEntry.toChar();
    sal_uInt16 address = idx[ch >> 8];
    return OUString((address != 0xFFFF ? &idxStr[address + (ch & 0xFF)] : &ch), 1);
}

} } } }
<|endoftext|>


<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2015, Youssef Kashef
// Copyright (c) 2015, ELM Library Project
// 3-clause BSD License
//
//M*/
#include "elm/core/graph/graphattr.h"

#include <boost/thread/thread.hpp>

#include "elm/core/debug_utils.h"
#include "elm/core/exception.h"
#include "elm/core/graph/base_GraphVertexOp.h"
#include "elm/core/graph/graphattr_impl.h"

using namespace boost;
using namespace cv;
using namespace elm;

typedef std::vector<VtxColor > VecColor;

GraphAttr::~GraphAttr()
{
    impl.reset();
}

GraphAttr::GraphAttr()
    : impl(new GraphAttr_Impl())
{
}

GraphAttr::GraphAttr(const Mat1i &map_img, const Mat1b &mask)
    : impl(new GraphAttr_Impl(map_img, mask))
{
}

size_t GraphAttr::num_vertices() const
{
    return static_cast<size_t>(boost::num_vertices(impl->g));
}

float GraphAttr::operator ()(int idx_u, int idx_v) const
{
    VecColor vtx_ids = VerticesIds();
    GraphAttrTraits::vertex_descriptor u, v;

    impl->findVertex(vtx_ids[idx_u], u);
    impl->findVertex(vtx_ids[idx_v], v);

    typename property_map < GraphAttrType, edge_weight_t >::type
            weight = get(edge_weight, impl->g);

    GraphAttrTraits::edge_descriptor e;
    bool found;

    boost::tie(e, found) = edge(u, v, impl->g);
    return found? get(weight, e) : 0.f;
}

void GraphAttr::AdjacencyMat(Mat1f &adj) const
{
    int nb_vertices = static_cast<int>(num_vertices());
    if(adj.rows < nb_vertices || adj.cols < nb_vertices) {

        adj = Mat1f(nb_vertices, nb_vertices);
    }

    // a lot of clutter just to traverse all edges
    typename property_map <GraphAttrType, edge_weight_t >::type
            weight = get(edge_weight, impl->g);

    GraphAttrTraits::vertex_iterator begin, end, next_u;
    tie(begin, end) = vertices(impl->g);

    int idx_u=0;
    for (next_u = begin; next_u != end; ++next_u, idx_u++) {

        GraphAttrTraits::vertex_iterator next_v;
        int idx_v=0;
        for (next_v = begin; next_v != end; ++next_v, idx_v++) {

            GraphAttrTraits::edge_descriptor e;
            bool found;

            tie(e, found) = edge(*next_u, *next_v, impl->g);
            adj(idx_u, idx_v) = found? get(weight, e) : 0.f;
        }
    }
}

VecI GraphAttr::VerticesIds() const
{
    VecI vtx_ids(num_vertices());

    property_map<GraphAttrType, vertex_color_t>::type
            vtx_color_lut = get(vertex_color, impl->g);

    GraphAttrTraits::vertex_iterator vi, vi_end, next;
    tie(vi, vi_end) = vertices(impl->g);
    int i=0;
    for (next = vi; vi != vi_end; vi = next) {

        ++next;
        vtx_ids[i++] = vtx_color_lut[*vi];
    }

    return vtx_ids;
}

void GraphAttr::addAttributes(int vtx_id, const Mat1f &attr)
{
    VtxDescriptor descriptor;
    if(impl->findVertex(vtx_id, descriptor)) {

        property_map<GraphAttrType, vertex_index2_t>::type
                vertex_attributes = get(vertex_index2, impl->g);

        vertex_attributes[descriptor] = attr;
    }
    else {
        std::stringstream s;
        s << "No vertex with id (" << vtx_id << ").";
        ELM_THROW_KEY_ERROR(s.str());
    }
}

Mat1f GraphAttr::getAttributes(int vtx_id) const
{
    VtxDescriptor descriptor;
    if(impl->findVertex(vtx_id, descriptor)) {

        property_map<GraphAttrType, vertex_index2_t>::type
                vertex_attributes = get(vertex_index2, impl->g);

        return vertex_attributes[descriptor];
    }
    else {
        std::stringstream s;
        s << "No vertex with id (" << vtx_id << ").";
        ELM_THROW_KEY_ERROR(s.str());
    }
}

Mat1f GraphAttr::applyVertexToMap(int vtx_id, Mat1f (*func)(const Mat1i &img, const Mat &mask)) const
{
    Mat1f vtx_result;

    VtxDescriptor vtx_descriptor;
    if(impl->findVertex(vtx_id, vtx_descriptor)) {

        property_map<GraphAttrType, vertex_color_t>::type
                vertex_color_id = get(vertex_color, impl->g);

        int vtx_color = vertex_color_id[vtx_descriptor];

        Mat1i map_img = impl->MapImg();
        Mat1b _mask = map_img == vtx_color;
        vtx_result = func(map_img, _mask);
    }
    else {
        std::stringstream s;
        s << "No vertex with id (" << vtx_id << ").";
        ELM_THROW_KEY_ERROR(s.str());
    }

    return vtx_result;
}

Mat1f GraphAttr::applyVertexOpToMap(int vtx_id, base_GraphVertexOp &vtx_op) const
{
    Mat1f vtx_result;

    VtxDescriptor vtx_descriptor;
    if(impl->findVertex(vtx_id, vtx_descriptor)) {

        property_map<GraphAttrType, vertex_color_t>::type
                vertex_color_id = get(vertex_color, impl->g);

        int vtx_color = vertex_color_id[vtx_descriptor];
        Mat1i map_img = impl->MapImg();
        Mat1b _mask = map_img == vtx_color;
        vtx_op.mutableOpCaller(map_img, _mask, vtx_result);
    }
    else {
        std::stringstream s;
        s << "No vertex with id (" << vtx_id << ").";
        ELM_THROW_KEY_ERROR(s.str());
    }

    return vtx_result;
}

VecMat1f GraphAttr::applyVerticesToMap(Mat1f (*func)(const Mat1i &img, const Mat &mask)) const
{
    VecMat1f results(num_vertices());

    property_map<GraphAttrType, vertex_color_t>::type
            vertex_color_id = get(vertex_color, impl->g);

    GraphAttrTraits::vertex_iterator vi, vi_end, next;
    tie(vi, vi_end) = vertices(impl->g);

    thread_group group;

    impl->MapImg();

    int i=0;
    for (next = vi; vi != vi_end; vi = ++next) {

        VtxColor vtx_color = vertex_color_id[*vi];

        group.create_thread(
                    boost::bind(&GraphAttr::apply_masked, this,
                                func,
                                vtx_color,
                                boost::ref(results[i++]))
                            );
    }
    group.join_all();

    return results;
}

int GraphAttr::contractEdges(int id_u, int id_v)
{
    VtxDescriptor u;
    VtxDescriptor v;

    // remove (u, v) and (v, u) edges
    impl->removeEdges(id_u, id_v, u, v);

    // TODO: merge all u and v out-edges with common targets
    // TODO: merge all u and v in-edges with common sources
    // move the rest of u out-edges to v
    // move the rest of u in-edges to v
    graph_traits<GraphAttrTraits>::out_edge_iterator e, e_end;
    //graph_traits<GraphAttrTraits>::edge_descriptor e_v;

    typename property_map <GraphAttrType, edge_weight_t >::type
            weight = get(edge_weight, impl->g);

    std::vector< std::pair<VtxDescriptor, VtxDescriptor> > obsolete_edges;

//    property_map<GraphAttrType, vertex_color_t>::type
//            vertex_color_id = get(vertex_color, impl->g);

    for(tie(e, e_end) = out_edges(u, impl->g); e != e_end; ++e) {

        VtxDescriptor src, dst;
        src = source(*e, impl->g);
        dst = target(*e, impl->g);

        // move or merge edge?
        if(src == u) {

//            EdgeWeightProp e_prop = get(weight, *e);
//            bool found;
//            boost::tie(e_v, found) = edge(v, dst, impl->g);

            add_edge(v, dst, get(weight, *e), impl->g); // move edge
        }
        else if(dst == u) {

            add_edge(src, v, get(weight, *e), impl->g); // move edge
        }
        else {

            std::stringstream s;
            s << "Neither edge source nor its target is  vertex u="<<
                 u << "with id=" << id_u << ".";
            ELM_THROW_VALUE_ERROR(s.str());
        }

        // keep track of edges to remove later
        obsolete_edges.push_back(std::make_pair(src, dst));
    }

    // must remove obsolete edges before removing vertex
    VtxDescriptor src, dst;
    for(size_t i=0; i<obsolete_edges.size(); i++) {

        tie(src, dst) = obsolete_edges[i];
        impl->removeEdges(src, dst);
    }

    impl->removeVertex(id_u, u);

    // let map reflect vertex merge
    impl->recordVertexSubstitution(id_u, id_v);

    return id_v;
}

void GraphAttr::removeEdges(int vtx_u, int vtx_v)
{
    VtxDescriptor u, v;
    return impl->removeEdges(vtx_u, vtx_v, u, v);
}

int GraphAttr::VertexIndex(int vtx_id) const
{
    VtxDescriptor v;
    if(!impl->findVertex(vtx_id, v)) {

        std::stringstream s;
        s << "No vertex with id (" << vtx_id << ").";
        ELM_THROW_KEY_ERROR(s.str());
    }

    VecI ids = VerticesIds();
    bool found = false;
    int idx = -1;
    for(int i=0; i < static_cast<int>(ids.size()) && !found; i++) {

        if(ids[i] == vtx_id) {

            idx = i;
            found = true;
        }
    }

    return idx;
}

VecI GraphAttr::getNeighbors(int vtx_id) const
{
    VtxDescriptor u;
    if(!impl->findVertex(vtx_id, u)) {

        std::stringstream s;
        s << "No vertex with id (" << vtx_id << ").";
        ELM_THROW_KEY_ERROR(s.str());
    }

    VecI neigh_ids;

    // Property accessor
    property_map<GraphAttrType, vertex_color_t>::type
            vertex_color_id = get(vertex_color, impl->g);

    graph_traits<GraphAttrTraits>::out_edge_iterator e, e_end;
    for(tie(e, e_end) = out_edges(u, impl->g); e != e_end; ++e) {

        VtxDescriptor src, dst;
        src = source(*e, impl->g);
        dst = target(*e, impl->g);

        // move or merge edge?
        if(src == u) {

            neigh_ids.push_back(vertex_color_id[dst]);
        }
        else if(dst == u) {

            neigh_ids.push_back(vertex_color_id[src]);
        }
        else {

            std::stringstream s;
            s << "Neither edge source nor its target is  vertex u="<<
                 u << "with id=" << vtx_id << ".";
            ELM_THROW_VALUE_ERROR(s.str());
        }
    }

    return neigh_ids;
}

void GraphAttr::removeVertex(int vtx_id)
{
    VtxDescriptor u;

    if(!impl->findVertex(vtx_id, u)) {

        std::stringstream s;
        s << "No vertex with id (" << vtx_id << ").";
        ELM_THROW_KEY_ERROR(s.str());
    }

    graph_traits<GraphAttrTraits>::out_edge_iterator e, e_end;

    std::vector< std::pair<VtxDescriptor, VtxDescriptor> > obsolete_edges;

    for(tie(e, e_end) = out_edges(u, impl->g); e != e_end; ++e) {

        VtxDescriptor src, dst;
        src = source(*e, impl->g);
        dst = target(*e, impl->g);

        // move or merge edge?
        if(src != u && dst != u) {

            std::stringstream s;
            s << "Neither edge source nor its target is vertex u="<<
                 u << "with id=" << vtx_id << ".";
            ELM_THROW_VALUE_ERROR(s.str());
        }

        // keep track of edges to remove later
        obsolete_edges.push_back(std::make_pair(src, dst));
    }

    // must remove obsolete edges before removing vertex
    VtxDescriptor src, dst;
    for(size_t i=0; i<obsolete_edges.size(); i++) {

        tie(src, dst) = obsolete_edges[i];
        impl->removeEdges(src, dst);
    }

    impl->removeVertex(vtx_id, u);

    // let map reflect vertex merge
    impl->recordVertexSubstitution(vtx_id, impl->ID_UNASSIGNED);
}

Mat1i GraphAttr::MapImg() const
{
    return impl->MapImg();
}

void GraphAttr::apply_masked(cv::Mat1f (*func) (const cv::Mat1i &img, const cv::Mat &mask),
                             int color,
                             Mat1f &dst) const
{
    Mat1i map_img = impl->MapImg();
    Mat _mask = (map_img == color);
    dst = func(map_img, _mask);
}

<commit_msg>no more need to mimic vertex removal as substitution with unassigned<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2015, Youssef Kashef
// Copyright (c) 2015, ELM Library Project
// 3-clause BSD License
//
//M*/
#include "elm/core/graph/graphattr.h"

#include <boost/thread/thread.hpp>

#include "elm/core/debug_utils.h"
#include "elm/core/exception.h"
#include "elm/core/graph/base_GraphVertexOp.h"
#include "elm/core/graph/graphattr_impl.h"

using namespace boost;
using namespace cv;
using namespace elm;

typedef std::vector<VtxColor > VecColor;

GraphAttr::~GraphAttr()
{
    impl.reset();
}

GraphAttr::GraphAttr()
    : impl(new GraphAttr_Impl())
{
}

GraphAttr::GraphAttr(const Mat1i &map_img, const Mat1b &mask)
    : impl(new GraphAttr_Impl(map_img, mask))
{
}

size_t GraphAttr::num_vertices() const
{
    return static_cast<size_t>(boost::num_vertices(impl->g));
}

float GraphAttr::operator ()(int idx_u, int idx_v) const
{
    VecColor vtx_ids = VerticesIds();
    GraphAttrTraits::vertex_descriptor u, v;

    impl->findVertex(vtx_ids[idx_u], u);
    impl->findVertex(vtx_ids[idx_v], v);

    typename property_map < GraphAttrType, edge_weight_t >::type
            weight = get(edge_weight, impl->g);

    GraphAttrTraits::edge_descriptor e;
    bool found;

    boost::tie(e, found) = edge(u, v, impl->g);
    return found? get(weight, e) : 0.f;
}

void GraphAttr::AdjacencyMat(Mat1f &adj) const
{
    int nb_vertices = static_cast<int>(num_vertices());
    if(adj.rows < nb_vertices || adj.cols < nb_vertices) {

        adj = Mat1f(nb_vertices, nb_vertices);
    }

    // a lot of clutter just to traverse all edges
    typename property_map <GraphAttrType, edge_weight_t >::type
            weight = get(edge_weight, impl->g);

    GraphAttrTraits::vertex_iterator begin, end, next_u;
    tie(begin, end) = vertices(impl->g);

    int idx_u=0;
    for (next_u = begin; next_u != end; ++next_u, idx_u++) {

        GraphAttrTraits::vertex_iterator next_v;
        int idx_v=0;
        for (next_v = begin; next_v != end; ++next_v, idx_v++) {

            GraphAttrTraits::edge_descriptor e;
            bool found;

            tie(e, found) = edge(*next_u, *next_v, impl->g);
            adj(idx_u, idx_v) = found? get(weight, e) : 0.f;
        }
    }
}

VecI GraphAttr::VerticesIds() const
{
    VecI vtx_ids(num_vertices());

    property_map<GraphAttrType, vertex_color_t>::type
            vtx_color_lut = get(vertex_color, impl->g);

    GraphAttrTraits::vertex_iterator vi, vi_end, next;
    tie(vi, vi_end) = vertices(impl->g);
    int i=0;
    for (next = vi; vi != vi_end; vi = next) {

        ++next;
        vtx_ids[i++] = vtx_color_lut[*vi];
    }

    return vtx_ids;
}

void GraphAttr::addAttributes(int vtx_id, const Mat1f &attr)
{
    VtxDescriptor descriptor;
    if(impl->findVertex(vtx_id, descriptor)) {

        property_map<GraphAttrType, vertex_index2_t>::type
                vertex_attributes = get(vertex_index2, impl->g);

        vertex_attributes[descriptor] = attr;
    }
    else {
        std::stringstream s;
        s << "No vertex with id (" << vtx_id << ").";
        ELM_THROW_KEY_ERROR(s.str());
    }
}

Mat1f GraphAttr::getAttributes(int vtx_id) const
{
    VtxDescriptor descriptor;
    if(impl->findVertex(vtx_id, descriptor)) {

        property_map<GraphAttrType, vertex_index2_t>::type
                vertex_attributes = get(vertex_index2, impl->g);

        return vertex_attributes[descriptor];
    }
    else {
        std::stringstream s;
        s << "No vertex with id (" << vtx_id << ").";
        ELM_THROW_KEY_ERROR(s.str());
    }
}

Mat1f GraphAttr::applyVertexToMap(int vtx_id, Mat1f (*func)(const Mat1i &img, const Mat &mask)) const
{
    Mat1f vtx_result;

    VtxDescriptor vtx_descriptor;
    if(impl->findVertex(vtx_id, vtx_descriptor)) {

        property_map<GraphAttrType, vertex_color_t>::type
                vertex_color_id = get(vertex_color, impl->g);

        int vtx_color = vertex_color_id[vtx_descriptor];

        Mat1i map_img = impl->MapImg();
        Mat1b _mask = map_img == vtx_color;
        vtx_result = func(map_img, _mask);
    }
    else {
        std::stringstream s;
        s << "No vertex with id (" << vtx_id << ").";
        ELM_THROW_KEY_ERROR(s.str());
    }

    return vtx_result;
}

Mat1f GraphAttr::applyVertexOpToMap(int vtx_id, base_GraphVertexOp &vtx_op) const
{
    Mat1f vtx_result;

    VtxDescriptor vtx_descriptor;
    if(impl->findVertex(vtx_id, vtx_descriptor)) {

        property_map<GraphAttrType, vertex_color_t>::type
                vertex_color_id = get(vertex_color, impl->g);

        int vtx_color = vertex_color_id[vtx_descriptor];
        Mat1i map_img = impl->MapImg();
        Mat1b _mask = map_img == vtx_color;
        vtx_op.mutableOpCaller(map_img, _mask, vtx_result);
    }
    else {
        std::stringstream s;
        s << "No vertex with id (" << vtx_id << ").";
        ELM_THROW_KEY_ERROR(s.str());
    }

    return vtx_result;
}

VecMat1f GraphAttr::applyVerticesToMap(Mat1f (*func)(const Mat1i &img, const Mat &mask)) const
{
    VecMat1f results(num_vertices());

    property_map<GraphAttrType, vertex_color_t>::type
            vertex_color_id = get(vertex_color, impl->g);

    GraphAttrTraits::vertex_iterator vi, vi_end, next;
    tie(vi, vi_end) = vertices(impl->g);

    thread_group group;

    impl->MapImg();

    int i=0;
    for (next = vi; vi != vi_end; vi = ++next) {

        VtxColor vtx_color = vertex_color_id[*vi];

        group.create_thread(
                    boost::bind(&GraphAttr::apply_masked, this,
                                func,
                                vtx_color,
                                boost::ref(results[i++]))
                            );
    }
    group.join_all();

    return results;
}

int GraphAttr::contractEdges(int id_u, int id_v)
{
    VtxDescriptor u;
    VtxDescriptor v;

    // remove (u, v) and (v, u) edges
    impl->removeEdges(id_u, id_v, u, v);

    // TODO: merge all u and v out-edges with common targets
    // TODO: merge all u and v in-edges with common sources
    // move the rest of u out-edges to v
    // move the rest of u in-edges to v
    graph_traits<GraphAttrTraits>::out_edge_iterator e, e_end;
    //graph_traits<GraphAttrTraits>::edge_descriptor e_v;

    typename property_map <GraphAttrType, edge_weight_t >::type
            weight = get(edge_weight, impl->g);

    std::vector< std::pair<VtxDescriptor, VtxDescriptor> > obsolete_edges;

//    property_map<GraphAttrType, vertex_color_t>::type
//            vertex_color_id = get(vertex_color, impl->g);

    for(tie(e, e_end) = out_edges(u, impl->g); e != e_end; ++e) {

        VtxDescriptor src, dst;
        src = source(*e, impl->g);
        dst = target(*e, impl->g);

        // move or merge edge?
        if(src == u) {

//            EdgeWeightProp e_prop = get(weight, *e);
//            bool found;
//            boost::tie(e_v, found) = edge(v, dst, impl->g);

            add_edge(v, dst, get(weight, *e), impl->g); // move edge
        }
        else if(dst == u) {

            add_edge(src, v, get(weight, *e), impl->g); // move edge
        }
        else {

            std::stringstream s;
            s << "Neither edge source nor its target is  vertex u="<<
                 u << "with id=" << id_u << ".";
            ELM_THROW_VALUE_ERROR(s.str());
        }

        // keep track of edges to remove later
        obsolete_edges.push_back(std::make_pair(src, dst));
    }

    // must remove obsolete edges before removing vertex
    VtxDescriptor src, dst;
    for(size_t i=0; i<obsolete_edges.size(); i++) {

        tie(src, dst) = obsolete_edges[i];
        impl->removeEdges(src, dst);
    }

    impl->removeVertex(id_u, u);

    // let map reflect vertex merge
    impl->recordVertexSubstitution(id_u, id_v);

    return id_v;
}

void GraphAttr::removeEdges(int vtx_u, int vtx_v)
{
    VtxDescriptor u, v;
    return impl->removeEdges(vtx_u, vtx_v, u, v);
}

int GraphAttr::VertexIndex(int vtx_id) const
{
    VtxDescriptor v;
    if(!impl->findVertex(vtx_id, v)) {

        std::stringstream s;
        s << "No vertex with id (" << vtx_id << ").";
        ELM_THROW_KEY_ERROR(s.str());
    }

    VecI ids = VerticesIds();
    bool found = false;
    int idx = -1;
    for(int i=0; i < static_cast<int>(ids.size()) && !found; i++) {

        if(ids[i] == vtx_id) {

            idx = i;
            found = true;
        }
    }

    return idx;
}

VecI GraphAttr::getNeighbors(int vtx_id) const
{
    VtxDescriptor u;
    if(!impl->findVertex(vtx_id, u)) {

        std::stringstream s;
        s << "No vertex with id (" << vtx_id << ").";
        ELM_THROW_KEY_ERROR(s.str());
    }

    VecI neigh_ids;

    // Property accessor
    property_map<GraphAttrType, vertex_color_t>::type
            vertex_color_id = get(vertex_color, impl->g);

    graph_traits<GraphAttrTraits>::out_edge_iterator e, e_end;
    for(tie(e, e_end) = out_edges(u, impl->g); e != e_end; ++e) {

        VtxDescriptor src, dst;
        src = source(*e, impl->g);
        dst = target(*e, impl->g);

        // move or merge edge?
        if(src == u) {

            neigh_ids.push_back(vertex_color_id[dst]);
        }
        else if(dst == u) {

            neigh_ids.push_back(vertex_color_id[src]);
        }
        else {

            std::stringstream s;
            s << "Neither edge source nor its target is  vertex u="<<
                 u << "with id=" << vtx_id << ".";
            ELM_THROW_VALUE_ERROR(s.str());
        }
    }

    return neigh_ids;
}

void GraphAttr::removeVertex(int vtx_id)
{
    VtxDescriptor u;

    if(!impl->findVertex(vtx_id, u)) {

        std::stringstream s;
        s << "No vertex with id (" << vtx_id << ").";
        ELM_THROW_KEY_ERROR(s.str());
    }

    graph_traits<GraphAttrTraits>::out_edge_iterator e, e_end;

    std::vector< std::pair<VtxDescriptor, VtxDescriptor> > obsolete_edges;

    for(tie(e, e_end) = out_edges(u, impl->g); e != e_end; ++e) {

        VtxDescriptor src, dst;
        src = source(*e, impl->g);
        dst = target(*e, impl->g);

        // move or merge edge?
        if(src != u && dst != u) {

            std::stringstream s;
            s << "Neither edge source nor its target is vertex u="<<
                 u << "with id=" << vtx_id << ".";
            ELM_THROW_VALUE_ERROR(s.str());
        }

        // keep track of edges to remove later
        obsolete_edges.push_back(std::make_pair(src, dst));
    }

    // must remove obsolete edges before removing vertex
    VtxDescriptor src, dst;
    for(size_t i=0; i<obsolete_edges.size(); i++) {

        tie(src, dst) = obsolete_edges[i];
        impl->removeEdges(src, dst);
    }

    impl->removeVertex(vtx_id, u); // also lets map reflect vertex merge
}

Mat1i GraphAttr::MapImg() const
{
    return impl->MapImg();
}

void GraphAttr::apply_masked(cv::Mat1f (*func) (const cv::Mat1i &img, const cv::Mat &mask),
                             int color,
                             Mat1f &dst) const
{
    Mat1i map_img = impl->MapImg();
    Mat _mask = (map_img == color);
    dst = func(map_img, _mask);
}

<|endoftext|>


<commit_before>/*****************************************************************************
 * messages.hpp : Information about a stream
 ****************************************************************************
 * Copyright (C) 2006-2007 the VideoLAN team
 * $Id$
 *
 * Authors: Jean-Baptiste Kempf <jb (at) videolan.org>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

#ifndef QVLC_MESSAGES_DIALOG_H_
#define QVLC_MESSAGES_DIALOG_H_ 1

#include "util/qvlcframe.hpp"
#include "util/singleton.hpp"
#include "ui/messages_panel.h"
#include <stdarg.h>
#include <vlc_atomic.h>
#include <QMutex>

class QPushButton;
class QTreeWidget;
class QTreeWidgetItem;
class MsgEvent;

class MessagesDialog : public QVLCFrame, public Singleton<MessagesDialog>
{
    Q_OBJECT
private:
    MessagesDialog( intf_thread_t * );
    virtual ~MessagesDialog();

    Ui::messagesPanelWidget ui;
    static void sinkMessage( void *, vlc_log_t *, unsigned );
    void customEvent( QEvent * );
    void sinkMessage( const MsgEvent * );
    bool matchFilter( const QString& );

    atomic_uint verbosity;
    static void MsgCallback( void *, int, const vlc_log_t *, const char *,
                             va_list );

private slots:
    bool save();
    void updateConfig();
    void changeVerbosity( int );
    void updateOrClear();
    void tabChanged( int );
    void filterMessages();

private:
    void buildTree( QTreeWidgetItem *, vlc_object_t * );

    friend class    Singleton<MessagesDialog>;
    QPushButton *updateButton;
    QMutex messageLocker;
#ifndef NDEBUG
    QTreeWidget *pldebugTree;
    void updatePLTree();
#endif
};

#endif
<commit_msg>Qt: fix mismatching sign types<commit_after>/*****************************************************************************
 * messages.hpp : Information about a stream
 ****************************************************************************
 * Copyright (C) 2006-2007 the VideoLAN team
 * $Id$
 *
 * Authors: Jean-Baptiste Kempf <jb (at) videolan.org>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

#ifndef QVLC_MESSAGES_DIALOG_H_
#define QVLC_MESSAGES_DIALOG_H_ 1

#include "util/qvlcframe.hpp"
#include "util/singleton.hpp"
#include "ui/messages_panel.h"
#include <stdarg.h>
#include <vlc_atomic.h>
#include <QMutex>

class QPushButton;
class QTreeWidget;
class QTreeWidgetItem;
class MsgEvent;

class MessagesDialog : public QVLCFrame, public Singleton<MessagesDialog>
{
    Q_OBJECT
private:
    MessagesDialog( intf_thread_t * );
    virtual ~MessagesDialog();

    Ui::messagesPanelWidget ui;
    static void sinkMessage( void *, vlc_log_t *, unsigned );
    void customEvent( QEvent * );
    void sinkMessage( const MsgEvent * );
    bool matchFilter( const QString& );

    atomic_int verbosity;
    static void MsgCallback( void *, int, const vlc_log_t *, const char *,
                             va_list );

private slots:
    bool save();
    void updateConfig();
    void changeVerbosity( int );
    void updateOrClear();
    void tabChanged( int );
    void filterMessages();

private:
    void buildTree( QTreeWidgetItem *, vlc_object_t * );

    friend class    Singleton<MessagesDialog>;
    QPushButton *updateButton;
    QMutex messageLocker;
#ifndef NDEBUG
    QTreeWidget *pldebugTree;
    void updatePLTree();
#endif
};

#endif
<|endoftext|>


<commit_before>
#include "JitVM.h"
#include <libevm/VM.h>
#include <evmjit/libevmjit/ExecutionEngine.h>
#include <evmjit/libevmjit/Utils.h>

namespace dev
{
namespace eth
{

bytesConstRef JitVM::go(ExtVMFace& _ext, OnOpFunc const&, uint64_t)
{
	using namespace jit;

	RuntimeData data{{},nullptr,nullptr};

#define set(INDEX, VALUE) data.elems[INDEX] = eth2llvm(VALUE)
	set(RuntimeData::Gas, m_gas);
	set(RuntimeData::Address, fromAddress(_ext.myAddress));
	set(RuntimeData::Caller, fromAddress(_ext.caller));
	set(RuntimeData::Origin, fromAddress(_ext.origin));
	set(RuntimeData::CallValue, _ext.value);
	set(RuntimeData::CallDataSize, _ext.data.size());
	set(RuntimeData::GasPrice, _ext.gasPrice);
	set(RuntimeData::PrevHash, _ext.previousBlock.hash);
	set(RuntimeData::CoinBase, fromAddress(_ext.currentBlock.coinbaseAddress));
	set(RuntimeData::TimeStamp, _ext.currentBlock.timestamp);
	set(RuntimeData::Number, _ext.currentBlock.number);
	set(RuntimeData::Difficulty, _ext.currentBlock.difficulty);
	set(RuntimeData::GasLimit, _ext.currentBlock.gasLimit);
	set(RuntimeData::CodeSize, _ext.code.size());   // TODO: Use constant
	data.callData = _ext.data.data();
	data.code = _ext.code.data();
#undef set

	ExecutionEngine engine;
	auto env = reinterpret_cast<Env*>(&_ext);
	auto exitCode = engine.run(_ext.code, &data, env);

	switch (exitCode)
	{
	case ReturnCode::BadJumpDestination:
		BOOST_THROW_EXCEPTION(BadJumpDestination());
	case ReturnCode::OutOfGas:
		BOOST_THROW_EXCEPTION(OutOfGas());
	case ReturnCode::StackTooSmall:
		BOOST_THROW_EXCEPTION(StackTooSmall());
	case ReturnCode::BadInstruction:
		BOOST_THROW_EXCEPTION(BadInstruction());
	default:
		break;
	}

	m_gas = llvm2eth(data.elems[RuntimeData::Gas]);
	m_output = std::move(engine.returnData);
	return {m_output.data(), m_output.size()};  // TODO: This all bytesConstRef stuff sucks
}

}
}

namespace
{
	// MSVS linker ignores export symbols in Env.cpp if nothing point at least one of them
	extern "C" void env_sload();
	void linkerWorkaround()
	{
		env_sload();
		(void)linkerWorkaround; // suppress unused function warning from GCC
	}
}
<commit_msg>Fix MSVC warning<commit_after>
#include "JitVM.h"
#include <libevm/VM.h>
#include <evmjit/libevmjit/ExecutionEngine.h>
#include <evmjit/libevmjit/Utils.h>

namespace dev
{
namespace eth
{

bytesConstRef JitVM::go(ExtVMFace& _ext, OnOpFunc const&, uint64_t)
{
	using namespace jit;

	RuntimeData data{{},nullptr,nullptr};

#define set(INDEX, VALUE) data.elems[INDEX] = eth2llvm(VALUE)
	set(RuntimeData::Gas, m_gas);
	set(RuntimeData::Address, fromAddress(_ext.myAddress));
	set(RuntimeData::Caller, fromAddress(_ext.caller));
	set(RuntimeData::Origin, fromAddress(_ext.origin));
	set(RuntimeData::CallValue, _ext.value);
	set(RuntimeData::CallDataSize, _ext.data.size());
	set(RuntimeData::GasPrice, _ext.gasPrice);
	set(RuntimeData::PrevHash, _ext.previousBlock.hash);
	set(RuntimeData::CoinBase, fromAddress(_ext.currentBlock.coinbaseAddress));
	set(RuntimeData::TimeStamp, _ext.currentBlock.timestamp);
	set(RuntimeData::Number, _ext.currentBlock.number);
	set(RuntimeData::Difficulty, _ext.currentBlock.difficulty);
	set(RuntimeData::GasLimit, _ext.currentBlock.gasLimit);
	set(RuntimeData::CodeSize, _ext.code.size());   // TODO: Use constant
	data.callData = _ext.data.data();
	data.code = _ext.code.data();
#undef set

	ExecutionEngine engine;
	auto env = reinterpret_cast<Env*>(&_ext);
	auto exitCode = engine.run(_ext.code, &data, env);

	switch (exitCode)
	{
	case ReturnCode::BadJumpDestination:
		BOOST_THROW_EXCEPTION(BadJumpDestination());
	case ReturnCode::OutOfGas:
		BOOST_THROW_EXCEPTION(OutOfGas());
	case ReturnCode::StackTooSmall:
		BOOST_THROW_EXCEPTION(StackTooSmall());
	case ReturnCode::BadInstruction:
		BOOST_THROW_EXCEPTION(BadInstruction());
	default:
		break;
	}

	m_gas = llvm2eth(data.elems[RuntimeData::Gas]);
	m_output = std::move(engine.returnData);
	return {m_output.data(), m_output.size()};  // TODO: This all bytesConstRef stuff sucks
}

}
}

namespace
{
	// MSVS linker ignores export symbols in Env.cpp if nothing point at least one of them
	extern "C" void env_sload();
	void linkerWorkaround()
	{
		env_sload();
		(void)&linkerWorkaround; // suppress unused function warning from GCC
	}
}
<|endoftext|>


<commit_before>/****************************************************************************
**
** QtMEL is a Qt Media Encoding Library that allows to encode video and audio streams
** Copyright (C) 2013 Kirill Bukaev(aka KIBSOFT).
** Contact: Kirill Bukaev (support@kibsoft.ru)
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License as published by the Free Software Foundation; either
** version 2.1 of the License, or (at your option) any later version.
**
** This library is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
** Lesser General Public License for more details.
**
** You should have received a copy of the GNU Lesser General Public
** License along with this library; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
**
****************************************************************************/

#include "audiograbber.h"
#include "../../3rdparty/RtAudio.h"

int handleData(void *outputBuffer, void *inputBuffer, unsigned int nBufferFrames,
               double streamTime, RtAudioStreamStatus status, void *data)
{
    Q_UNUSED(outputBuffer)
    Q_UNUSED(streamTime)
    Q_UNUSED(status)

    AudioGrabber *grabber = static_cast<AudioGrabber *>(data);

    int bytesReady = nBufferFrames * grabber->format().channelCount() * 2;
    QByteArray array;
    array.resize(bytesReady);
    memcpy(array.data(), inputBuffer, bytesReady);

    grabber->onDataAvailable(array);

    return 0;
}

AudioFormat::AudioFormat()
    : m_sampleRate(-1)
    , m_format(AudioFormat::SignedInt16)
    , m_channelCount(-1)
{
}

AudioFormat::~AudioFormat()
{
}

void AudioFormat::setSampleRate(int rate)
{
    m_sampleRate = rate;
}

int AudioFormat::sampleRate() const
{
    return m_sampleRate;
}

void AudioFormat::setFormat(AudioFormat::Format format)
{
    m_format = format;
}

AudioFormat::Format AudioFormat::format() const
{
    return m_format;
}

void AudioFormat::setChannelCount(int count)
{
    m_channelCount = count;
}

int AudioFormat::channelCount() const
{
    return m_channelCount;
}

AudioGrabber::AudioGrabber(QObject *parent)
    : AbstractGrabber(parent)
    , m_deviceIndex(-1)
{
    init();
}

AudioGrabber::~AudioGrabber()
{
    cleanup();
}

void AudioGrabber::setDeviceIndex(int index)
{
    if (m_deviceIndex != index) {
        m_deviceIndex = index;
    }
}

int AudioGrabber::deviceIndex() const
{
    return m_deviceIndex;
}

void AudioGrabber::setFormat(const AudioFormat &format)
{
    m_format = format;
}

AudioFormat AudioGrabber::format() const
{
    return m_format;
}

int AudioGrabber::grabbedAudioDataSize() const
{
    return m_grabbedAudioDataSize;
}

int AudioGrabber::elapsedMilliseconds() const
{
    if (!m_rtAudio || state() == AudioGrabber::StoppedState)
        return 0;

    return m_rtAudio->getStreamTime() * 1000;
}

QHash<int, QString> AudioGrabber::availableDevices()
{
    RtAudio rtAudio;
    int deviceCount = rtAudio.getDeviceCount();
    RtAudio::DeviceInfo info;
    QHash<int, QString> devices;

    for (int i = 0; i < deviceCount; ++i) {
        info = rtAudio.getDeviceInfo(i);

        if (info.inputChannels > 0) {
            devices.insert(i, QString::fromStdString(info.name));
        }
    }

    return devices;
}

bool AudioGrabber::start()
{
    if (state() == AbstractGrabber::StoppedState) {
        if (deviceIndex() < 0 || deviceIndex() > availableDevices().count()) {
            setError(AbstractGrabber::DeviceNotFoundError, tr("Device to be grabbed was not found."));
            return false;
        }

        m_rtAudio = new RtAudio;

        unsigned int bufferFrames = 2048;
        RtAudio::StreamParameters params;
        params.deviceId = deviceIndex();
        params.nChannels = format().channelCount();
        params.firstChannel = 0;

        try {
            m_rtAudio->openStream(NULL, &params, format().format(), format().sampleRate(), &bufferFrames, &handleData, this);
            m_rtAudio->startStream();
        } catch (RtError&) {
            setError(AbstractGrabber::DeviceOpenError, tr("Unable to open device."));
            return false;
        }

        setState(AbstractGrabber::ActiveState);

        return true;
    }

    return false;
}

void AudioGrabber::stop()
{
    if (state() != AbstractGrabber::StoppedState) {
        m_rtAudio->closeStream();
        cleanup();

        setState(AbstractGrabber::StoppedState);
    }
}

void AudioGrabber::suspend()
{
    if (state() == AbstractGrabber::ActiveState) {
        m_rtAudio->stopStream();

        setState(AbstractGrabber::SuspendedState);
    }
}

void AudioGrabber::resume()
{
    if (state() == AbstractGrabber::SuspendedState) {
        m_rtAudio->startStream();

        setState(AbstractGrabber::ActiveState);
    }
}

void AudioGrabber::init()
{
    m_grabbedAudioDataSize = 0;
}

void AudioGrabber::cleanup()
{
    if (m_rtAudio) {
        delete m_rtAudio;
        m_rtAudio = 0;
    }

    init();
}

void AudioGrabber::onDataAvailable(const QByteArray &data)
{
    if (data.size() > 0) {
        m_grabbedAudioDataSize += data.size();

        Q_EMIT dataAvailable(data);
    }
}
<commit_msg>Crash fix<commit_after>/****************************************************************************
**
** QtMEL is a Qt Media Encoding Library that allows to encode video and audio streams
** Copyright (C) 2013 Kirill Bukaev(aka KIBSOFT).
** Contact: Kirill Bukaev (support@kibsoft.ru)
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License as published by the Free Software Foundation; either
** version 2.1 of the License, or (at your option) any later version.
**
** This library is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
** Lesser General Public License for more details.
**
** You should have received a copy of the GNU Lesser General Public
** License along with this library; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
**
****************************************************************************/

#include "audiograbber.h"
#include "../../3rdparty/RtAudio.h"

int handleData(void *outputBuffer, void *inputBuffer, unsigned int nBufferFrames,
               double streamTime, RtAudioStreamStatus status, void *data)
{
    Q_UNUSED(outputBuffer)
    Q_UNUSED(streamTime)
    Q_UNUSED(status)

    AudioGrabber *grabber = static_cast<AudioGrabber *>(data);

    int bytesReady = nBufferFrames * grabber->format().channelCount() * 2;
    QByteArray array;
    array.resize(bytesReady);
    memcpy(array.data(), inputBuffer, bytesReady);

    grabber->onDataAvailable(array);

    return 0;
}

AudioFormat::AudioFormat()
    : m_sampleRate(-1)
    , m_format(AudioFormat::SignedInt16)
    , m_channelCount(-1)
{
}

AudioFormat::~AudioFormat()
{
}

void AudioFormat::setSampleRate(int rate)
{
    m_sampleRate = rate;
}

int AudioFormat::sampleRate() const
{
    return m_sampleRate;
}

void AudioFormat::setFormat(AudioFormat::Format format)
{
    m_format = format;
}

AudioFormat::Format AudioFormat::format() const
{
    return m_format;
}

void AudioFormat::setChannelCount(int count)
{
    m_channelCount = count;
}

int AudioFormat::channelCount() const
{
    return m_channelCount;
}

AudioGrabber::AudioGrabber(QObject *parent)
    : AbstractGrabber(parent)
    , m_deviceIndex(-1)
{
    init();
}

AudioGrabber::~AudioGrabber()
{
    cleanup();
}

void AudioGrabber::setDeviceIndex(int index)
{
    if (m_deviceIndex != index) {
        m_deviceIndex = index;
    }
}

int AudioGrabber::deviceIndex() const
{
    return m_deviceIndex;
}

void AudioGrabber::setFormat(const AudioFormat &format)
{
    m_format = format;
}

AudioFormat AudioGrabber::format() const
{
    return m_format;
}

int AudioGrabber::grabbedAudioDataSize() const
{
    return m_grabbedAudioDataSize;
}

int AudioGrabber::elapsedMilliseconds() const
{
    if (!m_rtAudio || state() == AudioGrabber::StoppedState)
        return 0;

    return m_rtAudio->getStreamTime() * 1000;
}

QHash<int, QString> AudioGrabber::availableDevices()
{
    RtAudio rtAudio;
    int deviceCount = rtAudio.getDeviceCount();
    RtAudio::DeviceInfo info;
    QHash<int, QString> devices;

    for (int i = 0; i < deviceCount; ++i) {
        info = rtAudio.getDeviceInfo(i);

        if (info.inputChannels > 0) {
            devices.insert(i, QString::fromStdString(info.name));
        }
    }

    return devices;
}

bool AudioGrabber::start()
{
    if (state() == AbstractGrabber::StoppedState) {
        if (deviceIndex() < 0 || deviceIndex() > availableDevices().count()) {
            setError(AbstractGrabber::DeviceNotFoundError, tr("Device to be grabbed was not found."));
            return false;
        }

        m_rtAudio = new RtAudio;

        unsigned int bufferFrames = 2048;
        RtAudio::StreamParameters params;
        params.deviceId = deviceIndex();
        params.nChannels = format().channelCount();
        params.firstChannel = 0;

        try {
            m_rtAudio->openStream(NULL, &params, format().format(), format().sampleRate(), &bufferFrames, &handleData, this);
            m_rtAudio->startStream();
        } catch (RtError&) {
            setError(AbstractGrabber::DeviceOpenError, tr("Unable to open device."));
            return false;
        }

        setState(AbstractGrabber::ActiveState);

        return true;
    }

    return false;
}

void AudioGrabber::stop()
{
    if (state() != AbstractGrabber::StoppedState) {
        m_rtAudio->closeStream();
        cleanup();

        setState(AbstractGrabber::StoppedState);
    }
}

void AudioGrabber::suspend()
{
    if (state() == AbstractGrabber::ActiveState) {
        m_rtAudio->stopStream();

        setState(AbstractGrabber::SuspendedState);
    }
}

void AudioGrabber::resume()
{
    if (state() == AbstractGrabber::SuspendedState) {
        m_rtAudio->startStream();

        setState(AbstractGrabber::ActiveState);
    }
}

void AudioGrabber::init()
{
    m_grabbedAudioDataSize = 0;
    m_rtAudio = 0;
}

void AudioGrabber::cleanup()
{
    if (m_rtAudio)
        delete m_rtAudio;

    init();
}

void AudioGrabber::onDataAvailable(const QByteArray &data)
{
    if (data.size() > 0) {
        m_grabbedAudioDataSize += data.size();

        Q_EMIT dataAvailable(data);
    }
}
<|endoftext|>


<commit_before>
#include <qstylesheet.h>

#include <klocale.h>
#include <kstandarddirs.h>
#include <kglobal.h>
#include <kdebug.h>

#include "device.h"
#include "helper.h"

using namespace OpieHelper;

Base::Base( CategoryEdit* edit,
            KSync::KonnectorUIDHelper* helper,
            const QString &tz,
            bool metaSyncing, Device* dev )
{
    m_metaSyncing = metaSyncing;
    m_edit = edit;
    m_helper = helper;
    m_tz = tz;
    m_device = dev;
}
Base::~Base()
{

}
QDateTime Base::fromUTC( time_t time )
{
   struct tm *lt;

   /* getenv can be NULL */
   char* ptrTz = getenv( "TZ");
   QString real_TZ = ptrTz ? QString::fromLocal8Bit( ptrTz ) : QString::null;

   if (!m_tz.isEmpty() )
       setenv( "TZ", m_tz, true );

   kdDebug(5229) << "TimeZone was " << real_TZ << " TimeZone now is " << m_tz << endl;
#if defined(_OS_WIN32) || defined (Q_OS_WIN32) || defined (Q_OS_WIN64)
    _tzset();
#else
    tzset();
#endif
    lt = localtime( &time );
    QDateTime dt;
    dt.setDate( QDate( lt->tm_year + 1900, lt->tm_mon + 1, lt->tm_mday ) );
    dt.setTime( QTime( lt->tm_hour, lt->tm_min, lt->tm_sec ) );

    if (!m_tz.isEmpty() ) {
        unsetenv("TZ");
        if (!real_TZ.isEmpty() )
            setenv("TZ",  real_TZ, true );
    }
    kdDebug(5229) << "DateTime is " << dt.toString() << endl;
    // done
    return dt;
}
time_t Base::toUTC( const QDateTime& dt )
{
    time_t tmp;
    struct tm *lt;

    /* getenv can be NULL */
    char* ptrTz = getenv( "TZ");
    QString real_TZ = ptrTz ? QString::fromLocal8Bit( getenv("TZ") ) : QString::null;

    if ( !m_tz.isEmpty() )
        setenv( "TZ", m_tz, true );

#if defined(_OS_WIN32) || defined (Q_OS_WIN32) || defined (Q_OS_WIN64)
    _tzset();
#else
    tzset();
#endif

    // get a tm structure from the system to get the correct tz_name
    tmp = time( 0 );
    lt = localtime( &tmp );

    lt->tm_sec = dt.time().second();
    lt->tm_min = dt.time().minute();
    lt->tm_hour = dt.time().hour();
    lt->tm_mday = dt.date().day();
    lt->tm_mon = dt.date().month() - 1; // 0-11 instead of 1-12
    lt->tm_year = dt.date().year() - 1900; // year - 1900
    //lt->tm_wday = dt.date().dayOfWeek(); ignored anyway
    //lt->tm_yday = dt.date().dayOfYear(); ignored anyway
    lt->tm_wday = -1;
    lt->tm_yday = -1;
    // tm_isdst negative -> mktime will find out about DST
    lt->tm_isdst = -1;
    // keep tm_zone and tm_gmtoff
    tmp = mktime( lt );

    if (!m_tz.isEmpty() ) {
        unsetenv("TZ");
        if (!real_TZ.isEmpty() )
            setenv("TZ",  real_TZ, true );
    }
    return tmp;
}
bool Base::isMetaSyncingEnabled()const
{
    return m_metaSyncing;
}
void Base::setMetaSyncingEnabled(bool meta )
{
    m_metaSyncing = meta;
}
KTempFile* Base::file() {
    KTempFile* fi = new KTempFile( locateLocal("tmp",  "opie-konnector"),  "new");
    return fi;
}
QString Base::categoriesToNumber( const QStringList &list, const QString &app )
{
    kdDebug(5226) << "categoriesToNumber " << list.join(";") << endl;
    QString dummy;
    QValueList<OpieCategories>::ConstIterator catIt;
    QValueList<OpieCategories> categories = m_edit->categories();
    bool found = false;
    for ( QStringList::ConstIterator listIt = list.begin(); listIt != list.end(); ++listIt ) {
        found  = false;
        for ( catIt = categories.begin(); catIt != categories.end(); ++catIt ) {
            if ( (*catIt).name() == (*listIt) ) { // the same name
	        kdDebug(5226) << "Found " << (*listIt) << endl;
                found= true;
                dummy.append( (*catIt).id() + ";");
            }
        }
        if ( !found ){
	 kdDebug(5226) << "Not Found category " << (*listIt) << endl;
         dummy.append( QString::number(m_edit->addCategory( app, (*listIt) ) ) + ";" );  // generate a new category
	}
    }
    if ( !dummy.isEmpty() )
        dummy.remove(dummy.length() -1,  1 ); //remove the last ;

    return dummy;
}
QStringList Base::categoriesToNumberList( const QStringList &list, const QString &app )
{
    QStringList dummy;
    QValueList<OpieCategories>::ConstIterator catIt;
    QValueList<OpieCategories> categories = m_edit->categories();
    bool found = false;

    for ( QStringList::ConstIterator listIt = list.begin(); listIt != list.end(); ++listIt ) {
        for ( catIt = categories.begin(); catIt != categories.end(); ++catIt ) {
            if ( (*catIt).name() == (*listIt) ) { // the same name
                found= true;
                dummy <<  (*catIt).id();
            }
        }
        if ( !found ) {
            dummy << QString::number( m_edit->addCategory(app, (*listIt) ) );
        }
    }
    return dummy;
}
QString Base::konnectorId( const QString &appName,  const QString &uid )
{
    QString id;
    QString id2;
    // Konnector-.length() ==  10
    if ( uid.startsWith( "Konnector-" ) ) { // not converted
        id2 =  uid.mid( 10 );
    }else if ( m_helper) {
        id =  m_helper->konnectorId( appName,  uid );
        //                        konnector kde
        if (id.isEmpty() ) { // generate new id
            id2 = QString::number( newId() );
            id = QString::fromLatin1("Konnector-") + id2;
        }else if ( id.startsWith( "Konnector-" ) ) { // not converted
            id2 =  id.mid( 10 );
        }
        m_kde2opie.append( Kontainer( id,     uid ) );
    }
    return id2;
}
QString Base::kdeId( const QString &appName,  const QString &uid )
{
    QString ret;
    if ( m_helper == 0 ) {
        ret = QString::fromLatin1("Konnector-")  + uid;
    }
    else{ // only if meta
        ret = m_helper->kdeId( appName, "Konnector-"+uid,  "Konnector-"+uid);
    }
    return ret;
}
// code copyrighted by tt FIXME
// GPL from Qtopia
int Base::newId()
{
    static QMap<int,  bool> ids;
    int id = -1 * (int) ::time(NULL );
    while ( ids.contains( id ) ){
        id += -1;
        if ( id > 0 )
            id = -1;
    }
    ids.insert( id, true );
    return id;
}
const Device* Base::device() {
    return m_device;
}
QString Base::escape( const QString& string ) {
    return QStyleSheet::escape( string );
}
<commit_msg>Add a IntelliSync(tm) unfsck modus This darn thing assigns 0 to every uid... so we check for that now<commit_after>
#include <qstylesheet.h>

#include <klocale.h>
#include <kstandarddirs.h>
#include <kglobal.h>
#include <kdebug.h>

#include "device.h"
#include "helper.h"

using namespace OpieHelper;

Base::Base( CategoryEdit* edit,
            KSync::KonnectorUIDHelper* helper,
            const QString &tz,
            bool metaSyncing, Device* dev )
{
    m_metaSyncing = metaSyncing;
    m_edit = edit;
    m_helper = helper;
    m_tz = tz;
    m_device = dev;
}
Base::~Base()
{

}
QDateTime Base::fromUTC( time_t time )
{
   struct tm *lt;

   /* getenv can be NULL */
   char* ptrTz = getenv( "TZ");
   QString real_TZ = ptrTz ? QString::fromLocal8Bit( ptrTz ) : QString::null;

   if (!m_tz.isEmpty() )
       setenv( "TZ", m_tz, true );

   kdDebug(5229) << "TimeZone was " << real_TZ << " TimeZone now is " << m_tz << endl;
#if defined(_OS_WIN32) || defined (Q_OS_WIN32) || defined (Q_OS_WIN64)
    _tzset();
#else
    tzset();
#endif
    lt = localtime( &time );
    QDateTime dt;
    dt.setDate( QDate( lt->tm_year + 1900, lt->tm_mon + 1, lt->tm_mday ) );
    dt.setTime( QTime( lt->tm_hour, lt->tm_min, lt->tm_sec ) );

    if (!m_tz.isEmpty() ) {
        unsetenv("TZ");
        if (!real_TZ.isEmpty() )
            setenv("TZ",  real_TZ, true );
    }
    kdDebug(5229) << "DateTime is " << dt.toString() << endl;
    // done
    return dt;
}
time_t Base::toUTC( const QDateTime& dt )
{
    time_t tmp;
    struct tm *lt;

    /* getenv can be NULL */
    char* ptrTz = getenv( "TZ");
    QString real_TZ = ptrTz ? QString::fromLocal8Bit( getenv("TZ") ) : QString::null;

    if ( !m_tz.isEmpty() )
        setenv( "TZ", m_tz, true );

#if defined(_OS_WIN32) || defined (Q_OS_WIN32) || defined (Q_OS_WIN64)
    _tzset();
#else
    tzset();
#endif

    // get a tm structure from the system to get the correct tz_name
    tmp = time( 0 );
    lt = localtime( &tmp );

    lt->tm_sec = dt.time().second();
    lt->tm_min = dt.time().minute();
    lt->tm_hour = dt.time().hour();
    lt->tm_mday = dt.date().day();
    lt->tm_mon = dt.date().month() - 1; // 0-11 instead of 1-12
    lt->tm_year = dt.date().year() - 1900; // year - 1900
    //lt->tm_wday = dt.date().dayOfWeek(); ignored anyway
    //lt->tm_yday = dt.date().dayOfYear(); ignored anyway
    lt->tm_wday = -1;
    lt->tm_yday = -1;
    // tm_isdst negative -> mktime will find out about DST
    lt->tm_isdst = -1;
    // keep tm_zone and tm_gmtoff
    tmp = mktime( lt );

    if (!m_tz.isEmpty() ) {
        unsetenv("TZ");
        if (!real_TZ.isEmpty() )
            setenv("TZ",  real_TZ, true );
    }
    return tmp;
}
bool Base::isMetaSyncingEnabled()const
{
    return m_metaSyncing;
}
void Base::setMetaSyncingEnabled(bool meta )
{
    m_metaSyncing = meta;
}
KTempFile* Base::file() {
    KTempFile* fi = new KTempFile( locateLocal("tmp",  "opie-konnector"),  "new");
    return fi;
}
QString Base::categoriesToNumber( const QStringList &list, const QString &app )
{
    kdDebug(5226) << "categoriesToNumber " << list.join(";") << endl;
    QString dummy;
    QValueList<OpieCategories>::ConstIterator catIt;
    QValueList<OpieCategories> categories = m_edit->categories();
    bool found = false;
    for ( QStringList::ConstIterator listIt = list.begin(); listIt != list.end(); ++listIt ) {
        found  = false;
        for ( catIt = categories.begin(); catIt != categories.end(); ++catIt ) {
            if ( (*catIt).name() == (*listIt) ) { // the same name
	        kdDebug(5226) << "Found " << (*listIt) << endl;
                found= true;
                dummy.append( (*catIt).id() + ";");
            }
        }
        if ( !found ){
	 kdDebug(5226) << "Not Found category " << (*listIt) << endl;
         dummy.append( QString::number(m_edit->addCategory( app, (*listIt) ) ) + ";" );  // generate a new category
	}
    }
    if ( !dummy.isEmpty() )
        dummy.remove(dummy.length() -1,  1 ); //remove the last ;

    return dummy;
}
QStringList Base::categoriesToNumberList( const QStringList &list, const QString &app )
{
    QStringList dummy;
    QValueList<OpieCategories>::ConstIterator catIt;
    QValueList<OpieCategories> categories = m_edit->categories();
    bool found = false;

    for ( QStringList::ConstIterator listIt = list.begin(); listIt != list.end(); ++listIt ) {
        for ( catIt = categories.begin(); catIt != categories.end(); ++catIt ) {
            if ( (*catIt).name() == (*listIt) ) { // the same name
                found= true;
                dummy <<  (*catIt).id();
            }
        }
        if ( !found ) {
            dummy << QString::number( m_edit->addCategory(app, (*listIt) ) );
        }
    }
    return dummy;
}
QString Base::konnectorId( const QString &appName,  const QString &uid )
{
    QString id;
    QString id2;
    // Konnector-.length() ==  10
    if ( uid.startsWith( "Konnector-" ) ) { // not converted
        id2 =  uid.mid( 10 );
    }else if ( m_helper) {
        id =  m_helper->konnectorId( appName,  uid );
        //                        konnector kde
        if (id.isEmpty() ) { // generate new id
            id2 = QString::number( newId() );
            id = QString::fromLatin1("Konnector-") + id2;
        }else if ( id.startsWith( "Konnector-" ) ) { // not converted
            id2 =  id.mid( 10 );
        }
        m_kde2opie.append( Kontainer( id,     uid ) );
    }
    return id2;
}
/*
 * IntelliSync(tm) is completely broken in regards to assigning UID's
 * it's always assigning the 0. So for us to work properly we need to rely
 * on uids!
 * We'll see if it equals '0' and then prolly assign a new uid
 */
QString Base::kdeId( const QString &appName,  const QString &_uid )
{
    QString uid = _uid;
    if (_uid.stripWhiteSpace() == QString::fromLatin1("0") ) {
        kdDebug() << "broken uid found!!! reassigning" << endl;
        uid = QString::number( newId() );
    }

    QString ret;
    if ( !m_helper )
        ret = QString::fromLatin1("Konnector-")  + uid;

    else // only if meta
        ret = m_helper->kdeId( appName, "Konnector-"+uid,  "Konnector-"+uid);

    return ret;
}
// code copyrighted by tt FIXME
// GPL from Qtopia
int Base::newId()
{
    static QMap<int,  bool> ids;
    int id = -1 * (int) ::time(NULL );
    while ( ids.contains( id ) ){
        id += -1;
        if ( id > 0 )
            id = -1;
    }
    ids.insert( id, true );
    return id;
}
const Device* Base::device() {
    return m_device;
}
QString Base::escape( const QString& string ) {
    return QStyleSheet::escape( string );
}
<|endoftext|>


<commit_before><commit_msg>let's have some sensible indentation<commit_after><|endoftext|>


<commit_before>/*
FileName:MultiWindowEventHook.cpp

Author- Michael Evanchik

*/
#include <windows.h>
#include <fstream>
using namespace std;
LRESULT CALLBACK WindowProc(HWND hwnd,UINT uMsg,WPARAM wParam,LPARAM lParam);//Window CallBack Procedure

//Initialized Data to be shared with all instance of the dll
#pragma data_seg("Shared")
HWND hTarget=NULL;
HWND hApp = NULL;
int num=0 ;// Number of the subclassed window handle ,for use in the dll
bool done=FALSE;
HINSTANCE hInstance=NULL;
#pragma data_seg()
// Initialised data End of data share

// Uninitialised Data to be shared with all instance of the dll
#pragma bss_seg("Shared1")
HWND hndll[100];  // array to store handles
int form[100] ;  // Forms which we need to subclass
long OldWndHndl[100] ; //array to store old window handles
BOOL blnsubclassed[100];
HHOOK hWinHook;
long MESSAGE;
long NEW_MESSAGE;
long NEW_MESSAGE_WPARAM;
#pragma bss_seg()

//End Uninitialized data

BOOL WINAPI DllMain(
  HANDLE hinstDLL,  // handle to the DLL module
  DWORD fdwReason,     // reason for calling function
  LPVOID lpvReserved   // reserved
)

{

	switch(fdwReason)
	{

	case DLL_PROCESS_ATTACH:
		{
			hInstance=(HINSTANCE)hinstDLL;
		}
		break;

	case DLL_PROCESS_DETACH:
		{

		//	UnSubClass();
		//	UnhookWindowsHookEx(hWinHook);

		}
		break;

	}

return TRUE;

}

//This function wld get all the handles from the Our application and store in in the array
int WINAPI FillHandleArray(HWND hwndSubclass,int intFrmNUm)
{

	hndll[num]=hwndSubclass; // fill the array with the handle
    form[num]=intFrmNUm;  //fill the corresponding array for the form number
	blnsubclassed[num]=FALSE;// set the state to not subclassed
	num=num+1;
	return 1;
}// End of the fill array function

// Function to set the original window procedure of each subclassed window
int WINAPI UnSubclass()
{
	int count;
	for(count=0;count<num;count++)
	{
		if((int)hndll[count]>1)
		{
			SetWindowLong(hndll[count],GWL_WNDPROC,OldWndHndl[count]);   //Set back the old window procedure
			return 1;
		}
	}
return 0;

}//End UnSubclass function

//The CBT hook Proc(Computer Based Training Hook)
LRESULT CALLBACK CBTProc(int nCode,WPARAM wParam,LPARAM lParam)
{

	if (nCode==HCBT_ACTIVATE)  //Called when the application window is activated
	{

		if((HWND)(wParam)==hTarget)  //check if the window activated is Our Targer App
		{

			int count;
			for (count=0;count<num;count++)
			{
				if (blnsubclassed[count]==FALSE)
				{
					if(((int)hndll[count])>1)
					{
						OldWndHndl[count]=SetWindowLong(hndll[count],GWL_WNDPROC,(long)WindowProc);  //Subclass !!!!
					}

					blnsubclassed[count]=TRUE;	// Set state as subclassed
				}
			}

		}
	}
	if (nCode==HCBT_DESTROYWND) //Called when the application window is destroyed
	{

		if((HWND)wParam==hTarget)
			SendNotifyMessage(hApp,WM_APP +1024,(WPARAM)wParam,(LPARAM)lParam);// Send the message  to the vb app
	}
	return CallNextHookEx(NULL, nCode, wParam, lParam);
}//End of the hook procedure

// Get the handles of the Targetwindow and of the Our application
int WINAPI SetHandle(HWND HandleofTarget ,HWND HandleofApp, long iMessageToTrap, long iMessageToReplace, long iMessageToReplace_wParam)
{

	hTarget=HandleofTarget;
	hApp=HandleofApp;
	MESSAGE=iMessageToTrap;
	NEW_MESSAGE=iMessageToReplace;
	NEW_MESSAGE_WPARAM = iMessageToReplace_wParam;
	FillHandleArray(HandleofTarget,1);
	hWinHook=SetWindowsHookEx(WH_CBT,(HOOKPROC)CBTProc,hInstance,GetWindowThreadProcessId(hTarget,NULL));
//	if(hWinHook==NULL)
//		return 0;
//	else
		return 1;

}//End this function
//Window Procedures of the subclassed windows
LRESULT CALLBACK WindowProc(
  HWND hwnd,
  UINT uMsg,
  WPARAM wParam,
  LPARAM lParam
)
{
	long val;
	int count;
	for(count=0;count<num;count++)
	{
		if(hndll[count]==hwnd)
		{
			val=count;   // this gets us the exact position of this window procedure in the array
		}
	}

	if(uMsg==MESSAGE)
	{
		if(HIWORD(wParam)==0)
		{
			//char h[5];
			//itoa(NEW_MESSAGE_WPARAM,h,10);
			//MessageBox(NULL,h,"df",0);
			//			char hi[5];
			//itoa(NEW_MESSAGE,hi,10);
			//MessageBox(NULL,hi,"df2",0);
			return CallWindowProc((WNDPROC)OldWndHndl[val],hwnd,NEW_MESSAGE,NEW_MESSAGE_WPARAM,lParam);
		}
		else
		{
			return CallWindowProc((WNDPROC)OldWndHndl[val],hwnd,uMsg,wParam,lParam);
		}
	}
	else
	{
		return CallWindowProc((WNDPROC)OldWndHndl[val],hwnd,uMsg,wParam,lParam);
	}
	//long result;
	//if(uMsg==273) //Message Implying Menu Clicks
		//if(HIWORD(wParam)==0)
				//result=SendNotifyMessage(hApp,WM_APP +1024,(WPARAM)(LOWORD(wParam)),(LPARAM)uMsg);// Send the message  to the vb app

}//End Procedure

<commit_msg>Delete MultiWindowEventHook.cpp<commit_after><|endoftext|>