hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
19a85bc07636f9b3bd5953bc165fe69e082cc5de
151,338
cpp
C++
src/postgres/backend/optimizer/plan/createplan.cpp
jessesleeping/my_peloton
a19426cfe34a04692a11008eaffc9c3c9b49abc4
[ "Apache-2.0" ]
6
2017-04-28T00:38:52.000Z
2018-11-06T07:06:49.000Z
src/postgres/backend/optimizer/plan/createplan.cpp
jessesleeping/my_peloton
a19426cfe34a04692a11008eaffc9c3c9b49abc4
[ "Apache-2.0" ]
57
2016-03-19T22:27:55.000Z
2017-07-08T00:41:51.000Z
src/postgres/backend/optimizer/plan/createplan.cpp
eric-haibin-lin/pelotondb
904d6bbd041a0498ee0e034d4f9f9f27086c3cab
[ "Apache-2.0" ]
4
2016-07-17T20:44:56.000Z
2018-06-27T01:01:36.000Z
/*------------------------------------------------------------------------- * * createplan.c * Routines to create the desired plan for processing a query. * Planning is complete, we just need to convert the selected * Path into a Plan. * * Portions Copyright (c) 1996-2015, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * * * IDENTIFICATION * src/backend/optimizer/plan/createplan.c * *------------------------------------------------------------------------- */ #include "postgres.h" #include <limits.h> #include <math.h> #include "access/stratnum.h" #include "access/sysattr.h" #include "catalog/pg_class.h" #include "foreign/fdwapi.h" #include "miscadmin.h" #include "nodes/makefuncs.h" #include "nodes/nodeFuncs.h" #include "optimizer/clauses.h" #include "optimizer/cost.h" #include "optimizer/paths.h" #include "optimizer/placeholder.h" #include "optimizer/plancat.h" #include "optimizer/planmain.h" #include "optimizer/planner.h" #include "optimizer/predtest.h" #include "optimizer/prep.h" #include "optimizer/restrictinfo.h" #include "optimizer/subselect.h" #include "optimizer/tlist.h" #include "optimizer/var.h" #include "parser/parse_clause.h" #include "parser/parsetree.h" #include "utils/lsyscache.h" static Plan *create_plan_recurse(PlannerInfo *root, Path *best_path); static Plan *create_scan_plan(PlannerInfo *root, Path *best_path); static List *build_path_tlist(PlannerInfo *root, Path *path); static bool use_physical_tlist(PlannerInfo *root, RelOptInfo *rel); static void disuse_physical_tlist(PlannerInfo *root, Plan *plan, Path *path); static Plan *create_gating_plan(PlannerInfo *root, Plan *plan, List *quals); static Plan *create_join_plan(PlannerInfo *root, JoinPath *best_path); static Plan *create_append_plan(PlannerInfo *root, AppendPath *best_path); static Plan *create_merge_append_plan(PlannerInfo *root, MergeAppendPath *best_path); static Result *create_result_plan(PlannerInfo *root, ResultPath *best_path); static Material *create_material_plan(PlannerInfo *root, MaterialPath *best_path); static Plan *create_unique_plan(PlannerInfo *root, UniquePath *best_path); static SeqScan *create_seqscan_plan(PlannerInfo *root, Path *best_path, List *tlist, List *scan_clauses); static SampleScan *create_samplescan_plan(PlannerInfo *root, Path *best_path, List *tlist, List *scan_clauses); static Scan *create_indexscan_plan(PlannerInfo *root, IndexPath *best_path, List *tlist, List *scan_clauses, bool indexonly); static BitmapHeapScan *create_bitmap_scan_plan(PlannerInfo *root, BitmapHeapPath *best_path, List *tlist, List *scan_clauses); static Plan *create_bitmap_subplan(PlannerInfo *root, Path *bitmapqual, List **qual, List **indexqual, List **indexECs); static TidScan *create_tidscan_plan(PlannerInfo *root, TidPath *best_path, List *tlist, List *scan_clauses); static SubqueryScan *create_subqueryscan_plan(PlannerInfo *root, Path *best_path, List *tlist, List *scan_clauses); static FunctionScan *create_functionscan_plan(PlannerInfo *root, Path *best_path, List *tlist, List *scan_clauses); static ValuesScan *create_valuesscan_plan(PlannerInfo *root, Path *best_path, List *tlist, List *scan_clauses); static CteScan *create_ctescan_plan(PlannerInfo *root, Path *best_path, List *tlist, List *scan_clauses); static WorkTableScan *create_worktablescan_plan(PlannerInfo *root, Path *best_path, List *tlist, List *scan_clauses); static ForeignScan *create_foreignscan_plan(PlannerInfo *root, ForeignPath *best_path, List *tlist, List *scan_clauses); static CustomScan *create_customscan_plan(PlannerInfo *root, CustomPath *best_path, List *tlist, List *scan_clauses); static NestLoop *create_nestloop_plan(PlannerInfo *root, NestPath *best_path, Plan *outer_plan, Plan *inner_plan); static MergeJoin *create_mergejoin_plan(PlannerInfo *root, MergePath *best_path, Plan *outer_plan, Plan *inner_plan); static HashJoin *create_hashjoin_plan(PlannerInfo *root, HashPath *best_path, Plan *outer_plan, Plan *inner_plan); static Node *replace_nestloop_params(PlannerInfo *root, Node *expr); static Node *replace_nestloop_params_mutator(Node *node, PlannerInfo *root); static void process_subquery_nestloop_params(PlannerInfo *root, List *subplan_params); static List *fix_indexqual_references(PlannerInfo *root, IndexPath *index_path); static List *fix_indexorderby_references(PlannerInfo *root, IndexPath *index_path); static Node *fix_indexqual_operand(Node *node, IndexOptInfo *index, int indexcol); static List *get_switched_clauses(List *clauses, Relids outerrelids); static List *order_qual_clauses(PlannerInfo *root, List *clauses); static void copy_path_costsize(Plan *dest, Path *src); static void copy_plan_costsize(Plan *dest, Plan *src); static SeqScan *make_seqscan(List *qptlist, List *qpqual, Index scanrelid); static SampleScan *make_samplescan(List *qptlist, List *qpqual, Index scanrelid); static IndexScan *make_indexscan(List *qptlist, List *qpqual, Index scanrelid, Oid indexid, List *indexqual, List *indexqualorig, List *indexorderby, List *indexorderbyorig, List *indexorderbyops, ScanDirection indexscandir); static IndexOnlyScan *make_indexonlyscan(List *qptlist, List *qpqual, Index scanrelid, Oid indexid, List *indexqual, List *indexorderby, List *indextlist, ScanDirection indexscandir); static BitmapIndexScan *make_bitmap_indexscan(Index scanrelid, Oid indexid, List *indexqual, List *indexqualorig); static BitmapHeapScan *make_bitmap_heapscan(List *qptlist, List *qpqual, Plan *lefttree, List *bitmapqualorig, Index scanrelid); static TidScan *make_tidscan(List *qptlist, List *qpqual, Index scanrelid, List *tidquals); static FunctionScan *make_functionscan(List *qptlist, List *qpqual, Index scanrelid, List *functions, bool funcordinality); static ValuesScan *make_valuesscan(List *qptlist, List *qpqual, Index scanrelid, List *values_lists); static CteScan *make_ctescan(List *qptlist, List *qpqual, Index scanrelid, int ctePlanId, int cteParam); static WorkTableScan *make_worktablescan(List *qptlist, List *qpqual, Index scanrelid, int wtParam); static BitmapAnd *make_bitmap_and(List *bitmapplans); static BitmapOr *make_bitmap_or(List *bitmapplans); static NestLoop *make_nestloop(List *tlist, List *joinclauses, List *otherclauses, List *nestParams, Plan *lefttree, Plan *righttree, JoinType jointype); static HashJoin *make_hashjoin(List *tlist, List *joinclauses, List *otherclauses, List *hashclauses, Plan *lefttree, Plan *righttree, JoinType jointype); static Hash *make_hash(Plan *lefttree, Oid skewTable, AttrNumber skewColumn, bool skewInherit, Oid skewColType, int32 skewColTypmod); static MergeJoin *make_mergejoin(List *tlist, List *joinclauses, List *otherclauses, List *mergeclauses, Oid *mergefamilies, Oid *mergecollations, int *mergestrategies, bool *mergenullsfirst, Plan *lefttree, Plan *righttree, JoinType jointype); static Sort *make_sort(PlannerInfo *root, Plan *lefttree, int numCols, AttrNumber *sortColIdx, Oid *sortOperators, Oid *collations, bool *nullsFirst, double limit_tuples); static Plan *prepare_sort_from_pathkeys(PlannerInfo *root, Plan *lefttree, List *pathkeys, Relids relids, const AttrNumber *reqColIdx, bool adjust_tlist_in_place, int *p_numsortkeys, AttrNumber **p_sortColIdx, Oid **p_sortOperators, Oid **p_collations, bool **p_nullsFirst); static EquivalenceMember *find_ec_member_for_tle(EquivalenceClass *ec, TargetEntry *tle, Relids relids); static Material *make_material(Plan *lefttree); /* * create_plan * Creates the access plan for a query by recursively processing the * desired tree of pathnodes, starting at the node 'best_path'. For * every pathnode found, we create a corresponding plan node containing * appropriate id, target list, and qualification information. * * The tlists and quals in the plan tree are still in planner format, * ie, Vars still correspond to the parser's numbering. This will be * fixed later by setrefs.c. * * best_path is the best access path * * Returns a Plan tree. */ Plan * create_plan(PlannerInfo *root, Path *best_path) { Plan *plan; /* plan_params should not be in use in current query level */ Assert(root->plan_params == NIL); /* Initialize this module's private___ workspace in PlannerInfo */ root->curOuterRels = NULL; root->curOuterParams = NIL; /* Recursively process the path tree */ plan = create_plan_recurse(root, best_path); /* Check we successfully assigned all NestLoopParams to plan nodes */ if (root->curOuterParams != NIL) elog(ERROR, "failed to assign all NestLoopParams to plan nodes"); /* * Reset plan_params to ensure param IDs used for nestloop params are not * re-used later */ root->plan_params = NIL; return plan; } /* * create_plan_recurse * Recursive guts of create_plan(). */ static Plan * create_plan_recurse(PlannerInfo *root, Path *best_path) { Plan *plan; switch (best_path->pathtype) { case T_SeqScan: case T_SampleScan: case T_IndexScan: case T_IndexOnlyScan: case T_BitmapHeapScan: case T_TidScan: case T_SubqueryScan: case T_FunctionScan: case T_ValuesScan: case T_CteScan: case T_WorkTableScan: case T_ForeignScan: case T_CustomScan: plan = create_scan_plan(root, best_path); break; case T_HashJoin: case T_MergeJoin: case T_NestLoop: plan = create_join_plan(root, (JoinPath *) best_path); break; case T_Append: plan = create_append_plan(root, (AppendPath *) best_path); break; case T_MergeAppend: plan = create_merge_append_plan(root, (MergeAppendPath *) best_path); break; case T_Result: plan = (Plan *) create_result_plan(root, (ResultPath *) best_path); break; case T_Material: plan = (Plan *) create_material_plan(root, (MaterialPath *) best_path); break; case T_Unique: plan = create_unique_plan(root, (UniquePath *) best_path); break; default: elog(ERROR, "unrecognized node type: %d", (int) best_path->pathtype); plan = NULL; /* keep compiler quiet */ break; } return plan; } /* * create_scan_plan * Create a scan plan for the parent relation of 'best_path'. */ static Plan * create_scan_plan(PlannerInfo *root, Path *best_path) { RelOptInfo *rel = best_path->parent; List *tlist; List *scan_clauses; Plan *plan; /* * For table scans, rather than using the relation targetlist (which is * only those Vars actually needed by the query), we prefer to generate a * tlist containing all Vars in order. This will allow the executor to * optimize away projection of the table tuples, if possible. (Note that * planner.c may replace the tlist we generate here, forcing projection to * occur.) */ if (use_physical_tlist(root, rel)) { if (best_path->pathtype == T_IndexOnlyScan) { /* For index-only scan, the preferred tlist is the index's */ tlist = static_cast<List *>(copyObject(((IndexPath *) best_path)->indexinfo->indextlist)); } else { tlist = build_physical_tlist(root, rel); /* if fail because of dropped cols, use regular method */ if (tlist == NIL) tlist = build_path_tlist(root, best_path); } } else { tlist = build_path_tlist(root, best_path); } /* * Extract the relevant restriction clauses from the parent relation. The * executor must apply all these restrictions during the scan, except for * pseudoconstants which we'll take care of below. */ scan_clauses = rel->baserestrictinfo; /* * If this is a parameterized scan, we also need to enforce all the join * clauses available from the outer relation(s). * * For paranoia's sake, don't modify the stored baserestrictinfo list. */ if (best_path->param_info) scan_clauses = list_concat(list_copy(scan_clauses), best_path->param_info->ppi_clauses); switch (best_path->pathtype) { case T_SeqScan: plan = (Plan *) create_seqscan_plan(root, best_path, tlist, scan_clauses); break; case T_SampleScan: plan = (Plan *) create_samplescan_plan(root, best_path, tlist, scan_clauses); break; case T_IndexScan: plan = (Plan *) create_indexscan_plan(root, (IndexPath *) best_path, tlist, scan_clauses, false); break; case T_IndexOnlyScan: plan = (Plan *) create_indexscan_plan(root, (IndexPath *) best_path, tlist, scan_clauses, true); break; case T_BitmapHeapScan: plan = (Plan *) create_bitmap_scan_plan(root, (BitmapHeapPath *) best_path, tlist, scan_clauses); break; case T_TidScan: plan = (Plan *) create_tidscan_plan(root, (TidPath *) best_path, tlist, scan_clauses); break; case T_SubqueryScan: plan = (Plan *) create_subqueryscan_plan(root, best_path, tlist, scan_clauses); break; case T_FunctionScan: plan = (Plan *) create_functionscan_plan(root, best_path, tlist, scan_clauses); break; case T_ValuesScan: plan = (Plan *) create_valuesscan_plan(root, best_path, tlist, scan_clauses); break; case T_CteScan: plan = (Plan *) create_ctescan_plan(root, best_path, tlist, scan_clauses); break; case T_WorkTableScan: plan = (Plan *) create_worktablescan_plan(root, best_path, tlist, scan_clauses); break; case T_ForeignScan: plan = (Plan *) create_foreignscan_plan(root, (ForeignPath *) best_path, tlist, scan_clauses); break; case T_CustomScan: plan = (Plan *) create_customscan_plan(root, (CustomPath *) best_path, tlist, scan_clauses); break; default: elog(ERROR, "unrecognized node type: %d", (int) best_path->pathtype); plan = NULL; /* keep compiler quiet */ break; } /* * If there are any pseudoconstant clauses attached to this node, insert a * gating Result node that evaluates the pseudoconstants as one-time * quals. */ if (root->hasPseudoConstantQuals) plan = create_gating_plan(root, plan, scan_clauses); return plan; } /* * Build a target list (ie, a list of TargetEntry) for the Path's output. */ static List * build_path_tlist(PlannerInfo *root, Path *path) { RelOptInfo *rel = path->parent; List *tlist = NIL; int resno = 1; ListCell *v; foreach(v, rel->reltargetlist) { /* Do we really need to copy here? Not sure */ Node *node = (Node *) copyObject(lfirst(v)); /* * If it's a parameterized path, there might be lateral references in * the tlist, which need to be replaced with Params. There's no need * to remake the TargetEntry nodes, so apply this to each list item * separately. */ if (path->param_info) node = replace_nestloop_params(root, node); tlist = lappend(tlist, makeTargetEntry((Expr *) node, resno, NULL, false)); resno++; } return tlist; } /* * use_physical_tlist * Decide whether to use a tlist matching relation structure, * rather than only those Vars actually referenced. */ static bool use_physical_tlist(PlannerInfo *root, RelOptInfo *rel) { int i; ListCell *lc; /* * We can do this for real relation scans, subquery scans, function scans, * values scans, and CTE scans (but not for, eg, joins). */ if (rel->rtekind != RTE_RELATION && rel->rtekind != RTE_SUBQUERY && rel->rtekind != RTE_FUNCTION && rel->rtekind != RTE_VALUES && rel->rtekind != RTE_CTE) return false; /* * Can't do it with inheritance cases either (mainly because Append * doesn't project). */ if (rel->reloptkind != RELOPT_BASEREL) return false; /* * Can't do it if any system columns or whole-row Vars are requested. * (This could possibly be fixed but would take some fragile assumptions * in setrefs.c, I think.) */ for (i = rel->min_attr; i <= 0; i++) { if (!bms_is_empty(rel->attr_needed[i - rel->min_attr])) return false; } /* * Can't do it if the rel is required to emit any placeholder expressions, * either. */ foreach(lc, root->placeholder_list) { PlaceHolderInfo *phinfo = (PlaceHolderInfo *) lfirst(lc); if (bms_nonempty_difference(phinfo->ph_needed, rel->relids) && bms_is_subset(phinfo->ph_eval_at, rel->relids)) return false; } return true; } /* * disuse_physical_tlist * Switch a plan node back to emitting only Vars actually referenced. * * If the plan node immediately above a scan would prefer to get only * needed Vars and not a physical tlist, it must call this routine to * undo the decision made by use_physical_tlist(). Currently, Hash, Sort, * and Material nodes want this, so they don't have to store useless columns. */ static void disuse_physical_tlist(PlannerInfo *root, Plan *plan, Path *path) { /* Only need to undo it for path types handled by create_scan_plan() */ switch (path->pathtype) { case T_SeqScan: case T_SampleScan: case T_IndexScan: case T_IndexOnlyScan: case T_BitmapHeapScan: case T_TidScan: case T_SubqueryScan: case T_FunctionScan: case T_ValuesScan: case T_CteScan: case T_WorkTableScan: case T_ForeignScan: case T_CustomScan: plan->targetlist = build_path_tlist(root, path); break; default: break; } } /* * create_gating_plan * Deal with pseudoconstant qual clauses * * If the node's quals list includes any pseudoconstant quals, put them * into a gating Result node atop the already-built plan. Otherwise, * return the plan as-is. * * Note that we don't change cost or size estimates when doing gating. * The costs of qual eval were already folded into the plan's startup cost. * Leaving the size alone amounts to assuming that the gating qual will * succeed, which is the conservative estimate for planning upper queries. * We certainly don't want to assume the output size is zero (unless the * gating qual is actually constant FALSE, and that case is dealt with in * clausesel.c). Interpolating between the two cases is silly, because * it doesn't reflect what will really happen at runtime, and besides which * in most cases we have only a very bad idea of the probability of the gating * qual being true. */ static Plan * create_gating_plan(PlannerInfo *root, Plan *plan, List *quals) { List *pseudoconstants; /* Sort into desirable execution order while still in RestrictInfo form */ quals = order_qual_clauses(root, quals); /* Pull out any pseudoconstant quals from the RestrictInfo list */ pseudoconstants = extract_actual_clauses(quals, true); if (!pseudoconstants) return plan; return (Plan *) make_result(root, plan->targetlist, (Node *) pseudoconstants, plan); } /* * create_join_plan * Create a join plan for 'best_path' and (recursively) plans for its * inner and outer paths. */ static Plan * create_join_plan(PlannerInfo *root, JoinPath *best_path) { Plan *outer_plan; Plan *inner_plan; Plan *plan; Relids saveOuterRels = root->curOuterRels; outer_plan = create_plan_recurse(root, best_path->outerjoinpath); /* For a nestloop, include outer relids in curOuterRels for inner side */ if (best_path->path.pathtype == T_NestLoop) root->curOuterRels = bms_union(root->curOuterRels, best_path->outerjoinpath->parent->relids); inner_plan = create_plan_recurse(root, best_path->innerjoinpath); switch (best_path->path.pathtype) { case T_MergeJoin: plan = (Plan *) create_mergejoin_plan(root, (MergePath *) best_path, outer_plan, inner_plan); break; case T_HashJoin: plan = (Plan *) create_hashjoin_plan(root, (HashPath *) best_path, outer_plan, inner_plan); break; case T_NestLoop: /* Restore curOuterRels */ bms_free(root->curOuterRels); root->curOuterRels = saveOuterRels; plan = (Plan *) create_nestloop_plan(root, (NestPath *) best_path, outer_plan, inner_plan); break; default: elog(ERROR, "unrecognized node type: %d", (int) best_path->path.pathtype); plan = NULL; /* keep compiler quiet */ break; } /* * If there are any pseudoconstant clauses attached to this node, insert a * gating Result node that evaluates the pseudoconstants as one-time * quals. */ if (root->hasPseudoConstantQuals) plan = create_gating_plan(root, plan, best_path->joinrestrictinfo); #ifdef NOT_USED /* * * Expensive function pullups may have pulled local predicates * into * this path node. Put them in the qpqual of the plan node. * JMH, * 6/15/92 */ if (get_loc_restrictinfo(best_path) != NIL) set_qpqual((Plan) plan, list_concat(get_qpqual((Plan) plan), get_actual_clauses(get_loc_restrictinfo(best_path)))); #endif return plan; } /* * create_append_plan * Create an Append plan for 'best_path' and (recursively) plans * for its subpaths. * * Returns a Plan node. */ static Plan * create_append_plan(PlannerInfo *root, AppendPath *best_path) { Append *plan; List *tlist = build_path_tlist(root, &best_path->path); List *subplans = NIL; ListCell *subpaths; /* * The subpaths list could be empty, if every child was proven empty by * constraint exclusion. In that case generate a dummy plan that returns * no rows. * * Note that an AppendPath with no members is also generated in certain * cases where there was no appending construct at all, but we know the * relation is empty (see set_dummy_rel_pathlist). */ if (best_path->subpaths == NIL) { /* Generate a Result plan with constant-FALSE gating qual */ return (Plan *) make_result(root, tlist, (Node *) list_make1(makeBoolConst(false, false)), NULL); } /* Build the plan for each child */ foreach(subpaths, best_path->subpaths) { Path *subpath = (Path *) lfirst(subpaths); subplans = lappend(subplans, create_plan_recurse(root, subpath)); } /* * XXX ideally, if there's just one child, we'd not bother to generate an * Append node but just return the single child. At the moment this does * not work because the varno of the child scan plan won't match the * parent-rel Vars it'll be asked to emit. */ plan = make_append(subplans, tlist); return (Plan *) plan; } /* * create_merge_append_plan * Create a MergeAppend plan for 'best_path' and (recursively) plans * for its subpaths. * * Returns a Plan node. */ static Plan * create_merge_append_plan(PlannerInfo *root, MergeAppendPath *best_path) { MergeAppend *node = makeNode(MergeAppend); Plan *plan = &node->plan; List *tlist = build_path_tlist(root, &best_path->path); List *pathkeys = best_path->path.pathkeys; List *subplans = NIL; ListCell *subpaths; /* * We don't have the actual creation of the MergeAppend node split out * into a separate make_xxx function. This is because we want to run * prepare_sort_from_pathkeys on it before we do so on the individual * child plans, to make cross-checking the sort info easier. */ copy_path_costsize(plan, (Path *) best_path); plan->targetlist = tlist; plan->qual = NIL; plan->lefttree = NULL; plan->righttree = NULL; /* Compute sort column info, and adjust MergeAppend's tlist as needed */ (void) prepare_sort_from_pathkeys(root, plan, pathkeys, best_path->path.parent->relids, NULL, true, &node->numCols, &node->sortColIdx, &node->sortOperators, &node->collations, &node->nullsFirst); /* * Now prepare the child plans. We must apply prepare_sort_from_pathkeys * even to subplans that don't need an explicit sort, to make sure they * are returning the same sort key columns the MergeAppend expects. */ foreach(subpaths, best_path->subpaths) { Path *subpath = (Path *) lfirst(subpaths); Plan *subplan; int numsortkeys; AttrNumber *sortColIdx; Oid *sortOperators; Oid *collations; bool *nullsFirst; /* Build the child plan */ subplan = create_plan_recurse(root, subpath); /* Compute sort column info, and adjust subplan's tlist as needed */ subplan = prepare_sort_from_pathkeys(root, subplan, pathkeys, subpath->parent->relids, node->sortColIdx, false, &numsortkeys, &sortColIdx, &sortOperators, &collations, &nullsFirst); /* * Check that we got the same sort key information. We just Assert * that the sortops match, since those depend only on the pathkeys; * but it seems like a good idea to check the sort column numbers * explicitly, to ensure the tlists really do match up. */ Assert(numsortkeys == node->numCols); if (memcmp(sortColIdx, node->sortColIdx, numsortkeys * sizeof(AttrNumber)) != 0) elog(ERROR, "MergeAppend child's targetlist doesn't match MergeAppend"); Assert(memcmp(sortOperators, node->sortOperators, numsortkeys * sizeof(Oid)) == 0); Assert(memcmp(collations, node->collations, numsortkeys * sizeof(Oid)) == 0); Assert(memcmp(nullsFirst, node->nullsFirst, numsortkeys * sizeof(bool)) == 0); /* Now, insert a Sort node if subplan isn't sufficiently ordered */ if (!pathkeys_contained_in(pathkeys, subpath->pathkeys)) subplan = (Plan *) make_sort(root, subplan, numsortkeys, sortColIdx, sortOperators, collations, nullsFirst, best_path->limit_tuples); subplans = lappend(subplans, subplan); } node->mergeplans = subplans; return (Plan *) node; } /* * create_result_plan * Create a Result plan for 'best_path'. * This is only used for the case of a query with an empty jointree. * * Returns a Plan node. */ static Result * create_result_plan(PlannerInfo *root, ResultPath *best_path) { List *tlist; List *quals; /* The tlist will be installed later, since we have no RelOptInfo */ Assert(best_path->path.parent == NULL); tlist = NIL; /* best_path->quals is just bare clauses */ quals = order_qual_clauses(root, best_path->quals); return make_result(root, tlist, (Node *) quals, NULL); } /* * create_material_plan * Create a Material plan for 'best_path' and (recursively) plans * for its subpaths. * * Returns a Plan node. */ static Material * create_material_plan(PlannerInfo *root, MaterialPath *best_path) { Material *plan; Plan *subplan; subplan = create_plan_recurse(root, best_path->subpath); /* We don't want any excess columns in the materialized tuples */ disuse_physical_tlist(root, subplan, best_path->subpath); plan = make_material(subplan); copy_path_costsize(&plan->plan, (Path *) best_path); return plan; } /* * create_unique_plan * Create a Unique plan for 'best_path' and (recursively) plans * for its subpaths. * * Returns a Plan node. */ static Plan * create_unique_plan(PlannerInfo *root, UniquePath *best_path) { Plan *plan; Plan *subplan; List *in_operators; List *uniq_exprs; List *newtlist; int nextresno; bool newitems; int numGroupCols; AttrNumber *groupColIdx; int groupColPos; ListCell *l; subplan = create_plan_recurse(root, best_path->subpath); /* Done if we don't need to do any actual unique-ifying */ if (best_path->umethod == UNIQUE_PATH_NOOP) return subplan; /* * As constructed, the subplan has a "flat" tlist containing just the Vars * needed here and at upper levels. The values we are supposed to * unique-ify may be expressions in these variables. We have to add any * such expressions to the subplan's tlist. * * The subplan may have a "physical" tlist if it is a simple scan plan. If * we're going to sort, this should be reduced to the regular tlist, so * that we don't sort more data than we need to. For hashing, the tlist * should be left as-is if we don't need to add any expressions; but if we * do have to add expressions, then a projection step will be needed at * runtime anyway, so we may as well remove unneeded items. Therefore * newtlist starts from build_path_tlist() not just a copy of the * subplan's tlist; and we don't install it into the subplan unless we are * sorting or stuff has to be added. */ in_operators = best_path->in_operators; uniq_exprs = best_path->uniq_exprs; /* initialize modified subplan tlist as just the "required" vars */ newtlist = build_path_tlist(root, &best_path->path); nextresno = list_length(newtlist) + 1; newitems = false; foreach(l, uniq_exprs) { Node *uniqexpr = static_cast<Node *>(lfirst(l)); TargetEntry *tle; tle = tlist_member(uniqexpr, newtlist); if (!tle) { tle = makeTargetEntry((Expr *) uniqexpr, nextresno, NULL, false); newtlist = lappend(newtlist, tle); nextresno++; newitems = true; } } if (newitems || best_path->umethod == UNIQUE_PATH_SORT) { /* * If the top plan node can't do projections and its existing target * list isn't already what we need, we need to add a Result node to * help it along. */ if (!is_projection_capable_plan(subplan) && !tlist_same_exprs(newtlist, subplan->targetlist)) subplan = (Plan *) make_result(root, newtlist, NULL, subplan); else subplan->targetlist = newtlist; } /* * Build control information showing which subplan output columns are to * be examined by the grouping step. Unfortunately we can't merge this * with the previous loop, since we didn't then know which version of the * subplan tlist we'd end up using. */ newtlist = subplan->targetlist; numGroupCols = list_length(uniq_exprs); groupColIdx = (AttrNumber *) palloc(numGroupCols * sizeof(AttrNumber)); groupColPos = 0; foreach(l, uniq_exprs) { Node *uniqexpr = static_cast<Node *>(lfirst(l)); TargetEntry *tle; tle = tlist_member(uniqexpr, newtlist); if (!tle) /* shouldn't happen */ elog(ERROR, "failed to find unique expression in subplan tlist"); groupColIdx[groupColPos++] = tle->resno; } if (best_path->umethod == UNIQUE_PATH_HASH) { long numGroups; Oid *groupOperators; numGroups = (long) Min(best_path->path.rows, (double) LONG_MAX); /* * Get the hashable equality operators for the Agg node to use. * Normally these are the same as the IN clause operators, but if * those are cross-type operators then the equality operators are the * ones for the IN clause operators' RHS datatype. */ groupOperators = (Oid *) palloc(numGroupCols * sizeof(Oid)); groupColPos = 0; foreach(l, in_operators) { Oid in_oper = lfirst_oid(l); Oid eq_oper; if (!get_compatible_hash_operators(in_oper, NULL, &eq_oper)) elog(ERROR, "could not find compatible hash operator___ for operator___ %u", in_oper); groupOperators[groupColPos++] = eq_oper; } /* * Since the Agg node is going to project anyway, we can give it the * minimum output tlist, without any stuff we might have added to the * subplan tlist. */ plan = (Plan *) make_agg(root, build_path_tlist(root, &best_path->path), NIL, AGG_HASHED, NULL, numGroupCols, groupColIdx, groupOperators, NIL, numGroups, subplan); } else { List *sortList = NIL; /* Create an ORDER BY list to sort the input compatibly */ groupColPos = 0; foreach(l, in_operators) { Oid in_oper = lfirst_oid(l); Oid sortop; Oid eqop; TargetEntry *tle; SortGroupClause *sortcl; sortop = get_ordering_op_for_equality_op(in_oper, false); if (!OidIsValid(sortop)) /* shouldn't happen */ elog(ERROR, "could not find ordering operator___ for equality operator___ %u", in_oper); /* * The Unique node will need equality operators. Normally these * are the same as the IN clause operators, but if those are * cross-type operators then the equality operators are the ones * for the IN clause operators' RHS datatype. */ eqop = get_equality_op_for_ordering_op(sortop, NULL); if (!OidIsValid(eqop)) /* shouldn't happen */ elog(ERROR, "could not find equality operator___ for ordering operator___ %u", sortop); tle = get_tle_by_resno(subplan->targetlist, groupColIdx[groupColPos]); Assert(tle != NULL); sortcl = makeNode(SortGroupClause); sortcl->tleSortGroupRef = assignSortGroupRef(tle, subplan->targetlist); sortcl->eqop = eqop; sortcl->sortop = sortop; sortcl->nulls_first = false; sortcl->hashable = false; /* no need to make this accurate */ sortList = lappend(sortList, sortcl); groupColPos++; } plan = (Plan *) make_sort_from_sortclauses(root, sortList, subplan); plan = (Plan *) make_unique(plan, sortList); } /* Adjust output size estimate (other fields should be OK already) */ plan->plan_rows = best_path->path.rows; return plan; } /***************************************************************************** * * BASE-RELATION SCAN METHODS * *****************************************************************************/ /* * create_seqscan_plan * Returns a seqscan plan for the base relation scanned by 'best_path' * with restriction clauses 'scan_clauses' and targetlist 'tlist'. */ static SeqScan * create_seqscan_plan(PlannerInfo *root, Path *best_path, List *tlist, List *scan_clauses) { SeqScan *scan_plan; Index scan_relid = best_path->parent->relid; /* it should be a base rel... */ Assert(scan_relid > 0); Assert(best_path->parent->rtekind == RTE_RELATION); /* Sort clauses into best execution order */ scan_clauses = order_qual_clauses(root, scan_clauses); /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */ scan_clauses = extract_actual_clauses(scan_clauses, false); /* Replace any outer-relation variables with nestloop params */ if (best_path->param_info) { scan_clauses = (List *) replace_nestloop_params(root, (Node *) scan_clauses); } scan_plan = make_seqscan(tlist, scan_clauses, scan_relid); copy_path_costsize(&scan_plan->plan, best_path); return scan_plan; } /* * create_samplescan_plan * Returns a samplecan plan for the base relation scanned by 'best_path' * with restriction clauses 'scan_clauses' and targetlist 'tlist'. */ static SampleScan * create_samplescan_plan(PlannerInfo *root, Path *best_path, List *tlist, List *scan_clauses) { SampleScan *scan_plan; Index scan_relid = best_path->parent->relid; /* it should be a base rel with tablesample clause... */ Assert(scan_relid > 0); Assert(best_path->parent->rtekind == RTE_RELATION); Assert(best_path->pathtype == T_SampleScan); /* Sort clauses into best execution order */ scan_clauses = order_qual_clauses(root, scan_clauses); /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */ scan_clauses = extract_actual_clauses(scan_clauses, false); /* Replace any outer-relation variables with nestloop params */ if (best_path->param_info) { scan_clauses = (List *) replace_nestloop_params(root, (Node *) scan_clauses); } scan_plan = make_samplescan(tlist, scan_clauses, scan_relid); copy_path_costsize(&scan_plan->plan, best_path); return scan_plan; } /* * create_indexscan_plan * Returns an indexscan plan for the base relation scanned by 'best_path' * with restriction clauses 'scan_clauses' and targetlist 'tlist'. * * We use this for both plain IndexScans and IndexOnlyScans, because the * qual preprocessing work is the same for both. Note that the caller tells * us which to build --- we don't look at best_path->path.pathtype, because * create_bitmap_subplan needs to be able to override the prior decision. */ static Scan * create_indexscan_plan(PlannerInfo *root, IndexPath *best_path, List *tlist, List *scan_clauses, bool indexonly) { Scan *scan_plan; List *indexquals = best_path->indexquals; List *indexorderbys = best_path->indexorderbys; Index baserelid = best_path->path.parent->relid; Oid indexoid = best_path->indexinfo->indexoid; List *qpqual; List *stripped_indexquals; List *fixed_indexquals; List *fixed_indexorderbys; List *indexorderbyops = NIL; ListCell *l; /* it should be a base rel... */ Assert(baserelid > 0); Assert(best_path->path.parent->rtekind == RTE_RELATION); /* * Build "stripped" indexquals structure (no RestrictInfos) to pass to * executor as indexqualorig */ stripped_indexquals = get_actual_clauses(indexquals); /* * The executor needs a copy with the indexkey on the left of each clause * and with index Vars substituted for table ones. */ fixed_indexquals = fix_indexqual_references(root, best_path); /* * Likewise fix up index attr references in the ORDER BY expressions. */ fixed_indexorderbys = fix_indexorderby_references(root, best_path); /* * The qpqual list must contain all restrictions not automatically handled * by the index, other than pseudoconstant clauses which will be handled * by a separate gating plan node. All the predicates in the indexquals * will be checked (either by the index itself, or by nodeIndexscan.c), * but if there are any "special" operators involved then they must be * included in qpqual. The upshot is that qpqual must contain * scan_clauses minus whatever appears in indexquals. * * In normal cases simple pointer equality checks will be enough to spot * duplicate RestrictInfos, so we try that first. * * Another common case is that a scan_clauses entry is generated from the * same EquivalenceClass as some indexqual, and is therefore redundant * with it, though not equal. (This happens when indxpath.c prefers a * different derived equality than what generate_join_implied_equalities * picked for a parameterized scan's ppi_clauses.) * * In some situations (particularly with OR'd index conditions) we may * have scan_clauses that are not equal to, but are logically implied by, * the index quals; so we also try a predicate_implied_by() check to see * if we can discard quals that way. (predicate_implied_by assumes its * first input contains only immutable functions, so we have to check * that.) * * We can also discard quals that are implied by a partial index's * predicate, but only in a plain SELECT; when scanning a target relation * of UPDATE/DELETE/SELECT FOR UPDATE, we must leave such quals in the * plan so that they'll be properly rechecked by EvalPlanQual testing. * * Note: if you change this bit of code you should also look at * extract_nonindex_conditions() in costsize.c. */ qpqual = NIL; foreach(l, scan_clauses) { RestrictInfo *rinfo = (RestrictInfo *) lfirst(l); Assert(IsA(rinfo, RestrictInfo)); if (rinfo->pseudoconstant) continue; /* we may drop pseudoconstants here */ if (list_member_ptr(indexquals, rinfo)) continue; /* simple duplicate */ if (is_redundant_derived_clause(rinfo, indexquals)) continue; /* derived from same EquivalenceClass */ if (!contain_mutable_functions((Node *) rinfo->clause)) { List *clausel = list_make1(rinfo->clause); if (predicate_implied_by(clausel, indexquals)) continue; /* provably implied by indexquals */ if (best_path->indexinfo->indpred) { if (baserelid != root->parse->resultRelation && get_plan_rowmark(root->rowMarks, baserelid) == NULL) if (predicate_implied_by(clausel, best_path->indexinfo->indpred)) continue; /* implied by index predicate */ } } qpqual = lappend(qpqual, rinfo); } /* Sort clauses into best execution order */ qpqual = order_qual_clauses(root, qpqual); /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */ qpqual = extract_actual_clauses(qpqual, false); /* * We have to replace any outer-relation variables with nestloop params in * the indexqualorig, qpqual, and indexorderbyorig expressions. A bit * annoying to have to do this separately from the processing in * fix_indexqual_references --- rethink this when generalizing the inner * indexscan support. But note we can't really do this earlier because * it'd break the comparisons to predicates above ... (or would it? Those * wouldn't have outer refs) */ if (best_path->path.param_info) { stripped_indexquals = (List *) replace_nestloop_params(root, (Node *) stripped_indexquals); qpqual = (List *) replace_nestloop_params(root, (Node *) qpqual); indexorderbys = (List *) replace_nestloop_params(root, (Node *) indexorderbys); } /* * If there are ORDER BY expressions, look up the sort operators for their * result datatypes. */ if (indexorderbys) { ListCell *pathkeyCell, *exprCell; /* * PathKey contains OID of the btree opfamily we're sorting by, but * that's not quite enough because we need the expression's datatype * to look up the sort operator___ in the operator___ family. */ Assert(list_length(best_path->path.pathkeys) == list_length(indexorderbys)); forboth(pathkeyCell, best_path->path.pathkeys, exprCell, indexorderbys) { PathKey *pathkey = (PathKey *) lfirst(pathkeyCell); Node *expr = (Node *) lfirst(exprCell); Oid exprtype = exprType(expr); Oid sortop; /* Get sort operator___ from opfamily */ sortop = get_opfamily_member(pathkey->pk_opfamily, exprtype, exprtype, pathkey->pk_strategy); if (!OidIsValid(sortop)) elog(ERROR, "failed to find sort operator___ for ORDER BY expression"); indexorderbyops = lappend_oid(indexorderbyops, sortop); } } /* Finally ready to build the plan node */ if (indexonly) scan_plan = (Scan *) make_indexonlyscan(tlist, qpqual, baserelid, indexoid, fixed_indexquals, fixed_indexorderbys, best_path->indexinfo->indextlist, best_path->indexscandir); else scan_plan = (Scan *) make_indexscan(tlist, qpqual, baserelid, indexoid, fixed_indexquals, stripped_indexquals, fixed_indexorderbys, indexorderbys, indexorderbyops, best_path->indexscandir); copy_path_costsize(&scan_plan->plan, &best_path->path); return scan_plan; } /* * create_bitmap_scan_plan * Returns a bitmap scan plan for the base relation scanned by 'best_path' * with restriction clauses 'scan_clauses' and targetlist 'tlist'. */ static BitmapHeapScan * create_bitmap_scan_plan(PlannerInfo *root, BitmapHeapPath *best_path, List *tlist, List *scan_clauses) { Index baserelid = best_path->path.parent->relid; Plan *bitmapqualplan; List *bitmapqualorig; List *indexquals; List *indexECs; List *qpqual; ListCell *l; BitmapHeapScan *scan_plan; /* it should be a base rel... */ Assert(baserelid > 0); Assert(best_path->path.parent->rtekind == RTE_RELATION); /* Process the bitmapqual tree into a Plan tree and qual lists */ bitmapqualplan = create_bitmap_subplan(root, best_path->bitmapqual, &bitmapqualorig, &indexquals, &indexECs); /* * The qpqual list must contain all restrictions not automatically handled * by the index, other than pseudoconstant clauses which will be handled * by a separate gating plan node. All the predicates in the indexquals * will be checked (either by the index itself, or by * nodeBitmapHeapscan.c), but if there are any "special" operators * involved then they must be added to qpqual. The upshot is that qpqual * must contain scan_clauses minus whatever appears in indexquals. * * This loop is similar to the comparable code in create_indexscan_plan(), * but with some differences because it has to compare the scan clauses to * stripped (no RestrictInfos) indexquals. See comments there for more * info. * * In normal cases simple equal() checks will be enough to spot duplicate * clauses, so we try that first. We next see if the scan clause is * redundant with any top-level indexqual by virtue of being generated * from the same EC. After that, try predicate_implied_by(). * * Unlike create_indexscan_plan(), we need take no special thought here * for partial index predicates; this is because the predicate conditions * are already listed in bitmapqualorig and indexquals. Bitmap scans have * to do it that way because predicate conditions need to be rechecked if * the scan becomes lossy, so they have to be included in bitmapqualorig. */ qpqual = NIL; foreach(l, scan_clauses) { RestrictInfo *rinfo = (RestrictInfo *) lfirst(l); Node *clause = (Node *) rinfo->clause; Assert(IsA(rinfo, RestrictInfo)); if (rinfo->pseudoconstant) continue; /* we may drop pseudoconstants here */ if (list_member(indexquals, clause)) continue; /* simple duplicate */ if (rinfo->parent_ec && list_member_ptr(indexECs, rinfo->parent_ec)) continue; /* derived from same EquivalenceClass */ if (!contain_mutable_functions(clause)) { List *clausel = list_make1(clause); if (predicate_implied_by(clausel, indexquals)) continue; /* provably implied by indexquals */ } qpqual = lappend(qpqual, rinfo); } /* Sort clauses into best execution order */ qpqual = order_qual_clauses(root, qpqual); /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */ qpqual = extract_actual_clauses(qpqual, false); /* * When dealing with special operators, we will at this point have * duplicate clauses in qpqual and bitmapqualorig. We may as well drop * 'em from bitmapqualorig, since there's no point in making the tests * twice. */ bitmapqualorig = list_difference_ptr(bitmapqualorig, qpqual); /* * We have to replace any outer-relation variables with nestloop params in * the qpqual and bitmapqualorig expressions. (This was already done for * expressions attached to plan nodes in the bitmapqualplan tree.) */ if (best_path->path.param_info) { qpqual = (List *) replace_nestloop_params(root, (Node *) qpqual); bitmapqualorig = (List *) replace_nestloop_params(root, (Node *) bitmapqualorig); } /* Finally ready to build the plan node */ scan_plan = make_bitmap_heapscan(tlist, qpqual, bitmapqualplan, bitmapqualorig, baserelid); copy_path_costsize(&scan_plan->scan.plan, &best_path->path); return scan_plan; } /* * Given a bitmapqual tree, generate the Plan tree that implements it * * As byproducts, we also return in *qual and *indexqual the qual lists * (in implicit-AND form, without RestrictInfos) describing the original index * conditions and the generated indexqual conditions. (These are the same in * simple cases, but when special index operators are involved, the former * list includes the special conditions while the latter includes the actual * indexable conditions derived from them.) Both lists include partial-index * predicates, because we have to recheck predicates as well as index * conditions if the bitmap scan becomes lossy. * * In addition, we return a list of EquivalenceClass pointers for all the * top-level indexquals that were possibly-redundantly derived from ECs. * This allows removal of scan_clauses that are redundant with such quals. * (We do not attempt to detect such redundancies for quals that are within * OR subtrees. This could be done in a less hacky way if we returned the * indexquals in RestrictInfo form, but that would be slower and still pretty * messy, since we'd have to build new___ RestrictInfos in many cases.) */ static Plan * create_bitmap_subplan(PlannerInfo *root, Path *bitmapqual, List **qual, List **indexqual, List **indexECs) { Plan *plan; if (IsA(bitmapqual, BitmapAndPath)) { BitmapAndPath *apath = (BitmapAndPath *) bitmapqual; List *subplans = NIL; List *subquals = NIL; List *subindexquals = NIL; List *subindexECs = NIL; ListCell *l; /* * There may well be redundant quals among the subplans, since a * top-level WHERE qual might have gotten used to form several * different index quals. We don't try exceedingly hard to eliminate * redundancies, but we do eliminate obvious duplicates by using * list_concat_unique. */ foreach(l, apath->bitmapquals) { Plan *subplan; List *subqual; List *subindexqual; List *subindexEC; subplan = create_bitmap_subplan(root, (Path *) lfirst(l), &subqual, &subindexqual, &subindexEC); subplans = lappend(subplans, subplan); subquals = list_concat_unique(subquals, subqual); subindexquals = list_concat_unique(subindexquals, subindexqual); /* Duplicates in indexECs aren't worth getting rid of */ subindexECs = list_concat(subindexECs, subindexEC); } plan = (Plan *) make_bitmap_and(subplans); plan->startup_cost = apath->path.startup_cost; plan->total_cost = apath->path.total_cost; plan->plan_rows = clamp_row_est(apath->bitmapselectivity * apath->path.parent->tuples); plan->plan_width = 0; /* meaningless */ *qual = subquals; *indexqual = subindexquals; *indexECs = subindexECs; } else if (IsA(bitmapqual, BitmapOrPath)) { BitmapOrPath *opath = (BitmapOrPath *) bitmapqual; List *subplans = NIL; List *subquals = NIL; List *subindexquals = NIL; bool const_true_subqual = false; bool const_true_subindexqual = false; ListCell *l; /* * Here, we only detect qual-free subplans. A qual-free subplan would * cause us to generate "... OR true ..." which we may as well reduce * to just "true". We do not try to eliminate redundant subclauses * because (a) it's not as likely as in the AND case, and (b) we might * well be working with hundreds or even thousands of OR conditions, * perhaps from a long IN list. The performance of list_append_unique * would be unacceptable. */ foreach(l, opath->bitmapquals) { Plan *subplan; List *subqual; List *subindexqual; List *subindexEC; subplan = create_bitmap_subplan(root, (Path *) lfirst(l), &subqual, &subindexqual, &subindexEC); subplans = lappend(subplans, subplan); if (subqual == NIL) const_true_subqual = true; else if (!const_true_subqual) subquals = lappend(subquals, make_ands_explicit(subqual)); if (subindexqual == NIL) const_true_subindexqual = true; else if (!const_true_subindexqual) subindexquals = lappend(subindexquals, make_ands_explicit(subindexqual)); } /* * In the presence of ScalarArrayOpExpr quals, we might have built * BitmapOrPaths with just one subpath; don't add an OR step. */ if (list_length(subplans) == 1) { plan = (Plan *) linitial(subplans); } else { plan = (Plan *) make_bitmap_or(subplans); plan->startup_cost = opath->path.startup_cost; plan->total_cost = opath->path.total_cost; plan->plan_rows = clamp_row_est(opath->bitmapselectivity * opath->path.parent->tuples); plan->plan_width = 0; /* meaningless */ } /* * If there were constant-TRUE subquals, the OR reduces to constant * TRUE. Also, avoid generating one-element ORs, which could happen * due to redundancy elimination or ScalarArrayOpExpr quals. */ if (const_true_subqual) *qual = NIL; else if (list_length(subquals) <= 1) *qual = subquals; else *qual = list_make1(make_orclause(subquals)); if (const_true_subindexqual) *indexqual = NIL; else if (list_length(subindexquals) <= 1) *indexqual = subindexquals; else *indexqual = list_make1(make_orclause(subindexquals)); *indexECs = NIL; } else if (IsA(bitmapqual, IndexPath)) { IndexPath *ipath = (IndexPath *) bitmapqual; IndexScan *iscan; List *subindexECs; ListCell *l; /* Use the regular indexscan plan build machinery... */ iscan = (IndexScan *) create_indexscan_plan(root, ipath, NIL, NIL, false); Assert(IsA(iscan, IndexScan)); /* then convert to a bitmap indexscan */ plan = (Plan *) make_bitmap_indexscan(iscan->scan.scanrelid, iscan->indexid, iscan->indexqual, iscan->indexqualorig); plan->startup_cost = 0.0; plan->total_cost = ipath->indextotalcost; plan->plan_rows = clamp_row_est(ipath->indexselectivity * ipath->path.parent->tuples); plan->plan_width = 0; /* meaningless */ *qual = get_actual_clauses(ipath->indexclauses); *indexqual = get_actual_clauses(ipath->indexquals); foreach(l, ipath->indexinfo->indpred) { Expr *pred = (Expr *) lfirst(l); /* * We know that the index predicate must have been implied by the * query condition as a whole, but it may or may not be implied by * the conditions that got pushed into the bitmapqual. Avoid * generating redundant conditions. */ if (!predicate_implied_by(list_make1(pred), ipath->indexclauses)) { *qual = lappend(*qual, pred); *indexqual = lappend(*indexqual, pred); } } subindexECs = NIL; foreach(l, ipath->indexquals) { RestrictInfo *rinfo = (RestrictInfo *) lfirst(l); if (rinfo->parent_ec) subindexECs = lappend(subindexECs, rinfo->parent_ec); } *indexECs = subindexECs; } else { elog(ERROR, "unrecognized node type: %d", nodeTag(bitmapqual)); plan = NULL; /* keep compiler quiet */ } return plan; } /* * create_tidscan_plan * Returns a tidscan plan for the base relation scanned by 'best_path' * with restriction clauses 'scan_clauses' and targetlist 'tlist'. */ static TidScan * create_tidscan_plan(PlannerInfo *root, TidPath *best_path, List *tlist, List *scan_clauses) { TidScan *scan_plan; Index scan_relid = best_path->path.parent->relid; List *tidquals = best_path->tidquals; List *ortidquals; /* it should be a base rel... */ Assert(scan_relid > 0); Assert(best_path->path.parent->rtekind == RTE_RELATION); /* Sort clauses into best execution order */ scan_clauses = order_qual_clauses(root, scan_clauses); /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */ scan_clauses = extract_actual_clauses(scan_clauses, false); /* Replace any outer-relation variables with nestloop params */ if (best_path->path.param_info) { tidquals = (List *) replace_nestloop_params(root, (Node *) tidquals); scan_clauses = (List *) replace_nestloop_params(root, (Node *) scan_clauses); } /* * Remove any clauses that are TID quals. This is a bit tricky since the * tidquals list has implicit OR semantics. */ ortidquals = tidquals; if (list_length(ortidquals) > 1) ortidquals = list_make1(make_orclause(ortidquals)); scan_clauses = list_difference(scan_clauses, ortidquals); scan_plan = make_tidscan(tlist, scan_clauses, scan_relid, tidquals); copy_path_costsize(&scan_plan->scan.plan, &best_path->path); return scan_plan; } /* * create_subqueryscan_plan * Returns a subqueryscan plan for the base relation scanned by 'best_path' * with restriction clauses 'scan_clauses' and targetlist 'tlist'. */ static SubqueryScan * create_subqueryscan_plan(PlannerInfo *root, Path *best_path, List *tlist, List *scan_clauses) { SubqueryScan *scan_plan; Index scan_relid = best_path->parent->relid; /* it should be a subquery base rel... */ Assert(scan_relid > 0); Assert(best_path->parent->rtekind == RTE_SUBQUERY); /* Sort clauses into best execution order */ scan_clauses = order_qual_clauses(root, scan_clauses); /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */ scan_clauses = extract_actual_clauses(scan_clauses, false); /* Replace any outer-relation variables with nestloop params */ if (best_path->param_info) { scan_clauses = (List *) replace_nestloop_params(root, (Node *) scan_clauses); process_subquery_nestloop_params(root, best_path->parent->subplan_params); } scan_plan = make_subqueryscan(tlist, scan_clauses, scan_relid, best_path->parent->subplan); copy_path_costsize(&scan_plan->scan.plan, best_path); return scan_plan; } /* * create_functionscan_plan * Returns a functionscan plan for the base relation scanned by 'best_path' * with restriction clauses 'scan_clauses' and targetlist 'tlist'. */ static FunctionScan * create_functionscan_plan(PlannerInfo *root, Path *best_path, List *tlist, List *scan_clauses) { FunctionScan *scan_plan; Index scan_relid = best_path->parent->relid; RangeTblEntry *rte; List *functions; /* it should be a function base rel... */ Assert(scan_relid > 0); rte = planner_rt_fetch(scan_relid, root); Assert(rte->rtekind == RTE_FUNCTION); functions = rte->functions; /* Sort clauses into best execution order */ scan_clauses = order_qual_clauses(root, scan_clauses); /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */ scan_clauses = extract_actual_clauses(scan_clauses, false); /* Replace any outer-relation variables with nestloop params */ if (best_path->param_info) { scan_clauses = (List *) replace_nestloop_params(root, (Node *) scan_clauses); /* The function expressions could contain nestloop params, too */ functions = (List *) replace_nestloop_params(root, (Node *) functions); } scan_plan = make_functionscan(tlist, scan_clauses, scan_relid, functions, rte->funcordinality); copy_path_costsize(&scan_plan->scan.plan, best_path); return scan_plan; } /* * create_valuesscan_plan * Returns a valuesscan plan for the base relation scanned by 'best_path' * with restriction clauses 'scan_clauses' and targetlist 'tlist'. */ static ValuesScan * create_valuesscan_plan(PlannerInfo *root, Path *best_path, List *tlist, List *scan_clauses) { ValuesScan *scan_plan; Index scan_relid = best_path->parent->relid; RangeTblEntry *rte; List *values_lists; /* it should be a values base rel... */ Assert(scan_relid > 0); rte = planner_rt_fetch(scan_relid, root); Assert(rte->rtekind == RTE_VALUES); values_lists = rte->values_lists; /* Sort clauses into best execution order */ scan_clauses = order_qual_clauses(root, scan_clauses); /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */ scan_clauses = extract_actual_clauses(scan_clauses, false); /* Replace any outer-relation variables with nestloop params */ if (best_path->param_info) { scan_clauses = (List *) replace_nestloop_params(root, (Node *) scan_clauses); /* The values lists could contain nestloop params, too */ values_lists = (List *) replace_nestloop_params(root, (Node *) values_lists); } scan_plan = make_valuesscan(tlist, scan_clauses, scan_relid, values_lists); copy_path_costsize(&scan_plan->scan.plan, best_path); return scan_plan; } /* * create_ctescan_plan * Returns a ctescan plan for the base relation scanned by 'best_path' * with restriction clauses 'scan_clauses' and targetlist 'tlist'. */ static CteScan * create_ctescan_plan(PlannerInfo *root, Path *best_path, List *tlist, List *scan_clauses) { CteScan *scan_plan; Index scan_relid = best_path->parent->relid; RangeTblEntry *rte; SubPlan *ctesplan = NULL; int plan_id; int cte_param_id; PlannerInfo *cteroot; Index levelsup; int ndx; ListCell *lc; Assert(scan_relid > 0); rte = planner_rt_fetch(scan_relid, root); Assert(rte->rtekind == RTE_CTE); Assert(!rte->self_reference); /* * Find the referenced CTE, and locate the SubPlan previously made for it. */ levelsup = rte->ctelevelsup; cteroot = root; while (levelsup-- > 0) { cteroot = cteroot->parent_root; if (!cteroot) /* shouldn't happen */ elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename); } /* * Note: cte_plan_ids can be shorter than cteList, if we are still working * on planning the CTEs (ie, this is a side-reference from another CTE). * So we mustn't use forboth here. */ ndx = 0; foreach(lc, cteroot->parse->cteList) { CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc); if (strcmp(cte->ctename, rte->ctename) == 0) break; ndx++; } if (lc == NULL) /* shouldn't happen */ elog(ERROR, "could not find CTE \"%s\"", rte->ctename); if (ndx >= list_length(cteroot->cte_plan_ids)) elog(ERROR, "could not find plan for CTE \"%s\"", rte->ctename); plan_id = list_nth_int(cteroot->cte_plan_ids, ndx); Assert(plan_id > 0); foreach(lc, cteroot->init_plans) { ctesplan = (SubPlan *) lfirst(lc); if (ctesplan->plan_id == plan_id) break; } if (lc == NULL) /* shouldn't happen */ elog(ERROR, "could not find plan for CTE \"%s\"", rte->ctename); /* * We need the CTE param ID, which is the sole member of the SubPlan's * setParam list. */ cte_param_id = linitial_int(ctesplan->setParam); /* Sort clauses into best execution order */ scan_clauses = order_qual_clauses(root, scan_clauses); /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */ scan_clauses = extract_actual_clauses(scan_clauses, false); /* Replace any outer-relation variables with nestloop params */ if (best_path->param_info) { scan_clauses = (List *) replace_nestloop_params(root, (Node *) scan_clauses); } scan_plan = make_ctescan(tlist, scan_clauses, scan_relid, plan_id, cte_param_id); copy_path_costsize(&scan_plan->scan.plan, best_path); return scan_plan; } /* * create_worktablescan_plan * Returns a worktablescan plan for the base relation scanned by 'best_path' * with restriction clauses 'scan_clauses' and targetlist 'tlist'. */ static WorkTableScan * create_worktablescan_plan(PlannerInfo *root, Path *best_path, List *tlist, List *scan_clauses) { WorkTableScan *scan_plan; Index scan_relid = best_path->parent->relid; RangeTblEntry *rte; Index levelsup; PlannerInfo *cteroot; Assert(scan_relid > 0); rte = planner_rt_fetch(scan_relid, root); Assert(rte->rtekind == RTE_CTE); Assert(rte->self_reference); /* * We need to find the worktable param ID, which is in the plan level * that's processing the recursive UNION, which is one level *below* where * the CTE comes from. */ levelsup = rte->ctelevelsup; if (levelsup == 0) /* shouldn't happen */ elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename); levelsup--; cteroot = root; while (levelsup-- > 0) { cteroot = cteroot->parent_root; if (!cteroot) /* shouldn't happen */ elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename); } if (cteroot->wt_param_id < 0) /* shouldn't happen */ elog(ERROR, "could not find param ID for CTE \"%s\"", rte->ctename); /* Sort clauses into best execution order */ scan_clauses = order_qual_clauses(root, scan_clauses); /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */ scan_clauses = extract_actual_clauses(scan_clauses, false); /* Replace any outer-relation variables with nestloop params */ if (best_path->param_info) { scan_clauses = (List *) replace_nestloop_params(root, (Node *) scan_clauses); } scan_plan = make_worktablescan(tlist, scan_clauses, scan_relid, cteroot->wt_param_id); copy_path_costsize(&scan_plan->scan.plan, best_path); return scan_plan; } /* * create_foreignscan_plan * Returns a foreignscan plan for the relation scanned by 'best_path' * with restriction clauses 'scan_clauses' and targetlist 'tlist'. */ static ForeignScan * create_foreignscan_plan(PlannerInfo *root, ForeignPath *best_path, List *tlist, List *scan_clauses) { ForeignScan *scan_plan; RelOptInfo *rel = best_path->path.parent; Index scan_relid = rel->relid; Oid rel_oid = InvalidOid; Bitmapset *attrs_used = NULL; ListCell *lc; int i; Assert(rel->fdwroutine != NULL); /* * If we're scanning a base relation, fetch its OID. (Irrelevant if * scanning a join relation.) */ if (scan_relid > 0) { RangeTblEntry *rte; Assert(rel->rtekind == RTE_RELATION); rte = planner_rt_fetch(scan_relid, root); Assert(rte->rtekind == RTE_RELATION); rel_oid = rte->relid; } /* * Sort clauses into best execution order. We do this first since the FDW * might have more info than we do and wish to adjust the ordering. */ scan_clauses = order_qual_clauses(root, scan_clauses); /* * Let the FDW perform its processing on the restriction clauses and * generate the plan node. Note that the FDW might remove restriction * clauses that it intends to execute remotely, or even add more (if it * has selected some join clauses for remote use but also wants them * rechecked locally). */ scan_plan = rel->fdwroutine->GetForeignPlan(root, rel, rel_oid, best_path, tlist, scan_clauses); /* Copy cost data from Path to Plan; no need to make FDW do this */ copy_path_costsize(&scan_plan->scan.plan, &best_path->path); /* Copy foreign server OID; likewise, no need to make FDW do this */ scan_plan->fs_server = rel->serverid; /* Likewise, copy the relids that are represented by this foreign scan */ scan_plan->fs_relids = best_path->path.parent->relids; /* * Replace any outer-relation variables with nestloop params in the qual * and fdw_exprs expressions. We do this last so that the FDW doesn't * have to be involved. (Note that parts of fdw_exprs could have come * from join clauses, so doing this beforehand on the scan_clauses * wouldn't work.) We assume fdw_scan_tlist contains no such variables. */ if (best_path->path.param_info) { scan_plan->scan.plan.qual = (List *) replace_nestloop_params(root, (Node *) scan_plan->scan.plan.qual); scan_plan->fdw_exprs = (List *) replace_nestloop_params(root, (Node *) scan_plan->fdw_exprs); } /* * Detect whether any system columns are requested from rel. This is a * bit of a kluge and might go away someday, so we intentionally leave it * out of the API presented to FDWs. * * First, examine all the attributes needed for joins or final output. * Note: we must look at reltargetlist, not the attr_needed data, because * attr_needed isn't computed for inheritance child rels. */ pull_varattnos((Node *) rel->reltargetlist, rel->relid, &attrs_used); /* Add all the attributes used by restriction clauses. */ foreach(lc, rel->baserestrictinfo) { RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc); pull_varattnos((Node *) rinfo->clause, rel->relid, &attrs_used); } /* Now, are any system columns requested from rel? */ scan_plan->fsSystemCol = false; for (i = FirstLowInvalidHeapAttributeNumber + 1; i < 0; i++) { if (bms_is_member(i - FirstLowInvalidHeapAttributeNumber, attrs_used)) { scan_plan->fsSystemCol = true; break; } } bms_free(attrs_used); return scan_plan; } /* * create_custom_plan * * Transform a CustomPath into a Plan. */ static CustomScan * create_customscan_plan(PlannerInfo *root, CustomPath *best_path, List *tlist, List *scan_clauses) { CustomScan *cplan; RelOptInfo *rel = best_path->path.parent; /* * Sort clauses into the best execution order, although custom-scan * provider can reorder them again. */ scan_clauses = order_qual_clauses(root, scan_clauses); /* * Invoke custom plan provider to create the Plan node represented by the * CustomPath. */ cplan = (CustomScan *) best_path->methods->PlanCustomPath(root, rel, best_path, tlist, scan_clauses); Assert(IsA(cplan, CustomScan)); /* * Copy cost data from Path to Plan; no need to make custom-plan providers * do this */ copy_path_costsize(&cplan->scan.plan, &best_path->path); /* Likewise, copy the relids that are represented by this custom scan */ cplan->custom_relids = best_path->path.parent->relids; /* * Replace any outer-relation variables with nestloop params in the qual * and custom_exprs expressions. We do this last so that the custom-plan * provider doesn't have to be involved. (Note that parts of custom_exprs * could have come from join clauses, so doing this beforehand on the * scan_clauses wouldn't work.) We assume custom_scan_tlist contains no * such variables. */ if (best_path->path.param_info) { cplan->scan.plan.qual = (List *) replace_nestloop_params(root, (Node *) cplan->scan.plan.qual); cplan->custom_exprs = (List *) replace_nestloop_params(root, (Node *) cplan->custom_exprs); } return cplan; } /***************************************************************************** * * JOIN METHODS * *****************************************************************************/ static NestLoop * create_nestloop_plan(PlannerInfo *root, NestPath *best_path, Plan *outer_plan, Plan *inner_plan) { NestLoop *join_plan; List *tlist = build_path_tlist(root, &best_path->path); List *joinrestrictclauses = best_path->joinrestrictinfo; List *joinclauses; List *otherclauses; Relids outerrelids; List *nestParams; ListCell *cell; ListCell *prev; ListCell *next; /* Sort join qual clauses into best execution order */ joinrestrictclauses = order_qual_clauses(root, joinrestrictclauses); /* Get the join qual clauses (in plain expression form) */ /* Any pseudoconstant clauses are ignored here */ if (IS_OUTER_JOIN(best_path->jointype)) { extract_actual_join_clauses(joinrestrictclauses, &joinclauses, &otherclauses); } else { /* We can treat all clauses alike for an inner join */ joinclauses = extract_actual_clauses(joinrestrictclauses, false); otherclauses = NIL; } /* Replace any outer-relation variables with nestloop params */ if (best_path->path.param_info) { joinclauses = (List *) replace_nestloop_params(root, (Node *) joinclauses); otherclauses = (List *) replace_nestloop_params(root, (Node *) otherclauses); } /* * Identify any nestloop parameters that should be supplied by this join * node, and move them from root->curOuterParams to the nestParams list. */ outerrelids = best_path->outerjoinpath->parent->relids; nestParams = NIL; prev = NULL; for (cell = list_head(root->curOuterParams); cell; cell = next) { NestLoopParam *nlp = (NestLoopParam *) lfirst(cell); next = lnext(cell); if (IsA(nlp->paramval, Var) && bms_is_member(nlp->paramval->varno, outerrelids)) { root->curOuterParams = list_delete_cell(root->curOuterParams, cell, prev); nestParams = lappend(nestParams, nlp); } else if (IsA(nlp->paramval, PlaceHolderVar) && bms_overlap(((PlaceHolderVar *) nlp->paramval)->phrels, outerrelids) && bms_is_subset(find_placeholder_info(root, (PlaceHolderVar *) nlp->paramval, false)->ph_eval_at, outerrelids)) { root->curOuterParams = list_delete_cell(root->curOuterParams, cell, prev); nestParams = lappend(nestParams, nlp); } else prev = cell; } join_plan = make_nestloop(tlist, joinclauses, otherclauses, nestParams, outer_plan, inner_plan, best_path->jointype); copy_path_costsize(&join_plan->join.plan, &best_path->path); return join_plan; } static MergeJoin * create_mergejoin_plan(PlannerInfo *root, MergePath *best_path, Plan *outer_plan, Plan *inner_plan) { List *tlist = build_path_tlist(root, &best_path->jpath.path); List *joinclauses; List *otherclauses; List *mergeclauses; List *outerpathkeys; List *innerpathkeys; int nClauses; Oid *mergefamilies; Oid *mergecollations; int *mergestrategies; bool *mergenullsfirst; MergeJoin *join_plan; int i; ListCell *lc; ListCell *lop; ListCell *lip; /* Sort join qual clauses into best execution order */ /* NB: do NOT reorder the mergeclauses */ joinclauses = order_qual_clauses(root, best_path->jpath.joinrestrictinfo); /* Get the join qual clauses (in plain expression form) */ /* Any pseudoconstant clauses are ignored here */ if (IS_OUTER_JOIN(best_path->jpath.jointype)) { extract_actual_join_clauses(joinclauses, &joinclauses, &otherclauses); } else { /* We can treat all clauses alike for an inner join */ joinclauses = extract_actual_clauses(joinclauses, false); otherclauses = NIL; } /* * Remove the mergeclauses from the list of join qual clauses, leaving the * list of quals that must be checked as qpquals. */ mergeclauses = get_actual_clauses(best_path->path_mergeclauses); joinclauses = list_difference(joinclauses, mergeclauses); /* * Replace any outer-relation variables with nestloop params. There * should not be any in the mergeclauses. */ if (best_path->jpath.path.param_info) { joinclauses = (List *) replace_nestloop_params(root, (Node *) joinclauses); otherclauses = (List *) replace_nestloop_params(root, (Node *) otherclauses); } /* * Rearrange mergeclauses, if needed, so that the outer variable is always * on the left; mark the mergeclause restrictinfos with correct * outer_is_left status. */ mergeclauses = get_switched_clauses(best_path->path_mergeclauses, best_path->jpath.outerjoinpath->parent->relids); /* * Create explicit sort nodes for the outer and inner paths if necessary. * Make sure there are no excess columns in the inputs if sorting. */ if (best_path->outersortkeys) { disuse_physical_tlist(root, outer_plan, best_path->jpath.outerjoinpath); outer_plan = (Plan *) make_sort_from_pathkeys(root, outer_plan, best_path->outersortkeys, -1.0); outerpathkeys = best_path->outersortkeys; } else outerpathkeys = best_path->jpath.outerjoinpath->pathkeys; if (best_path->innersortkeys) { disuse_physical_tlist(root, inner_plan, best_path->jpath.innerjoinpath); inner_plan = (Plan *) make_sort_from_pathkeys(root, inner_plan, best_path->innersortkeys, -1.0); innerpathkeys = best_path->innersortkeys; } else innerpathkeys = best_path->jpath.innerjoinpath->pathkeys; /* * If specified, add a materialize node to shield the inner plan from the * need to handle mark/restore. */ if (best_path->materialize_inner) { Plan *matplan = (Plan *) make_material(inner_plan); /* * We assume the materialize will not spill to disk, and therefore * charge just cpu_operator_cost per tuple. (Keep this estimate in * sync with final_cost_mergejoin.) */ copy_plan_costsize(matplan, inner_plan); matplan->total_cost += cpu_operator_cost * matplan->plan_rows; inner_plan = matplan; } /* * Compute the opfamily/collation/strategy/nullsfirst arrays needed by the * executor. The information is in the pathkeys for the two inputs, but * we need to be careful about the possibility of mergeclauses sharing a * pathkey (compare find_mergeclauses_for_pathkeys()). */ nClauses = list_length(mergeclauses); Assert(nClauses == list_length(best_path->path_mergeclauses)); mergefamilies = (Oid *) palloc(nClauses * sizeof(Oid)); mergecollations = (Oid *) palloc(nClauses * sizeof(Oid)); mergestrategies = (int *) palloc(nClauses * sizeof(int)); mergenullsfirst = (bool *) palloc(nClauses * sizeof(bool)); lop = list_head(outerpathkeys); lip = list_head(innerpathkeys); i = 0; foreach(lc, best_path->path_mergeclauses) { RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc); EquivalenceClass *oeclass; EquivalenceClass *ieclass; PathKey *opathkey; PathKey *ipathkey; EquivalenceClass *opeclass; EquivalenceClass *ipeclass; ListCell *l2; /* fetch outer/inner eclass from mergeclause */ Assert(IsA(rinfo, RestrictInfo)); if (rinfo->outer_is_left) { oeclass = rinfo->left_ec; ieclass = rinfo->right_ec; } else { oeclass = rinfo->right_ec; ieclass = rinfo->left_ec; } Assert(oeclass != NULL); Assert(ieclass != NULL); /* * For debugging purposes, we check that the eclasses match the paths' * pathkeys. In typical cases the merge clauses are one-to-one with * the pathkeys, but when dealing with partially redundant query * conditions, we might have clauses that re-reference earlier path * keys. The case that we need to reject is where a pathkey is * entirely skipped over. * * lop and lip reference the first as-yet-unused pathkey elements; * it's okay to match them, or any element before them. If they're * NULL then we have found all pathkey elements to be used. */ if (lop) { opathkey = (PathKey *) lfirst(lop); opeclass = opathkey->pk_eclass; if (oeclass == opeclass) { /* fast path for typical case */ lop = lnext(lop); } else { /* redundant clauses ... must match something before lop */ foreach(l2, outerpathkeys) { if (l2 == lop) break; opathkey = (PathKey *) lfirst(l2); opeclass = opathkey->pk_eclass; if (oeclass == opeclass) break; } if (oeclass != opeclass) elog(ERROR, "outer pathkeys do not match mergeclauses"); } } else { /* redundant clauses ... must match some already-used pathkey */ opathkey = NULL; opeclass = NULL; foreach(l2, outerpathkeys) { opathkey = (PathKey *) lfirst(l2); opeclass = opathkey->pk_eclass; if (oeclass == opeclass) break; } if (l2 == NULL) elog(ERROR, "outer pathkeys do not match mergeclauses"); } if (lip) { ipathkey = (PathKey *) lfirst(lip); ipeclass = ipathkey->pk_eclass; if (ieclass == ipeclass) { /* fast path for typical case */ lip = lnext(lip); } else { /* redundant clauses ... must match something before lip */ foreach(l2, innerpathkeys) { if (l2 == lip) break; ipathkey = (PathKey *) lfirst(l2); ipeclass = ipathkey->pk_eclass; if (ieclass == ipeclass) break; } if (ieclass != ipeclass) elog(ERROR, "inner pathkeys do not match mergeclauses"); } } else { /* redundant clauses ... must match some already-used pathkey */ ipathkey = NULL; ipeclass = NULL; foreach(l2, innerpathkeys) { ipathkey = (PathKey *) lfirst(l2); ipeclass = ipathkey->pk_eclass; if (ieclass == ipeclass) break; } if (l2 == NULL) elog(ERROR, "inner pathkeys do not match mergeclauses"); } /* pathkeys should match each other too (more debugging) */ if (opathkey->pk_opfamily != ipathkey->pk_opfamily || opathkey->pk_eclass->ec_collation != ipathkey->pk_eclass->ec_collation || opathkey->pk_strategy != ipathkey->pk_strategy || opathkey->pk_nulls_first != ipathkey->pk_nulls_first) elog(ERROR, "left and right pathkeys do not match in mergejoin"); /* OK, save info for executor */ mergefamilies[i] = opathkey->pk_opfamily; mergecollations[i] = opathkey->pk_eclass->ec_collation; mergestrategies[i] = opathkey->pk_strategy; mergenullsfirst[i] = opathkey->pk_nulls_first; i++; } /* * Note: it is not an error if we have additional pathkey elements (i.e., * lop or lip isn't NULL here). The input paths might be better-sorted * than we need for the current mergejoin. */ /* * Now we can build the mergejoin node. */ join_plan = make_mergejoin(tlist, joinclauses, otherclauses, mergeclauses, mergefamilies, mergecollations, mergestrategies, mergenullsfirst, outer_plan, inner_plan, best_path->jpath.jointype); /* Costs of sort and material steps are included in path cost already */ copy_path_costsize(&join_plan->join.plan, &best_path->jpath.path); return join_plan; } static HashJoin * create_hashjoin_plan(PlannerInfo *root, HashPath *best_path, Plan *outer_plan, Plan *inner_plan) { List *tlist = build_path_tlist(root, &best_path->jpath.path); List *joinclauses; List *otherclauses; List *hashclauses; Oid skewTable = InvalidOid; AttrNumber skewColumn = InvalidAttrNumber; bool skewInherit = false; Oid skewColType = InvalidOid; int32 skewColTypmod = -1; HashJoin *join_plan; Hash *hash_plan; /* Sort join qual clauses into best execution order */ joinclauses = order_qual_clauses(root, best_path->jpath.joinrestrictinfo); /* There's no point in sorting the hash clauses ... */ /* Get the join qual clauses (in plain expression form) */ /* Any pseudoconstant clauses are ignored here */ if (IS_OUTER_JOIN(best_path->jpath.jointype)) { extract_actual_join_clauses(joinclauses, &joinclauses, &otherclauses); } else { /* We can treat all clauses alike for an inner join */ joinclauses = extract_actual_clauses(joinclauses, false); otherclauses = NIL; } /* * Remove the hashclauses from the list of join qual clauses, leaving the * list of quals that must be checked as qpquals. */ hashclauses = get_actual_clauses(best_path->path_hashclauses); joinclauses = list_difference(joinclauses, hashclauses); /* * Replace any outer-relation variables with nestloop params. There * should not be any in the hashclauses. */ if (best_path->jpath.path.param_info) { joinclauses = (List *) replace_nestloop_params(root, (Node *) joinclauses); otherclauses = (List *) replace_nestloop_params(root, (Node *) otherclauses); } /* * Rearrange hashclauses, if needed, so that the outer variable is always * on the left. */ hashclauses = get_switched_clauses(best_path->path_hashclauses, best_path->jpath.outerjoinpath->parent->relids); /* We don't want any excess columns in the hashed tuples */ disuse_physical_tlist(root, inner_plan, best_path->jpath.innerjoinpath); /* If we expect batching, suppress excess columns in outer tuples too */ if (best_path->num_batches > 1) disuse_physical_tlist(root, outer_plan, best_path->jpath.outerjoinpath); /* * If there is a single join clause and we can identify the outer variable * as a simple column reference, supply its identity for possible use in * skew optimization. (Note: in principle we could do skew optimization * with multiple join clauses, but we'd have to be able to determine the * most common combinations of outer values, which we don't currently have * enough stats for.) */ if (list_length(hashclauses) == 1) { OpExpr *clause = (OpExpr *) linitial(hashclauses); Node *node; Assert(is_opclause(clause)); node = (Node *) linitial(clause->args); if (IsA(node, RelabelType)) node = (Node *) ((RelabelType *) node)->arg; if (IsA(node, Var)) { Var *var = (Var *) node; RangeTblEntry *rte; rte = root->simple_rte_array[var->varno]; if (rte->rtekind == RTE_RELATION) { skewTable = rte->relid; skewColumn = var->varattno; skewInherit = rte->inh; skewColType = var->vartype; skewColTypmod = var->vartypmod; } } } /* * Build the hash node and hash join node. */ hash_plan = make_hash(inner_plan, skewTable, skewColumn, skewInherit, skewColType, skewColTypmod); join_plan = make_hashjoin(tlist, joinclauses, otherclauses, hashclauses, outer_plan, (Plan *) hash_plan, best_path->jpath.jointype); copy_path_costsize(&join_plan->join.plan, &best_path->jpath.path); return join_plan; } /***************************************************************************** * * SUPPORTING ROUTINES * *****************************************************************************/ /* * replace_nestloop_params * Replace outer-relation Vars and PlaceHolderVars in the given expression * with nestloop Params * * All Vars and PlaceHolderVars belonging to the relation(s) identified by * root->curOuterRels are replaced by Params, and entries are added to * root->curOuterParams if not already present. */ static Node * replace_nestloop_params(PlannerInfo *root, Node *expr) { /* No setup needed for tree walk, so away we go */ return replace_nestloop_params_mutator(expr, root); } static Node * replace_nestloop_params_mutator(Node *node, PlannerInfo *root) { if (node == NULL) return NULL; if (IsA(node, Var)) { Var *var = (Var *) node; Param *param; NestLoopParam *nlp; ListCell *lc; /* Upper-level Vars should be long gone at this point */ Assert(var->varlevelsup == 0); /* If not to be replaced, we can just return the Var unmodified */ if (!bms_is_member(var->varno, root->curOuterRels)) return node; /* Create a Param representing the Var */ param = assign_nestloop_param_var(root, var); /* Is this param already listed in root->curOuterParams? */ foreach(lc, root->curOuterParams) { nlp = (NestLoopParam *) lfirst(lc); if (nlp->paramno == param->paramid) { Assert(equal(var, nlp->paramval)); /* Present, so we can just return the Param */ return (Node *) param; } } /* No, so add it */ nlp = makeNode(NestLoopParam); nlp->paramno = param->paramid; nlp->paramval = var; root->curOuterParams = lappend(root->curOuterParams, nlp); /* And return the replacement Param */ return (Node *) param; } if (IsA(node, PlaceHolderVar)) { PlaceHolderVar *phv = (PlaceHolderVar *) node; Param *param; NestLoopParam *nlp; ListCell *lc; /* Upper-level PlaceHolderVars should be long gone at this point */ Assert(phv->phlevelsup == 0); /* * Check whether we need to replace the PHV. We use bms_overlap as a * cheap/quick test to see if the PHV might be evaluated in the outer * rels, and then grab its PlaceHolderInfo to tell for sure. */ if (!bms_overlap(phv->phrels, root->curOuterRels) || !bms_is_subset(find_placeholder_info(root, phv, false)->ph_eval_at, root->curOuterRels)) { /* * We can't replace the whole PHV, but we might still need to * replace Vars or PHVs within its expression, in case it ends up * actually getting evaluated here. (It might get evaluated in * this plan node, or some child node; in the latter case we don't * really need to process the expression here, but we haven't got * enough info to tell if that's the case.) Flat-copy the PHV * node and then recurse on its expression. * * Note that after doing this, we might have different * representations of the contents of the same PHV in different * parts of the plan tree. This is OK because equal() will just * match on phid/phlevelsup, so setrefs.c will still recognize an * upper-level reference to a lower-level copy of the same PHV. */ PlaceHolderVar *newphv = makeNode(PlaceHolderVar); memcpy(newphv, phv, sizeof(PlaceHolderVar)); newphv->phexpr = (Expr *) replace_nestloop_params_mutator((Node *) phv->phexpr, root); return (Node *) newphv; } /* Create a Param representing the PlaceHolderVar */ param = assign_nestloop_param_placeholdervar(root, phv); /* Is this param already listed in root->curOuterParams? */ foreach(lc, root->curOuterParams) { nlp = (NestLoopParam *) lfirst(lc); if (nlp->paramno == param->paramid) { Assert(equal(phv, nlp->paramval)); /* Present, so we can just return the Param */ return (Node *) param; } } /* No, so add it */ nlp = makeNode(NestLoopParam); nlp->paramno = param->paramid; nlp->paramval = (Var *) phv; root->curOuterParams = lappend(root->curOuterParams, nlp); /* And return the replacement Param */ return (Node *) param; } return expression_tree_mutator(node, reinterpret_cast<expression_tree_mutator_fptr>(replace_nestloop_params_mutator), (void *) root); } /* * process_subquery_nestloop_params * Handle params of a parameterized subquery that need to be fed * from an outer nestloop. * * Currently, that would be *all* params that a subquery in FROM has demanded * from the current query level, since they must be LATERAL references. * * The subplan's references to the outer variables are already represented * as PARAM_EXEC Params, so we need not modify the subplan here. What we * do need to do is add entries to root->curOuterParams to signal the parent * nestloop plan node that it must provide these values. */ static void process_subquery_nestloop_params(PlannerInfo *root, List *subplan_params) { ListCell *ppl; foreach(ppl, subplan_params) { PlannerParamItem *pitem = (PlannerParamItem *) lfirst(ppl); if (IsA(pitem->item, Var)) { Var *var = (Var *) pitem->item; NestLoopParam *nlp; ListCell *lc; /* If not from a nestloop outer rel, complain */ if (!bms_is_member(var->varno, root->curOuterRels)) elog(ERROR, "non-LATERAL parameter required by subquery"); /* Is this param already listed in root->curOuterParams? */ foreach(lc, root->curOuterParams) { nlp = (NestLoopParam *) lfirst(lc); if (nlp->paramno == pitem->paramId) { Assert(equal(var, nlp->paramval)); /* Present, so nothing to do */ break; } } if (lc == NULL) { /* No, so add it */ nlp = makeNode(NestLoopParam); nlp->paramno = pitem->paramId; nlp->paramval = static_cast<Var *>(copyObject(var)); root->curOuterParams = lappend(root->curOuterParams, nlp); } } else if (IsA(pitem->item, PlaceHolderVar)) { PlaceHolderVar *phv = (PlaceHolderVar *) pitem->item; NestLoopParam *nlp; ListCell *lc; /* If not from a nestloop outer rel, complain */ if (!bms_is_subset(find_placeholder_info(root, phv, false)->ph_eval_at, root->curOuterRels)) elog(ERROR, "non-LATERAL parameter required by subquery"); /* Is this param already listed in root->curOuterParams? */ foreach(lc, root->curOuterParams) { nlp = (NestLoopParam *) lfirst(lc); if (nlp->paramno == pitem->paramId) { Assert(equal(phv, nlp->paramval)); /* Present, so nothing to do */ break; } } if (lc == NULL) { /* No, so add it */ nlp = makeNode(NestLoopParam); nlp->paramno = pitem->paramId; nlp->paramval = static_cast<Var *>(copyObject(phv)); root->curOuterParams = lappend(root->curOuterParams, nlp); } } else elog(ERROR, "unexpected type of subquery parameter"); } } /* * fix_indexqual_references * Adjust indexqual clauses to the form the executor's indexqual * machinery needs. * * We have four tasks here: * * Remove RestrictInfo nodes from the input clauses. * * Replace any outer-relation Var or PHV nodes with nestloop Params. * (XXX eventually, that responsibility should go elsewhere?) * * Index keys must be represented by Var nodes with varattno set to the * index's attribute number, not the attribute number in the original rel. * * If the index key is on the right, commute the clause to put it on the * left. * * The result is a modified copy of the path's indexquals list --- the * original is not changed. Note also that the copy shares no substructure * with the original; this is needed in case there is a subplan in it (we need * two separate copies of the subplan tree, or things will go awry). */ static List * fix_indexqual_references(PlannerInfo *root, IndexPath *index_path) { IndexOptInfo *index = index_path->indexinfo; List *fixed_indexquals; ListCell *lcc, *lci; fixed_indexquals = NIL; forboth(lcc, index_path->indexquals, lci, index_path->indexqualcols) { RestrictInfo *rinfo = (RestrictInfo *) lfirst(lcc); int indexcol = lfirst_int(lci); Node *clause; Assert(IsA(rinfo, RestrictInfo)); /* * Replace any outer-relation variables with nestloop params. * * This also makes a copy of the clause, so it's safe to modify it * in-place below. */ clause = replace_nestloop_params(root, (Node *) rinfo->clause); if (IsA(clause, OpExpr)) { OpExpr *op = (OpExpr *) clause; if (list_length(op->args) != 2) elog(ERROR, "indexqual clause is not binary opclause"); /* * Check to see if the indexkey is on the right; if so, commute * the clause. The indexkey should be the side that refers to * (only) the base relation. */ if (!bms_equal(rinfo->left_relids, index->rel->relids)) CommuteOpExpr(op); /* * Now replace the indexkey expression with an index Var. */ linitial(op->args) = fix_indexqual_operand(static_cast<Node *>(linitial(op->args)), index, indexcol); } else if (IsA(clause, RowCompareExpr)) { RowCompareExpr *rc = (RowCompareExpr *) clause; Expr *newrc; List *indexcolnos; bool var_on_left; ListCell *lca, *lcai; /* * Re-discover which index columns are used in the rowcompare. */ newrc = adjust_rowcompare_for_index(rc, index, indexcol, &indexcolnos, &var_on_left); /* * Trouble if adjust_rowcompare_for_index thought the * RowCompareExpr didn't match the index as-is; the clause should * have gone through that routine already. */ if (newrc != (Expr *) rc) elog(ERROR, "inconsistent results from adjust_rowcompare_for_index"); /* * Check to see if the indexkey is on the right; if so, commute * the clause. */ if (!var_on_left) CommuteRowCompareExpr(rc); /* * Now replace the indexkey expressions with index Vars. */ Assert(list_length(rc->largs) == list_length(indexcolnos)); forboth(lca, rc->largs, lcai, indexcolnos) { lfirst(lca) = fix_indexqual_operand(static_cast<Node *>(lfirst(lca)), index, lfirst_int(lcai)); } } else if (IsA(clause, ScalarArrayOpExpr)) { ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause; /* Never need to commute... */ /* Replace the indexkey expression with an index Var. */ linitial(saop->args) = fix_indexqual_operand(static_cast<Node *>(linitial(saop->args)), index, indexcol); } else if (IsA(clause, NullTest)) { NullTest *nt = (NullTest *) clause; /* Replace the indexkey expression with an index Var. */ nt->arg = (Expr *) fix_indexqual_operand((Node *) nt->arg, index, indexcol); } else elog(ERROR, "unsupported indexqual type: %d", (int) nodeTag(clause)); fixed_indexquals = lappend(fixed_indexquals, clause); } return fixed_indexquals; } /* * fix_indexorderby_references * Adjust indexorderby clauses to the form the executor's index * machinery needs. * * This is a simplified version of fix_indexqual_references. The input does * not have RestrictInfo nodes, and we assume that indxpath.c already * commuted the clauses to put the index keys on the left. Also, we don't * bother to support any cases except simple OpExprs, since nothing else * is allowed for ordering operators. */ static List * fix_indexorderby_references(PlannerInfo *root, IndexPath *index_path) { IndexOptInfo *index = index_path->indexinfo; List *fixed_indexorderbys; ListCell *lcc, *lci; fixed_indexorderbys = NIL; forboth(lcc, index_path->indexorderbys, lci, index_path->indexorderbycols) { Node *clause = (Node *) lfirst(lcc); int indexcol = lfirst_int(lci); /* * Replace any outer-relation variables with nestloop params. * * This also makes a copy of the clause, so it's safe to modify it * in-place below. */ clause = replace_nestloop_params(root, clause); if (IsA(clause, OpExpr)) { OpExpr *op = (OpExpr *) clause; if (list_length(op->args) != 2) elog(ERROR, "indexorderby clause is not binary opclause"); /* * Now replace the indexkey expression with an index Var. */ linitial(op->args) = fix_indexqual_operand(static_cast<Node *>(linitial(op->args)), index, indexcol); } else elog(ERROR, "unsupported indexorderby type: %d", (int) nodeTag(clause)); fixed_indexorderbys = lappend(fixed_indexorderbys, clause); } return fixed_indexorderbys; } /* * fix_indexqual_operand * Convert an indexqual expression to a Var referencing the index column. * * We represent index keys by Var nodes having varno == INDEX_VAR and varattno * equal to the index's attribute number (index column position). * * Most of the code here is just for sanity cross-checking that the given * expression actually matches the index column it's claimed to. */ static Node * fix_indexqual_operand(Node *node, IndexOptInfo *index, int indexcol) { Var *result; int pos; ListCell *indexpr_item; /* * Remove any binary-compatible relabeling of the indexkey */ if (IsA(node, RelabelType)) node = (Node *) ((RelabelType *) node)->arg; Assert(indexcol >= 0 && indexcol < index->ncolumns); if (index->indexkeys[indexcol] != 0) { /* It's a simple index column */ if (IsA(node, Var) && ((Var *) node)->varno == index->rel->relid && ((Var *) node)->varattno == index->indexkeys[indexcol]) { result = (Var *) copyObject(node); result->varno = INDEX_VAR; result->varattno = indexcol + 1; return (Node *) result; } else elog(ERROR, "index key does not match expected index column"); } /* It's an index expression, so find and cross-check the expression */ indexpr_item = list_head(index->indexprs); for (pos = 0; pos < index->ncolumns; pos++) { if (index->indexkeys[pos] == 0) { if (indexpr_item == NULL) elog(ERROR, "too few entries in indexprs list"); if (pos == indexcol) { Node *indexkey; indexkey = (Node *) lfirst(indexpr_item); if (indexkey && IsA(indexkey, RelabelType)) indexkey = (Node *) ((RelabelType *) indexkey)->arg; if (equal(node, indexkey)) { result = makeVar(INDEX_VAR, indexcol + 1, exprType(static_cast<const Node *>(lfirst(indexpr_item))), -1, exprCollation(static_cast<const Node *>(lfirst(indexpr_item))), 0); return (Node *) result; } else elog(ERROR, "index key does not match expected index column"); } indexpr_item = lnext(indexpr_item); } } /* Ooops... */ elog(ERROR, "index key does not match expected index column"); return NULL; /* keep compiler quiet */ } /* * get_switched_clauses * Given a list of merge or hash joinclauses (as RestrictInfo nodes), * extract the bare clauses, and rearrange the elements within the * clauses, if needed, so the outer join variable is on the left and * the inner is on the right. The original clause data structure is not * touched; a modified list is returned. We do, however, set the transient * outer_is_left field in each RestrictInfo to show which side was which. */ static List * get_switched_clauses(List *clauses, Relids outerrelids) { List *t_list = NIL; ListCell *l; foreach(l, clauses) { RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(l); OpExpr *clause = (OpExpr *) restrictinfo->clause; Assert(is_opclause(clause)); if (bms_is_subset(restrictinfo->right_relids, outerrelids)) { /* * Duplicate just enough of the structure to allow commuting the * clause without changing the original list. Could use * copyObject, but a complete deep copy is overkill. */ OpExpr *temp = makeNode(OpExpr); temp->opno = clause->opno; temp->opfuncid = InvalidOid; temp->opresulttype = clause->opresulttype; temp->opretset = clause->opretset; temp->opcollid = clause->opcollid; temp->inputcollid = clause->inputcollid; temp->args = list_copy(clause->args); temp->location = clause->location; /* Commute it --- note this modifies the temp node in-place. */ CommuteOpExpr(temp); t_list = lappend(t_list, temp); restrictinfo->outer_is_left = false; } else { Assert(bms_is_subset(restrictinfo->left_relids, outerrelids)); t_list = lappend(t_list, clause); restrictinfo->outer_is_left = true; } } return t_list; } /* * order_qual_clauses * Given a list of qual clauses that will all be evaluated at the same * plan node, sort the list into the order we want to check the quals * in at runtime. * * Ideally the order should be driven by a combination of execution cost and * selectivity, but it's not immediately clear how to account for both, * and given the uncertainty of the estimates the reliability of the decisions * would be doubtful anyway. So we just order by estimated per-tuple cost, * being careful not to change the order when (as is often the case) the * estimates are identical. * * Although this will work on either bare clauses or RestrictInfos, it's * much faster to apply it to RestrictInfos, since it can re-use cost * information that is cached in RestrictInfos. * * Note: some callers pass lists that contain entries that will later be * removed; this is the easiest way to let this routine see RestrictInfos * instead of bare clauses. It's OK because we only sort by cost, but * a cost/selectivity combination would likely do the wrong thing. */ static List * order_qual_clauses(PlannerInfo *root, List *clauses) { typedef struct { Node *clause; Cost cost; } QualItem; int nitems = list_length(clauses); QualItem *items; ListCell *lc; int i; List *result; /* No need to work hard for 0 or 1 clause */ if (nitems <= 1) return clauses; /* * Collect the items and costs into an array. This is to avoid repeated * cost_qual_eval work if the inputs aren't RestrictInfos. */ items = (QualItem *) palloc(nitems * sizeof(QualItem)); i = 0; foreach(lc, clauses) { Node *clause = (Node *) lfirst(lc); QualCost qcost; cost_qual_eval_node(&qcost, clause, root); items[i].clause = clause; items[i].cost = qcost.per_tuple; i++; } /* * Sort. We don't use qsort() because it's not guaranteed stable for * equal keys. The expected number of entries is small enough that a * simple insertion sort should be good enough. */ for (i = 1; i < nitems; i++) { QualItem newitem = items[i]; int j; /* insert newitem into the already-sorted subarray */ for (j = i; j > 0; j--) { if (newitem.cost >= items[j - 1].cost) break; items[j] = items[j - 1]; } items[j] = newitem; } /* Convert back to a list */ result = NIL; for (i = 0; i < nitems; i++) result = lappend(result, items[i].clause); return result; } /* * Copy cost and size info from a Path node to the Plan node created from it. * The executor usually won't use this info, but it's needed by EXPLAIN. */ static void copy_path_costsize(Plan *dest, Path *src) { if (src) { dest->startup_cost = src->startup_cost; dest->total_cost = src->total_cost; dest->plan_rows = src->rows; dest->plan_width = src->parent->width; } else { dest->startup_cost = 0; dest->total_cost = 0; dest->plan_rows = 0; dest->plan_width = 0; } } /* * Copy cost and size info from a lower plan node to an inserted node. * (Most callers alter the info after copying it.) */ static void copy_plan_costsize(Plan *dest, Plan *src) { if (src) { dest->startup_cost = src->startup_cost; dest->total_cost = src->total_cost; dest->plan_rows = src->plan_rows; dest->plan_width = src->plan_width; } else { dest->startup_cost = 0; dest->total_cost = 0; dest->plan_rows = 0; dest->plan_width = 0; } } /***************************************************************************** * * PLAN NODE BUILDING ROUTINES * * Some of these are exported because they are called to build plan nodes * in contexts where we're not deriving the plan node from a path node. * *****************************************************************************/ static SeqScan * make_seqscan(List *qptlist, List *qpqual, Index scanrelid) { SeqScan *node = makeNode(SeqScan); Plan *plan = &node->plan; /* cost should be inserted by caller */ plan->targetlist = qptlist; plan->qual = qpqual; plan->lefttree = NULL; plan->righttree = NULL; node->scanrelid = scanrelid; return node; } static SampleScan * make_samplescan(List *qptlist, List *qpqual, Index scanrelid) { SampleScan *node = makeNode(SampleScan); Plan *plan = &node->plan; /* cost should be inserted by caller */ plan->targetlist = qptlist; plan->qual = qpqual; plan->lefttree = NULL; plan->righttree = NULL; node->scanrelid = scanrelid; return node; } static IndexScan * make_indexscan(List *qptlist, List *qpqual, Index scanrelid, Oid indexid, List *indexqual, List *indexqualorig, List *indexorderby, List *indexorderbyorig, List *indexorderbyops, ScanDirection indexscandir) { IndexScan *node = makeNode(IndexScan); Plan *plan = &node->scan.plan; /* cost should be inserted by caller */ plan->targetlist = qptlist; plan->qual = qpqual; plan->lefttree = NULL; plan->righttree = NULL; node->scan.scanrelid = scanrelid; node->indexid = indexid; node->indexqual = indexqual; node->indexqualorig = indexqualorig; node->indexorderby = indexorderby; node->indexorderbyorig = indexorderbyorig; node->indexorderbyops = indexorderbyops; node->indexorderdir = indexscandir; return node; } static IndexOnlyScan * make_indexonlyscan(List *qptlist, List *qpqual, Index scanrelid, Oid indexid, List *indexqual, List *indexorderby, List *indextlist, ScanDirection indexscandir) { IndexOnlyScan *node = makeNode(IndexOnlyScan); Plan *plan = &node->scan.plan; /* cost should be inserted by caller */ plan->targetlist = qptlist; plan->qual = qpqual; plan->lefttree = NULL; plan->righttree = NULL; node->scan.scanrelid = scanrelid; node->indexid = indexid; node->indexqual = indexqual; node->indexorderby = indexorderby; node->indextlist = indextlist; node->indexorderdir = indexscandir; return node; } static BitmapIndexScan * make_bitmap_indexscan(Index scanrelid, Oid indexid, List *indexqual, List *indexqualorig) { BitmapIndexScan *node = makeNode(BitmapIndexScan); Plan *plan = &node->scan.plan; /* cost should be inserted by caller */ plan->targetlist = NIL; /* not used */ plan->qual = NIL; /* not used */ plan->lefttree = NULL; plan->righttree = NULL; node->scan.scanrelid = scanrelid; node->indexid = indexid; node->indexqual = indexqual; node->indexqualorig = indexqualorig; return node; } static BitmapHeapScan * make_bitmap_heapscan(List *qptlist, List *qpqual, Plan *lefttree, List *bitmapqualorig, Index scanrelid) { BitmapHeapScan *node = makeNode(BitmapHeapScan); Plan *plan = &node->scan.plan; /* cost should be inserted by caller */ plan->targetlist = qptlist; plan->qual = qpqual; plan->lefttree = lefttree; plan->righttree = NULL; node->scan.scanrelid = scanrelid; node->bitmapqualorig = bitmapqualorig; return node; } static TidScan * make_tidscan(List *qptlist, List *qpqual, Index scanrelid, List *tidquals) { TidScan *node = makeNode(TidScan); Plan *plan = &node->scan.plan; /* cost should be inserted by caller */ plan->targetlist = qptlist; plan->qual = qpqual; plan->lefttree = NULL; plan->righttree = NULL; node->scan.scanrelid = scanrelid; node->tidquals = tidquals; return node; } SubqueryScan * make_subqueryscan(List *qptlist, List *qpqual, Index scanrelid, Plan *subplan) { SubqueryScan *node = makeNode(SubqueryScan); Plan *plan = &node->scan.plan; /* * Cost is figured here for the convenience of prepunion.c. Note this is * only correct for the case where qpqual is empty; otherwise caller * should overwrite cost with a better estimate. */ copy_plan_costsize(plan, subplan); plan->total_cost += cpu_tuple_cost * subplan->plan_rows; plan->targetlist = qptlist; plan->qual = qpqual; plan->lefttree = NULL; plan->righttree = NULL; node->scan.scanrelid = scanrelid; node->subplan = subplan; return node; } static FunctionScan * make_functionscan(List *qptlist, List *qpqual, Index scanrelid, List *functions, bool funcordinality) { FunctionScan *node = makeNode(FunctionScan); Plan *plan = &node->scan.plan; /* cost should be inserted by caller */ plan->targetlist = qptlist; plan->qual = qpqual; plan->lefttree = NULL; plan->righttree = NULL; node->scan.scanrelid = scanrelid; node->functions = functions; node->funcordinality = funcordinality; return node; } static ValuesScan * make_valuesscan(List *qptlist, List *qpqual, Index scanrelid, List *values_lists) { ValuesScan *node = makeNode(ValuesScan); Plan *plan = &node->scan.plan; /* cost should be inserted by caller */ plan->targetlist = qptlist; plan->qual = qpqual; plan->lefttree = NULL; plan->righttree = NULL; node->scan.scanrelid = scanrelid; node->values_lists = values_lists; return node; } static CteScan * make_ctescan(List *qptlist, List *qpqual, Index scanrelid, int ctePlanId, int cteParam) { CteScan *node = makeNode(CteScan); Plan *plan = &node->scan.plan; /* cost should be inserted by caller */ plan->targetlist = qptlist; plan->qual = qpqual; plan->lefttree = NULL; plan->righttree = NULL; node->scan.scanrelid = scanrelid; node->ctePlanId = ctePlanId; node->cteParam = cteParam; return node; } static WorkTableScan * make_worktablescan(List *qptlist, List *qpqual, Index scanrelid, int wtParam) { WorkTableScan *node = makeNode(WorkTableScan); Plan *plan = &node->scan.plan; /* cost should be inserted by caller */ plan->targetlist = qptlist; plan->qual = qpqual; plan->lefttree = NULL; plan->righttree = NULL; node->scan.scanrelid = scanrelid; node->wtParam = wtParam; return node; } ForeignScan * make_foreignscan(List *qptlist, List *qpqual, Index scanrelid, List *fdw_exprs, List *fdw_private, List *fdw_scan_tlist) { ForeignScan *node = makeNode(ForeignScan); Plan *plan = &node->scan.plan; /* cost will be filled in by create_foreignscan_plan */ plan->targetlist = qptlist; plan->qual = qpqual; plan->lefttree = NULL; plan->righttree = NULL; node->scan.scanrelid = scanrelid; /* fs_server will be filled in by create_foreignscan_plan */ node->fs_server = InvalidOid; node->fdw_exprs = fdw_exprs; node->fdw_private = fdw_private; node->fdw_scan_tlist = fdw_scan_tlist; /* fs_relids will be filled in by create_foreignscan_plan */ node->fs_relids = NULL; /* fsSystemCol will be filled in by create_foreignscan_plan */ node->fsSystemCol = false; return node; } Append * make_append(List *appendplans, List *tlist) { Append *node = makeNode(Append); Plan *plan = &node->plan; double total_size; ListCell *subnode; /* * Compute cost as sum of subplan costs. We charge nothing extra for the * Append itself, which perhaps is too optimistic, but since it doesn't do * any selection or projection, it is a pretty cheap node. * * If you change this, see also create_append_path(). Also, the size * calculations should match set_append_rel_pathlist(). It'd be better * not to duplicate all this logic, but some callers of this function * aren't working from an appendrel or AppendPath, so there's noplace to * copy the data from. */ plan->startup_cost = 0; plan->total_cost = 0; plan->plan_rows = 0; total_size = 0; foreach(subnode, appendplans) { Plan *subplan = (Plan *) lfirst(subnode); if (subnode == list_head(appendplans)) /* first node? */ plan->startup_cost = subplan->startup_cost; plan->total_cost += subplan->total_cost; plan->plan_rows += subplan->plan_rows; total_size += subplan->plan_width * subplan->plan_rows; } if (plan->plan_rows > 0) plan->plan_width = rint(total_size / plan->plan_rows); else plan->plan_width = 0; plan->targetlist = tlist; plan->qual = NIL; plan->lefttree = NULL; plan->righttree = NULL; node->appendplans = appendplans; return node; } RecursiveUnion * make_recursive_union(List *tlist, Plan *lefttree, Plan *righttree, int wtParam, List *distinctList, long numGroups) { RecursiveUnion *node = makeNode(RecursiveUnion); Plan *plan = &node->plan; int numCols = list_length(distinctList); cost_recursive_union(plan, lefttree, righttree); plan->targetlist = tlist; plan->qual = NIL; plan->lefttree = lefttree; plan->righttree = righttree; node->wtParam = wtParam; /* * convert SortGroupClause list into arrays of attr indexes and equality * operators, as wanted by executor */ node->numCols = numCols; if (numCols > 0) { int keyno = 0; AttrNumber *dupColIdx; Oid *dupOperators; ListCell *slitem; dupColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols); dupOperators = (Oid *) palloc(sizeof(Oid) * numCols); foreach(slitem, distinctList) { SortGroupClause *sortcl = (SortGroupClause *) lfirst(slitem); TargetEntry *tle = get_sortgroupclause_tle(sortcl, plan->targetlist); dupColIdx[keyno] = tle->resno; dupOperators[keyno] = sortcl->eqop; Assert(OidIsValid(dupOperators[keyno])); keyno++; } node->dupColIdx = dupColIdx; node->dupOperators = dupOperators; } node->numGroups = numGroups; return node; } static BitmapAnd * make_bitmap_and(List *bitmapplans) { BitmapAnd *node = makeNode(BitmapAnd); Plan *plan = &node->plan; /* cost should be inserted by caller */ plan->targetlist = NIL; plan->qual = NIL; plan->lefttree = NULL; plan->righttree = NULL; node->bitmapplans = bitmapplans; return node; } static BitmapOr * make_bitmap_or(List *bitmapplans) { BitmapOr *node = makeNode(BitmapOr); Plan *plan = &node->plan; /* cost should be inserted by caller */ plan->targetlist = NIL; plan->qual = NIL; plan->lefttree = NULL; plan->righttree = NULL; node->bitmapplans = bitmapplans; return node; } static NestLoop * make_nestloop(List *tlist, List *joinclauses, List *otherclauses, List *nestParams, Plan *lefttree, Plan *righttree, JoinType jointype) { NestLoop *node = makeNode(NestLoop); Plan *plan = &node->join.plan; /* cost should be inserted by caller */ plan->targetlist = tlist; plan->qual = otherclauses; plan->lefttree = lefttree; plan->righttree = righttree; node->join.jointype = jointype; node->join.joinqual = joinclauses; node->nestParams = nestParams; return node; } static HashJoin * make_hashjoin(List *tlist, List *joinclauses, List *otherclauses, List *hashclauses, Plan *lefttree, Plan *righttree, JoinType jointype) { HashJoin *node = makeNode(HashJoin); Plan *plan = &node->join.plan; /* cost should be inserted by caller */ plan->targetlist = tlist; plan->qual = otherclauses; plan->lefttree = lefttree; plan->righttree = righttree; node->hashclauses = hashclauses; node->join.jointype = jointype; node->join.joinqual = joinclauses; return node; } static Hash * make_hash(Plan *lefttree, Oid skewTable, AttrNumber skewColumn, bool skewInherit, Oid skewColType, int32 skewColTypmod) { Hash *node = makeNode(Hash); Plan *plan = &node->plan; copy_plan_costsize(plan, lefttree); /* * For plausibility, make startup & total costs equal total cost of input * plan; this only affects EXPLAIN display not decisions. */ plan->startup_cost = plan->total_cost; plan->targetlist = lefttree->targetlist; plan->qual = NIL; plan->lefttree = lefttree; plan->righttree = NULL; node->skewTable = skewTable; node->skewColumn = skewColumn; node->skewInherit = skewInherit; node->skewColType = skewColType; node->skewColTypmod = skewColTypmod; return node; } static MergeJoin * make_mergejoin(List *tlist, List *joinclauses, List *otherclauses, List *mergeclauses, Oid *mergefamilies, Oid *mergecollations, int *mergestrategies, bool *mergenullsfirst, Plan *lefttree, Plan *righttree, JoinType jointype) { MergeJoin *node = makeNode(MergeJoin); Plan *plan = &node->join.plan; /* cost should be inserted by caller */ plan->targetlist = tlist; plan->qual = otherclauses; plan->lefttree = lefttree; plan->righttree = righttree; node->mergeclauses = mergeclauses; node->mergeFamilies = mergefamilies; node->mergeCollations = mergecollations; node->mergeStrategies = mergestrategies; node->mergeNullsFirst = mergenullsfirst; node->join.jointype = jointype; node->join.joinqual = joinclauses; return node; } /* * make_sort --- basic routine to build a Sort plan node * * Caller must have built the sortColIdx, sortOperators, collations, and * nullsFirst arrays already. * limit_tuples is as for cost_sort (in particular, pass -1 if no limit) */ static Sort * make_sort(PlannerInfo *root, Plan *lefttree, int numCols, AttrNumber *sortColIdx, Oid *sortOperators, Oid *collations, bool *nullsFirst, double limit_tuples) { Sort *node = makeNode(Sort); Plan *plan = &node->plan; Path sort_path; /* dummy for result of cost_sort */ copy_plan_costsize(plan, lefttree); /* only care about copying size */ cost_sort(&sort_path, root, NIL, lefttree->total_cost, lefttree->plan_rows, lefttree->plan_width, 0.0, work_mem, limit_tuples); plan->startup_cost = sort_path.startup_cost; plan->total_cost = sort_path.total_cost; plan->targetlist = lefttree->targetlist; plan->qual = NIL; plan->lefttree = lefttree; plan->righttree = NULL; node->numCols = numCols; node->sortColIdx = sortColIdx; node->sortOperators = sortOperators; node->collations = collations; node->nullsFirst = nullsFirst; return node; } /* * prepare_sort_from_pathkeys * Prepare to sort according to given pathkeys * * This is used to set up for both Sort and MergeAppend nodes. It calculates * the executor's representation of the sort key information, and adjusts the * plan targetlist if needed to add resjunk sort columns. * * Input parameters: * 'lefttree' is the plan node which yields input tuples * 'pathkeys' is the list of pathkeys by which the result is to be sorted * 'relids' identifies the child relation being sorted, if any * 'reqColIdx' is NULL or an array of required sort key column numbers * 'adjust_tlist_in_place' is TRUE if lefttree must be modified in-place * * We must convert the pathkey information into arrays of sort key column * numbers, sort operator___ OIDs, collation OIDs, and nulls-first flags, * which is the representation the executor wants. These are returned into * the output parameters *p_numsortkeys etc. * * When looking for matches to an EquivalenceClass's members, we will only * consider child EC members if they match 'relids'. This protects against * possible incorrect matches to child expressions that contain no Vars. * * If reqColIdx isn't NULL then it contains sort key column numbers that * we should match. This is used when making child plans for a MergeAppend; * it's an error if we can't match the columns. * * If the pathkeys include expressions that aren't simple Vars, we will * usually need to add resjunk items to the input plan's targetlist to * compute these expressions, since the Sort/MergeAppend node itself won't * do any such calculations. If the input plan type isn't one that can do * projections, this means adding a Result node just to do the projection. * However, the caller can pass adjust_tlist_in_place = TRUE to force the * lefttree tlist to be modified in-place regardless of whether the node type * can project --- we use this for fixing the tlist of MergeAppend itself. * * Returns the node which is to be the input to the Sort (either lefttree, * or a Result stacked atop lefttree). */ static Plan * prepare_sort_from_pathkeys(PlannerInfo *root, Plan *lefttree, List *pathkeys, Relids relids, const AttrNumber *reqColIdx, bool adjust_tlist_in_place, int *p_numsortkeys, AttrNumber **p_sortColIdx, Oid **p_sortOperators, Oid **p_collations, bool **p_nullsFirst) { List *tlist = lefttree->targetlist; ListCell *i; int numsortkeys; AttrNumber *sortColIdx; Oid *sortOperators; Oid *collations; bool *nullsFirst; /* * We will need at most list_length(pathkeys) sort columns; possibly less */ numsortkeys = list_length(pathkeys); sortColIdx = (AttrNumber *) palloc(numsortkeys * sizeof(AttrNumber)); sortOperators = (Oid *) palloc(numsortkeys * sizeof(Oid)); collations = (Oid *) palloc(numsortkeys * sizeof(Oid)); nullsFirst = (bool *) palloc(numsortkeys * sizeof(bool)); numsortkeys = 0; foreach(i, pathkeys) { PathKey *pathkey = (PathKey *) lfirst(i); EquivalenceClass *ec = pathkey->pk_eclass; EquivalenceMember *em; TargetEntry *tle = NULL; Oid pk_datatype = InvalidOid; Oid sortop; ListCell *j; if (ec->ec_has_volatile) { /* * If the pathkey's EquivalenceClass is volatile, then it must * have come from an ORDER BY clause, and we have to match it to * that same targetlist entry. */ if (ec->ec_sortref == 0) /* can't happen */ elog(ERROR, "volatile EquivalenceClass has no sortref"); tle = get_sortgroupref_tle(ec->ec_sortref, tlist); Assert(tle); Assert(list_length(ec->ec_members) == 1); pk_datatype = ((EquivalenceMember *) linitial(ec->ec_members))->em_datatype; } else if (reqColIdx != NULL) { /* * If we are given a sort column number to match, only consider * the single TLE at that position. It's possible that there is * no such TLE, in which case fall through and generate a resjunk * targetentry (we assume this must have happened in the parent * plan as well). If there is a TLE but it doesn't match the * pathkey's EC, we do the same, which is probably the wrong thing * but we'll leave it to caller to complain about the mismatch. */ tle = get_tle_by_resno(tlist, reqColIdx[numsortkeys]); if (tle) { em = find_ec_member_for_tle(ec, tle, relids); if (em) { /* found expr at right place in tlist */ pk_datatype = em->em_datatype; } else tle = NULL; } } else { /* * Otherwise, we can sort by any non-constant expression listed in * the pathkey's EquivalenceClass. For now, we take the first * tlist item found in the EC. If there's no match, we'll generate * a resjunk entry using the first EC member that is an expression * in the input's vars. (The non-const restriction only matters * if the EC is below_outer_join; but if it isn't, it won't * contain consts anyway, else we'd have discarded the pathkey as * redundant.) * * XXX if we have a choice, is there any way of figuring out which * might be cheapest to execute? (For example, int4lt is likely * much cheaper to execute than numericlt, but both might appear * in the same equivalence class___...) Not clear that we ever will * have an interesting choice in practice, so it may not matter. */ foreach(j, tlist) { tle = (TargetEntry *) lfirst(j); em = find_ec_member_for_tle(ec, tle, relids); if (em) { /* found expr already in tlist */ pk_datatype = em->em_datatype; break; } tle = NULL; } } if (!tle) { /* * No matching tlist item; look for a computable expression. Note * that we treat Aggrefs as if they were variables; this is * necessary when attempting to sort the output from an Agg node * for use in a WindowFunc (since grouping_planner will have * treated the Aggrefs as variables, too). */ Expr *sortexpr = NULL; foreach(j, ec->ec_members) { EquivalenceMember *em = (EquivalenceMember *) lfirst(j); List *exprvars; ListCell *k; /* * We shouldn't be trying to sort by an equivalence class___ that * contains a constant, so no need to consider such cases any * further. */ if (em->em_is_const) continue; /* * Ignore child members unless they match the rel being * sorted. */ if (em->em_is_child && !bms_equal(em->em_relids, relids)) continue; sortexpr = em->em_expr; exprvars = pull_var_clause((Node *) sortexpr, PVC_INCLUDE_AGGREGATES, PVC_INCLUDE_PLACEHOLDERS); foreach(k, exprvars) { if (!tlist_member_ignore_relabel(static_cast<Node *>(lfirst(k)), tlist)) break; } list_free(exprvars); if (!k) { pk_datatype = em->em_datatype; break; /* found usable expression */ } } if (!j) elog(ERROR, "could not find pathkey item to sort"); /* * Do we need to insert a Result node? */ if (!adjust_tlist_in_place && !is_projection_capable_plan(lefttree)) { /* copy needed so we don't modify input's tlist below */ tlist = static_cast<List *>(copyObject(tlist)); lefttree = (Plan *) make_result(root, tlist, NULL, lefttree); } /* Don't bother testing is_projection_capable_plan again */ adjust_tlist_in_place = true; /* * Add resjunk entry to input's tlist */ tle = makeTargetEntry(sortexpr, list_length(tlist) + 1, NULL, true); tlist = lappend(tlist, tle); lefttree->targetlist = tlist; /* just in case NIL before */ } /* * Look up the correct sort operator___ from the PathKey's slightly * abstracted representation. */ sortop = get_opfamily_member(pathkey->pk_opfamily, pk_datatype, pk_datatype, pathkey->pk_strategy); if (!OidIsValid(sortop)) /* should not happen */ elog(ERROR, "could not find member %d(%u,%u) of opfamily %u", pathkey->pk_strategy, pk_datatype, pk_datatype, pathkey->pk_opfamily); /* Add the column to the sort arrays */ sortColIdx[numsortkeys] = tle->resno; sortOperators[numsortkeys] = sortop; collations[numsortkeys] = ec->ec_collation; nullsFirst[numsortkeys] = pathkey->pk_nulls_first; numsortkeys++; } /* Return results */ *p_numsortkeys = numsortkeys; *p_sortColIdx = sortColIdx; *p_sortOperators = sortOperators; *p_collations = collations; *p_nullsFirst = nullsFirst; return lefttree; } /* * find_ec_member_for_tle * Locate an EquivalenceClass member matching the given TLE, if any * * Child EC members are ignored unless they match 'relids'. */ static EquivalenceMember * find_ec_member_for_tle(EquivalenceClass *ec, TargetEntry *tle, Relids relids) { Expr *tlexpr; ListCell *lc; /* We ignore binary-compatible relabeling on both ends */ tlexpr = tle->expr; while (tlexpr && IsA(tlexpr, RelabelType)) tlexpr = ((RelabelType *) tlexpr)->arg; foreach(lc, ec->ec_members) { EquivalenceMember *em = (EquivalenceMember *) lfirst(lc); Expr *emexpr; /* * We shouldn't be trying to sort by an equivalence class___ that * contains a constant, so no need to consider such cases any further. */ if (em->em_is_const) continue; /* * Ignore child members unless they match the rel being sorted. */ if (em->em_is_child && !bms_equal(em->em_relids, relids)) continue; /* Match if same expression (after stripping relabel) */ emexpr = em->em_expr; while (emexpr && IsA(emexpr, RelabelType)) emexpr = ((RelabelType *) emexpr)->arg; if (equal(emexpr, tlexpr)) return em; } return NULL; } /* * make_sort_from_pathkeys * Create sort plan to sort according to given pathkeys * * 'lefttree' is the node which yields input tuples * 'pathkeys' is the list of pathkeys by which the result is to be sorted * 'limit_tuples' is the bound on the number of output tuples; * -1 if no bound */ Sort * make_sort_from_pathkeys(PlannerInfo *root, Plan *lefttree, List *pathkeys, double limit_tuples) { int numsortkeys; AttrNumber *sortColIdx; Oid *sortOperators; Oid *collations; bool *nullsFirst; /* Compute sort column info, and adjust lefttree as needed */ lefttree = prepare_sort_from_pathkeys(root, lefttree, pathkeys, NULL, NULL, false, &numsortkeys, &sortColIdx, &sortOperators, &collations, &nullsFirst); /* Now build the Sort node */ return make_sort(root, lefttree, numsortkeys, sortColIdx, sortOperators, collations, nullsFirst, limit_tuples); } /* * make_sort_from_sortclauses * Create sort plan to sort according to given sortclauses * * 'sortcls' is a list of SortGroupClauses * 'lefttree' is the node which yields input tuples */ Sort * make_sort_from_sortclauses(PlannerInfo *root, List *sortcls, Plan *lefttree) { List *sub_tlist = lefttree->targetlist; ListCell *l; int numsortkeys; AttrNumber *sortColIdx; Oid *sortOperators; Oid *collations; bool *nullsFirst; /* Convert list-ish representation to arrays wanted by executor */ numsortkeys = list_length(sortcls); sortColIdx = (AttrNumber *) palloc(numsortkeys * sizeof(AttrNumber)); sortOperators = (Oid *) palloc(numsortkeys * sizeof(Oid)); collations = (Oid *) palloc(numsortkeys * sizeof(Oid)); nullsFirst = (bool *) palloc(numsortkeys * sizeof(bool)); numsortkeys = 0; foreach(l, sortcls) { SortGroupClause *sortcl = (SortGroupClause *) lfirst(l); TargetEntry *tle = get_sortgroupclause_tle(sortcl, sub_tlist); sortColIdx[numsortkeys] = tle->resno; sortOperators[numsortkeys] = sortcl->sortop; collations[numsortkeys] = exprCollation((Node *) tle->expr); nullsFirst[numsortkeys] = sortcl->nulls_first; numsortkeys++; } return make_sort(root, lefttree, numsortkeys, sortColIdx, sortOperators, collations, nullsFirst, -1.0); } /* * make_sort_from_groupcols * Create sort plan to sort based on grouping columns * * 'groupcls' is the list of SortGroupClauses * 'grpColIdx' gives the column numbers to use * * This might look like it could be merged with make_sort_from_sortclauses, * but presently we *must* use the grpColIdx[] array to locate sort columns, * because the child plan's tlist is not marked with ressortgroupref info * appropriate to the grouping node. So, only the sort ordering info * is used from the SortGroupClause entries. */ Sort * make_sort_from_groupcols(PlannerInfo *root, List *groupcls, AttrNumber *grpColIdx, Plan *lefttree) { List *sub_tlist = lefttree->targetlist; ListCell *l; int numsortkeys; AttrNumber *sortColIdx; Oid *sortOperators; Oid *collations; bool *nullsFirst; /* Convert list-ish representation to arrays wanted by executor */ numsortkeys = list_length(groupcls); sortColIdx = (AttrNumber *) palloc(numsortkeys * sizeof(AttrNumber)); sortOperators = (Oid *) palloc(numsortkeys * sizeof(Oid)); collations = (Oid *) palloc(numsortkeys * sizeof(Oid)); nullsFirst = (bool *) palloc(numsortkeys * sizeof(bool)); numsortkeys = 0; foreach(l, groupcls) { SortGroupClause *grpcl = (SortGroupClause *) lfirst(l); TargetEntry *tle = get_tle_by_resno(sub_tlist, grpColIdx[numsortkeys]); if (!tle) elog(ERROR, "could not retrive tle for sort-from-groupcols"); sortColIdx[numsortkeys] = tle->resno; sortOperators[numsortkeys] = grpcl->sortop; collations[numsortkeys] = exprCollation((Node *) tle->expr); nullsFirst[numsortkeys] = grpcl->nulls_first; numsortkeys++; } return make_sort(root, lefttree, numsortkeys, sortColIdx, sortOperators, collations, nullsFirst, -1.0); } static Material * make_material(Plan *lefttree) { Material *node = makeNode(Material); Plan *plan = &node->plan; /* cost should be inserted by caller */ plan->targetlist = lefttree->targetlist; plan->qual = NIL; plan->lefttree = lefttree; plan->righttree = NULL; return node; } /* * materialize_finished_plan: stick a Material node atop a completed plan * * There are a couple of places where we want to attach a Material node * after completion of subquery_planner(). This currently requires hackery. * Since subquery_planner has already run SS_finalize_plan on the subplan * tree, we have to kluge up parameter lists for the Material node. * Possibly this could be fixed by postponing SS_finalize_plan processing * until setrefs.c is run? */ Plan * materialize_finished_plan(Plan *subplan) { Plan *matplan; Path matpath; /* dummy for result of cost_material */ matplan = (Plan *) make_material(subplan); /* Set cost data */ cost_material(&matpath, subplan->startup_cost, subplan->total_cost, subplan->plan_rows, subplan->plan_width); matplan->startup_cost = matpath.startup_cost; matplan->total_cost = matpath.total_cost; matplan->plan_rows = subplan->plan_rows; matplan->plan_width = subplan->plan_width; /* parameter kluge --- see comments above */ matplan->extParam = bms_copy(subplan->extParam); matplan->allParam = bms_copy(subplan->allParam); return matplan; } Agg * make_agg(PlannerInfo *root, List *tlist, List *qual, AggStrategy aggstrategy, const AggClauseCosts *aggcosts, int numGroupCols, AttrNumber *grpColIdx, Oid *grpOperators, List *groupingSets, long numGroups, Plan *lefttree) { Agg *node = makeNode(Agg); Plan *plan = &node->plan; Path agg_path; /* dummy for result of cost_agg */ QualCost qual_cost; node->aggstrategy = aggstrategy; node->numCols = numGroupCols; node->grpColIdx = grpColIdx; node->grpOperators = grpOperators; node->numGroups = numGroups; copy_plan_costsize(plan, lefttree); /* only care about copying size */ cost_agg(&agg_path, root, aggstrategy, aggcosts, numGroupCols, numGroups, lefttree->startup_cost, lefttree->total_cost, lefttree->plan_rows); plan->startup_cost = agg_path.startup_cost; plan->total_cost = agg_path.total_cost; /* * We will produce a single output tuple if not grouping, and a tuple per * group otherwise. */ if (aggstrategy == AGG_PLAIN) plan->plan_rows = groupingSets ? list_length(groupingSets) : 1; else plan->plan_rows = numGroups; node->groupingSets = groupingSets; /* * We also need to account for the cost of evaluation of the qual (ie, the * HAVING clause) and the tlist. Note that cost_qual_eval doesn't charge * anything for Aggref nodes; this is okay since they are really * comparable to Vars. * * See notes in add_tlist_costs_to_plan about why only make_agg, * make_windowagg and make_group worry about tlist eval cost. */ if (qual) { cost_qual_eval(&qual_cost, qual, root); plan->startup_cost += qual_cost.startup; plan->total_cost += qual_cost.startup; plan->total_cost += qual_cost.per_tuple * plan->plan_rows; } add_tlist_costs_to_plan(root, plan, tlist); plan->qual = qual; plan->targetlist = tlist; plan->lefttree = lefttree; plan->righttree = NULL; return node; } WindowAgg * make_windowagg(PlannerInfo *root, List *tlist, List *windowFuncs, Index winref, int partNumCols, AttrNumber *partColIdx, Oid *partOperators, int ordNumCols, AttrNumber *ordColIdx, Oid *ordOperators, int frameOptions, Node *startOffset, Node *endOffset, Plan *lefttree) { WindowAgg *node = makeNode(WindowAgg); Plan *plan = &node->plan; Path windowagg_path; /* dummy for result of cost_windowagg */ node->winref = winref; node->partNumCols = partNumCols; node->partColIdx = partColIdx; node->partOperators = partOperators; node->ordNumCols = ordNumCols; node->ordColIdx = ordColIdx; node->ordOperators = ordOperators; node->frameOptions = frameOptions; node->startOffset = startOffset; node->endOffset = endOffset; copy_plan_costsize(plan, lefttree); /* only care about copying size */ cost_windowagg(&windowagg_path, root, windowFuncs, partNumCols, ordNumCols, lefttree->startup_cost, lefttree->total_cost, lefttree->plan_rows); plan->startup_cost = windowagg_path.startup_cost; plan->total_cost = windowagg_path.total_cost; /* * We also need to account for the cost of evaluation of the tlist. * * See notes in add_tlist_costs_to_plan about why only make_agg, * make_windowagg and make_group worry about tlist eval cost. */ add_tlist_costs_to_plan(root, plan, tlist); plan->targetlist = tlist; plan->lefttree = lefttree; plan->righttree = NULL; /* WindowAgg nodes never have a qual clause */ plan->qual = NIL; return node; } Group * make_group(PlannerInfo *root, List *tlist, List *qual, int numGroupCols, AttrNumber *grpColIdx, Oid *grpOperators, double numGroups, Plan *lefttree) { Group *node = makeNode(Group); Plan *plan = &node->plan; Path group_path; /* dummy for result of cost_group */ QualCost qual_cost; node->numCols = numGroupCols; node->grpColIdx = grpColIdx; node->grpOperators = grpOperators; copy_plan_costsize(plan, lefttree); /* only care about copying size */ cost_group(&group_path, root, numGroupCols, numGroups, lefttree->startup_cost, lefttree->total_cost, lefttree->plan_rows); plan->startup_cost = group_path.startup_cost; plan->total_cost = group_path.total_cost; /* One output tuple per estimated result group */ plan->plan_rows = numGroups; /* * We also need to account for the cost of evaluation of the qual (ie, the * HAVING clause) and the tlist. * * XXX this double-counts the cost of evaluation of any expressions used * for grouping, since in reality those will have been evaluated at a * lower plan level and will only be copied by the Group node. Worth * fixing? * * See notes in add_tlist_costs_to_plan about why only make_agg, * make_windowagg and make_group worry about tlist eval cost. */ if (qual) { cost_qual_eval(&qual_cost, qual, root); plan->startup_cost += qual_cost.startup; plan->total_cost += qual_cost.startup; plan->total_cost += qual_cost.per_tuple * plan->plan_rows; } add_tlist_costs_to_plan(root, plan, tlist); plan->qual = qual; plan->targetlist = tlist; plan->lefttree = lefttree; plan->righttree = NULL; return node; } /* * distinctList is a list of SortGroupClauses, identifying the targetlist items * that should be considered by the Unique filter. The input path must * already be sorted accordingly. */ Unique * make_unique(Plan *lefttree, List *distinctList) { Unique *node = makeNode(Unique); Plan *plan = &node->plan; int numCols = list_length(distinctList); int keyno = 0; AttrNumber *uniqColIdx; Oid *uniqOperators; ListCell *slitem; copy_plan_costsize(plan, lefttree); /* * Charge one cpu_operator_cost per comparison per input tuple. We assume * all columns get compared at most of the tuples. (XXX probably this is * an overestimate.) */ plan->total_cost += cpu_operator_cost * plan->plan_rows * numCols; /* * plan->plan_rows is left as a copy of the input subplan's plan_rows; ie, * we assume the filter removes nothing. The caller must alter this if he * has a better idea. */ plan->targetlist = lefttree->targetlist; plan->qual = NIL; plan->lefttree = lefttree; plan->righttree = NULL; /* * convert SortGroupClause list into arrays of attr indexes and equality * operators, as wanted by executor */ Assert(numCols > 0); uniqColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols); uniqOperators = (Oid *) palloc(sizeof(Oid) * numCols); foreach(slitem, distinctList) { SortGroupClause *sortcl = (SortGroupClause *) lfirst(slitem); TargetEntry *tle = get_sortgroupclause_tle(sortcl, plan->targetlist); uniqColIdx[keyno] = tle->resno; uniqOperators[keyno] = sortcl->eqop; Assert(OidIsValid(uniqOperators[keyno])); keyno++; } node->numCols = numCols; node->uniqColIdx = uniqColIdx; node->uniqOperators = uniqOperators; return node; } /* * distinctList is a list of SortGroupClauses, identifying the targetlist * items that should be considered by the SetOp filter. The input path must * already be sorted accordingly. */ SetOp * make_setop(SetOpCmd cmd, SetOpStrategy strategy, Plan *lefttree, List *distinctList, AttrNumber flagColIdx, int firstFlag, long numGroups, double outputRows) { SetOp *node = makeNode(SetOp); Plan *plan = &node->plan; int numCols = list_length(distinctList); int keyno = 0; AttrNumber *dupColIdx; Oid *dupOperators; ListCell *slitem; copy_plan_costsize(plan, lefttree); plan->plan_rows = outputRows; /* * Charge one cpu_operator_cost per comparison per input tuple. We assume * all columns get compared at most of the tuples. */ plan->total_cost += cpu_operator_cost * lefttree->plan_rows * numCols; plan->targetlist = lefttree->targetlist; plan->qual = NIL; plan->lefttree = lefttree; plan->righttree = NULL; /* * convert SortGroupClause list into arrays of attr indexes and equality * operators, as wanted by executor */ Assert(numCols > 0); dupColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols); dupOperators = (Oid *) palloc(sizeof(Oid) * numCols); foreach(slitem, distinctList) { SortGroupClause *sortcl = (SortGroupClause *) lfirst(slitem); TargetEntry *tle = get_sortgroupclause_tle(sortcl, plan->targetlist); dupColIdx[keyno] = tle->resno; dupOperators[keyno] = sortcl->eqop; Assert(OidIsValid(dupOperators[keyno])); keyno++; } node->cmd = cmd; node->strategy = strategy; node->numCols = numCols; node->dupColIdx = dupColIdx; node->dupOperators = dupOperators; node->flagColIdx = flagColIdx; node->firstFlag = firstFlag; node->numGroups = numGroups; return node; } /* * make_lockrows * Build a LockRows plan node */ LockRows * make_lockrows(Plan *lefttree, List *rowMarks, int epqParam) { LockRows *node = makeNode(LockRows); Plan *plan = &node->plan; copy_plan_costsize(plan, lefttree); /* charge cpu_tuple_cost to reflect locking costs (underestimate?) */ plan->total_cost += cpu_tuple_cost * plan->plan_rows; plan->targetlist = lefttree->targetlist; plan->qual = NIL; plan->lefttree = lefttree; plan->righttree = NULL; node->rowMarks = rowMarks; node->epqParam = epqParam; return node; } /* * Note: offset_est and count_est are passed in to save having to repeat * work already done to estimate the values of the limitOffset and limitCount * expressions. Their values are as returned by preprocess_limit (0 means * "not relevant", -1 means "couldn't estimate"). Keep the code below in sync * with that function! */ Limit * make_limit(Plan *lefttree, Node *limitOffset, Node *limitCount, int64 offset_est, int64 count_est) { Limit *node = makeNode(Limit); Plan *plan = &node->plan; copy_plan_costsize(plan, lefttree); /* * Adjust the output rows count and costs according to the offset/limit. * This is only a cosmetic issue if we are at top level, but if we are * building a subquery then it's important to report correct info to the * outer planner. * * When the offset or count couldn't be estimated, use 10% of the * estimated number of rows emitted from the subplan. */ if (offset_est != 0) { double offset_rows; if (offset_est > 0) offset_rows = (double) offset_est; else offset_rows = clamp_row_est(lefttree->plan_rows * 0.10); if (offset_rows > plan->plan_rows) offset_rows = plan->plan_rows; if (plan->plan_rows > 0) plan->startup_cost += (plan->total_cost - plan->startup_cost) * offset_rows / plan->plan_rows; plan->plan_rows -= offset_rows; if (plan->plan_rows < 1) plan->plan_rows = 1; } if (count_est != 0) { double count_rows; if (count_est > 0) count_rows = (double) count_est; else count_rows = clamp_row_est(lefttree->plan_rows * 0.10); if (count_rows > plan->plan_rows) count_rows = plan->plan_rows; if (plan->plan_rows > 0) plan->total_cost = plan->startup_cost + (plan->total_cost - plan->startup_cost) * count_rows / plan->plan_rows; plan->plan_rows = count_rows; if (plan->plan_rows < 1) plan->plan_rows = 1; } plan->targetlist = lefttree->targetlist; plan->qual = NIL; plan->lefttree = lefttree; plan->righttree = NULL; node->limitOffset = limitOffset; node->limitCount = limitCount; return node; } /* * make_result * Build a Result plan node * * If we have a subplan, assume that any evaluation costs for the gating qual * were already factored into the subplan's startup cost, and just copy the * subplan cost. If there's no subplan, we should include the qual eval * cost. In either case, tlist eval cost is not to be included here. */ Result * make_result(PlannerInfo *root, List *tlist, Node *resconstantqual, Plan *subplan) { Result *node = makeNode(Result); Plan *plan = &node->plan; if (subplan) copy_plan_costsize(plan, subplan); else { plan->startup_cost = 0; plan->total_cost = cpu_tuple_cost; plan->plan_rows = 1; /* wrong if we have a set-valued function? */ plan->plan_width = 0; /* XXX is it worth being smarter? */ if (resconstantqual) { QualCost qual_cost; cost_qual_eval(&qual_cost, (List *) resconstantqual, root); /* resconstantqual is evaluated once at startup */ plan->startup_cost += qual_cost.startup + qual_cost.per_tuple; plan->total_cost += qual_cost.startup + qual_cost.per_tuple; } } plan->targetlist = tlist; plan->qual = NIL; plan->lefttree = subplan; plan->righttree = NULL; node->resconstantqual = resconstantqual; return node; } /* * make_modifytable * Build a ModifyTable plan node * * Currently, we don't charge anything extra for the actual table modification * work, nor for the WITH CHECK OPTIONS or RETURNING expressions if any. It * would only be window dressing, since these are always top-level nodes and * there is no way for the costs to change any higher-level planning choices. * But we might want to make it look better sometime. */ ModifyTable * make_modifytable(PlannerInfo *root, CmdType operation, bool canSetTag, Index nominalRelation, List *resultRelations, List *subplans, List *withCheckOptionLists, List *returningLists, List *rowMarks, OnConflictExpr *onconflict, int epqParam) { ModifyTable *node = makeNode(ModifyTable); Plan *plan = &node->plan; double total_size; List *fdw_private_list; ListCell *subnode; ListCell *lc; int i; Assert(list_length(resultRelations) == list_length(subplans)); Assert(withCheckOptionLists == NIL || list_length(resultRelations) == list_length(withCheckOptionLists)); Assert(returningLists == NIL || list_length(resultRelations) == list_length(returningLists)); /* * Compute cost as sum of subplan costs. */ plan->startup_cost = 0; plan->total_cost = 0; plan->plan_rows = 0; total_size = 0; foreach(subnode, subplans) { Plan *subplan = (Plan *) lfirst(subnode); if (subnode == list_head(subplans)) /* first node? */ plan->startup_cost = subplan->startup_cost; plan->total_cost += subplan->total_cost; plan->plan_rows += subplan->plan_rows; total_size += subplan->plan_width * subplan->plan_rows; } if (plan->plan_rows > 0) plan->plan_width = rint(total_size / plan->plan_rows); else plan->plan_width = 0; node->plan.lefttree = NULL; node->plan.righttree = NULL; node->plan.qual = NIL; /* setrefs.c will fill in the targetlist, if needed */ node->plan.targetlist = NIL; node->operation = operation; node->canSetTag = canSetTag; node->nominalRelation = nominalRelation; node->resultRelations = resultRelations; node->resultRelIndex = -1; /* will be set correctly in setrefs.c */ node->plans = subplans; if (!onconflict) { node->onConflictAction = ONCONFLICT_NONE; node->onConflictSet = NIL; node->onConflictWhere = NULL; node->arbiterIndexes = NIL; node->exclRelRTI = 0; node->exclRelTlist = NIL; } else { node->onConflictAction = onconflict->action; node->onConflictSet = onconflict->onConflictSet; node->onConflictWhere = onconflict->onConflictWhere; /* * If a set of unique index inference elements was provided (an * INSERT...ON CONFLICT "inference specification"), then infer * appropriate unique indexes (or throw an error if none are * available). */ node->arbiterIndexes = infer_arbiter_indexes(root); node->exclRelRTI = onconflict->exclRelIndex; node->exclRelTlist = onconflict->exclRelTlist; } node->withCheckOptionLists = withCheckOptionLists; node->returningLists = returningLists; node->rowMarks = rowMarks; node->epqParam = epqParam; /* * For each result relation that is a foreign table, allow the FDW to * construct private___ plan data, and accumulate it all into a list. */ fdw_private_list = NIL; i = 0; foreach(lc, resultRelations) { Index rti = lfirst_int(lc); FdwRoutine *fdwroutine; List *fdw_private; /* * If possible, we want to get the FdwRoutine from our RelOptInfo for * the table. But sometimes we don't have a RelOptInfo and must get * it the hard way. (In INSERT, the target relation is not scanned, * so it's not a baserel; and there are also corner cases for * updatable views where the target rel isn't a baserel.) */ if (rti < root->simple_rel_array_size && root->simple_rel_array[rti] != NULL) { RelOptInfo *resultRel = root->simple_rel_array[rti]; fdwroutine = resultRel->fdwroutine; } else { RangeTblEntry *rte = planner_rt_fetch(rti, root); Assert(rte->rtekind == RTE_RELATION); if (rte->relkind == RELKIND_FOREIGN_TABLE) fdwroutine = GetFdwRoutineByRelId(rte->relid); else fdwroutine = NULL; } if (fdwroutine != NULL && fdwroutine->PlanForeignModify != NULL) fdw_private = fdwroutine->PlanForeignModify(root, node, rti, i); else fdw_private = NIL; fdw_private_list = lappend(fdw_private_list, fdw_private); i++; } node->fdwPrivLists = fdw_private_list; return node; } /* * is_projection_capable_plan * Check whether a given Plan node is able to do projection. */ bool is_projection_capable_plan(Plan *plan) { /* Most plan types can project, so just list the ones that can't */ switch (nodeTag(plan)) { case T_Hash: case T_Material: case T_Sort: case T_Unique: case T_SetOp: case T_LockRows: case T_Limit: case T_ModifyTable: case T_Append: case T_MergeAppend: case T_RecursiveUnion: return false; default: break; } return true; }
29.627643
98
0.690217
[ "transform" ]
19ae83551984be272276d60404e82c9d7f828627
32,084
cpp
C++
plugin/viewfinder.cpp
meego-tablet-ux/meego-app-camera
914b48defe18043da0961f8d9de1956358f61ee4
[ "Apache-2.0" ]
null
null
null
plugin/viewfinder.cpp
meego-tablet-ux/meego-app-camera
914b48defe18043da0961f8d9de1956358f61ee4
[ "Apache-2.0" ]
null
null
null
plugin/viewfinder.cpp
meego-tablet-ux/meego-app-camera
914b48defe18043da0961f8d9de1956358f61ee4
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2011 Intel Corporation. * * This program is licensed under the terms and conditions of the * Apache License, version 2.0. The full text of the Apache License is at * http://www.apache.org/licenses/LICENSE-2.0 */ #include <sys/statvfs.h> #include <QTimer> #include <QDateTime> #include <QDir> #include <QAudioEncoderSettings> #include <QtLocation/QGeoCoordinate> #include <QFutureWatcher> #include <QFuture> #include <QSettings> #include <QApplication> #include <QFile> #include "cameraifadaptor.h" #include "viewfinder.h" #include "settings.h" #include "exifdatafactory.h" #include "jpegexiferizer.h" #include <QGLFramebufferObject> #include <QStyleOptionGraphicsItem> namespace { QString addGeoTag(QString tmpPath, QString destPath, QGeoCoordinate coord, int orientation, bool frontFacingCamera) { ExifDataFactory *factory = new ExifDataFactory(coord, orientation, frontFacingCamera); JpegExiferizer exifer(tmpPath, destPath); exifer.setExifDataFactory(factory); exifer.doIt(); delete factory; QFile::remove(tmpPath); return destPath; } } QTM_USE_NAMESPACE bool compare_sizes (const QSize &s1, const QSize &s2) { int max_1, max_2; int min_1, min_2; if (s1.width () > s1.height ()) { max_1 = s1.width (); min_1 = s1.height (); } else { max_1 = s1.height (); min_1 = s1.width (); } if (s2.width () > s2.height ()) { max_2 = s2.width (); min_2 = s2.height (); } else { max_2 = s2.height (); min_2 = s2.width (); } if (max_1 > max_2) { return true; } else if (max_2 > max_1) { return false; } else { if (min_1 > min_2) { return true; } else { return false; } } } /* ViewFinder is an encapsulation of all the camera logic along with a QML element to display it */ ViewFinder::ViewFinder (QDeclarativeItem *_parent) : QDeclarativeItem (_parent), _ready (false), _started(false), _init(true), _cameraCount (0), _currentCamera (0), _recording (false), _duration (0), _zoom (0.0), _canFocus (false), _canLockFocus(false), _cameraHasFlash (true), _thumbnailer (0), _cameraService (0), _camera (0), _viewFinder (0), _imageCapture (0), _settings (0), _currentOrientation(0), _lastPhotoOrientation(0), _bPolicyAware(true), _resourceSet(0), _bSkipCameraReset(false) { _settings = new Settings (); init();//QTimer::singleShot(0, this, SLOT(init())); } void ViewFinder::init() { foreach (const QByteArray &deviceName, QCamera::availableDevices ()) { QString description = QCamera::deviceDescription (deviceName); #ifdef SHOW_DEBUG qDebug () << deviceName << " " << description; #endif } QList<QByteArray> devs(QCamera::availableDevices ()); _cameraCount = devs.count (); emit cameraCountChanged (); // Try to restore the last used camera QByteArray strDev(_settings->cameraDevice()); int nFind; if (strDev.isEmpty() || 0 > (nFind = devs.indexOf(strDev))) { // previously used camera can't be found - set to the first available strDev = _cameraCount ? devs[0] : ""; _settings->setCameraDevice(strDev); } else { _currentCamera = nFind; } if (policyAware()) { initResourcePolicy(); acquire(); } else { setCamera (strDev); } qRegisterMetaType<QGeoCoordinate>("QGeoCoordinate"); connect(&photoThread, SIGNAL(lastCoordinate(QGeoCoordinate)), this, SLOT(setLastCoordinate(QGeoCoordinate))); photoThread.start(); QTimer::singleShot(0, this, SLOT(initExtra())); } void ViewFinder::initExtra() { _thumbnailer = new Thumbnailer (); connect (_thumbnailer, SIGNAL (created (const QString &, const QString &)), this, SLOT (thumbnailCreated (const QString &, const QString &))); connect (_thumbnailer, SIGNAL (error (const QStringList &, const int &, const QString &)), this, SLOT (thumbnailError (const QStringList &, const int &, const QString &))); connect(&_futureWatcher, SIGNAL(finished()),this,SLOT(completeImage())); // retrieve pictures and videos location from user-dirs.dirs or user-dirs.defaults files QString strUserDirsFile(QDir::homePath() + "/.config/user-dirs.dirs"); if (QFile::exists(strUserDirsFile)) { QSettings userDirs(strUserDirsFile, QSettings::NativeFormat); _strPicturesDir = QString::fromUtf8(userDirs.value("XDG_PICTURES_DIR").toByteArray()); _strVideosDir = QString::fromUtf8(userDirs.value("XDG_VIDEOS_DIR").toByteArray()); } if (_strPicturesDir.isEmpty() || _strVideosDir.isEmpty()) { strUserDirsFile = "/etc/xdg/user-dirs.defaults"; if (QFile::exists(strUserDirsFile)) { QSettings userDirs(strUserDirsFile, QSettings::NativeFormat); if (_strPicturesDir.isEmpty()) _strPicturesDir = QString::fromUtf8(userDirs.value("PICTURES").toByteArray()); if (_strVideosDir.isEmpty()) _strVideosDir = QString::fromUtf8(userDirs.value("VIDEOS").toByteArray()); } if (_strPicturesDir.isEmpty()) _strPicturesDir = "Pictures"; if (_strVideosDir.isEmpty()) _strVideosDir = "Videos"; } _strPicturesDir.replace("$HOME/", ""); _strVideosDir.replace("$HOME/", ""); _strPicturesDir += "/Camera"; _strVideosDir += "/Camera"; if (QDir::home().mkpath (_strPicturesDir) == false) { #ifdef SHOW_DEBUG qDebug () << "Error making camera directory: " << QDir::homePath () << "/Pictures/Camera"; #endif } if (QDir::home().mkpath (_strVideosDir) == false) { #ifdef SHOW_DEBUG qDebug () << "Error making camera directory: " << QDir::homePath () << "/Pictures/Camera"; #endif } _strPicturesDir.prepend(QDir::homePath() + '/'); _strVideosDir.prepend(QDir::homePath() + '/'); _lastPhotoOrientation =_settings->lastCapturedPhotoOrientation(); setImageLocation(_settings->lastCapturedPhotoPath()); } ViewFinder::~ViewFinder () { #ifdef SHOW_DEBUG qDebug () << "Shutting down"; #endif _camera->stop (); if (_freeSpaceCheckTimer) { delete _freeSpaceCheckTimer; } delete _audioSource; delete _mediaRecorder; delete _imageCapture; delete _camera; delete _thumbnailer; } void ViewFinder::releaseCamera() { _ready = false; _canFocus = _canLockFocus = false; // Shut down the camera if (_camera) { _camera->stop (); } delete _imageCapture; delete _audioSource; delete _mediaRecorder; delete _camera; _imageCapture = 0; _audioSource = 0; _mediaRecorder = 0; _camera = 0; } bool ViewFinder::setCamera (const QByteArray &cameraDevice) { releaseCamera(); if (cameraDevice.isEmpty ()) { #ifdef SHOW_DEBUG qDebug () << "Setting default camera"; #endif _camera = new QCamera; } else { #ifdef SHOW_DEBUG qDebug () << "Setting camera to " << cameraDevice; #endif _camera = new QCamera (cameraDevice); } connect(_camera, SIGNAL(statusChanged(QCamera::Status)), this, SLOT(onCameraStatusChanged(QCamera::Status))); int flashModesNumber = 0; flashModesNumber += _camera->exposure()->isFlashModeSupported(QCameraExposure::FlashOn); flashModesNumber += _camera->exposure()->isFlashModeSupported(QCameraExposure::FlashAuto); flashModesNumber += _camera->exposure()->isFlashModeSupported(QCameraExposure::FlashRedEyeReduction); flashModesNumber += _camera->exposure()->isFlashModeSupported(QCameraExposure::FlashFill); flashModesNumber += _camera->exposure()->isFlashModeSupported(QCameraExposure::FlashTorch); flashModesNumber += _camera->exposure()->isFlashModeSupported(QCameraExposure::FlashSlowSyncFrontCurtain); flashModesNumber += _camera->exposure()->isFlashModeSupported(QCameraExposure::FlashSlowSyncRearCurtain); flashModesNumber += _camera->exposure()->isFlashModeSupported(QCameraExposure::FlashManual); flashModesNumber += _camera->exposure()->isFlashModeSupported(QCameraExposure::FlashOff); _flashSettingsAvaliable = (flashModesNumber > 1); emit flashSettingsAvaliableChanged(); #ifdef SHOW_DEBUG if (_camera->isMetaDataAvailable ()) { qDebug () << "Metadata is available"; foreach (const QString &mdname, _camera->availableExtendedMetaData ()) { qDebug () << " --- " << mdname; } foreach (QtMultimediaKit::MetaData md, _camera->availableMetaData ()) { qDebug () << " +++ " << md; } } else { qDebug () << "Metadata is not available"; } connect (_camera, SIGNAL (metaDataAvailableChanged (bool)), this, SLOT (metadataAvailableChanged (bool))); #endif _audioSource = new QAudioCaptureSource (_camera); #ifdef SHOW_DEBUG foreach (const QString &audioInput, _audioSource->audioInputs ()) { qDebug () << "Audio input: " << audioInput << " - " << _audioSource->audioDescription (audioInput); } qDebug () << "Default source: " << _audioSource->defaultAudioInput (); #endif QAudioEncoderSettings audioSettings; audioSettings.setCodec ("audio/vorbis"); audioSettings.setQuality (QtMultimediaKit::HighQuality); QVideoEncoderSettings videoSettings; videoSettings.setCodec ("video/theora"); _mediaRecorder = new QMediaRecorder (_camera); #ifdef SHOW_DEBUG foreach (QSize resolution, _mediaRecorder->supportedResolutions ()) { qDebug () << "Supported video resolution: " << resolution.width () << "x" << resolution.height (); } #endif if (_settings->videoWidth () != 0 && _settings->videoHeight () != 0) { videoSettings.setResolution (_settings->videoWidth (), _settings->videoHeight ()); #ifdef SHOW_DEBUG qDebug () << "Using requested resolution: " << _settings->videoWidth () << "x" << _settings->videoHeight (); #endif } else if(_mediaRecorder->supportedResolutions ().contains(QSize(1280,720))) { videoSettings.setResolution (1280, 720); #ifdef SHOW_DEBUG qDebug () << "Using preferred resolution: 1280x720"; #endif } else { #ifdef SHOW_DEBUG qDebug () << "Using default resolution"; #endif } #ifdef SHOW_DEBUG foreach (qreal framerate, _mediaRecorder->supportedFrameRates ()) { qDebug () << "Supported video frame rate: " << framerate; } #endif if (_settings->videoFPS () != 0) { videoSettings.setFrameRate (_settings->videoFPS ()); #ifdef SHOW_DEBUG qDebug () << "Using requested FPS: " << _settings->videoFPS (); #endif } else if(_mediaRecorder->supportedFrameRates ().contains(30)) { videoSettings.setFrameRate (30); #ifdef SHOW_DEBUG qDebug () << "Using preferred FPS: 30"; #endif } else { #ifdef SHOW_DEBUG qDebug () << "Using default FPS"; #endif } QList<QStringList> preferredCodecCombos; preferredCodecCombos << QString("audio/mpeg, video/x-h264, mp4").split(", "); preferredCodecCombos << QString("audio/vorbis, video/theora, ogg").split(", "); QStringList audioCodecs; QStringList videoCodecs; QStringList containers; foreach (QString codec, _mediaRecorder->supportedAudioCodecs ()) { #ifdef SHOW_DEBUG qDebug () << "Codec: " << codec; #endif audioCodecs << codec; } foreach (QString codec, _mediaRecorder->supportedVideoCodecs ()) { #ifdef SHOW_DEBUG qDebug () << "Codec: " << codec; #endif videoCodecs << codec; } foreach (QString container, _mediaRecorder->supportedContainers ()) { #ifdef SHOW_DEBUG qDebug () << "Container: " << container; #endif containers.append(container); } bool foundMatch = false; foreach (QStringList codecCombo, preferredCodecCombos) { #ifdef SHOW_DEBUG qDebug() << "tuple: " << codecCombo; qDebug() << "codecCombo[0]" << codecCombo[0]; #endif if (audioCodecs.contains(codecCombo[0]) && videoCodecs.contains(codecCombo[1]) && containers.contains(codecCombo[2])) { #ifdef SHOW_DEBUG qDebug() << "preferred tuple found: " << codecCombo; #endif foundMatch = true; audioSettings.setCodec(codecCombo[0]); videoSettings.setCodec(codecCombo[1]); _mediaRecorder->setEncodingSettings(audioSettings, videoSettings, codecCombo[2]); _videoFilenameExtension = codecCombo[2]; } } if (!foundMatch) { #ifdef SHOW_DEBUG qDebug() << "No codec combos found! pretending that ogg works"; #endif videoSettings.setCodec ("video/theora"); audioSettings.setCodec ("audio/vorbis"); _mediaRecorder->setEncodingSettings (audioSettings, videoSettings, "ogg"); _videoFilenameExtension = "ogg"; } #ifdef SHOW_DEBUG qDebug () << "Selected container: " << _mediaRecorder->containerMimeType (); #endif connect (_mediaRecorder, SIGNAL (stateChanged (QMediaRecorder::State)), this, SLOT (mediaRecorderStateChanged (QMediaRecorder::State))); connect (_mediaRecorder, SIGNAL (error (QMediaRecorder::Error)), this, SLOT (mediaRecorderError (QMediaRecorder::Error))); connect (_mediaRecorder, SIGNAL (durationChanged (qint64)), this, SLOT (mediaRecorderDurationChanged (qint64))); _imageCapture = new QCameraImageCapture (_camera); QList <QSize> resolutions; resolutions = _imageCapture->supportedResolutions (); QSize imageSize; if (!resolutions.isEmpty ()) { qSort (resolutions.begin (), resolutions.end (), compare_sizes); #ifdef SHOW_DEBUG foreach (QSize size, resolutions) { qDebug () << "Sorted resolution: " << size.width () << "x" << size.height (); } #endif imageSize = resolutions.first (); } else { imageSize = QSize (1280, 800); } QImageEncoderSettings imageSettings; imageSettings.setResolution (imageSize); _imageCapture->setEncodingSettings (imageSettings); #ifdef SHOW_DEBUG qDebug () << "Using resolution: " << _imageCapture->encodingSettings ().resolution ().width () << "x" << _imageCapture->encodingSettings ().resolution ().height (); #endif if (_viewFinder == 0) { _viewFinder = new QGraphicsVideoItem (this); _viewFinder->setVideoRenderingMode(VideoRenderingHintOverlay); } QRectF itemBounds = this->boundingRect (); QSize viewFinderSize(itemBounds.width(), itemBounds.height()); if (viewFinderSize.isEmpty()) viewFinderSize = QSize(1280, 800); _viewFinder->setSize (viewFinderSize); _viewFinder->setPos (0, 0); _camera->setViewfinder (_viewFinder); connect (_camera, SIGNAL (stateChanged (QCamera::State)), this, SLOT (updateCameraState (QCamera::State))); connect (_camera, SIGNAL (error (QCamera::Error)), this, SLOT (displayCameraError ())); connect (_camera, SIGNAL (lockStatusChanged (QCamera::LockStatus, QCamera::LockChangeReason)), this, SLOT (updateLockStatus (QCamera::LockStatus, QCamera::LockChangeReason))); connect (_camera, SIGNAL(locked()), this, SLOT(locked())); connect (_camera, SIGNAL(lockFailed()), this, SLOT(locked())); // still do a shot even if focus locking failed connect (_imageCapture, SIGNAL (imageCaptured (int, const QImage &)), this, SLOT (imageCaptured (int, const QImage &))); connect (_imageCapture, SIGNAL (imageSaved (int, const QString &)), this, SLOT (imageSaved (int, const QString &))); connect (_imageCapture, SIGNAL (error (int, QCameraImageCapture::Error, const QString &)), this, SLOT (imageCaptureError (int, QCameraImageCapture::Error, const QString &))); connect (_imageCapture, SIGNAL (readyForCaptureChanged (bool)), this, SLOT (imageReadyForCaptureChanged (bool))); connect( _imageCapture, SIGNAL(readyForCaptureChanged (bool)), this, SLOT(readyForCaptureChanged(bool))); // updateCameraState (_camera->state ()); updateLockStatus (_camera->lockStatus (), QCamera::UserRequest); imageReadyForCaptureChanged (_imageCapture->isReadyForCapture ()); mediaRecorderStateChanged (_mediaRecorder->state ()); // set focus mode QCameraFocus *cameraFocus(_camera->focus ()); if (cameraFocus->isFocusModeSupported(QCameraFocus::AutoFocus)) cameraFocus->setFocusMode(QCameraFocus::AutoFocus); if (cameraFocus->isFocusPointModeSupported(QCameraFocus::FocusPointCenter)) cameraFocus->setFocusPointMode(QCameraFocus::FocusPointCenter); // set capture mode from settings _camera->setCaptureMode (Video != _settings->captureMode () ? QCamera::CaptureStillImage : QCamera::CaptureVideo); _camera->start (); _started = true; // set the flag to avoid starting camera second time // Fire this on an idle so that the signal will be picked up when the // object has been created QTimer::singleShot(1000, this, SLOT(checkSpace ())); return true; } void ViewFinder::updateCameraState (QCamera::State state) { #ifdef SHOW_DEBUG qDebug () << "Updated state: " << state; #endif if (state != QCamera::ActiveState) { return; } _canFocus = _camera->focus ()->isAvailable (); emit canFocusChanged (); _canLockFocus = _canFocus && _camera->supportedLocks().testFlag(QCamera::LockFocus); if (_canLockFocus && 2 == _cameraCount && 1 == _currentCamera) // mrst hack: front camera doesn't support focus _canLockFocus = false; if (_canFocus) { _maxZoom = _camera->focus()->maximumDigitalZoom() * _camera->focus()->maximumOpticalZoom(); // Recalculate the zoom as relative to the current camera's max zoom if (_maxZoom > 1.0) _camera->focus ()->zoomTo (1.0 + (_zoom * _camera->focus ()->maximumOpticalZoom ()), 1.0); } else { _maxZoom = 1.; // zoom not supported } emit maxZoomChanged (); // Generate the flash menu _cameraHasFlash = _camera->exposure ()->isFlashModeSupported (QCameraExposure::FlashOn); emit cameraHasFlashChanged (); QStringList menu; _cameraHasAutoFlash = _camera->exposure ()->isFlashModeSupported (QCameraExposure::FlashAuto); if (_cameraHasAutoFlash) { menu.append ("Auto");//menu.append (tr ("Auto")); } menu.append ("Off");// menu.append (tr ("Off")); if (_cameraHasFlash) { menu.append ("On");//menu.append (tr ("On")); } _flashModel = QVariant::fromValue (menu); emit flashModelChanged (); if ((!_cameraHasFlash && Off != flashMode()) || (!_cameraHasAutoFlash && Auto == flashMode())) setFlashMode(Off); else setFlashMode(_settings->flashMode()); } void ViewFinder::onCameraStatusChanged(QCamera::Status status) { if(status == QCamera::ActiveStatus) emit cameraReady(); } void ViewFinder::displayCameraError () { qDebug () << "Camera error: " << _camera->errorString (); } void ViewFinder::updateLockStatus (QCamera::LockStatus status, QCamera::LockChangeReason reason) { #ifdef SHOW_DEBUG qDebug () << "Camera lock changed: " << status << " (Reason " << reason << ")"; #endif } void ViewFinder::takePhoto () { if (!ready()) return; _ready = false; QString filename = generateTemporaryImageFilename(); #ifdef SHOW_DEBUG qDebug () << "Filename: " << filename; #endif // FIXME: Use toUTF8? //_imageCapture->capture (filename.toAscii ()); photoThread.takePhoto(filename,_imageCapture); // save orientation here as device can be rotated during long snapshot operation _settings->setLastCapturedPhotoOrientation( _lastPhotoOrientation = currentOrientation()); } void ViewFinder::imageCaptured (int id, const QImage &preview) { Q_UNUSED(preview) #ifdef SHOW_DEBUG qDebug () << "Image captured: " << id; #endif //emit imageCapturedSig (); } void ViewFinder::completeImage () { QString filename = _futureWatcher.future().result(); #ifdef SHOW_DEBUG qDebug () << "Image completed: " << filename; #endif setImageLocation(filename); //_cameraService->emitImageCaptured (filename); } void ViewFinder::imageSaved (int id, const QString &filename) { _ready = _imageCapture->isReadyForCapture(); QString realFileName = generateImageFilename(); #ifdef SHOW_DEBUG qDebug () << "Image saved: " << id << " - " << filename; #endif QFuture<QString> future = QtConcurrent::run(addGeoTag, filename, realFileName, m_lastCoordinate, currentOrientation(), (currentCamera() == (cameraCount()-1)) ); _futureWatcher.setFuture(future); if (_canLockFocus) _camera->unlock(QCamera::LockFocus); } void ViewFinder::imageCaptureError (int id, QCameraImageCapture::Error error, const QString &message) { _ready = _imageCapture->isReadyForCapture(); if (error == QCameraImageCapture::OutOfSpaceError) { emit noSpaceOnDevice (); } #ifdef SHOW_DEBUG qDebug () << "Image error: " << id << " - " << message << "(" << error << ")"; #endif } void ViewFinder::readyForCaptureChanged(bool isReady) { _ready = isReady; if ( isReady ) emit imageCapturedSig (); } void ViewFinder::imageReadyForCaptureChanged (bool ready) { #ifdef SHOW_DEBUG qDebug () << "Image ready for capture: " << (ready ? "true" : "false"); #endif _ready = ready; emit readyChanged (); } /* void ViewFinder::checkSupportedFlashModes () { } */ void ViewFinder::setFlashMode (int mode) { QCameraExposure::FlashMode m = QCameraExposure::FlashOff; // This is an ugly hack to prevent the flash when the user-facing camera // is selected. Qt-mobility cannot associate a camera with a flash if (_currentCamera == 1 && Off != mode) { return; } switch (mode) { case ViewFinder::Off: m = QCameraExposure::FlashOff; break; case ViewFinder::On: m = QCameraExposure::FlashOn; break; case ViewFinder::Auto: m = QCameraExposure::FlashAuto; break; } #ifdef SHOW_DEBUG qDebug () << "Setting flash to " << mode << "(" << m << ")"; #endif _settings->setFlashMode ((ViewFinder::FlashMode) mode); _camera->exposure ()->setFlashMode (m); emit (flashModeChanged ()); } int ViewFinder::flashMode () { return _settings->flashMode (); } bool ViewFinder::changeCamera () { if (!ready()) { // wait for a ready state before allowing to change camera again as it leads to crash sometimes return false; } int nextCamera = _currentCamera + 1; if (nextCamera >= _cameraCount) { nextCamera = 0; } #ifdef SHOW_DEBUG qDebug () << "Switching from camera " << _currentCamera << " to " << nextCamera; #endif if (nextCamera == _currentCamera) { // If we're still on the same camera then we don't need to do anything return true; } int _lastCamera = _currentCamera; QByteArray strDev; if (setCamera (strDev = QCamera::availableDevices ()[_currentCamera = nextCamera]) == true) { _settings->setCameraDevice(strDev); #if 0 // Compiling this will pretend that the camera can focus. _canFocus = true; emit canFocusChanged (); #endif emit cameraChanged (); return true; } // error switching cameras _currentCamera = _lastCamera; return false; } void ViewFinder::setCaptureMode (ViewFinder::CaptureMode mode) { #ifdef SHOW_DEBUG qDebug () << "Setting capture mode: " << mode; #endif if (!_camera) return; if (policyAware()) { _bSkipCameraReset = true; // don't need to reset camera object just release and acquire resources needed release(); QTimer::singleShot(0, this, SLOT(acquire())); } switch (mode) { case ViewFinder::Still: #ifdef SHOW_DEBUG qDebug () << "Image capture"; #endif _camera->setCaptureMode (QCamera::CaptureStillImage); break; case ViewFinder::Video: #ifdef SHOW_DEBUG qDebug () << "Video capture"; #endif _camera->setCaptureMode (QCamera::CaptureVideo); break; default: #ifdef SHOW_DEBUG qDebug () << "Unknown capture mode"; #endif break; } _settings->setCaptureMode (mode); emit captureModeChanged (); } ViewFinder::CaptureMode ViewFinder::captureMode () { return _settings->captureMode (); } void ViewFinder::setZoom (qreal z) { if (!_canFocus || _maxZoom <= 1) // return if zoom is unsupported return; _zoom = z; _camera->focus ()->zoomTo (1.0 + (z * _camera->focus ()->maximumOpticalZoom ()), 1.0); #ifdef SHOW_DEBUG qDebug () << "Setting zoom to:" << _zoom; #endif emit zoomChanged (); } void ViewFinder::startRecording () { QString filename = generateVideoFilename (); QUrl url; #ifdef SHOW_DEBUG qDebug () << "Starting recording" << filename; #endif url = QUrl::fromLocalFile (filename); _currentLocation = url.toString (); emit capturedVideoLocationChanged(); _mediaRecorder->setOutputLocation (QUrl (filename)); // Check if we're running out of space every 5 seconds _freeSpaceCheckTimer = new QTimer (this); connect (_freeSpaceCheckTimer, SIGNAL (timeout ()), this, SLOT (checkSpace ())); _freeSpaceCheckTimer->start (5000); // _camera->searchAndLock (); _mediaRecorder->record (); setRecording (true); } void ViewFinder::endRecording () { QString mimetype = QString ("video/mpeg"); #ifdef SHOW_DEBUG qDebug () << "Ending recording"; #endif _freeSpaceCheckTimer->stop (); delete _freeSpaceCheckTimer; _freeSpaceCheckTimer = 0; setRecording (false); _mediaRecorder->stop (); //_camera->unlock (); _thumbnailer->requestThumbnail (_currentLocation, mimetype); } QString ViewFinder::generateTemporaryImageFilename () const { return QString("/var/tmp/%1").arg(generateBaseImageFilename ()); } QString ViewFinder::generateImageFilename () const { QString path(picturesDir() + '/'); return path.append(generateBaseImageFilename ()); } QString ViewFinder::generateBaseImageFilename () const { QDateTime now = QDateTime::currentDateTime (); return now.toString ("yyyy.MM.dd-hh.mm.ss'.jpg'"); } QString ViewFinder::generateVideoFilename () const { QString path(videosDir() + '/'); QDateTime now = QDateTime::currentDateTime (); return path.append (now.toString ("yyyy.MM.dd-hh.mm.ss")).append (".%1").arg(_videoFilenameExtension); } void ViewFinder::mediaRecorderStateChanged (QMediaRecorder::State state) { #ifdef SHOW_DEBUG qDebug () << "Media recorder state changed: " << state; #endif } void ViewFinder::mediaRecorderError (QMediaRecorder::Error error) { if (error == QMediaRecorder::ResourceError) { // We don't get a more specific error so it might be out of space checkSpace (); } #ifdef SHOW_DEBUG qDebug () << "Media recorder error: " << _mediaRecorder->errorString (); #endif } void ViewFinder::mediaRecorderDurationChanged (qint64 duration) { #ifdef SHOW_DEBUG qDebug () << "Duration: " << duration; #endif setDuration (duration); } QString ViewFinder::durationString() { qint64 val = _duration / 1000; return QObject::tr("%1:%2:%3").arg((val / 3600), 0).arg(((val % 3600) / 60), 2, 'g', -1, '0').arg((val % 60), 2, 'g', -1, '0'); } void ViewFinder::geometryChanged (const QRectF &newGeometry, const QRectF &oldGeometry) { #ifdef SHOW_DEBUG qDebug () << "Geometry changed: " << oldGeometry.width () << "x" << oldGeometry.height () << " -> " << newGeometry.width () << "x" << newGeometry.height (); #endif if (newGeometry != oldGeometry) if (newGeometry.width () > 0 && newGeometry.height () > 0) if(_viewFinder) _viewFinder->setSize(newGeometry.size().toSize()); QDeclarativeItem::geometryChanged (newGeometry, oldGeometry); } void ViewFinder::checkSpace () { QString homePath = QDir::homePath (); struct statvfs buf; if (statvfs (homePath.toAscii (), &buf) < 0) { #ifdef SHOW_DEBUG qDebug () << " Error stating filesystem"; #endif emit noSpaceOnDevice (); return; } #ifdef SHOW_DEBUG qDebug () << "Free space: " << buf.f_bsize * buf.f_bavail << "(" << buf.f_bavail << " * " << buf.f_bsize << ")"; #endif // Limit to 5mb space if (buf.f_bsize * buf.f_bavail < (1024 * 1024 * 5)) { #ifdef SHOW_DEBUG qDebug () << "No free space"; #endif emit noSpaceOnDevice (); return; } } void ViewFinder::thumbnailCreated (const QString &url, const QString &md5sum) { Q_UNUSED(url) _settings->setLastCapturedPhotoOrientation(1); // no rotation // find a thumbnail - need to look into dir as we don't know file extention QString strDir(QString("%1/.thumbnails/normal").arg (QDir::homePath ())); QDir d(strDir); QStringList list(d.entryList (QStringList() << (md5sum + ".*"))); setImageLocation(!list.isEmpty() ? strDir + '/' + list[0] : QString::null); #ifdef SHOW_DEBUG qDebug () << "Thumbnail completed: " << _imageLocation; #endif } void ViewFinder::thumbnailError (const QStringList &urls, const int &errorId, const QString &errorMessage) { Q_UNUSED(urls) qDebug () << "Thumbnail Error: " << errorMessage << "(" << errorId << ")"; } void ViewFinder::metadataAvailableChanged (bool avail) { #ifdef SHOW_DEBUG qDebug () << "Metadata available: " << avail; #endif } void ViewFinder::enterStandbyMode () { // check that camera is started and the application actualy lost focus if (_camera && _started && 0 == qApp->activeWindow ()) { _camera->stop (); _started = false; } } void ViewFinder::leaveStandbyMode () { // don't start camera if it's already started if (_camera && !_started && 0 != qApp->activeWindow ()) { _camera->start (); _started = true; } if (0 == _camera && policyAware()) { acquire(); } } void ViewFinder::setCurrentOrientation(int orientation) { _currentOrientation = orientation; emit currentOrientationChanged(); } void ViewFinder::setImageLocation(const QString & _str) { _imageLocation = _str; emit imageLocationChanged(); _settings->setLastCapturedPhotoPath(_imageLocation);} void ViewFinder::initResourcePolicy() { _resourceSet = new ResourcePolicy::ResourceSet("camera", this); _resourceSet->setAlwaysReply(); ResourcePolicy::VideoResource *videoResource = new ResourcePolicy::VideoResource(); // videoResource->setProcessID(QCoreApplication::applicationPid()); _resourceSet->addResourceObject(videoResource); _resourceSet->addResource(ResourcePolicy::VideoRecorderType); connect(_resourceSet, SIGNAL(resourcesGranted(const QList<ResourcePolicy::ResourceType>&)), this, SLOT(resourceAcquiredHandler(const QList<ResourcePolicy::ResourceType>&))); connect(_resourceSet, SIGNAL(lostResources()), this, SLOT(resourceLostHandler())); } void ViewFinder::acquire() { // for video capturing need both audio and video resources if (Video == captureMode()) { // audio playback should be limited during recording - we don't need other sounds to desturb video recording if (!_resourceSet->contains(ResourcePolicy::AudioPlaybackType)) { ResourcePolicy::AudioResource *audioResource = new ResourcePolicy::AudioResource("camera"); audioResource->setProcessID(QCoreApplication::applicationPid()); _resourceSet->addResourceObject(audioResource); _resourceSet->addResource(ResourcePolicy::AudioRecorderType); } } else { if (_resourceSet->contains(ResourcePolicy::AudioPlaybackType)) { _resourceSet->deleteResource(ResourcePolicy::AudioPlaybackType); _resourceSet->deleteResource(ResourcePolicy::AudioRecorderType); } } _resourceSet->acquire(); } void ViewFinder::release() { _resourceSet->release(); } void ViewFinder::resourceAcquiredHandler(const QList<ResourcePolicy::ResourceType> &) { if (_bSkipCameraReset) { _bSkipCameraReset = false; return; } if (_cameraCount > _currentCamera) { setCamera(QCamera::availableDevices()[_currentCamera]); } } void ViewFinder::resourceLostHandler() { // some other app requested to release all resources if (recording()) { endRecording(); } releaseCamera(); } void ViewFinder::startFocus() { if (_camera) { _camera->unlock(QCamera::LockFocus); _camera->searchAndLock(QCamera::LockFocus); } } void ViewFinder::locked() { if (_camera->requestedLocks().testFlag(QCamera::LockFocus)) { emit focusLocked(); } } //QML_DECLARE_TYPE(ViewFinder);
27.469178
166
0.677378
[ "geometry", "object" ]
30a9b75ff067479c45054caacdb425636e5834c1
1,486
cpp
C++
Medium/714 - Best Time to Buy and Sell Stock with Transaction Fee.cpp
WangZixuan/Leetcode
4593e8b48c4ce810567473a825735ffde3f7a0f0
[ "WTFPL" ]
11
2015-08-06T15:43:48.000Z
2022-02-16T01:30:24.000Z
Medium/714 - Best Time to Buy and Sell Stock with Transaction Fee.cpp
WangZixuan/Leetcode
4593e8b48c4ce810567473a825735ffde3f7a0f0
[ "WTFPL" ]
1
2015-08-17T13:33:55.000Z
2015-08-27T03:43:47.000Z
Medium/714 - Best Time to Buy and Sell Stock with Transaction Fee.cpp
WangZixuan/Leetcode
4593e8b48c4ce810567473a825735ffde3f7a0f0
[ "WTFPL" ]
2
2021-09-30T14:39:05.000Z
2021-10-02T11:02:20.000Z
/* Best Time to Buy and Sell Stock with Transaction Fee Your are given an array of integers prices, for which the i-th element is the price of a given stock on day i; and a non-negative integer fee representing a transaction fee. You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction. You may not buy more than 1 share of a stock at a time (ie. you must sell the stock share before you buy again.) Return the maximum profit you can make. Example 1: Input: prices = [1, 3, 2, 8, 4, 9], fee = 2 Output: 8 Explanation: The maximum profit can be achieved by: Buying at prices[0] = 1 Selling at prices[3] = 8 Buying at prices[4] = 4 Selling at prices[5] = 9 The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8. Note: 0 < prices.length <= 50000. 0 < prices[i] < 50000. 0 <= fee < 50000. @author Zixuan @date 2017/10/22 */ #include <vector> #include <algorithm> using namespace std; class Solution { public: int maxProfit(vector<int>& prices, int fee) { //Reference: https://discuss.leetcode.com/topic/107977/c-concise-solution-o-n-time-o-1-space //s0 = profit having no stock //s1 = profit having 1 stock //update s0 by selling the stock from s1, so s0 = max(s0, s1+p-fee); //update s1 by buying the stock from s0, so s1 = max(s1, s0-p); auto s0 = 0, s1 = -1000000; for (auto p : prices) { auto temp = s0; s0 = max(s0, s1 + p - fee); s1 = max(s1, temp - p); } return s0; } };
27.018182
173
0.66891
[ "vector" ]
30ad0ab986d1f788f54adab5bbeeb4d39c5e10b8
6,367
cxx
C++
src/AcdTileDim.cxx
fermi-lat/AcdUtil
0fc8537ebc7c90dec9cb4a72e1ee274b78dd1b09
[ "BSD-3-Clause" ]
null
null
null
src/AcdTileDim.cxx
fermi-lat/AcdUtil
0fc8537ebc7c90dec9cb4a72e1ee274b78dd1b09
[ "BSD-3-Clause" ]
null
null
null
src/AcdTileDim.cxx
fermi-lat/AcdUtil
0fc8537ebc7c90dec9cb4a72e1ee274b78dd1b09
[ "BSD-3-Clause" ]
null
null
null
// File and Version information: // $Header: /nfs/slac/g/glast/ground/cvs/AcdUtil/src/AcdTileDim.cxx,v 1.17.162.1 2009/06/08 17:14:04 echarles Exp $ // // Implementation file of AcdTileDim // // Authors: // // Eric Charles // // #include "AcdUtil/AcdTileDim.h" #include "GlastSvc/GlastDetSvc/IGlastDetSvc.h" #include "CLHEP/Geometry/Transform3D.h" AcdTileSection::AcdTileSection() :m_trapezoid(false), m_xmean(0.), m_xdiff(0.), m_shared(-1), m_sharedWidth(0.){ } double AcdTileSection::widthAtLocalY(double localY) const { if ( m_trapezoid ) { return m_xmean + m_xdiff * ( localY / m_dim[1] ); } return m_dim[0]; } void AcdTileSection::activeDistance(const HepPoint3D& localPoint, int iVol, double& activeX, double& activeY) const { activeX = (widthAtLocalY(localPoint.y())/2.) - fabs(localPoint.x() - m_xdiff); activeY = (m_dim[1]/2.) - fabs(localPoint.y()); // If no shared edges, we are done if ( m_shared < 0 ) return; // first make sure that it actually hit the tile piece if ( activeY < 0. ) return; // Ok, it hit the tile. Correct for the fact that it bends around if ( iVol == 0 ) { // top, check for hitting near bent tile if ( m_shared == 1 && localPoint.y() > 0 ) { // hit +Y side of TOP tile near +Y edge, // add the extra size of the bent piece activeY += fabs(m_sharedWidth); } else if ( m_shared == 3 && localPoint.y() < 0 ) { // hit -Y side of TOP tile near -Y edge, // add the extra size of the bent piece activeY += fabs(m_sharedWidth); } } else if ( iVol == 1 ) { // side, check for hitting near top tile if ( m_shared == 1 && localPoint.y() > 0 ) { // hit upper part of BENT piece on -Y side ( local Y goes UP ) // is a shared piece. but this is a short side, so take the distance to the // other side of this volume activeY = (m_dim[1]/2.) + localPoint.y(); } else if ( m_shared == 3 && localPoint.y() < 0 ) { // hit upper part of BENT piece on +Y side ( local Y goes DOWN ) // is a shared piece. but this is a short side, so take the distance to the // other side of this volume activeY = (m_dim[1]/2.) - localPoint.y(); } } } /// Constructor: takes the tile id, the volume id, and the detector service AcdTileDim::AcdTileDim(const idents::AcdId& acdId, IAcdGeometrySvc& acdGeomSvc) :m_acdId(acdId), m_acdGeomSvc(acdGeomSvc), m_doneGaps(false){ m_minusXGap[0] = 0.; m_minusXGap[1] = 0.; m_plusXGap[0] = 0.; m_plusXGap[1] = 0.; m_sc = getVals(); } AcdTileDim::~AcdTileDim() { for ( std::vector<AcdTileSection*>::iterator itr = m_sections.begin(); itr != m_sections.end(); itr++ ) { AcdTileSection* sect = *itr; delete sect; } } /// this function access the detector service to get the geometry information StatusCode AcdTileDim::getVals() { std::map<idents::AcdId, int>::const_iterator itrFind = m_acdGeomSvc.getAcdIdVolCountCol().find(m_acdId); if ( itrFind == m_acdGeomSvc.getAcdIdVolCountCol().end() ) { return StatusCode::FAILURE; } int nVol = itrFind->second; bool isOk = m_acdGeomSvc.fillScrewHoleData(m_acdId,m_screwHoles); if ( ! isOk ) return StatusCode::FAILURE; for ( int iVol(0); iVol < nVol; iVol++ ) { AcdTileSection* sect = new AcdTileSection; sect->m_dim.clear(); isOk = m_acdGeomSvc.fillTileData(m_acdId,iVol,sect->m_trans,sect->m_dim,sect->m_center,sect->m_corners); if ( ! isOk ) { std::cerr << "Failed to fillTileData " << m_acdId.id() << ' ' << iVol << std::endl; return StatusCode::FAILURE; } sect->m_invTrans = sect->m_trans.inverse(); if ( sect->m_dim.size() == 5 ) { sect->m_trapezoid = true; sect->m_xmean = sect->m_dim[0] + sect->m_dim[3]; sect->m_xmean /= 2.; sect->m_xdiff = sect->m_dim[4]; }else { sect->m_trapezoid = false; sect->m_xmean = 0.; sect->m_xdiff = 0.; } m_sections.push_back(sect); } if ( nVol == 2 ) { isOk = m_acdGeomSvc.fillTileSharedEdgeData(m_acdId,m_sections[0]->m_dim,m_sections[1]->m_dim, m_sections[0]->m_shared, m_sections[0]->m_shared, m_sections[0]->m_sharedWidth,m_sections[1]->m_sharedWidth); } if ( ! isOk ) return StatusCode::FAILURE; return StatusCode::SUCCESS; } StatusCode AcdTileDim::latchGaps() { if ( m_doneGaps ) return StatusCode::SUCCESS; if ( m_sections.size() == 0 ) return StatusCode::FAILURE; const AcdTileSection* sect = m_sections[0]; HepPoint3D c1, c2, l1, l2; double aX(0.), aY(0.); bool isRealGap(false); if ( m_acdGeomSvc.getNextTileCorners( m_acdId, -1, c1, c2, isRealGap) != StatusCode::SUCCESS ) { return StatusCode::FAILURE; } if ( isRealGap ) { l1 = sect->m_trans * c1; l2 = sect->m_trans * c2; sect->activeDistance(l1,0,aX,aY); m_minusXGap[0] = aX < 0 ? -1. * aX : 0; sect->activeDistance(l2,0,aX,aY); m_minusXGap[1] = aX < 0 ? -1. * aX : 0; } if ( m_acdGeomSvc.getNextTileCorners( m_acdId, 1, c1, c2, isRealGap) != StatusCode::SUCCESS ) { return StatusCode::FAILURE; } if ( isRealGap ) { l1 = sect->m_trans * c1; l2 = sect->m_trans * c2; sect->activeDistance(l1,0,aX,aY); m_plusXGap[0] = aX < 0 ? -1. * aX : 0; sect->activeDistance(l2,0,aX,aY); m_plusXGap[1] = aX < 0 ? -1. * aX : 0; } m_doneGaps = true; return StatusCode::SUCCESS; } float AcdTileDim::gapAtLocalY(int side, double localY) const { float gap = 0.; float yFrac = localY / m_sections[0]->m_dim[1]; yFrac += 0.5; float yFrac2 = 1. - yFrac; switch ( side ) { case -1: gap += m_minusXGap[0] * yFrac2; gap += m_minusXGap[1] * yFrac; break; case 1: gap += m_plusXGap[0] * yFrac2; gap += m_plusXGap[1] * yFrac; break; } if ( gap > 20. ) { std::cout << "Gap at LocalY " << side << ' ' << localY << ' ' << yFrac << ' ' << yFrac2 << std::endl; std::cout << m_minusXGap[0] << ' ' << m_minusXGap[1] << ' ' << gap << std::endl; std::cout << m_plusXGap[0] << ' ' << m_plusXGap[1] << ' ' << gap << std::endl; } return gap; } float AcdTileDim::gapSize(const HepPoint3D& localPoint, int iVol) const { if ( iVol == 1 ) { return 0.; } return gapAtLocalY( (localPoint.x() < 0 ? -1 : 1) , localPoint.y() ); }
29.892019
117
0.611748
[ "geometry", "vector" ]
30b37ea023b899ecb80705e89249229725de12bc
1,478
cc
C++
onnxruntime/core/providers/nuphar/runtime/compute_ctx.cc
dennyac/onnxruntime
d5175795d2b7f2db18b0390f394a49238f814668
[ "MIT" ]
6,036
2019-05-07T06:03:57.000Z
2022-03-31T17:59:54.000Z
onnxruntime/core/providers/nuphar/runtime/compute_ctx.cc
dennyac/onnxruntime
d5175795d2b7f2db18b0390f394a49238f814668
[ "MIT" ]
5,730
2019-05-06T23:04:55.000Z
2022-03-31T23:55:56.000Z
onnxruntime/core/providers/nuphar/runtime/compute_ctx.cc
dennyac/onnxruntime
d5175795d2b7f2db18b0390f394a49238f814668
[ "MIT" ]
1,566
2019-05-07T01:30:07.000Z
2022-03-31T17:06:50.000Z
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "core/providers/nuphar/runtime/compute_ctx.h" namespace onnxruntime { namespace nuphar { KernelComputeCtx::KernelComputeCtx( const nuphar::NupharRuntimeHandle* handle, std::unordered_map<std::string, int64_t>& realized_dims, DataAllocFunc data_alloc_func, int allocator_offset_count) : data_alloc_func_(data_alloc_func), handle_(handle), realized_dims_(realized_dims) { internal_ort_buffer_unique_ptrs_.resize(allocator_offset_count); } void KernelComputeCtx::CreateFuncComputeCtx(const NupharFuncInfo* func_info, bool with_update) { ORT_ENFORCE_DEBUG(nullptr != func_info); if (func_compute_ctx_map_.find(func_info) == func_compute_ctx_map_.end()) { func_compute_ctx_map_.emplace(func_info, FuncComputeCtx()); } FuncComputeCtx& func_compute_ctx = func_compute_ctx_map_.at(func_info); size_t num_input = func_info->ort_input_allocators.size(); std::vector<const void*>& ort_input_data = func_compute_ctx.ort_input_data; std::vector<const int64_t*>& ort_input_shapes = func_compute_ctx.ort_input_shapes; ort_input_data.resize(num_input); ort_input_shapes.resize(num_input); // with_update is set false to create a bunch of ctx in advance and then update later. // e.g. in model_parallelism if (with_update) { UpdateFuncComputeCtx(func_info); } } } // namespace nuphar } // namespace onnxruntime
33.590909
96
0.773342
[ "vector" ]
30be16f4d89a46587a38c03dbddccd3d51896280
706
hpp
C++
Firstgraphicsproject/Ball.hpp
Style22/Tulika-Brick-Breaker
34a3b35b62e6f688fc78a4c8f8355c280b6971ef
[ "MIT" ]
null
null
null
Firstgraphicsproject/Ball.hpp
Style22/Tulika-Brick-Breaker
34a3b35b62e6f688fc78a4c8f8355c280b6971ef
[ "MIT" ]
null
null
null
Firstgraphicsproject/Ball.hpp
Style22/Tulika-Brick-Breaker
34a3b35b62e6f688fc78a4c8f8355c280b6971ef
[ "MIT" ]
null
null
null
#pragma once #include <SFML/Graphics.hpp> #include "Paddle.hpp" class Ball { public: Ball(); Ball(sf::Texture* texture); std::string lastCollision = "wall"; int* gameState; float speed = 500; float boundryX = 800; //float boundryX = 650; float boundryY = 600; float angle = 0; float maxAngleOfReflection = 0.6f; sf::Vector2f velocity; sf::Vector2f direction; sf::Sprite ballSprite; //position of object sf::Vector2f position; int lastHitIDS[2]; //object rectangle sf::FloatRect rect; Paddle* paddle; // debug bool drawDebug = false; sf::RectangleShape debugRectangle; //function update void update(float deltaTime); //function draw void draw(sf::RenderWindow* window); };
16.809524
37
0.709632
[ "object" ]
30c1b2fa00a0ce6c0ae8d6f162fed1d142a5dc89
1,937
cpp
C++
src/bvh.cpp
cdyk/toytrace
f542d24d38c9a7414a7a846c88958fe4ba8ca8c5
[ "MIT" ]
null
null
null
src/bvh.cpp
cdyk/toytrace
f542d24d38c9a7414a7a846c88958fe4ba8ca8c5
[ "MIT" ]
null
null
null
src/bvh.cpp
cdyk/toytrace
f542d24d38c9a7414a7a846c88958fe4ba8ca8c5
[ "MIT" ]
null
null
null
#include <algorithm> #include <cassert> #include "bvh.h" namespace { struct sort_item { float key; unsigned index; }; } bvh::bvh(const std::vector<intersectable*>& items, float t0, float t1, unsigned axis) { unsigned N = unsigned(items.size()); if (N == 1) { children[0] = items[0]; bbox = children[0]->bounding_box(t0, t1); return; } std::vector<sort_item> sort_items(N); for (unsigned i = 0; i < N; i++) { auto item_bbox = items[i]->bounding_box(t0, t1); bbox.include(item_bbox); assert(!item_bbox.empty()); sort_items[i].key = item_bbox.min[axis] + item_bbox.max[axis]; sort_items[i].index = i; } std::sort(sort_items.begin(), sort_items.end(), [](const sort_item & a, const sort_item & b) { return a.key < b.key; }); if (N == 2) { children[0] = items[sort_items[0].index]; children[1] = items[sort_items[1].index]; return; } auto M = N / 2; std::vector<intersectable*> tmp; tmp.reserve(M + 1); tmp.resize(M); for (unsigned i = 0; i < M; i++) { tmp[i] = items[sort_items[i].index]; } children[0] = new bvh(tmp, t0, t1, (axis + 1)%3); tmp.resize(N-M); for (unsigned i = M; i < N; i++) { tmp[i-M] = items[sort_items[i].index]; } children[1] = new bvh(tmp, t0, t1, (axis + 1)%3); } bool bvh::intersect(const ray& r, float t_min, float t_max, intersection& isec) const { if (bbox.intersects(r, t_min, t_max) == false) return false; intersection isec_l, isec_r; bool hit_l = children[0]->intersect(r, t_min, t_max, isec_l); bool hit_r = children[1] && children[1]->intersect(r, t_min, t_max, isec_r); if (hit_l && hit_r) { isec = isec_l.t < isec_r.t ? isec_l : isec_r; return true; } else if (hit_l) { isec = isec_l; return true; } else if (hit_r) { isec = isec_r; return true; } return false; } aabb bvh::bounding_box(float time0, float time1) const { return bbox; }
21.764045
122
0.606608
[ "vector" ]
30c3412ca670561943a45d7b1be1731908625c2b
984
cpp
C++
test/euler_tour.aoj.GRL_5_D.test.cpp
yoshnary/cplib
41611c1cf8fd7118cb31ed533adcf2dc323a400a
[ "MIT" ]
null
null
null
test/euler_tour.aoj.GRL_5_D.test.cpp
yoshnary/cplib
41611c1cf8fd7118cb31ed533adcf2dc323a400a
[ "MIT" ]
2
2020-05-09T10:31:59.000Z
2020-06-18T18:31:52.000Z
test/euler_tour.aoj.GRL_5_D.test.cpp
yoshnary/cplib
41611c1cf8fd7118cb31ed533adcf2dc323a400a
[ "MIT" ]
null
null
null
#define PROBLEM "https://onlinejudge.u-aizu.ac.jp/courses/library/5/GRL/5/GRL_5_D" #include <iostream> #include "../lib/euler_tour.hpp" #include "../lib/segment_tree.hpp" int main() { int n; std::cin >> n; std::vector<std::vector<int>> edg(n); for (int i = 0; i < n; i++) { int k; std::cin >> k; for (int j = 0; j < k; j++) { int c; std::cin >> c; edg[i].push_back(c); edg[c].push_back(i); } } EulerTourE et(edg, 0); SegmentTree<long long> seg(2*n, std::plus<long long>(), 0); int q; std::cin >> q; while (q--) { int com, v; std::cin >> com >> v; if (com) { std::cout << seg.getval(0, et.left[v] + 1) << std::endl; } else { int w; std::cin >> w; long long val = seg.getval(et.left[v], et.left[v] + 1) + w; seg.update(et.left[v], val); seg.update(et.right[v], -val); } } return 0; }
28.114286
82
0.473577
[ "vector" ]
30d288f63f03db46374f0ec142a42117cce30cad
4,450
cc
C++
DreamDaq/dream_to_offline/dream2root.cc
ivivarel/DREMTubes
ac768990b4c5e2c23d986284ed10189f31796b38
[ "MIT" ]
3
2021-07-22T12:17:48.000Z
2021-07-27T07:22:54.000Z
DreamDaq/dream_to_offline/dream2root.cc
ivivarel/DREMTubes
ac768990b4c5e2c23d986284ed10189f31796b38
[ "MIT" ]
38
2021-07-14T15:41:04.000Z
2022-03-29T14:18:20.000Z
DreamDaq/dream_to_offline/dream2root.cc
ivivarel/DREMTubes
ac768990b4c5e2c23d986284ed10189f31796b38
[ "MIT" ]
7
2021-07-21T12:00:33.000Z
2021-11-13T10:45:30.000Z
#include <cassert> #include <cstring> #include <cstdlib> #include <iostream> #include <unistd.h> #include "TROOT.h" #include "TFile.h" #include "TTree.h" #include "myRawFile.h" #include "DreamRunInfo.h" #include "DreamDaqEvent.h" #include "DreamDaqEventUnpacker.hh" #include "DreamRawEventBrowser.hh" #include "dream_md5.h" #define EVENT_BUFFER_LEN 10000 using namespace std; void print_usage(const char *prog) { cout << "\nUsage: " << prog << " inputFile outputFile\n" << endl; } int main(int argc, char *argv[]) { DreamDaqEvent *event = 0; DreamDaqEventUnpacker *unpacker = 0; int status = EXIT_FAILURE; char *progname = strrchr(argv[0], '/'); if (progname) ++progname; else progname = argv[0]; if (argc != 3) { print_usage(progname); exit(EXIT_FAILURE); } const char *inputFile = argv[1]; const char *outputFile = argv[2]; // Open the input file if (RawFileOpen(inputFile)) exit(EXIT_FAILURE); // Initialize ROOT TROOT root("dream2root", "DREAM raw to root converter"); // Open the output file TFile ofile(outputFile, "RECREATE"); if (!ofile.IsOpen()) { cerr << "Failed to open file " << outputFile << endl; exit(EXIT_FAILURE); } // Build the event tree TTree *tree = new TTree("Events", "DREAM Event Data"); tree->Branch("Event", "DreamDaqEvent", &event, 64000); // Process events unsigned buf[EVENT_BUFFER_LEN]; unsigned event_count, daqDataFormatVersion, runNumber; for (event_count=0;;++event_count) { const int evsize = RawFileReadEventData(buf); if (evsize == RAWDATAEOF) { status = EXIT_SUCCESS; break; } else if (evsize == RAWDATAUNEXPECTEDEOF) { cerr << "ERROR: unexpected EOF at event " << event_count << " in file " << inputFile << endl; break; } else assert(evsize <= EVENT_BUFFER_LEN); // Collect the run info after we read the first event if (event_count == 0) { unsigned char md5[16]; const int md5status = md5_file_digest(inputFile, md5); assert(md5status == 0); // printf("md5sum is "); // for (unsigned j = 0; j < 16; ++j) { // printf("%02x", md5[j]); // } // printf("\n"); std::vector<unsigned> moduleSequence; const int seqStaus = DreamRawEventBrowser::subEventSequence( (unsigned char *)buf, evsize, &moduleSequence); if (seqStaus) { cerr << "ERROR: the first event in file " << inputFile << " is corrupt" << endl; ofile.Close(); unlink(outputFile); exit(EXIT_FAILURE); } // printf("ID sequence is:"); // for (unsigned i=0; i<moduleSequence.size(); ++i) // printf(" 0x%08x", *(&moduleSequence[0] + i)); // printf("\n"); runNumber = GetRunNumber(); // Here, we need to figure out the data format version. daqDataFormatVersion = 0; DreamRunInfo run("RunInfo", "DREAM Run Info", daqDataFormatVersion, runNumber, GetBegTime(), GetEndTime(), GetTotEvts(), &moduleSequence[0], moduleSequence.size(), md5); run.Write(); // Build the event event = new DreamDaqEvent(daqDataFormatVersion); // Associate an event unpacker with the event unpacker = new DreamDaqEventUnpacker(event); } // Collect the event info event->reset(); event->runNumber = runNumber; event->eventNumber = GetEventNumber(); event->spillNumber = GetSpillNumber(); event->timeSec = GetEventTimes(); event->timeUSec = GetEventTimeu(); if (unpacker->unpack(buf)) cerr << "ERROR: failed to unpack event " << event_count << " in file " << inputFile << endl; tree->Fill(); } RawFileClose(); ofile.Write(); ofile.Close(); cout << "Wrote " << event_count << " events to file " << outputFile << endl; exit(status); }
27.987421
72
0.538202
[ "vector" ]
30dfb60ae07915a582409bdb556155a7a4dfe71c
1,084
cpp
C++
leetcode/sliding_window/fruit_baskets.cpp
codingpotato/algorithm-cpp
793dc9e141000f48ea19c77ef0047923a7667358
[ "MIT" ]
null
null
null
leetcode/sliding_window/fruit_baskets.cpp
codingpotato/algorithm-cpp
793dc9e141000f48ea19c77ef0047923a7667358
[ "MIT" ]
null
null
null
leetcode/sliding_window/fruit_baskets.cpp
codingpotato/algorithm-cpp
793dc9e141000f48ea19c77ef0047923a7667358
[ "MIT" ]
null
null
null
#include <doctest/doctest.h> #include <map> #include <vector> // 904. Fruit Into Baskets class Solution { public: int totalFruit(const std::vector<int>& tree) { std::map<int, int> map; int size = tree.size(); int left = 0; int right = 0; map[tree[0]] = 0; int max = 0; while (right < size) { if (map.size() <= 2) { max = std::max(max, right - left + 1); ++right; if (right < size) { map[tree[right]] = right; } } else { int key = 0; int min_index = tree.size(); for (auto& kv : map) { if (kv.second < min_index) { key = kv.first; min_index = std::min(min_index, kv.second); } } left = min_index + 1; map.erase(key); } } return max; } }; TEST_CASE("Fruit Into Baskets") { Solution s; REQUIRE_EQ(s.totalFruit({1, 2, 1}), 3); REQUIRE_EQ(s.totalFruit({0, 1, 2, 2}), 3); REQUIRE_EQ(s.totalFruit({1, 2, 3, 2, 2}), 4); REQUIRE_EQ(s.totalFruit({3, 3, 3, 1, 2, 1, 1, 2, 3, 3, 4}), 5); }
23.06383
65
0.5
[ "vector" ]
30e2f08e58adfe2c18d8e172af692c06e5ac70cd
2,153
cpp
C++
dev/test-soundcube/src/testApp.cpp
YCAMInterlab/RAMDanceToolkit
5db15135f4ad6f6a9116610b909df99036f74797
[ "Apache-2.0" ]
52
2015-01-13T05:17:23.000Z
2021-05-09T14:09:39.000Z
dev/test-soundcube/src/testApp.cpp
YCAMInterlab/RAMDanceToolkit
5db15135f4ad6f6a9116610b909df99036f74797
[ "Apache-2.0" ]
7
2015-01-12T10:25:14.000Z
2018-09-18T12:34:15.000Z
dev/test-soundcube/src/testApp.cpp
YCAMInterlab/RAMDanceToolkit
5db15135f4ad6f6a9116610b909df99036f74797
[ "Apache-2.0" ]
31
2015-01-12T06:39:15.000Z
2020-04-06T07:05:08.000Z
#include "testApp.h" #include "SoundCube.h" ramSceneManager SM; SoundCube soundCube; #pragma mark - oF methods //-------------------------------------------------------------- void testApp::setup() { ofSetFrameRate(60); ofSetVerticalSync(true); ofBackground(ramColor::WHITE); /// ram setup // ------------------ ramInitialize(10000); vector<ramBaseScene*> scenes; scenes.push_back(soundCube.getPtr()); SM.setup(scenes); } //-------------------------------------------------------------- void testApp::update() { SM.update(); } //-------------------------------------------------------------- void testApp::draw() { SM.draw(); ramBeginCamera(); // ramPhysics::instance().debugDraw(); ramEndCamera(); } #pragma mark - ram methods //-------------------------------------------------------------- void testApp::drawActor(const ramActor &actor) { ramEnablePhysicsPrimitive(); ramDrawBasicActor(actor); } //-------------------------------------------------------------- void testApp::drawRigid(const ramRigidBody &rigid) { } #pragma mark - oF Events //-------------------------------------------------------------- void testApp::keyPressed(int key) { } //-------------------------------------------------------------- void testApp::keyReleased(int key) { } //-------------------------------------------------------------- void testApp::mouseMoved(int x, int y) { } //-------------------------------------------------------------- void testApp::mouseDragged(int x, int y, int button) { } //-------------------------------------------------------------- void testApp::mousePressed(int x, int y, int button) { } //-------------------------------------------------------------- void testApp::mouseReleased(int x, int y, int button) { } //-------------------------------------------------------------- void testApp::windowResized(int w, int h) { } //-------------------------------------------------------------- void testApp::gotMessage(ofMessage msg) { } //-------------------------------------------------------------- void testApp::dragEvent(ofDragInfo dragInfo) { }
17.941667
64
0.385044
[ "vector" ]
30e5f29ff8e176cc1f4e505de90b0913e01ad51e
5,651
cpp
C++
common/tests/TextConversionTests.cpp
clayne/micro-profiler
7b0e01f8ae8a8cdb6600b23d4dd5b7422c464c7b
[ "MIT" ]
194
2015-07-27T09:54:24.000Z
2022-03-21T20:50:22.000Z
common/tests/TextConversionTests.cpp
clayne/micro-profiler
7b0e01f8ae8a8cdb6600b23d4dd5b7422c464c7b
[ "MIT" ]
63
2015-08-19T16:42:33.000Z
2022-02-22T20:30:49.000Z
common/tests/TextConversionTests.cpp
clayne/micro-profiler
7b0e01f8ae8a8cdb6600b23d4dd5b7422c464c7b
[ "MIT" ]
33
2015-08-21T17:48:03.000Z
2022-02-23T03:54:17.000Z
#include <common/formatting.h> #include <ut/assert.h> #include <ut/test.h> using namespace std; namespace micro_profiler { namespace tests { namespace { template <unsigned char base, typename T> string itoa_s(T value, char min_width = 0, char padding = ' ') { string result(4, ' '); itoa<base>(result, value, min_width, padding); assert_is_true(result.size() > 4); return result.substr(4); } template <unsigned char base, typename T> string itoa_v(T value) { vector<char> vresult(10); itoa<base>(vresult, value); assert_is_true(vresult.size() > 10); return string(vresult.begin() + 10, vresult.end()); } } begin_test_suite( TextConversionTests ) test( ZeroIsConvertedToZeroCharacter ) { // ACT / ASSERT assert_equal("0", itoa_s<10>(static_cast<char>(0))); assert_equal("0", itoa_v<10>(static_cast<char>(0))); assert_equal("0", itoa_s<10>(static_cast<unsigned char>(0))); assert_equal("0", itoa_v<10>(static_cast<unsigned char>(0))); assert_equal("0", itoa_s<10>(static_cast<short>(0))); assert_equal("0", itoa_v<10>(static_cast<short>(0))); assert_equal("0", itoa_s<10>(static_cast<unsigned short>(0))); assert_equal("0", itoa_v<10>(static_cast<unsigned short>(0))); assert_equal("0", itoa_s<10>(static_cast<int>(0))); assert_equal("0", itoa_v<10>(static_cast<int>(0))); assert_equal("0", itoa_s<10>(static_cast<unsigned int>(0))); assert_equal("0", itoa_v<10>(static_cast<unsigned int>(0))); assert_equal("0", itoa_s<10>(static_cast<long>(0))); assert_equal("0", itoa_v<10>(static_cast<long>(0))); assert_equal("0", itoa_s<10>(static_cast<unsigned long>(0))); assert_equal("0", itoa_v<10>(static_cast<unsigned long>(0))); assert_equal("0", itoa_s<10>(static_cast<long long>(0))); assert_equal("0", itoa_v<10>(static_cast<long long>(0))); assert_equal("0", itoa_s<10>(static_cast<unsigned long long>(0))); assert_equal("0", itoa_v<10>(static_cast<unsigned long long>(0))); } test( OneIsConvertedToCharacterOne ) { // ACT / ASSERT assert_equal("1", itoa_s<2>(1)); assert_equal("1", itoa_v<3>(1)); assert_equal("1", itoa_s<4>(1)); assert_equal("1", itoa_v<5>(1)); assert_equal("1", itoa_s<6>(1)); assert_equal("1", itoa_v<7>(1)); assert_equal("1", itoa_s<8>(1)); assert_equal("1", itoa_v<9>(1)); assert_equal("1", itoa_s<10>(1)); assert_equal("1", itoa_v<11>(1)); assert_equal("1", itoa_v<12>(1)); assert_equal("1", itoa_s<13>(1)); assert_equal("1", itoa_v<14>(1)); assert_equal("1", itoa_s<15>(1)); assert_equal("1", itoa_v<16>(1)); } test( TenIsConvertedToOneZeroForAllBases ) { // ACT / ASSERT assert_equal("10", itoa_s<2>(2)); assert_equal("10", itoa_v<3>(3)); assert_equal("10", itoa_s<4>(4)); assert_equal("10", itoa_v<5>(5)); assert_equal("10", itoa_s<6>(6)); assert_equal("10", itoa_v<7>(7)); assert_equal("10", itoa_s<8>(8)); assert_equal("10", itoa_v<9>(9)); assert_equal("10", itoa_s<10>(10)); assert_equal("10", itoa_v<11>(11)); assert_equal("10", itoa_v<12>(12)); assert_equal("10", itoa_s<13>(13)); assert_equal("10", itoa_v<14>(14)); assert_equal("10", itoa_s<15>(15)); assert_equal("10", itoa_v<16>(16)); } test( RoundNumbersAreConvertedWithAccordingAmountOfZeroes ) { // ACT / ASSERT assert_equal("100", itoa_s<2>(4)); assert_equal("1000", itoa_s<2>(8)); assert_equal("10000", itoa_s<2>(16)); assert_equal("100000", itoa_s<2>(32)); assert_equal("1000000", itoa_s<2>(64)); assert_equal("10000000", itoa_s<2>(128)); assert_equal("100000000", itoa_s<2>(256)); assert_equal("100", itoa_s<3>(9)); assert_equal("1000", itoa_s<3>(27)); } test( HexDigitsAreAllConverted ) { // ACT / ASSERT assert_equal("2", itoa_s<16>(2)); assert_equal("3", itoa_s<16>(3)); assert_equal("4", itoa_s<16>(4)); assert_equal("5", itoa_s<16>(5)); assert_equal("6", itoa_s<16>(6)); assert_equal("7", itoa_s<16>(7)); assert_equal("8", itoa_s<16>(8)); assert_equal("9", itoa_s<16>(9)); assert_equal("A", itoa_s<16>(10)); assert_equal("B", itoa_s<16>(11)); assert_equal("C", itoa_s<16>(12)); assert_equal("D", itoa_s<16>(13)); assert_equal("E", itoa_s<16>(14)); assert_equal("F", itoa_s<16>(15)); } test( ArbitraryNumbersAreConverted ) { // ACT / ASSERT assert_equal("12272", itoa_s<8>(012272)); assert_equal("31415926", itoa_s<10>(31415926)); assert_equal("BAADF00D", itoa_s<16>(0xBAADF00D)); } test( NegativeNumbersAreConvertedAccordinglyToTheBase ) { // ACT / ASSERT assert_equal("-22272", itoa_s<8>(-022272)); assert_equal("-31415926", itoa_s<10>(-31415926)); assert_equal("-3AADF00D", itoa_s<16>(-0x3AADF00D)); } test( PaddingSymbolIsAppliedForAsManyTimesAsRequested ) { // ACT / ASSERT assert_equal("0012272", itoa_s<8>(012272, 7, '0')); assert_equal(" 31415926", itoa_s<10>(31415926, 9, ' ')); assert_equal("....BDFD", itoa_s<16>(0xBDFD, 8, '.')); } test( PaddingSymbolIsNotAppliedIfDigitsExceedPadding ) { // ACT / ASSERT assert_equal("12272", itoa_s<8>(012272, 1, '0')); assert_equal("31415926", itoa_s<10>(31415926, 3, 'z')); assert_equal("BDFD", itoa_s<16>(0xBDFD, 2, '.')); } test( MinusSignIsConsideredWhenApplyingPadding ) { // ACT / ASSERT assert_equal("-12272", itoa_s<10>(-12272, 6, '0')); assert_equal("-031415926", itoa_s<10>(-31415926, 10, '0')); } end_test_suite } }
29.279793
70
0.624314
[ "vector" ]
30eae86a1b25b47c39779dd6a802f11ed9420423
3,279
hh
C++
include/ftk/basic/contour_tree.hh
jiayixu64/ftk
f975db300a4ec87fcda06a625a217283e777fd87
[ "MIT" ]
1
2019-04-18T16:05:08.000Z
2019-04-18T16:05:08.000Z
include/ftk/basic/contour_tree.hh
jiayixu64/ftk
f975db300a4ec87fcda06a625a217283e777fd87
[ "MIT" ]
null
null
null
include/ftk/basic/contour_tree.hh
jiayixu64/ftk
f975db300a4ec87fcda06a625a217283e777fd87
[ "MIT" ]
1
2019-04-17T17:31:23.000Z
2019-04-17T17:31:23.000Z
#ifndef _FTK_CONTOUR_TREE_H #define _FTK_CONTOUR_TREE_H #include <set> #include <map> namespace ftk { template <class IdType> struct contour_tree { void add_node(IdType i) { nodes.insert(i); } bool has_node(IdType i) const { return nodes.find(i) != nodes.end(); } void add_arc(IdType lo, IdType hi) { upper_links[lo].insert(hi); lower_links[hi].insert(lo); } bool reduce_node(IdType i) { // remove a node whose up-degree and down-degree are both less or equal to 1 size_t ud = upper_degree(i), ld = lower_degree(i); if (ud > 1 || ld > 1) return false; // cannot do the node reduction else if (ud == 1 && ld == 0) { lower_links[upper_node(i)].erase(i); } else if (ud == 0 && ld == 1) { upper_links[lower_node(i)].erase(i); } else { // ud == 1 && ld == 1 auto hi = upper_node(i), lo = lower_node(i); lower_links[hi].erase(i); upper_links[lo].erase(i); lower_links[hi].insert(lo); upper_links[lo].insert(hi); } nodes.erase(i); upper_links.erase(i); lower_links.erase(i); return true; } bool is_leaf(IdType i) const { return upper_degree(i) + lower_degree(i) == 1; } size_t upper_degree(IdType lo) const { auto it = upper_links.find(lo); if (it != upper_links.end()) return it->second.size(); else return 0; } size_t lower_degree(IdType hi) const { auto it = lower_links.find(hi); if (it != lower_links.end()) return it->second.size(); else return 0; } IdType upper_node(IdType lo) const { // return the first upper node auto it = upper_links.find(lo); if (it != upper_links.end()) return *it->second.begin(); else return IdType(-1); } IdType lower_node(IdType hi) const { // return the first lower node auto it = lower_links.find(hi); if (it != lower_links.end()) return *it->second.begin(); else return IdType(-1); } const std::set<IdType>& upper_nodes(IdType i) const { auto it = upper_links.find(i); if (it != upper_links.end()) return it.second; else return std::set<IdType>(); } const std::set<IdType>& lower_nodes(IdType i) const { auto it = lower_links.find(i); if (it != lower_links.end()) return it.second; else return std::set<IdType>(); } void print() const { fprintf(stdout, "graph {\n"); for (const auto &kv : upper_links) { IdType i = kv.first; for (const auto j : kv.second) fprintf(stdout, "%zu -- %zu\n", i, j); } fprintf(stdout, "}\n"); } template <class ValueType> void print_with_values(const std::function<ValueType(IdType)>& value) const { for (const auto &kv : upper_links) { IdType i = kv.first; for (const auto j : kv.second) { fprintf(stderr, "%zu(%f) -- %zu(%f);\n", i, value(i), j, value(j)); } } } void reduce() { // remove all nodes whose up-degree and down-degree are both 1 std::vector<IdType> to_remove; for (auto i : nodes) if (upper_degree(i) == 1 && lower_degree(i) == 1) { to_remove.push_back(i); } for (auto i : to_remove) { reduce_node(i); } } protected: std::set<IdType> nodes; std::map<IdType, std::set<IdType> > upper_links, lower_links; }; } // namespace ftk #endif
27.325
107
0.608722
[ "vector" ]
30f79ab8787991b0ab5f63d92780014f880f7352
5,358
cpp
C++
src/mongo/db/pipeline/document_source_lookup_change_post_image.cpp
puppyofkosh/mongo
ed601dd01169b8c1fad9fb8d388da0523a1b48f5
[ "Apache-2.0" ]
1
2015-11-08T17:16:08.000Z
2015-11-08T17:16:08.000Z
src/mongo/db/pipeline/document_source_lookup_change_post_image.cpp
puppyofkosh/mongo
ed601dd01169b8c1fad9fb8d388da0523a1b48f5
[ "Apache-2.0" ]
null
null
null
src/mongo/db/pipeline/document_source_lookup_change_post_image.cpp
puppyofkosh/mongo
ed601dd01169b8c1fad9fb8d388da0523a1b48f5
[ "Apache-2.0" ]
1
2021-06-18T05:00:06.000Z
2021-06-18T05:00:06.000Z
/** * Copyright (C) 2017 MongoDB Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * As a special exception, the copyright holders give permission to link the * code of portions of this program with the OpenSSL library under certain * conditions as described in each individual source file and distribute * linked combinations including the program with the OpenSSL library. You * must comply with the GNU Affero General Public License in all respects * for all of the code used other than as permitted herein. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you do not * wish to do so, delete this exception statement from your version. If you * delete this exception statement from all source files in the program, * then also delete it in the license file. */ #include "mongo/platform/basic.h" #include "mongo/db/pipeline/document_source_lookup_change_post_image.h" #include "mongo/bson/simple_bsonelement_comparator.h" namespace mongo { constexpr StringData DocumentSourceLookupChangePostImage::kStageName; constexpr StringData DocumentSourceLookupChangePostImage::kFullDocumentFieldName; namespace { Value assertFieldHasType(const Document& fullDoc, StringData fieldName, BSONType expectedType) { auto val = fullDoc[fieldName]; uassert(40578, str::stream() << "failed to look up post image after change: expected \"" << fieldName << "\" field to have type " << typeName(expectedType) << ", instead found type " << typeName(val.getType()) << ": " << val.toString() << ", full object: " << fullDoc.toString(), val.getType() == expectedType); return val; } } // namespace DocumentSource::GetNextResult DocumentSourceLookupChangePostImage::getNext() { pExpCtx->checkForInterrupt(); auto input = pSource->getNext(); if (!input.isAdvanced()) { return input; } auto opTypeVal = assertFieldHasType( input.getDocument(), DocumentSourceChangeStream::kOperationTypeField, BSONType::String); if (opTypeVal.getString() != DocumentSourceChangeStream::kUpdateOpType) { return input; } MutableDocument output(input.releaseDocument()); output[kFullDocumentFieldName] = lookupPostImage(output.peek()); return output.freeze(); } NamespaceString DocumentSourceLookupChangePostImage::assertNamespaceMatches( const Document& inputDoc) const { auto namespaceObject = assertFieldHasType(inputDoc, DocumentSourceChangeStream::kNamespaceField, BSONType::Object) .getDocument(); auto dbName = assertFieldHasType(namespaceObject, "db"_sd, BSONType::String); auto collectionName = assertFieldHasType(namespaceObject, "coll"_sd, BSONType::String); NamespaceString nss(dbName.getString(), collectionName.getString()); uassert(40579, str::stream() << "unexpected namespace during post image lookup: " << nss.ns() << ", expected " << pExpCtx->ns.ns(), nss == pExpCtx->ns); return nss; } Value DocumentSourceLookupChangePostImage::lookupPostImage(const Document& updateOp) const { // Make sure we have a well-formed input. auto nss = assertNamespaceMatches(updateOp); auto documentKey = assertFieldHasType( updateOp, DocumentSourceChangeStream::kDocumentKeyField, BSONType::Object); auto matchSpec = BSON("$match" << documentKey); // TODO SERVER-29134 we need to extract the namespace from the document and set them on the new // ExpressionContext if we're getting notifications from an entire database. auto foreignExpCtx = pExpCtx->copyWith(nss); auto pipeline = uassertStatusOK(_mongod->makePipeline({matchSpec}, foreignExpCtx)); if (auto first = pipeline->getNext()) { auto lookedUpDocument = Value(*first); if (auto next = pipeline->getNext()) { uasserted(40580, str::stream() << "found more than document with documentKey " << documentKey.toString() << " while looking up post image after change: [" << lookedUpDocument.toString() << ", " << next->toString() << "]"); } return lookedUpDocument; } // We couldn't find it with the documentKey, it may have been deleted. return Value(BSONNULL); } } // namespace mongo
43.209677
99
0.654535
[ "object" ]
30fb9d67c4b4509f988482b849de76ec0641f262
56,321
cpp
C++
moos-ivp/ivp/src/lib_mbutil/MBUtils.cpp
EasternEdgeRobotics/2018
24df2fe56fa6d172ba3c34c1a97f249dbd796787
[ "MIT" ]
8
2019-05-27T08:46:46.000Z
2022-02-19T10:43:55.000Z
moos-ivp/ivp/src/lib_mbutil/MBUtils.cpp
EasternEdgeRobotics/2018
24df2fe56fa6d172ba3c34c1a97f249dbd796787
[ "MIT" ]
null
null
null
moos-ivp/ivp/src/lib_mbutil/MBUtils.cpp
EasternEdgeRobotics/2018
24df2fe56fa6d172ba3c34c1a97f249dbd796787
[ "MIT" ]
4
2019-04-05T18:34:38.000Z
2021-06-16T01:43:29.000Z
/*****************************************************************/ /* NAME: Michael Benjamin */ /* ORGN: Dept of Mechanical Eng / CSAIL, MIT Cambridge MA */ /* FILE: MBUtils.cpp */ /* DATE: (1996-2005) */ /* */ /* This file is part of IvP Helm Core Libs */ /* */ /* IvP Helm Core Libs is free software: you can redistribute it */ /* and/or modify it under the terms of the Lesser GNU General */ /* Public License as published by the Free Software Foundation, */ /* either version 3 of the License, or (at your option) any */ /* later version. */ /* */ /* IvP Helm Core Libs 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 Lesser GNU General Public License for more */ /* details. */ /* */ /* You should have received a copy of the Lesser GNU General */ /* Public License along with MOOS-IvP. If not, see */ /* <http://www.gnu.org/licenses/>. */ /*****************************************************************/ #include <cmath> #include <cstring> #include <cstdlib> #include <cstdio> #include <ctype.h> #include <iostream> #include "MBUtils.h" //added for time support in W32 platforms PMN - 18 July 2005 #ifdef _WIN32 #include "windows.h" #include "winbase.h" #include "winnt.h" #include <conio.h> #endif using namespace std; //---------------------------------------------------------------- // Procedure: parseString(string, char) // Example: svector = parseString("apples, pears,banannas", ','); // svector[0] = "apples" // svector[1] = " pears" // svector[2] = "bananas" vector<string> parseString(const string& string_str, char separator) { const char *str = string_str.c_str(); char *buff = new char[strlen(str)+1]; vector<string> rvector; while(str[0] != '\0') { int i=0; while((str[i]!=separator)&&(str[i]!='\0')) i++; strncpy(buff, str, i); buff[i] = '\0'; string nstr = buff; rvector.push_back(nstr); str += i; if(str[0]==separator) str++; } delete [] buff; return(rvector); } //---------------------------------------------------------------- // Procedure: parseStringQ(string, char) // Notes: Differs from "parseString" in that the separator is // ignored if it is found in an open-quote mode. That is // after an odd # of double-quote characters have appeared. // Example: str = "left=apples # left=pears # left=\"bana#nas\"" // w/out Q: svector = parseString(str, '#'); // svector[0] = [left=apples ] // svector[1] = [ left=pears ] // svector[2] = [ left="bana#] // svector[3] = [nas"] // Compare: svector = parseStringQ(str, '#'); // svector[0] = [left=apples ] // svector[1] = [ left=pears ] // svector[2] = [ left="bana#nas"] vector<string> parseStringQ(const string& string_str, char separator) { bool in_quotes = false; unsigned int brace_count = 0; const char *str = string_str.c_str(); char *buff = new char[strlen(str)+1]; vector<string> rvector; while(str[0] != '\0') { int i=0; while(((str[i]!=separator) || in_quotes || (brace_count>0)) && (str[i]!='\0')) { if(str[i]=='"') in_quotes = !in_quotes; else if(str[i]=='{') brace_count++; else if(str[i]=='}') { if(brace_count > 0) brace_count--; } i++; } strncpy(buff, str, i); buff[i] = '\0'; string nstr = buff; rvector.push_back(nstr); str += i; if(str[0]==separator) str++; } delete [] buff; return(rvector); } //---------------------------------------------------------------- // Procedure: parseStringZ(string, char) // Notes: Differs from "parseString" in that the separator is // ignored if it is found in an open-quote mode. That is // after an odd # of double-quote characters have appeared. vector<string> parseStringZ(const string& string_str, char separator, const string&protectors) { bool quote_protect = strContains(protectors, '"'); bool brace_protect = strContains(protectors, '{'); bool brack_protect = strContains(protectors, '['); bool paren_protect = strContains(protectors, '('); unsigned int quote_count = 0; unsigned int brace_count = 0; unsigned int brack_count = 0; unsigned int paren_count = 0; const char *str = string_str.c_str(); char *buff = new char[strlen(str)+1]; vector<string> rvector; while(str[0] != '\0') { int i=0; while(((str[i]!=separator) || (quote_count > 0) || (brace_count>0) || (brack_count > 0) || (paren_count>0)) && (str[i]!='\0')) { if(quote_protect && str[i]=='"') { if(quote_count == 0) quote_count = 1; else quote_count = 0; } if(brace_protect) { if(str[i]=='{') brace_count++; else if(str[i]=='}') { if(brace_count > 0) brace_count--; } } if(paren_protect) { if(str[i]=='(') paren_count++; else if(str[i]==')') { if(paren_count > 0) paren_count--; } } if(brack_protect) { if(str[i]=='[') brack_count++; else if(str[i]==']') { if(brack_count > 0) brack_count--; } } i++; } strncpy(buff, str, i); buff[i] = '\0'; string nstr = buff; rvector.push_back(nstr); str += i; if(str[0]==separator) str++; } delete [] buff; return(rvector); } //---------------------------------------------------------------- // Procedure: parseStringQ(string, char, unsigned int) // Purpose: Same as parseStringQ, but bundle component into strings // with length no greater than maxlen // Example: string_str = community=shoreside,hostip=128.30.24.232,foo=bar // maxlen = 40 // Result: rvector[0]="community=shoreside,hostip=128.30.24.232," // rvector[0]="foo=bar" vector<string> parseStringQ(const string& string_str, char separator, unsigned int maxlen) { vector<string> rvector; vector<string> svector = parseStringQ(string_str, separator); unsigned int i, vsize = svector.size(); string buffer; for(i=0; i<vsize; i++) { if(buffer == "") buffer = svector[i]; else { if((buffer.length() + 1 + svector[i].length()) <= maxlen) buffer = buffer + separator + svector[i]; else { rvector.push_back(buffer + ","); buffer = svector[i]; } } } if(buffer != "") rvector.push_back(buffer); return(rvector); } //---------------------------------------------------------------- // Procedure: parseString(string, string) // Example: svector = parseString("apples $@$ pears $@$ banannas", "$@$"); // svector[0] = "apples " // svector[1] = " pears " // svector[2] = " bananas" vector<string> parseString(const string& string_str, const string& separator) { string new_separator; char unique_char = (char)129; new_separator += unique_char; string new_string = findReplace(string_str, separator, new_separator); vector<string> rvector = parseString(new_string, unique_char); return(rvector); } //---------------------------------------------------------------- // Procedure: parseQuotedString(string, char) // Example: svector = parseQuotedString(""apples,pears",banannas", ','); // svector[0] = "apples,pears" // svector[1] = "bananas" vector<string> parseQuotedString(const string& string_str, char separator) { const char *str = string_str.c_str(); char *buff = new char[strlen(str)+1]; vector<string> rvector; // First count the number of double-quotes. If not an even number, // return an empty vector. string::size_type len = string_str.length(); int quote_counter = 0; for(string::size_type i=0; i<len; i++) if(string_str.at(i) == '"') quote_counter++; if((quote_counter % 2) != 0) { delete [] buff; return(rvector); } bool even_quote = true; while(str[0] != '\0') { string::size_type i=0; while(((str[i]!=separator) || !even_quote) && (str[i]!='\0')) { if(str[i]=='"') even_quote = !even_quote; i++; } strncpy(buff, str, i); buff[i] = '\0'; string nstr = buff; rvector.push_back(nstr); str += i; if(str[0]==separator) str++; } delete [] buff; return(rvector); } //---------------------------------------------------------------- // Procedure: parseStringToWords // Notes: Break up the string into a group of white space separated // chunks vector<string> parseStringToWords(const string& str, char grouping_char) { vector<string> rvector; string word; int grouping_char_count = 0; char rgc = 0; // right grouping char if(grouping_char == '(') rgc = ')'; else if(grouping_char == '{') rgc = '}'; else if(grouping_char == '[') rgc = ']'; else if(grouping_char == '\"') rgc = '\"'; unsigned int i, len = str.length(); for(i=0; i<len; i++) { char c = str.at(i); if((grouping_char != 0) && (c == grouping_char)) { grouping_char_count++; word.push_back(c); } else if((rgc != 0) && (c == rgc)) { grouping_char_count--; word.push_back(c); } else if(((c != '\t') && (c != ' ')) || (grouping_char_count > 0)) word.push_back(c); else { if(word.length() > 0) { rvector.push_back(word); word.clear(); } } } if(word.length() != 0) rvector.push_back(word); return(rvector); } //---------------------------------------------------------------- // Procedure: chompString(const string&, char) // Example: svector = chompString("apples, pears, bananas", ',') // svector[0] = "apples" // svector[1] = " pears, bananas" vector<string> chompString(const string& string_str, char separator) { const char *str = string_str.c_str(); char* buff = new char [strlen(str)+1]; vector<string> rvector; string::size_type i=0; while((str[i]!=separator)&&(str[i]!='\0')) i++; strncpy(buff, str, i); buff[i] = '\0'; string str_front = buff; rvector.push_back(str_front); str += i; if(str[0]==separator) str++; string str_back = str; rvector.push_back(str_back); delete [] buff; return(rvector); } //---------------------------------------------------------------- // Procedure: augmentSpec string augmentSpec(const string& orig, const string& new_part, char sep) { string return_str = orig; if(orig != "") return_str += sep; return(return_str + new_part); } //---------------------------------------------------------------- // Procedure: removeWhite(const string&) // Example: input_str = "apples, pears, bananas " // str = removeWhite(input_str) // str = "apples,pears,bananas" string removeWhite(const string& str) { string return_string; unsigned int i, vsize = str.length(); for(i=0; i<vsize; i++) { int c = (int)(str.at(i)); if((c != 9) && (c != 32)) return_string += str.at(i); } return(return_string); } //---------------------------------------------------------------- // Procedure: biteString(string&, char) // Example: input_str = "apples, pears, bananas" // str = biteString(input_str, ',') // str = "apples" // input_str = " pears, bananas" string biteString(string& str, char separator) { string::size_type len = str.length(); if(len == 0) return(""); bool found = false; string::size_type ix=0; string::size_type i=0; for(i=0; (!found && i<len); i++) { if(str[i] == separator) { found = true; ix = i; } } if(!found) { string str_front = str; str = ""; return(str_front); } string str_front(str.c_str(), ix); string str_back; if((ix+1) < len) str_back = str.substr(ix+1); str = str_back; return(str_front); } //---------------------------------------------------------------- // Procedure: biteStringX(string&, char) // Note: Same as biteString except blank ends will be removed // from both the returned and remaining value. string biteStringX(string& str, char separator) { string front = stripBlankEnds(biteString(str, separator)); str = stripBlankEnds(str); return(front); } //---------------------------------------------------------------- // Procedure: biteString(string&, char, char) // Note: Same as biteString(string,char) except the bite will // occur at the point where either of the two given // characters occur. string biteString(string& str, char sep1, char sep2) { if(str.length() == 0) return(""); string::size_type i=0; while((str[i]!=sep1) && (str[i]!=sep2) && (str[i]!='\0')) i++; string str_front(str.c_str(), i); if(str[i] == '\0') str = ""; else { string str_back(str.c_str()+i+1); str = str_back; } return(str_front); } //---------------------------------------------------------------- // Procedure: rbiteString(string&, char) // Example: input_str = "apples, pears, bananas" // str = rbiteString(input_str, ',') // str = " bananas" // input_str = "apples, pears" string rbiteString(string& str, char separator) { string::size_type len = str.length(); if(len == 0) return(""); bool found = false; string::size_type ix=0; string::size_type i=0; for(i=len-1; (!found && i!=0); i--) { if(str[i] == separator) { found = true; ix = i; } } if(!found) { string str_back = str; str = ""; return(str_back); } string str_front(str.c_str(), ix); string str_back; if((ix+1) < len) str_back = str.substr(ix+1); str = str_front; return(str_back); } //---------------------------------------------------------------- // Procedure: sortStrings // Note: O(n^2) simple bubble-sort algorithm vector<string> sortStrings(vector<string> svector) { vector<string>::size_type vsize = svector.size(); for(vector<string>::size_type i=0; i<vsize; i++) { for(vector<string>::size_type j=0; j<(vsize-1-i); j++) { if(svector[j+1] < svector[j]) { // compare the two neighbors string tmp = svector[j]; svector[j] = svector[j+1]; svector[j+1] = tmp; } } } return(svector); } //---------------------------------------------------------------- // Procedure: mergeVectors // Note: vector<string> mergeVectors(vector<string> vector1, vector<string> vector2) { vector<string>::size_type vsize = vector2.size(); for(vector<string>::size_type i=0; i<vsize; i++) vector1.push_back(vector2[i]); return(vector1); } //---------------------------------------------------------------- // Procedure: removeDuplicates // Note: Return a vector of strings such that no string is in // the vector more than once. vector<string> removeDuplicates(const vector<string>& svector) { vector<string> rvector; vector<string>::size_type vsize = svector.size(); for(vector<string>::size_type i=0; i<vsize; i++) if(!vectorContains(rvector, svector[i])) rvector.push_back(svector[i]); return(rvector); } //---------------------------------------------------------------- // Procedure: vectorContains // Note: bool vectorContains(const vector<string>& svector, const string& str) { vector<string>::size_type vsize = svector.size(); for(vector<string>::size_type i=0; i<vsize; i++) if(svector[i] == str) return(true); return(false); } //---------------------------------------------------------------- // Procedure: stripBlankEnds(string) string stripBlankEnds(const string& str) { if(str.length() == 0) return(""); const char *sPtr = str.c_str(); int length = strlen(sPtr); int i; int startIX=length; // assume all blanks #if 0 // Added Dec 23rd 2007 (mikerb) // Quick check to see if the string has already been stripped // of blank ends. Just return the original in that case. int s_char = (int)(sPtr[0]); int e_char = (int)(sPtr[length-1]); if((s_char != 9) && (s_char != 32) && (e_char != 9) && (e_char != 32)) return(str); #endif for(i=0; i<length; i++) { int cval = (int)(sPtr[i]); if(!((cval==9) || // 09:tab (cval==32))) { // 32:blank startIX = i; i = length; } } if(sPtr[startIX]==0) // If first non-blank is NULL term, startIX=length; // treat as if blank, empty line. if(startIX==length) { // Handle case where the string ret_string = ""; // whole string was blanks return(ret_string); // and/or tabs } int endIX=-1; for(i=length-1; i>=0; i--) { int cval = (int)(sPtr[i]); if(!((cval==9) || // 09:tab (cval==0) || // 00:NULL terminator (cval==32) || // 32:blank (cval==13) || // 13:car-return (cval==10))) { // 10:newline endIX = i; i = -1; } } if(startIX > endIX) { // Handle case where the string ret_string = ""; // whole string was blanks, return(ret_string); // tabs, newlines, or car-return } length = (endIX - startIX) + 1; char *buff = new char [length+1]; strncpy(buff, sPtr+startIX, length); buff[length] = '\0'; string ret_string = buff; delete [] buff; return(ret_string); } //---------------------------------------------------------------- // Procedure: tolower(string) string tolower(const string& str) { string rstr = str; string::size_type len = str.length(); for(string::size_type i=0; i<len; i++) rstr[i] = tolower(str[i]); return(rstr); } //---------------------------------------------------------------- // Procedure: toupper(string) string toupper(const string& str) { string rstr = str; string::size_type len = str.length(); for(string::size_type i=0; i<len; i++) rstr[i] = toupper(str[i]); return(rstr); } //---------------------------------------------------------------- // Procedure: truncString string truncString(const string& str, unsigned int newlen, string style) { unsigned int len = str.length(); if(newlen > len) return(str); if((style == "") || (style == "basic") || (style == "front")) return(str.substr(0, newlen)); if(style == "back") return(str.substr(len-newlen, newlen)); // Otherwise the style is request is assumed to be "middle" // It doesnt' make sense to middle down to a string less than 4 since // the two periods in the middle should have at least one character // on each side. If this is requested, just return trunc-front. if(newlen < 4) return(str.substr(0, newlen)); unsigned int back = newlen / 2; unsigned int front = newlen - back; back--; front--; string new_str = str.substr(0,front) + ".." + str.substr(len-back,len); return(new_str); } //---------------------------------------------------------------- // Procedure: xxxToString(value) string boolToString(bool val) { if(val) return("true"); else return("false"); } string intToString(int val) { char buff[500]; sprintf(buff, "%d", val); string str = buff; return(str); } string uintToString(unsigned int val) { char buff[500]; sprintf(buff, "%u", val); string str = buff; return(str); } string ulintToString(unsigned long int val) { char buff[500]; sprintf(buff, "%lu", val); string str = buff; return(str); } string floatToString(float val, int digits) { char format[10] = "%.5f\0"; if((digits>=0)&&(digits<=9)) format[2] = digits+48; if(val > (float)(pow((float)(2),(float)(64)))) format[3] = 'e'; char buff[1000]; sprintf(buff, format, val); string str = buff; return(str); } string doubleToString(double val, int digits) { char format[10] = "%.5f\0"; if((digits>=0)&&(digits<=9)) format[2] = digits+48; else if((digits >= 10) && (digits <= 19)) { format[2] = '1'; format[3] = (digits+38); format[4] = 'f'; format[5] = '\0'; } else { format[2] = '2'; format[3] = '0'; format[4] = 'f'; format[5] = '\0'; } if(val > (double)(pow((double)(2),(double)(128)))) format[3] = 'e'; char buff[1000]; sprintf(buff, format, val); string str = buff; return(str); } string doubleToStringX(double val, int digits) { string rstr = dstringCompact(doubleToString(val, digits)); if(rstr == "-0") return("0"); return(rstr); } string setToString(const set<string>& str_set) { string rstr; set<string>::iterator p; for(p=str_set.begin(); p!=str_set.end(); p++) { if(rstr != "") rstr += ","; rstr += *p; } return(rstr); } //---------------------------------------------------------------- // Procedure: intToCommaString string intToCommaString(int ival) { string str = intToString(ival); string new_str; unsigned int i, len = str.length(); for(i=0; i<len; i++) { new_str += str.at(i); if((((len-(i+1))%3)==0) && (i!=len-1)) new_str += ','; } return(new_str); } //---------------------------------------------------------------- // Procedure: uintToCommaString string uintToCommaString(unsigned int ival) { string str = uintToString(ival); string new_str; unsigned int i, len = str.length(); for(i=0; i<len; i++) { new_str += str.at(i); if((((len-(i+1))%3)==0) && (i!=len-1)) new_str += ','; } return(new_str); } //---------------------------------------------------------------- // Procedure: ulintToCommaString string ulintToCommaString(unsigned long int ival) { string str = ulintToString(ival); string new_str; unsigned int i, len = str.length(); for(i=0; i<len; i++) { new_str += str.at(i); if((((len-(i+1))%3)==0) && (i!=len-1)) new_str += ','; } return(new_str); } //---------------------------------------------------------------- // Procedure: dstringCompact // Note: Convert 6.43000 to 6.43 // 6.00000 to 6 // 6. to 6 string dstringCompact(const string& str) { if(str=="0") return("0"); string::size_type ssize = str.size(); if(ssize == 0) return(""); bool has_decimal = false; for(string::size_type i=0; i<ssize; i++) if(str[i] == '.') has_decimal = true; if(!has_decimal) return(str); char *buff = new char[ssize+1]; strcpy(buff, str.c_str()); buff[ssize] = '\0'; for(string::size_type j=ssize-1; ; j--) { if(buff[j] == '0') buff[j] = '\0'; else { if(buff[j] == '.') buff[j] = '\0'; break; } } string ret_str = buff; delete [] buff; return(ret_str); } //---------------------------------------------------------------- // Procedure: compactConsecutive // Note: f("Apple______Pear", '_') returns "Apple_Pear" // f("Too Bad", ' ') return "Too Bad" // string compactConsecutive(const string& str, char dchar) { string::size_type len = strlen(str.c_str()); if(len==0) return(""); char *buffer = new char [len+1]; buffer[0] = str[0]; string::size_type index = 1; for(string::size_type i=1; i<len; i++) { if((str[i] != dchar) || (str[i-1] != dchar)) { buffer[index] = str[i]; index++; } } buffer[index] = '\0'; string return_string = buffer; delete [] buffer; return(return_string); } //---------------------------------------------------------------- // Procedure: findReplace // Note: Added May 29, 2005 // Replace all occurances of fchar with rchar in str string findReplace(const string& str, char fchar, char rchar) { string rstr = str; string::size_type str_size = str.size(); for(string::size_type i=0; i<str_size; i++) if(str[i] == fchar) rstr[i] = rchar; return(rstr); } //---------------------------------------------------------------- // Procedure: padString // Note: Added Aug 1405 // Purpose: Pad the given string with enough blanks to reach the // length given by target_size. If front is true, pad on // to the front of the string. To the end otherwise. string padString(const string& str, std::string::size_type target_size, bool front) { string rstr = str; string::size_type str_size = str.size(); while(str_size < target_size) { if(front) rstr = " " + rstr; else rstr = rstr + " "; str_size++; } return(rstr); } //---------------------------------------------------------------- // Procedure: findReplace // Note: Added Jun1405 // Replace all occurances of fstr with rstr in str string findReplace(const string& str, const string& fstr, const string& rstr) { string::size_type posn = 0; string newstr = str; while(posn != string::npos) { posn = newstr.find(fstr, posn); if(posn != string::npos) { newstr.replace(posn, fstr.length(), rstr); posn += rstr.length(); } } return(newstr); } //---------------------------------------------------------------- // Procedure: stripComment // Note: Added July 14th 05 (on the flight to Oxford, pre-Pianosa) // Treat cstr as a comment indicator, e.g. "//". Return the // portion of the string to the left of the comment // Example: stripComment("Hello World // note", "//") // returns "Hello World " string stripComment(const string& str, const string& cstr) { string::size_type posn = str.find(cstr, 0); if(posn == string::npos) return(str); string::size_type ssize = str.size(); char *buff = new char[ssize+1]; strcpy(buff, str.c_str()); buff[ssize] = '\0'; buff[posn] = '\0'; string return_string = buff; delete [] buff; return(return_string); } //--------------------------------------------------------- // Procedure: isValidIPAddress // Purpose: Determine if the string is a valid IP address: // - has four numerical fields separated by a decimal point. // - each field is in the range 0-255 bool isValidIPAddress(const string& ipstring) { if(tolower(ipstring) == "localhost") return(true); vector<string> svector = parseString(ipstring, '.'); unsigned int i, vsize = svector.size(); if(vsize != 4) return(false); for(i=0; i<vsize; i++) { string part = stripBlankEnds(svector[i]); if(!isNumber(part)) return(false); double dval = atof(svector[i].c_str()); if((dval < 0) || (dval > 255)) return(false); } return(true); } //---------------------------------------------------------------- // Procedure: strContains // Note: Added July 14 05 (on the flight to Oxford) bool strContains(const string& str, const string& qstr) { string::size_type posn = str.find(qstr, 0); if(posn == string::npos) return(false); else return(true); } //---------------------------------------------------------------- // Procedure: strContains bool strContains(const string& str, const char c) { string::size_type posn = str.find_first_of(c, 0); if(posn == string::npos) return(false); else return(true); } //---------------------------------------------------------------- // Procedure: strBegins // Note: Added Nov 2nd 09 (on the flight to DC) bool strBegins(const string& str, const string& qstr, bool case_matters) { string::size_type i, qlen = qstr.length(); if((str.length() < qlen) || (qlen == 0)) return(false); if(case_matters) { for(i=0; i<qlen; i++) if(str[i] != qstr[i]) return(false); } else { for(i=0; i<qlen; i++) if(tolower(str[i]) != tolower(qstr[i])) return(false); } return(true); } //---------------------------------------------------------------- // Procedure: strBegins // Note: Added Nov 2nd 09 (on the flight to DC) bool strEnds(const string& str, const string& qstr, bool case_matters) { string::size_type qlen = qstr.length(); string::size_type slen = str.length(); if((slen < qlen) || (qlen == 0)) return(false); string::size_type i, start_ix = slen-qlen; if(case_matters) { for(i=0; i<qlen; i++) if(str[i+start_ix] != qstr[i]) return(false); } else { for(i=0; i<qlen; i++) if(tolower(str[i+start_ix]) != tolower(qstr[i])) return(false); } return(true); } //---------------------------------------------------------------- // Procedure: isBoolean bool isBoolean(const string& str) { string s = tolower(str); if((s == "true") || (s == "false")) return(true); return(false); } //---------------------------------------------------------------- // Procedure: stringIsFalse bool stringIsFalse(const string& str) { string s = tolower(str); if((s == "false") || (s == "0") || (s == "no")) return(true); return(false); } //---------------------------------------------------------------- // Procedure: strContainsWhite // Note: Returns true if the given string contains either a // blank or tab character. bool strContainsWhite(const string& str) { string::size_type posn = str.find_first_of(' ', 0); if(posn != string::npos) return(true); posn = str.find_first_of('\t', 0); if(posn != string::npos) return(true); return(false); } //---------------------------------------------------------------- // Procedure: svectorToString // Note: Added Jan1807/Jan1213 string svectorToString(const vector<string>& svector, char separator) { string result; unsigned int i, vsize = svector.size(); for(i=0; i<vsize; i++) { if(i>0) result += separator; result += svector[i]; } return(result); } //---------------------------------------------------------------- // Procedure: tokParse // Example: info = "fruit=apple, drink=water, temp=98.6"; // match = str_tok(info, "drink", ',', '=', rval); // Result: match:true rval:"water" bool tokParse(const string& str, const string& left, char gsep, char lsep, string& rstr) { rstr = "error"; vector<string> svector1 = parseStringQ(str, gsep); for(vector<string>::size_type i=0; i<svector1.size(); i++) { vector<string> svector2 = parseString(svector1[i], lsep); if(svector2.size() != 2) return(false); svector2[0] = stripBlankEnds(svector2[0]); if(svector2[0] == left) { rstr = svector2[1]; return(true); } } return(false); } //---------------------------------------------------------------- // Procedure: tokStringParse // Example: info = "fruit=apple, drink=water, temp=98.6"; // Input result = tokStringParse(info, "drink", ',', '='); // Result: result = "water" // Input result = tokStringParse(info, "foobar", ',', '='); // Result: result = "" string tokStringParse(const string& str, const string& left, char gsep, char lsep) { vector<string> svector1 = parseStringQ(str, gsep); for(vector<string>::size_type i=0; i<svector1.size(); i++) { vector<string> svector2 = parseString(svector1[i], lsep); if(svector2.size() != 2) return(""); svector2[0] = stripBlankEnds(svector2[0]); if(svector2[0] == left) return(stripBlankEnds(svector2[1])); } return(""); } //---------------------------------------------------------------- // Procedure: tokDoubleParse // Example: info = "fruit=23, drink=0.4, temp=98.6"; // Input result = str_tok(info, "drink", ',', '='); // Result: result = 0.4 // Input result = str_tok(info, "foobar", ',', '='); // Result: result = 0.0 double tokDoubleParse(const string& str, const string& left, char gsep, char lsep) { vector<string> svector1 = parseString(str, gsep); for(vector<string>::size_type i=0; i<svector1.size(); i++) { vector<string> svector2 = parseString(svector1[i], lsep); if(svector2.size() != 2) return(0); svector2[0] = stripBlankEnds(svector2[0]); if(svector2[0] == left) return(atof(svector2[1].c_str())); } return(0); } //---------------------------------------------------------------- // Procedure: minElement double minElement(const vector<double>& myvector) { if(myvector.size() == 0) return(0); double min_found = myvector[0]; unsigned int i, vsize = myvector.size(); for(i=1; i<vsize; i++) if(myvector[i] < min_found) min_found = myvector[i]; return(min_found); } //---------------------------------------------------------------- // Procedure: maxElement double maxElement(const vector<double>& myvector) { if(myvector.size() == 0) return(0); double max_found = myvector[0]; unsigned int i, vsize = myvector.size(); for(i=1; i<vsize; i++) if(myvector[i] > max_found) max_found = myvector[i]; return(max_found); } //---------------------------------------------------------------- // Procedure: vclip double vclip(const double& var, const double& low, const double& high) { if(var < low) return(low); if(var > high) return(high); return(var); } //---------------------------------------------------------------- // Procedure: vclip_min double vclip_min(const double& var, const double& low) { if(var < low) return(low); return(var); } //---------------------------------------------------------------- // Procedure: vclip_max double vclip_max(const double& var, const double& high) { if(var > high) return(high); return(var); } //---------------------------------------------------------------- // Procedure: randomDouble double randomDouble(double min, double max) { if(min > max) return(0); if(min == max) return(min); // get random integer in the range [0,10000] int rand_int = rand() % 10001; double pct = (double)(rand_int) / (double)(10000); double value = min + (pct * (max-min)); return(value); } //---------------------------------------------------------------- // Procedure: tokParse // Example: info = "fruit=apple, drink=water, temp=98.6"; // match = tokParse(info, "temp", ',', '=', rval); // Result: match:true rval:98.6 bool tokParse(const string& str, const string& left, char gsep, char lsep, double& rval) { string rstr; bool res = tokParse(str, left, gsep, lsep, rstr); if(!res) return(false); if(!isNumber(rstr)) return(false); rval = atof(rstr.c_str()); return(true); } //---------------------------------------------------------------- // Procedure: tokParse // Example: info = "fruit=apple, result=true, temp=98.6"; // match = tokParse(info, "temp", ',', '=', rval); // Result: match:true bval:true bool tokParse(const string& str, const string& left, char gsep, char lsep, bool& bval) { string rstr; bool res = tokParse(str, left, gsep, lsep, rstr); if(!res) return(false); if(!isBoolean(rstr)) return(false); bval = (tolower(rstr) == "true"); return(true); } //---------------------------------------------------------------- // Procedure: isAlphaNum bool isAlphaNum(const string& str, const std::string& achars) { unsigned int i, len = str.length(); if(len == 0) return(false); bool ok = true; for(i=0; (i<len)&&(ok); i++) { bool this_char_ok = false; char c = str.at(i); if((c >= 48) && (c <= 57)) // 0-9 this_char_ok = true; else if((c >= 65) && (c <= 90)) // A-Z this_char_ok = true; else if((c >= 97) && (c <= 122)) // a-z this_char_ok = true; else { unsigned int j, alen = achars.length(); for(j=0; (j<alen)&&!this_char_ok; j++) { if(c == achars.at(j)) this_char_ok = true; } } ok = ok && this_char_ok; } return(ok); } //---------------------------------------------------------------- // Procedure: isNumber bool isNumber(const string& str, bool blanks_allowed) { string newstr = str; if(blanks_allowed) newstr = stripBlankEnds(str); if(newstr.length() == 0) return(false); if((newstr.length() > 1) && (newstr.at(0) == '+')) newstr = newstr.substr(1, newstr.length()-1); const char *buff = newstr.c_str(); string::size_type len = newstr.length(); int digi_cnt = 0; int deci_cnt = 0; bool ok = true; for(string::size_type i=0; (i<len)&&ok; i++) { if((buff[i] >= 48) && (buff[i] <= 57)) digi_cnt++; else if(buff[i] == '.') { deci_cnt++; if(deci_cnt > 1) ok = false; } else if(buff[i] == '-') { if((digi_cnt > 0) || (deci_cnt > 0)) ok = false; } else ok = false; } if(digi_cnt == 0) ok = false; return(ok); } //---------------------------------------------------------------- // Procedure: isQuoted // Note: Returns true if the given string begins and ends w/ // a double-quote. Returns false otherwise. bool isQuoted(const string& str) { string mod_str = stripBlankEnds(str); if((mod_str[0] == '"') && (mod_str[str.length()-1] == '"')) return(true); return(false); } //---------------------------------------------------------------- // Procedure: isBraced // Note: Returns true if the given string begins with a '{' and // ends witha a '}'. Returns false otherwise. bool isBraced(const string& str) { string mod_str = stripBlankEnds(str); if((mod_str[0] == '{') && (mod_str[str.length()-1] == '}')) return(true); return(false); } //---------------------------------------------------------------- // Procedure: stripQuotes string stripQuotes(const string& given_str) { string str = stripBlankEnds(given_str); string::size_type len = str.length(); if(len < 2) return(given_str); if((str[0] != '"') || (str[len-1] != '"')) return(given_str); str.replace(len-1, 1, ""); str.replace(0, 1, ""); return(str); } //---------------------------------------------------------------- // Procedure: stripBraces string stripBraces(const string& given_str) { string str = stripBlankEnds(given_str); string::size_type len = str.length(); if(len < 2) return(given_str); if((str[0] != '{') || (str[len-1] != '}')) return(given_str); str.replace(len-1, 1, ""); str.replace(0, 1, ""); return(str); } //---------------------------------------------------------------- // Procedure: doubleToHex // Notes: Convert a double in the range [0,1.0] and convert it // to the range [0,255] in a hex representation given by // a two-character string. // Examples: 1.0 --> "00" // 1.0 --> "FF" // 0.9569 --> "F4" string doubleToHex(double g_val) { if(g_val < 0.0) return("00"); if(g_val > 1.0) return("FF"); double range0255 = g_val * 255.0; int left = (int)(range0255 / 16); int right = (int)(range0255) % 16; string left_str = intToString(left); if(left == 10) left_str = "A"; if(left == 11) left_str = "B"; if(left == 12) left_str = "C"; if(left == 13) left_str = "D"; if(left == 14) left_str = "E"; if(left == 15) left_str = "F"; string right_str = intToString(right); if(right == 10) right_str = "A"; if(right == 11) right_str = "B"; if(right == 12) right_str = "C"; if(right == 13) right_str = "D"; if(right == 14) right_str = "E"; if(right == 15) right_str = "F"; string str = left_str + right_str; return(str); } //---------------------------------------------------------------- // Procedure: getArg // Note1: Searches the array of stings (argv) looking for a // match to the given string (str). If no match is found // it returns zero. When a match is found it checks // to see if it "pos" is less than or equal to the number // of subarguments to the right of the matched argument. // (entries to the right with no leading '-' character). // If pos is less than or equal to the number of subargs, // it returns the subargument at position "pos". // Note2: We don't check here for multiple matches or for correct // number of subargs. It is assumed that such a check has // been done using the more powerful function "validateArgs". // Return: 0 if argument is not found or index is out of range. // >0 if argument is found, returns the position of the // subarg indicated by "pos" int getArg(int argc, char **argv, int pos, const char* str1, const char *str2) { for(int i=0; i<argc; i++) { for(int j=strlen(argv[i])-1; j>=0; j--) if(argv[i][j]==' ') argv[i][j] = '\0'; bool match1 = !strncmp(str1, argv[i], strlen(argv[i])); bool match2 = !strncmp(str1, argv[i], strlen(str1)); bool match3 = false; bool match4 = false; if(str2) { match3 = !strncmp(str2, argv[i], strlen(argv[i])); match4 = !strncmp(str2, argv[i], strlen(str2)); } if((match1 && match2) || (match3 && match4)) { int subArgCount=0; int ix = i+1; while((ix<argc)&&(argv[ix][0]!='-')) { subArgCount++; ix++; } if(pos<=subArgCount) return(i+pos); } } return(0); } //---------------------------------------------------------------- // Procedure: scanArgs // Note1: Searches the array of strings (argv) looking for a // match to the given string (str). bool scanArgs(int argc, char **argv, const char* str1, const char *str2, const char *str3) { for(int i=0; i<argc; i++) { bool match1 = !strncmp(str1, argv[i], strlen(argv[i])); bool match2 = !strncmp(str1, argv[i], strlen(str1)); if(match1 && match2) return(true); if(str2) { match1 = !strncmp(str2, argv[i], strlen(argv[i])); match2 = !strncmp(str2, argv[i], strlen(str2)); if(match1 && match2) return(true); } if(str3) { match1 = !strncmp(str3, argv[i], strlen(argv[i])); match2 = !strncmp(str3, argv[i], strlen(str2)); if(match1 && match2) return(true); } } return(false); } //---------------------------------------------------------------- // Procedure: validateArgs // Note1: Ensures that each argument in argv is legal, has the // correct number of arguments, and is not duplicated. // Note2: ms is of the form "arg1:#subargs arg2:#subargs ..." // For example: "prog:0 -num:1 -size:1 -dim:1 ...". // Return: NOERR: Arguments are valid. // INDEX: If error then return index of bad param int validateArgs(int argc, char *argv[], string ms) { bool NOERR=0; vector<string> svector = parseString(ms, ' '); vector<string>::size_type vsize = svector.size(); for(int i=0; i<argc; i++) { // Go through each arg if(argv[i][0] == '-') { // If begins with dash int subArgNum = 0; // Calculate for(int x=i+1; x<argc && argv[x][0] != '-'; x++) // Number of subArgNum++; // Sub-args bool matched = false; bool okCount = false; string arg = argv[i]; for(vector<string>::size_type j=0; j<vsize; j++) { string temp = svector[j]; if(temp != "") { vector<string> svector2 = parseString(temp, ':'); string tempPrefix = svector2[0]; if(arg == tempPrefix) { matched = true; string tempSuffix = svector2[1]; int msArgCount = atoi(tempSuffix.c_str()); if(msArgCount == subArgNum) okCount = true; } } } if((!matched) || (!okCount)) { return(i); } } } return(NOERR); } //---------------------------------------------------------- // Procedure: snapToStep // Purpose: Round the given number (gfloat) to the nearest // point on the number line containing intervals of // size "step". // Note: Ties go next higher point. // // Example: snapToStep(6.18, 0.05) returns: 6.20 // Example: snapToStep(6.18, 0.5) returns: 6.00 // Example: snapToStep(6.18, 5.0) returns: 5.00 double snapToStep(double orig_value, double step) { if(step <= 0) return(orig_value); double new_val = orig_value / step; // Divide by step long int itemp = 0; if(new_val < 0.0) itemp = (long int)(new_val-0.5); else itemp = (long int)(new_val+0.5); // round to nearest integer new_val = (double)itemp * step; // multiply again by the step return(new_val); } //---------------------------------------------------------- // Procedure: snapDownToStep // Purpose: Round the given number (value) to the next lowest // point on the number line containing intervals of // size "step". // // Example: snapToStep(9.98, 0.05) returns: 9.95 // Example: snapToStep(9.98, 0.50) returns: 9.50 // Example: snapToStep(9.98, 5.00) returns: 5.00 double snapDownToStep(double value, double step) { if(step <= 0) return(value); double new_val = value / step; // Divide by step long int itemp = (long int)(new_val); // round to nearest integer new_val = (double)itemp * step; // multiply again by the step return(new_val); } //------------------------------------------------------------- // Procedure: setBooleanOnString // Note: This function is designed to set the given boolean value // based on its existing value and the contents of the str. // Note: The case_tolow argument is true by default. By giving // the caller this option, some efficiency can be gained if // the caller knows that the str argument has already been // converted to lower case. bool setBooleanOnString(bool& boolval, string str, bool case_tolow) { if(case_tolow) str = tolower(str); if(str == "toggle") boolval = !boolval; else if((str == "on") || (str == "true")) boolval = true; else if((str == "off") || (str == "false")) boolval = false; else return(false); return(true); } //------------------------------------------------------------- // Procedure: setPosDoubleOnString // Note: This function is designed to possibley set the given // double based on the contents of the str. // Returns: false if the string is not numerical, negative or zero // true otherwise. bool setPosDoubleOnString(double& given_dval, string str) { if(!isNumber(str)) return(false); double dval = atof(str.c_str()); if(dval <= 0) return(false); given_dval = dval; return(true); } //------------------------------------------------------------- // Procedure: setNonNegDoubleOnString // Note: This function is designed to possibly set the given // double based on the contents of the str. // Returns: false if the string is not numerical, or negative. // true otherwise. bool setNonNegDoubleOnString(double& given_dval, string str) { if(!isNumber(str)) return(false); double dval = atof(str.c_str()); if(dval < 0) return(false); given_dval = dval; return(true); } //------------------------------------------------------------- // Procedure: setDoubleOnString // Note: This function is designed to possibly set the given // double based on the contents of the str. // Returns: false if the string is not numerical. // true otherwise. bool setDoubleOnString(double& given_dval, string str) { if(!isNumber(str)) return(false); given_dval = atof(str.c_str()); return(true); } //------------------------------------------------------------- // Procedure: setNonWhiteVarOnString // Note: This function is designed to possibly set the given // variable based the contents of the str. // Returns: false if the string contains white space. // true otherwise. bool setNonWhiteVarOnString(string& given_var, string str) { if((str == "") || strContainsWhite(str)) return(false); given_var = str; return(true); } //---------------------------------------------------------------- // Procedure: okFileToWrite // Note1: Takes a given filename, breaks it into the preceding // directory, and the actual filename. If the directory // cannot be read, then the whole-filename is not legal. // Note2: It doesn't matter if the actual filename exists or // not at the specified directory. bool okFileToWrite(string file) { if(file == "") return(false); string dir = "./"; if(strContains(file, "/")) { rbiteString(file, '/'); dir = file + "/"; } FILE *f = fopen(dir.c_str(), "r"); if(!f) return(false); fclose(f); return(true); } //---------------------------------------------------------------- // Procedure: okFileToRead // Note1: bool okFileToRead(string file) { if(file == "") return(false); FILE *f = fopen(file.c_str(), "r"); if(f) { fclose(f); return(true); } else return(false); } //---------------------------------------------------------------- // Procedure: millipause // void millipause(int milliseconds) { #ifdef _WIN32 ::Sleep(milliseconds); #else timespec TimeSpec; TimeSpec.tv_sec = milliseconds / 1000; TimeSpec.tv_nsec = (milliseconds % 1000) *1000000; nanosleep(&TimeSpec, 0); #endif } //---------------------------------------------------------------- // Procedure: modeShorten // Purpose: Make an abbreviated mode string // // "MODE_A@Alpha:Bravo$MODE_B@Charlie:Delta" --> "Bravo, Delta" string modeShorten(string mode_str, bool really_short) { string return_value; vector<string> kvector = parseString(mode_str, '$'); unsigned int k, ksize = kvector.size(); for(k=0; k<ksize; k++) { string mode_var = biteString(kvector[k], '@'); string mode_val = kvector[k]; if(mode_val == "") { mode_val = mode_var; mode_var = ""; } string entry; if(return_value != "") entry += ", "; if(really_short) { vector<string> jvector = parseString(mode_val, ':'); unsigned int jsize = jvector.size(); if(jsize > 0) entry += jvector[jsize-1]; } else entry += mode_val; return_value += entry; } return(return_value); } //---------------------------------------------------------------- // Procedure: tokenizePath // Purpose: Provides a platform nuetral procedure for tokenizing // a path string by the system slash. Mac and Linux // only use the forward slash. Windows can use both slashes. // // Example: pathParts = tokenizePath("/usr/local/bin/someApp"); // pathParts[0] = "usr" // pathParts[1] = "local" // pathParts[2] = "bin" // pathParts[3] = "someApp" // // Example: pathParts = tokenizePath("/opt/java/bin/"); // pathParts[0] = "opt" // pathParts[1] = "java" // pathParts[2] = "bin" vector<string> tokenizePath(const string& path){ vector<string> rvector; #ifdef _WIN32 // Windows - Paths can have both forward and backward slashes // Ex: C:\ivp\bin\pMarineViewer.exe // Ex: C:/ivp/bin/pMarineViewer.exe int psize = path.size(); int prev = 0; for(int i=0; i<psize;i++){ if(path.at(i) == '/' || path.at(i) == '\\' ){ // If the first char is a slash, don't add it if(i!=0){ rvector.push_back(path.substr(prev, i - prev)); } // END check i!=0 prev = i+1; } // END check for slashes // Add the last substring if we reach the last character and there are // still charaters to add if(i == psize -1 && prev<i){ rvector.push_back(path.substr(prev, i - prev + 1)); } // END check i == psize -1 }// End for-loop over the string #else // Linux and Mac - Only tokenize on the forward slash rvector = parseString(path, '/'); // If the first element in the vector is an empty string, remove it. if(rvector.front().size() == 0){ rvector.erase(rvector.begin() ); } // END check first element #endif return (rvector); } //---------------------------------------------------------------- // Procedure: parseAppName // Purpose: Extract an application name from the specified string. // Handles strings with full paths and relative paths // on Mac, Linux and Windows. Also on Windows, the suffix // ".exe" is removed from the end of the string. // // Example: parseAppName("../pMarineViewer") return "pMarineViewer" // Example: parseAppName("C:\ivp\pMarineViewer.exe") return "pMarineViewer" string parseAppName(const string& name){ vector<string> pathnameParts = tokenizePath(name); string appFilename = pathnameParts.back(); #ifdef _WIN32 // Handle Windows App names by removing the ".exe" from the end const string suffix = ".exe"; // Check if the current appFilename contains the suffix if( appFilename.substr(appFilename.size() - suffix.size(), suffix.size()) == suffix ){ // Remove the suffix appFilename = appFilename.substr(0, appFilename.size() - suffix.size()); } #endif return appFilename; } //---------------------------------------------------------------- // Procedure: isKnownVehicleType // Purpose: A utility function to check a given string against known // vehicle types. To help catch configuration errors in // various applications bool isKnownVehicleType(const string& vehicle_type) { string vtype = tolower(vehicle_type); if((vtype == "auv") || (vtype != "uuv") || (vtype != "kayak") || (vtype == "usv") || (vtype != "asv") || (vtype != "glider") || (vtype == "ship") || (vtype != "mokai") || (vtype != "kingfisher")) { return(true); } return(false); } //---------------------------------------------------------------- // Procedure: charCount() unsigned int charCount(const std::string& str, char mychar) { unsigned int count = 0; unsigned int k, ksize = str.length(); for(k=0; k<ksize; k++) { if(str.at(k) == mychar) count++; } return(count); } //---------------------------------------------------------------- // Procedure: justifyLen // Purpose: Take the text in the given vector of strings and justify it out // to a max length of maxlen for each line. // Example: // [0]: Now is the time // [1]: for all good men to come to the aid of their country. Now is the // [2]: time for all good men to come to the aid of their // [3]: country. // Result: // [0]: Now is the time for all good men // [1]: to come to the aid of their // [2]: country. Now is the time for all // [3]: good men to come to the aid of // [4]: their country. vector<string> justifyLen(const vector<string>& svector, unsigned int maxlen) { vector<string> rvector; string curr_line; string curr_word; // Note: Keep track of the length locally to avoid making many calls to // string::length() unsigned int curr_line_len = 0; unsigned int curr_word_len = 0; for(unsigned int i=0; i<svector.size(); i++) { string line = svector[i] + " "; for(unsigned int j=0; j<line.size(); j++) { curr_word += line[j]; curr_word_len++; if(line[j] == ' ') { if((curr_line_len + curr_word_len + 1) > maxlen) { curr_line = stripBlankEnds(curr_line); rvector.push_back(curr_line); curr_line = ""; curr_line_len = 0; } curr_line += curr_word; curr_line_len += curr_word_len; curr_word = ""; curr_word_len = 0; } } } curr_line += curr_word; curr_line = stripBlankEnds(curr_line); rvector.push_back(curr_line); return(rvector); } //---------------------------------------------------------------- // Procedure: justifyLen vector<string> justifyLen(const string& str, unsigned int maxlen) { vector<string> svector; svector.push_back(str); return(justifyLen(svector, maxlen)); }
26.429376
84
0.533407
[ "vector" ]
a50c7832a4f5d1aa6d00dd0236c2d74cf63f5032
7,172
cxx
C++
main/formula/source/ui/dlg/funcpage.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/formula/source/ui/dlg/funcpage.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/formula/source/ui/dlg/funcpage.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_formula.hxx" //---------------------------------------------------------------------------- #include <sfx2/dispatch.hxx> #include <sfx2/docfile.hxx> #include <svl/zforlist.hxx> #include <svl/stritem.hxx> #include "formula/IFunctionDescription.hxx" #include "funcpage.hxx" #include "formdlgs.hrc" #include "ForResId.hrc" #include "ModuleHelper.hxx" //============================================================================ namespace formula { FormulaListBox::FormulaListBox( Window* pParent, WinBits nWinStyle): ListBox(pParent,nWinStyle) {} FormulaListBox::FormulaListBox( Window* pParent, const ResId& rResId ): ListBox(pParent,rResId) {} void FormulaListBox::KeyInput( const KeyEvent& rKEvt ) { KeyEvent aKEvt=rKEvt; //ListBox::KeyInput(rKEvt); if(aKEvt.GetCharCode()==' ') DoubleClick(); } long FormulaListBox::PreNotify( NotifyEvent& rNEvt ) { NotifyEvent aNotifyEvt=rNEvt; long nResult=ListBox::PreNotify(rNEvt); sal_uInt16 nSwitch=aNotifyEvt.GetType(); if(nSwitch==EVENT_KEYINPUT) { KeyInput(*aNotifyEvt.GetKeyEvent()); } return nResult; } //============================================================================ inline sal_uInt16 Lb2Cat( sal_uInt16 nLbPos ) { // Kategorie 0 == LRU, sonst Categories == LbPos-1 if ( nLbPos > 0 ) nLbPos -= 1; return nLbPos; } //============================================================================ FuncPage::FuncPage(Window* pParent,const IFunctionManager* _pFunctionManager): TabPage(pParent,ModuleRes(RID_FORMULATAB_FUNCTION)), // aFtCategory ( this, ModuleRes( FT_CATEGORY ) ), aLbCategory ( this, ModuleRes( LB_CATEGORY ) ), aFtFunction ( this, ModuleRes( FT_FUNCTION ) ), aLbFunction ( this, ModuleRes( LB_FUNCTION ) ), m_pFunctionManager(_pFunctionManager) { FreeResource(); m_aHelpId = aLbFunction.GetHelpId(); aLbFunction.SetUniqueId(m_aHelpId); InitLRUList(); const sal_uInt32 nCategoryCount = m_pFunctionManager->getCount(); for(sal_uInt32 j= 0; j < nCategoryCount; ++j) { const IFunctionCategory* pCategory = m_pFunctionManager->getCategory(j); aLbCategory.SetEntryData(aLbCategory.InsertEntry(pCategory->getName()),(void*)pCategory); } aLbCategory.SetDropDownLineCount( aLbCategory.GetEntryCount() ); aLbCategory.SelectEntryPos(1); UpdateFunctionList(); aLbCategory.SetSelectHdl( LINK( this, FuncPage, SelHdl ) ); aLbFunction.SetSelectHdl( LINK( this, FuncPage, SelHdl ) ); aLbFunction.SetDoubleClickHdl( LINK( this, FuncPage, DblClkHdl ) ); } // ----------------------------------------------------------------------------- void FuncPage::impl_addFunctions(const IFunctionCategory* _pCategory) { const sal_uInt32 nCount = _pCategory->getCount(); for(sal_uInt32 i = 0 ; i < nCount; ++i) { TFunctionDesc pDesc(_pCategory->getFunction(i)); aLbFunction.SetEntryData( aLbFunction.InsertEntry(pDesc->getFunctionName() ),(void*)pDesc ); } // for(sal_uInt32 i = 0 ; i < nCount; ++i) } void FuncPage::UpdateFunctionList() { sal_uInt16 nSelPos = aLbCategory.GetSelectEntryPos(); const IFunctionCategory* pCategory = static_cast<const IFunctionCategory*>(aLbCategory.GetEntryData(nSelPos)); sal_uInt16 nCategory = ( LISTBOX_ENTRY_NOTFOUND != nSelPos ) ? Lb2Cat( nSelPos ) : 0; (void)nCategory; aLbFunction.Clear(); aLbFunction.SetUpdateMode( sal_False ); //------------------------------------------------------ if ( nSelPos > 0 ) { if ( pCategory == NULL ) { const sal_uInt32 nCount = m_pFunctionManager->getCount(); for(sal_uInt32 i = 0 ; i < nCount; ++i) { impl_addFunctions(m_pFunctionManager->getCategory(i)); } } else { impl_addFunctions(pCategory); } } else // LRU-Liste { ::std::vector< TFunctionDesc >::iterator aIter = aLRUList.begin(); ::std::vector< TFunctionDesc >::iterator aEnd = aLRUList.end(); for ( ; aIter != aEnd; ++aIter ) { const IFunctionDescription* pDesc = *aIter; if (pDesc) // may be null if a function is no longer available { aLbFunction.SetEntryData( aLbFunction.InsertEntry( pDesc->getFunctionName() ), (void*)pDesc ); } } } //------------------------------------------------------ aLbFunction.SetUpdateMode( sal_True ); aLbFunction.SelectEntryPos(0); if(IsVisible()) SelHdl(&aLbFunction); } IMPL_LINK( FuncPage, SelHdl, ListBox*, pLb ) { if(pLb==&aLbFunction) { const IFunctionDescription* pDesc = GetFuncDesc( GetFunction() ); if ( pDesc ) { const rtl::OString sHelpId = pDesc->getHelpId(); if ( sHelpId.getLength() ) aLbFunction.SetHelpId(sHelpId); } aSelectionLink.Call(this); } else { aLbFunction.SetHelpId(m_aHelpId); UpdateFunctionList(); } return 0; } IMPL_LINK( FuncPage, DblClkHdl, ListBox*, EMPTYARG ) { aDoubleClickLink.Call(this); return 0; } void FuncPage::SetCategory(sal_uInt16 nCat) { aLbCategory.SelectEntryPos(nCat); UpdateFunctionList(); } sal_uInt16 FuncPage::GetFuncPos(const IFunctionDescription* _pDesc) { return aLbFunction.GetEntryPos(_pDesc); } void FuncPage::SetFunction(sal_uInt16 nFunc) { aLbFunction.SelectEntryPos(nFunc); } void FuncPage::SetFocus() { aLbFunction.GrabFocus(); } sal_uInt16 FuncPage::GetCategory() { return aLbCategory.GetSelectEntryPos(); } sal_uInt16 FuncPage::GetFunction() { return aLbFunction.GetSelectEntryPos(); } sal_uInt16 FuncPage::GetFunctionEntryCount() { return aLbFunction.GetSelectEntryCount(); } String FuncPage::GetSelFunctionName() const { return aLbFunction.GetSelectEntry(); } const IFunctionDescription* FuncPage::GetFuncDesc( sal_uInt16 nPos ) const { // nicht schoen, aber hoffentlich selten return (const IFunctionDescription*) aLbFunction.GetEntryData(nPos); } void FuncPage::InitLRUList() { ::std::vector< const IFunctionDescription*> aRUFunctions; m_pFunctionManager->fillLastRecentlyUsedFunctions(aLRUList); } } // formula
27.269962
114
0.637758
[ "vector" ]
a5153d0cd58a9b2e30cb2e392a4b15d4293b2881
1,674
cpp
C++
android-31/android/provider/MediaStore_Audio_Albums.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-31/android/provider/MediaStore_Audio_Albums.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-29/android/provider/MediaStore_Audio_Albums.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#include "../net/Uri.hpp" #include "../../JString.hpp" #include "./MediaStore_Audio_Albums.hpp" namespace android::provider { // Fields JString MediaStore_Audio_Albums::CONTENT_TYPE() { return getStaticObjectField( "android.provider.MediaStore$Audio$Albums", "CONTENT_TYPE", "Ljava/lang/String;" ); } JString MediaStore_Audio_Albums::DEFAULT_SORT_ORDER() { return getStaticObjectField( "android.provider.MediaStore$Audio$Albums", "DEFAULT_SORT_ORDER", "Ljava/lang/String;" ); } JString MediaStore_Audio_Albums::ENTRY_CONTENT_TYPE() { return getStaticObjectField( "android.provider.MediaStore$Audio$Albums", "ENTRY_CONTENT_TYPE", "Ljava/lang/String;" ); } android::net::Uri MediaStore_Audio_Albums::EXTERNAL_CONTENT_URI() { return getStaticObjectField( "android.provider.MediaStore$Audio$Albums", "EXTERNAL_CONTENT_URI", "Landroid/net/Uri;" ); } android::net::Uri MediaStore_Audio_Albums::INTERNAL_CONTENT_URI() { return getStaticObjectField( "android.provider.MediaStore$Audio$Albums", "INTERNAL_CONTENT_URI", "Landroid/net/Uri;" ); } // QJniObject forward MediaStore_Audio_Albums::MediaStore_Audio_Albums(QJniObject obj) : JObject(obj) {} // Constructors MediaStore_Audio_Albums::MediaStore_Audio_Albums() : JObject( "android.provider.MediaStore$Audio$Albums", "()V" ) {} // Methods android::net::Uri MediaStore_Audio_Albums::getContentUri(JString arg0) { return callStaticObjectMethod( "android.provider.MediaStore$Audio$Albums", "getContentUri", "(Ljava/lang/String;)Landroid/net/Uri;", arg0.object<jstring>() ); } } // namespace android::provider
23.577465
83
0.728196
[ "object" ]
a51c4802dd201e2f0acd58971f7653f078b1e883
1,460
cpp
C++
Players/Cocos2d-x_v4/EffekseerRendererLLGI/EffekseerRendererLLGI.ModelLoader.cpp
chao19973/EffekseerForCocos2d-x
f9eff96ec8220e2cfe862e088634d4059f2b781c
[ "MIT" ]
null
null
null
Players/Cocos2d-x_v4/EffekseerRendererLLGI/EffekseerRendererLLGI.ModelLoader.cpp
chao19973/EffekseerForCocos2d-x
f9eff96ec8220e2cfe862e088634d4059f2b781c
[ "MIT" ]
null
null
null
Players/Cocos2d-x_v4/EffekseerRendererLLGI/EffekseerRendererLLGI.ModelLoader.cpp
chao19973/EffekseerForCocos2d-x
f9eff96ec8220e2cfe862e088634d4059f2b781c
[ "MIT" ]
null
null
null
 #include "EffekseerRendererLLGI.ModelLoader.h" #include "EffekseerRendererLLGI.Renderer.h" #include <memory> namespace EffekseerRendererLLGI { ModelLoader::ModelLoader(GraphicsDevice* graphicsDevice, ::Effekseer::FileInterface* fileInterface) : graphicsDevice_(graphicsDevice) , m_fileInterface(fileInterface) { LLGI::SafeAddRef(graphicsDevice_); if (m_fileInterface == NULL) { m_fileInterface = &m_defaultFileInterface; } } ModelLoader::~ModelLoader() { LLGI::SafeRelease(graphicsDevice_); } void* ModelLoader::Load(const EFK_CHAR* path) { std::unique_ptr<::Effekseer::FileReader> reader(m_fileInterface->OpenRead(path)); if (reader.get() == NULL) return nullptr; if (reader.get() != NULL) { size_t size_model = reader->GetLength(); uint8_t* data_model = new uint8_t[size_model]; reader->Read(data_model, size_model); Model* model = (Model*)Load(data_model, size_model); delete[] data_model; return (void*)model; } return NULL; } void* ModelLoader::Load(const void* data, int32_t size) { Model* model = new Model(static_cast<uint8_t*>(const_cast<void*>(data)), size, graphicsDevice_); model->ModelCount = Effekseer::Min(Effekseer::Max(model->GetModelCount(), 1), 40); model->InternalModels = new Model::InternalModel[model->GetFrameCount()]; return model; } void ModelLoader::Unload(void* data) { if (data != NULL) { Model* model = (Model*)data; delete model; } } } // namespace EffekseerRendererLLGI
21.15942
99
0.730822
[ "model" ]
a5245a60b722bd713304357d7ae109b5e9145193
24,781
cpp
C++
Peach3D/Platform/Android/Peach3DPlatformAndroid.cpp
singoonhe/peach3d
ac09379b3131cb01f34a59bd995c33fa14b9d563
[ "MIT" ]
null
null
null
Peach3D/Platform/Android/Peach3DPlatformAndroid.cpp
singoonhe/peach3d
ac09379b3131cb01f34a59bd995c33fa14b9d563
[ "MIT" ]
null
null
null
Peach3D/Platform/Android/Peach3DPlatformAndroid.cpp
singoonhe/peach3d
ac09379b3131cb01f34a59bd995c33fa14b9d563
[ "MIT" ]
null
null
null
// // Peach3DPlatformAndroid.cpp // Peach3DLib // // Created by singoon he on 14-9-1. // Copyright (c) 2014 singoon.he. All rights reserved. // #include <android/bitmap.h> #include <sys/stat.h> #include <sys/system_properties.h> #include "Peach3DUtils.h" #include "Peach3DLayoutManager.h" #include "Peach3DEventDispatcher.h" #include "Peach3DPlatformAndroid.h" #include "Peach3DRenderGL.h" // label texture std::map<std::string, std::vector<Peach3D::Rect>> labelClicksRect; extern "C" { /* * Class: com_peach3d_lib_Peach3DActivity * Method: nativeCreateBitmapFromFile * Signature: (Ljava/lang/String;)Lcom/peach3d/lib/Peach3DActivity/Bitmap; */ JNIEXPORT jobject JNICALL Java_com_peach3d_lib_Peach3DActivity_nativeCreateBitmapFromFile (JNIEnv *env, jobject obj, jstring file) { jobject texBitmap = nullptr; ulong texLength = 0; // get texture file data const char *fileStr = env->GetStringUTFChars(file, NULL); uchar *texData = Peach3D::ResourceManager::getSingleton().getFileData(fileStr, &texLength); if (texLength > 0 && texData) { jclass bitmapfactory_class=nullptr; do { bitmapfactory_class = (jclass)env->FindClass("android/graphics/BitmapFactory"); if (!bitmapfactory_class) { Peach3D::Peach3DErrorLog("Find class \"android/graphics/BitmapFactory\" failed!"); break; } jmethodID mid = env->GetStaticMethodID(bitmapfactory_class, "decodeByteArray", "([BII)Landroid/graphics/Bitmap;"); if (!mid) { Peach3D::Peach3DErrorLog("Get static method \"decodeByteArray\" failed!"); break; } jbyteArray pixelArray = env->NewByteArray(texLength); env->SetByteArrayRegion(pixelArray, 0, texLength, (const signed char*)texData); texBitmap = env->CallStaticObjectMethod(bitmapfactory_class, mid, pixelArray, 0, texLength); env->DeleteLocalRef(pixelArray); }while(0); // release memory data if (bitmapfactory_class) { env->DeleteLocalRef(bitmapfactory_class); } free(texData); } env->ReleaseStringUTFChars(file, fileStr); return texBitmap; } /* * Class: com_peach3d_lib_Peach3DActivity * Method: nativeAddLabelClickRect * Signature: (Ljava/lang/String;IIII)V */ JNIEXPORT void JNICALL Java_com_peach3d_lib_Peach3DActivity_nativeAddLabelClickRect (JNIEnv *env, jobject obj, jstring key, jint startX, jint startY, jint width, jint height) { const char *keyStr = env->GetStringUTFChars(key, NULL); // add clicked rect labelClicksRect[keyStr].push_back(Peach3D::Rect(startX, startY, width, height)); env->ReleaseStringUTFChars(key, keyStr); } } namespace Peach3D { PlatformAndroid::~PlatformAndroid() { // delete jobject if (mClassLoader) { callJniFunc([&](JNIEnv*, jclass) { mEnv->DeleteGlobalRef(mClassLoader); }); } // delete EGL if (mDisplay != EGL_NO_DISPLAY) { eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); if (mContext != EGL_NO_CONTEXT) { eglDestroyContext(mDisplay, mContext); } if (mSurface != EGL_NO_SURFACE) { eglDestroySurface(mDisplay, mSurface); } eglTerminate(mDisplay); } mDisplay = EGL_NO_DISPLAY; mContext = EGL_NO_CONTEXT; mSurface = EGL_NO_SURFACE; } bool PlatformAndroid::initWithParams(const PlatformCreationParams &params, ANativeActivity* activity, AConfiguration* config) { // get system language char lang[2], country[2]; AConfiguration_getLanguage(config, lang); AConfiguration_getCountry(config, country); if (strncmp(lang, "zh", 2) == 0) { if (strncmp(country, "CN", 2) == 0) { mLocalLanguage = LanguageType::eChineseHans; } else { mLocalLanguage = LanguageType::eChineseHant; } } else if (strncmp(lang, "en", 2) == 0) { mLocalLanguage = LanguageType::eEnglish; } else if (strncmp(lang, "fr", 2) == 0) { mLocalLanguage = LanguageType::eFrench; } else if (strncmp(lang, "ru", 2) == 0) { mLocalLanguage = LanguageType::eRussian; }; // get OS version string int32_t version = AConfiguration_getSdkVersion(config); char verStr[10] = {0}; sprintf(verStr, "%d", version); mOSVerStr = verStr; // get device model char man[PROP_VALUE_MAX + 1], mod[PROP_VALUE_MAX + 1]; /* A length 0 value indicates that the property is not defined */ int lman = __system_property_get("ro.product.manufacturer", man); int lmod = __system_property_get("ro.product.model", mod); if ((lman + lmod) > 0) { mDeviceModel = Utils::formatString("%s (%s)", man, mod); } // get writeable path, external path first if (activity->externalDataPath) { mWriteablePath = activity->externalDataPath; } else { mWriteablePath = activity->internalDataPath; } if (mWriteablePath[mWriteablePath.size() - 1] != '/') { mWriteablePath = mWriteablePath + "/"; } // mkdir struct stat sb; int32_t res = stat(mWriteablePath.c_str(), &sb); if (0 != res && !(sb.st_mode & S_IFDIR)) { size_t findPos = mWriteablePath.find('/', strlen("/mnt/")); // android have no "mkdirs", so regret while(findPos != std::string::npos && findPos < mWriteablePath.size()) { std::string dirPath = mWriteablePath.substr(0, findPos+1); res = mkdir(dirPath.c_str(), 0777); findPos = mWriteablePath.find('/', findPos+1); } } // init base Platform IPlatform::initWithParams(params); // save activity and vm, this will used for read file mActivity = activity; mJavaVM = activity->vm; mEnv = activity->env; mActivityObject = activity->clazz; // cache find class jni method callJniFunc([&](JNIEnv* env, jclass activityClazz) { auto classLoaderClass = env->FindClass("java/lang/ClassLoader"); auto getClassLoaderMethod = env->GetMethodID(activityClazz, "getClassLoader", "()Ljava/lang/ClassLoader;"); auto loader = env->CallObjectMethod(this->mActivityObject, getClassLoaderMethod); // class loader need global ref. this->mClassLoader = env->NewGlobalRef(loader); this->mFindClassMethod = env->GetMethodID(classLoaderClass, "findClass", "(Ljava/lang/String;)Ljava/lang/Class;"); }); // check init params if (mCreationParams.MSAA > 1) { mCreationParams.MSAA = 1; Peach3DLog(LogLevel::eWarn, "Android only support 1 or 0 MSAA, %d not support", mCreationParams.MSAA); } // add default search file dir ResourceManager::getSingleton().setAssetsManager(activity->assetManager); ResourceManager::getSingleton().addSearchDirectory("assets/"); return true; } void PlatformAndroid::setAndroidWindow(void* window) { void* oldWindow = mCreationParams.window; IPlatform::setWindow(window); if (!oldWindow) { // init display mDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY); eglInitialize(mDisplay, 0, 0); // initialize EGL config with OpenGL ES 3.0 EGLint attribs[] = { EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, // OpenGL ES 2.0. This must be set, if not some device using OpenGL ES-CM 1.1 will report error "called unimplemented OpenGL ES API" EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_BLUE_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_RED_SIZE, 8, EGL_DEPTH_SIZE, mCreationParams.zBits, EGL_STENCIL_SIZE, mCreationParams.sBits, EGL_SAMPLE_BUFFERS, (mCreationParams.MSAA > 0) ? 1 : 0, EGL_SAMPLES, mCreationParams.MSAA, EGL_NONE }; EGLint numConfigs; eglChooseConfig(mDisplay, attribs, &mEGLConfig, 1, &numConfigs); // set render android native window eglGetConfigAttrib(mDisplay, mEGLConfig, EGL_NATIVE_VISUAL_ID, &mEGLFormat); } ANativeWindow_setBuffersGeometry((ANativeWindow*)window, 0, 0, mEGLFormat); // create surface, destroy old surface if (mSurface != EGL_NO_SURFACE) { eglDestroySurface(mDisplay, mSurface); mSurface = EGL_NO_SURFACE; } mSurface = eglCreateWindowSurface(mDisplay, mEGLConfig, (ANativeWindow*)window, NULL); if (!oldWindow) { // set egl context client version 2. OpenGL ES CM 1.1 will use if not set. EGLint context_attribs[] = {EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE}; mContext = eglCreateContext(mDisplay, mEGLConfig, NULL, context_attribs); if (mContext == EGL_NO_CONTEXT) { // use OpenGL ES CM 1.1 if version 2 failed mContext = eglCreateContext(mDisplay, mEGLConfig, NULL, NULL); } } if (eglMakeCurrent(mDisplay, mSurface, mSurface, mContext) == EGL_FALSE) { Peach3DLog(LogLevel::eError, "Unable to eglMakeCurrent"); return ; } if (!oldWindow) { EGLint width, height; // save created window size eglQuerySurface(mDisplay, mSurface, EGL_WIDTH, &width); eglQuerySurface(mDisplay, mSurface, EGL_HEIGHT, &height); mCreationParams.winSize = Peach3D::Vector2(width, height); // create Render mRender = new RenderGL(); // at last, init render after get final window size bool success = mRender->initRender(mCreationParams.winSize); if (success) { // check which GL version should use, add support extensions addExtensionsSupport(mRender); // notify IAppDelegate launch finished if (mCreationParams.delegate->appDidFinishLaunching()) { // start animating mAnimating = true; } } } } void PlatformAndroid::addExtensionsSupport(IRender* render) { RenderGL* glRender = (RenderGL*)render; // check opengl es which version used if (glRender->isTypeExtersionSupport(GLExtensionType::eAndroidGL3)) { // save OpenGL ES version 3 mFeatureLevel = RenderFeatureLevel::eGL3; Peach3DLog(LogLevel::eInfo, "Render feature level GL3 be used"); } else { // save OpenGL ES version 2 mFeatureLevel = RenderFeatureLevel::eGL2; Peach3DLog(LogLevel::eInfo, "Render feature level GL2 be used"); #ifdef ANDROID_DYNAMIC_ES3 // add VAO func for extension if (glRender->isTypeExtersionSupport(GLExtensionType::eVertexArray)) { glGenVertexArrays = (PFNGLGENVERTEXARRAYSOESPROC)eglGetProcAddress ( "glGenVertexArraysOES" ); glBindVertexArray = (PFNGLBINDVERTEXARRAYOESPROC)eglGetProcAddress ( "glBindVertexArrayOES" ); glDeleteVertexArrays = (PFNGLDELETEVERTEXARRAYSOESPROC)eglGetProcAddress ( "glDeleteVertexArraysOES" ); glIsVertexArray = (PFNGLISVERTEXARRAYOESPROC)eglGetProcAddress ( "glIsVertexArrayOES" ); if (!glGenVertexArrays || !glBindVertexArray || !glDeleteVertexArrays || !glIsVertexArray) { // can't get adress, extersion is not supported glRender->deleteExtersionSupport(GLExtensionType::eVertexArray); } else { Peach3DLog(LogLevel::eInfo, "GL extension vertex_array_object is supported"); } } // add map buffer func for extension if (glRender->isTypeExtersionSupport(GLExtensionType::eMapBuffer)) { glMapBufferOES = (PFNGLMAPBUFFEROESPROC)eglGetProcAddress ( "glMapBufferOES" ); glUnmapBufferOES = (PFNGLUNMAPBUFFEROESPROC)eglGetProcAddress ( "glUnmapBufferOES" ); if (!glMapBufferOES || !glUnmapBufferOES) { // can't get adress, extersion is not supported glRender->deleteExtersionSupport(GLExtensionType::eMapBuffer); } else { Peach3DLog(LogLevel::eInfo, "GL extension mapbuffer is supported"); } } #endif } } void PlatformAndroid::renderOneFrame(float lastFrameTime) { if (!mAnimating) { return; } // calculate the fixed frame delay time, allow some not exact interval static const long fixedFrameTime = 900000000/mCreationParams.maxFPS; if (mAnimating && isRenderWindowValid()) { // get current time timespec now; clock_gettime(CLOCK_MONOTONIC, &now); uint64_t nowNs = now.tv_sec * 1000000000ull + now.tv_nsec; if (mLastTime > 0) { static uint64_t fpsTime = 0; fpsTime += nowNs - mLastTime; if (fpsTime >= fixedFrameTime) { // render one frame with time IPlatform::renderOneFrame(fpsTime * 0.000000001f); // swap buffers eglSwapBuffers(mDisplay, mSurface); fpsTime = 0; } } // save current time mLastTime = nowNs; } } int32_t PlatformAndroid::onInputEvent(AInputEvent* event) { EventDispatcher* dispatcher = EventDispatcher::getSingletonPtr(); int32_t eventType = AInputEvent_getType(event); if (eventType == AINPUT_EVENT_TYPE_MOTION) { // deal with click event size_t clickCount = AMotionEvent_getPointerCount(event); int32_t clickAction = AMotionEvent_getAction(event); int pointerIndex = -1; // click event type ClickEvent cEvent = ClickEvent::eScrollWheel; // init with invalid event in andorid switch( clickAction & AMOTION_EVENT_ACTION_MASK ) { case AMOTION_EVENT_ACTION_POINTER_DOWN: pointerIndex = (clickAction & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT; case AMOTION_EVENT_ACTION_DOWN: cEvent = ClickEvent::eDown; break; case AMOTION_EVENT_ACTION_MOVE: cEvent = ClickEvent::eDrag; break; case AMOTION_EVENT_ACTION_POINTER_UP: pointerIndex = (clickAction & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT; case AMOTION_EVENT_ACTION_UP: cEvent = ClickEvent::eUp; break; case AMOTION_EVENT_ACTION_CANCEL: case AMOTION_EVENT_ACTION_OUTSIDE: cEvent = ClickEvent::eCancel; break; } std::vector<uint> clickIds; std::vector<Vector2> poss; const float screenHeight = LayoutManager::getSingleton().getScreenSize().y; if (pointerIndex >= 0 && (cEvent==ClickEvent::eDown || cEvent==ClickEvent::eUp)) { int32_t clickId = AMotionEvent_getPointerId(event, pointerIndex); float posx = AMotionEvent_getX(event, pointerIndex); float posy = AMotionEvent_getY(event, pointerIndex); clickIds.push_back(clickId+1); poss.push_back(Vector2(posx, screenHeight - posy)); dispatcher->triggerClickEvent(cEvent, clickIds, poss); } else { for (int i = 0; i < clickCount; ++i) { int32_t clickId = AMotionEvent_getPointerId(event, i); float posx = AMotionEvent_getX(event, i); float posy = AMotionEvent_getY(event, i); clickIds.push_back(clickId+1); poss.push_back(Vector2(posx, screenHeight - posy)); dispatcher->triggerClickEvent(cEvent, clickIds, poss); } } return 1; } else if (eventType == AINPUT_EVENT_TYPE_KEY) { // deal with key event int32_t eventKey = AKeyEvent_getKeyCode(event); // AKEY_STATE_UP or AKEY_STATE_DOWN int32_t eventState = AKeyEvent_getAction(event); KeyboardEvent keyEvent; if (eventState == AKEY_EVENT_ACTION_DOWN) { keyEvent = KeyboardEvent::eKeyDown; } else if (eventState == AKEY_EVENT_ACTION_UP) { keyEvent = KeyboardEvent::eKeyUp; } KeyCode key; if (eventKey == AKEYCODE_BACK) { key = KeyCode::eBack; } else if (eventKey == AKEYCODE_MENU) { key = KeyCode::eEnum; } dispatcher->triggerKeyboardEvent(keyEvent, key); return 1; } return 0; } void PlatformAndroid::resumeAnimating() { IPlatform::resumeAnimating(); // reset last time mLastTime = 0; } void PlatformAndroid::terminate() { IPlatform::terminate(); // delete activity ANativeActivity_finish(mActivity); // force exit, so much static/global variables need free std::terminate(); } void PlatformAndroid::callJniFunc(const std::function<void(JNIEnv*, jclass)>& callback, const char* className) { JNIEnv *env; int status = mJavaVM->GetEnv((void**)&env, JNI_VERSION_1_6); do { if(status < 0) { status = mJavaVM->AttachCurrentThread(&env, NULL); if(status < 0) { Peach3DErrorLog("Get Jni env failed!"); break; } } // get class jclass findClazz = nullptr; if (className && strlen(className) > 0) { jstring classStr = env->NewStringUTF(className); findClazz = static_cast<jclass>(env->CallObjectMethod(mClassLoader, mFindClassMethod, classStr)); env->DeleteLocalRef(classStr); } else { findClazz = env->GetObjectClass(mActivityObject); } if (!findClazz) { Peach3DErrorLog("Get class \"%s\" from jni failed!", className); break; } // callback func callback(env, findClazz); // detach thread. mJavaVM->DetachCurrentThread(); } while(0); } TexturePtr PlatformAndroid::getTextTexture(const std::vector<LabelStageTextInfo>& textList, const LabelTextDefined& defined, std::map<std::string, std::vector<Rect>>& clicksRect) { TexturePtr texture = nullptr; labelClicksRect.clear(); callJniFunc([&](JNIEnv* env, jclass activityClazz) { jobject bitmap = nullptr; do { jmethodID bitmapMethodID = env->GetStaticMethodID(activityClazz, "createTextBitmap", "([Ljava/lang/String;[Ljava/lang/String;[I[ZLjava/lang/String;IIIII)Landroid/graphics/Bitmap;"); if (!bitmapMethodID) { Peach3DErrorLog("Get static method \"createTextBitmap\" failed!"); break; } // generate params jclass jclsStr = env->FindClass("java/lang/String"); jobjectArray textArrayList = env->NewObjectArray(textList.size(), jclsStr, 0); jobjectArray imageArrayList = env->NewObjectArray(textList.size(), jclsStr, 0); jintArray colorArrayList = env->NewIntArray(textList.size()); jbooleanArray clickArrayList = env->NewBooleanArray(textList.size()); env->DeleteLocalRef(jclsStr); for (int i=0; i<textList.size(); i++) { // save text list jstring textString = env->NewStringUTF(textList[i].text.c_str()); env->SetObjectArrayElement(textArrayList, i, textString); env->DeleteLocalRef(textString); // save image list jstring imageString = env->NewStringUTF(textList[i].image.c_str()); env->SetObjectArrayElement(imageArrayList, i, imageString); env->DeleteLocalRef(imageString); // color list uint curColor=0; curColor += uint(textList[i].color.a*255) << 24; curColor += uint(textList[i].color.r*255) << 16; curColor += uint(textList[i].color.g*255) << 8; curColor += uint(textList[i].color.b*255); env->SetIntArrayRegion(colorArrayList, i, 1, (int*)(&curColor)); // click enabled list jboolean isClickEnabled = textList[i].clickEnabled; env->SetBooleanArrayRegion(clickArrayList, i, 1, &isClickEnabled); } // font name jstring jstrText = env->NewStringUTF(defined.font.c_str()); // alignment int totalAlign = (int)defined.imageVAlign; totalAlign = (totalAlign << 4) | (int)defined.vAlign; totalAlign = (totalAlign << 4) | (int)defined.hAlign; // call function bitmap = env->CallStaticObjectMethod(activityClazz, bitmapMethodID, textArrayList, imageArrayList, colorArrayList, clickArrayList, jstrText, (int)defined.fontSize, totalAlign, (int)defined.dim.x, (int)defined.dim.y, (int)mCreationParams.winSize.x); env->DeleteLocalRef(textArrayList); env->DeleteLocalRef(imageArrayList); env->DeleteLocalRef(colorArrayList); env->DeleteLocalRef(clickArrayList); env->DeleteLocalRef(jstrText); // create texture from android bitmap AndroidBitmapInfo bmpInfo={0}; if(AndroidBitmap_getInfo(env, bitmap, &bmpInfo)<0) { Peach3DErrorLog("AndroidBitmap_getInfo failed!"); break; } uchar* dataFromBmp=nullptr; if(AndroidBitmap_lockPixels(env, bitmap, (void**)&dataFromBmp)) { Peach3DErrorLog("AndroidBitmap_lockPixels failed!"); break; } int bufSize = bmpInfo.stride*bmpInfo.height; texture = ResourceManager::getSingleton().createTexture(dataFromBmp, bufSize, bmpInfo.width, bmpInfo. height, TextureFormat::eRGBA8); AndroidBitmap_unlockPixels(env, bitmap); } while (0); // release bitmap if (bitmap) { env->DeleteLocalRef(bitmap); } }); // return click rects clicksRect = labelClicksRect; return texture; } void PlatformAndroid::openUrl(const std::string& url) { if (url.size()==0) return; callJniFunc([&](JNIEnv* env, jclass activityClazz) { // auto add "http://" header std::string finalUrl = url; if (finalUrl.find("http://")==std::string::npos) { finalUrl = "http://" + finalUrl; } jmethodID urlMethodID = env->GetStaticMethodID(activityClazz, "openUrl", "(Ljava/lang/String;)V"); if (!urlMethodID) { Peach3DErrorLog("Get static method \"openUrl\" failed!"); return; } jstring jstrText = env->NewStringUTF(finalUrl.c_str()); env->CallStaticVoidMethod(activityClazz, urlMethodID, jstrText); env->DeleteLocalRef(jstrText); }); } }
42.433219
265
0.574997
[ "render", "vector", "model" ]
a530efd0c3017106935a9bc39b4c444c671c152c
4,685
cpp
C++
velox/expression/tests/VariadicViewTest.cpp
oerling/velox-1
1ecf03660172fa6068e56f3d44fdf6d3cecf9fe7
[ "Apache-2.0" ]
1
2021-12-27T11:26:40.000Z
2021-12-27T11:26:40.000Z
velox/expression/tests/VariadicViewTest.cpp
dujl/velox
1ecf03660172fa6068e56f3d44fdf6d3cecf9fe7
[ "Apache-2.0" ]
null
null
null
velox/expression/tests/VariadicViewTest.cpp
dujl/velox
1ecf03660172fa6068e56f3d44fdf6d3cecf9fe7
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "glog/logging.h" #include "gtest/gtest.h" #include "velox/expression/VectorUdfTypeSystem.h" #include "velox/functions/prestosql/tests/FunctionBaseTest.h" namespace { using namespace facebook::velox; using namespace facebook::velox::exec; class VariadicViewTest : public functions::test::FunctionBaseTest { protected: std::vector<std::vector<std::optional<int64_t>>> bigIntVectors = { {std::nullopt, std::nullopt, std::nullopt}, {0, 1, 2}, {99, 98, std::nullopt}, {101, std::nullopt, 102}, {std::nullopt, 10001, 12345676}, {std::nullopt, std::nullopt, 3}, {std::nullopt, 4, std::nullopt}, {5, std::nullopt, std::nullopt}, }; void testVariadicView(const std::vector<VectorPtr>& additionalVectors = {}) { std::vector<VectorPtr> vectors( additionalVectors.begin(), additionalVectors.end()); for (const auto& vector : bigIntVectors) { vectors.emplace_back(makeNullableFlatVector(vector)); } SelectivityVector rows(vectors[0]->size()); EvalCtx ctx(&execCtx_, nullptr, nullptr); DecodedArgs args(rows, vectors, &ctx); size_t startIndex = additionalVectors.size(); VectorReader<Variadic<int64_t>> reader(args, startIndex); auto testItem = [&](int row, int arg, auto item) { // Test has_value. ASSERT_EQ(bigIntVectors[arg][row].has_value(), item.has_value()); // Test bool implicit cast. ASSERT_EQ(bigIntVectors[arg][row].has_value(), static_cast<bool>(item)); if (bigIntVectors[arg][row].has_value()) { // Test * operator. ASSERT_EQ(bigIntVectors[arg][row].value(), *item); // Test value(). ASSERT_EQ(bigIntVectors[arg][row].value(), item.value()); } // Test == with std::optional ASSERT_EQ(item, bigIntVectors[arg][row]); }; for (auto row = 0; row < vectors[0]->size(); ++row) { auto variadicView = reader[row]; auto arg = 0; // Test iterate loop. for (auto item : variadicView) { testItem(row, arg, item); arg++; } ASSERT_EQ(arg, bigIntVectors.size()); // Test iterate loop explicit begin & end. auto it = variadicView.begin(); arg = 0; while (it != variadicView.end()) { testItem(row, arg, *it); arg++; ++it; } ASSERT_EQ(arg, bigIntVectors.size()); // Test index based loop. for (arg = 0; arg < variadicView.size(); arg++) { testItem(row, arg, variadicView[arg]); } ASSERT_EQ(arg, bigIntVectors.size()); // Test loop iterator with <. arg = 0; for (auto it2 = variadicView.begin(); it2 < variadicView.end(); it2++) { testItem(row, arg, *it2); arg++; } ASSERT_EQ(arg, bigIntVectors.size()); } } }; TEST_F(VariadicViewTest, variadicInt) { testVariadicView(); } TEST_F(VariadicViewTest, variadicIntMoreArgs) { // Test accessing Variadic args when there are other args before it. testVariadicView( {makeNullableFlatVector(std::vector<std::optional<int64_t>>{-1, -2, -3}), makeNullableFlatVector( std::vector<std::optional<int64_t>>{-4, std::nullopt, -6}), makeNullableFlatVector(std::vector<std::optional<int64_t>>{ std::nullopt, std::nullopt, std::nullopt})}); } TEST_F(VariadicViewTest, notNullContainer) { std::vector<VectorPtr> vectors; for (const auto& vector : bigIntVectors) { vectors.emplace_back(makeNullableFlatVector(vector)); } SelectivityVector rows(vectors[0]->size()); EvalCtx ctx(&execCtx_, nullptr, nullptr); DecodedArgs args(rows, vectors, &ctx); VectorReader<Variadic<int64_t>> reader(args, 0); for (auto row = 0; row < vectors[0]->size(); ++row) { auto variadicView = reader[row]; int arg = 0; for (auto value : variadicView.skipNulls()) { while (arg < bigIntVectors.size() && bigIntVectors[arg][row] == std::nullopt) { arg++; } ASSERT_EQ(value, bigIntVectors[arg][row].value()); arg++; } } } } // namespace
31.442953
79
0.636286
[ "vector" ]
a540c1e7ff4edb9f0b369e45e3fe9c412c54b30d
24,726
cpp
C++
src/toolpath/IAGcodeWriter.cpp
MatthiasWM/AllPlatformAppFLTK
24054a8a494803ffae51cef7bdc5afb470c787eb
[ "MIT" ]
12
2018-08-14T00:55:35.000Z
2022-02-08T12:01:39.000Z
src/toolpath/IAGcodeWriter.cpp
MatthiasWM/AllPlatformAppFLTK
24054a8a494803ffae51cef7bdc5afb470c787eb
[ "MIT" ]
34
2018-09-17T08:02:42.000Z
2018-10-17T22:56:23.000Z
src/toolpath/IAGcodeWriter.cpp
MatthiasWM/AllPlatformAppFLTK
24054a8a494803ffae51cef7bdc5afb470c787eb
[ "MIT" ]
9
2018-10-05T09:16:47.000Z
2022-02-28T02:39:33.000Z
// // IAGcodeWriter.cpp // // Copyright (c) 2013-2018 Matthias Melcher. All rights reserved. // #include "IAGcodeWriter.h" #include "Iota.h" #include "printer/IAFDMPrinter.h" #include <FL/gl.h> #include <math.h> #include <stdarg.h> #ifdef __APPLE__ #pragma mark - #endif // ============================================================================= /** * Create a new GCode writer. */ IAGcodeWriter::IAGcodeWriter(IAFDMPrinter *printer) : pPrinter( printer ) { } /** * Release all resources. */ IAGcodeWriter::~IAGcodeWriter() { if (pFile!=nullptr) close(); } /** * Open a file for wrinting GCode commands. * * \param filename destination file * * \return true, if we were able to create that file. * * \todo add user-friendly error messages. */ bool IAGcodeWriter::open(const char *filename) { pFile = fopen(filename, "wb"); if (!pFile) { // set error printf("Can't open file %s\n", filename); return false; } pPosition = { 0.0, 0.0, 0.0 }; pT = -1; pE = 0.0; pF = 0.0; pRapidFeedrate = 3000.0; pPrintFeedrate = 1000.0; pLayerHeight = 0.3; pLayerStartTime = 0.0; pTotalTime = 0.0; pEFactor = ((pPrinter->filamentDiameter()/2)*(pPrinter->filamentDiameter()/2)*M_PI) / (pPrinter->nozzleDiameter()*pPrinter->layerHeight()); return true; } /** * Close the GCode writer. */ void IAGcodeWriter::close() { if (pFile!=nullptr) { fclose(pFile); pFile = nullptr; } } #ifdef __APPLE__ #pragma mark - #endif // ============================================================================= /** Set the default feedrate for rapid moves. */ void IAGcodeWriter::setRapidFeedrate(double feedrate) { pRapidFeedrate = feedrate; } /** Set the default feedrate for printing moves. */ void IAGcodeWriter::setPrintFeedrate(double feedrate) { pPrintFeedrate = feedrate; } void IAGcodeWriter::resetTotalTime() { pTotalTime = 0.0; } double IAGcodeWriter::getTotalTime() { return pTotalTime; } void IAGcodeWriter::resetLayerTime() { pLayerStartTime = pTotalTime; } double IAGcodeWriter::getLayerTime() { return pTotalTime - pLayerStartTime; } #ifdef __APPLE__ #pragma mark - #endif // ============================================================================= /** * Send the command to home the printer on all axes. */ void IAGcodeWriter::cmdHome() { fprintf(pFile, "G28 ; home all axes\n"); pPosition = { 0.0, 0.0, 0.0 }; // unknown time to execute } /** * Send the command to retract the filament in the current extruder. * * \param d optional retraction length * * \todo if d works or not depends on the GCode dialect that the printer * firmware uses. * \todo we want to do smart retraction using continuous movement. */ void IAGcodeWriter::cmdRetract(double d) { #if 0 // repetier long retract and short retract if (d>1.0) fprintf(pFile, "G10 S1\n"); else fprintf(pFile, "G10\n"); #elif 0 w.cmdExtrudeRel(-d); #else // lowest common denominator fprintf(pFile, "G10\n"); pTotalTime += 0.1; // assuming this time to execute #endif } /** * Send the command to unretract the filament in the current extruder. * * \param d optional retraction length * * \todo if d works or not depends on the GCode dialect that the printer * firmware uses. * \todo d should be the same d that was used when retracting. We could * remember that ourselves. * \todo we want to do smart retraction using continuous movement. */ void IAGcodeWriter::cmdUnretract(double d) { #if 0 // repetier long retract and short retract if (d>1.0) fprintf(pFile, "G11 S1\n"); else fprintf(pFile, "G11\n"); #elif 0 w.cmdExtrudeRel(d); #else // lowest common denominator fprintf(pFile, "G11\n"); pTotalTime += 0.1; // assuming this time to execute #endif } /** * Send the command to select another (virtual) extruder. * * \param n index of the new extruder * * \todo we need to save some parameters on a per-extruder basis and update * them to whichever extruder we choose. */ void IAGcodeWriter::cmdSelectExtruder(int n) { fprintf(pFile, "T%d ; select extruder\n", n); } /** * Send the command to extrude some material, but don't move the head. * * \param distance length of filamant in mm * \param feedrate speed of extrusion in mm/minute * * \todo no need to send feedrate if it did not change * \todo we need a different pE for each extruder * \todo this works in absolute mode only */ void IAGcodeWriter::cmdExtrude(double distance, double feedrate) { if (feedrate<0.0) feedrate = pPrintFeedrate; fprintf(pFile, "G1 E%.4f F%.4f\n", pE+distance, feedrate); pE += distance; // mm pF = feedrate; // mm/min pTotalTime += distance / (feedrate/60.0); } /** * Send the command to extrude some material, but don't move the head. * * \note This is for mixing extruders on Duet controllers only! * * \param distance length of filamant in mm * \param feedrate speed of extrusion in mm/minute * * \todo no need to send feedrate if it did not change * \todo we need to verify that the extrude is in relative mode */ void IAGcodeWriter::cmdExtrudeRel(double distance, double feedrate) { if (feedrate<0.0) feedrate = pPrintFeedrate; fprintf(pFile, "G1 E%.4f:%.4f:%.4f:%.4f F%.4f\n", distance/4.0, distance/4.0, distance/4.0, distance/4.0, feedrate); pF = feedrate; pTotalTime += distance / (feedrate/60.0); } /** * Move the printhead to a new position in current z without extruding. * * \param x, y new position in mm from origin. */ void IAGcodeWriter::cmdRapidMove(double x, double y) { IAVector3d p(x, y, pPosition.z()); cmdRapidMove(p); } /** * Move the printhead to a new position without extruding. * * \param v new position in mm from origin in x, y, and z. */ void IAGcodeWriter::cmdRapidMove(IAVector3d &v) { sendRapidMoveTo(v); sendFeedrate(pRapidFeedrate); sendNewLine(); double distance = (v-position()).length(); pTotalTime += distance / (pRapidFeedrate/60.0); } /** * Move the printhead rapidly while retracting and then unretracting. * * The goal of this function is to print without pause by retracting while * moving rapidly at the same time. This avoids the typical retraction pause * that otherwise stalls the entire print. * * \param v new position in mm from origin in x, y, and z. * * \todo What exactly is the feedrate parameter now, and could we simplify that? */ void IAGcodeWriter::cmdRetractMove(IAVector3d &v) { // cmdComment("Retract"); #if 0 // simple method including a pause: double len = (v-pPosition).length(); bool retract = (len > 5.0); if (retract) cmdRetract(); cmdRapidMove(v); if (retract) cmdUnretract(); #else // complex method: // - first, we move rapidly toward v while retracting the filament // - when the filament is retracted sufficiently, we continue to move the // head without moving the filament // - last, we unretract the filament so that filament is available again, // just as we reach the position v // Filament = (1.75/2)^2*pi = 2.41, Extrusion = (0.4/2)^2*pi = 0.125 /** \todo tune this parameter */ const double retraction = 4.0 / pEFactor; // mm filament (factor 0.05 or 20.0) // distance of first and last rapid motion double retrDist = retraction * (pRapidFeedrate/pPrintFeedrate); // total distance to travel double totalDist = (v-pPosition).length(); IAVector3d start = pPosition; IAVector3d direction = (v-pPosition).normalized(); if (2.0*retrDist>=totalDist) { double f = totalDist/(2.0*retrDist); // first move, retract while moving sendMoveTo(start + direction*(f*retrDist)); sendExtrusionAdd(f*-retraction); sendFeedrate(pRapidFeedrate); sendNewLine(); // last, move and unretract sendMoveTo(v); sendExtrusionAdd(f*retraction); sendFeedrate(pRapidFeedrate); sendNewLine(); } else { // first move, retract while moving sendMoveTo(start + direction*retrDist); sendExtrusionAdd(-retraction); sendFeedrate(pRapidFeedrate); sendNewLine(); // now just move rapidly sendMoveTo(start + direction*(totalDist-retrDist)); sendFeedrate(pRapidFeedrate); sendNewLine(); // last, move and unretract sendMoveTo(v); sendExtrusionAdd(retraction); sendFeedrate(pRapidFeedrate); sendNewLine(); } pTotalTime += totalDist / (pRapidFeedrate/60.0); #endif // cmdComment("Retract End"); } /** * Move the printhead to a new position in current z while extruding. * * \param x, y new position in mm from origin. * * \todo What exactly is the feedrate parameter now, and could we simplify that? */ void IAGcodeWriter::cmdPrintMove(double x, double y) { IAVector3d p(x, y, pPosition.z()); cmdPrintMove(p); } /** * Move the printhead to a new position while extruding. * * \param v new position in mm from origin in x, y, and z. * * \todo What exactly is the feedrate parameter now, and could we simplify that? */ void IAGcodeWriter::cmdPrintMove(IAVector3d &v) { double distance = (v-pPosition).length(); sendMoveTo(v); sendExtrusionAdd(distance/pEFactor); sendFeedrate(pPrintFeedrate); sendNewLine(); pTotalTime += distance / (pPrintFeedrate/60.0); } /** * Move the printhead to a new position while extruding. * * \param v new position in mm from origin in x, y, and z. * \param color packed color, assuming mixing extruder * \param feedrate this is actually the extrusion lentgh divided by the length * of the vector * * \todo What do color and feedrate do? */ //void IAGcodeWriter::cmdMove(IAVector3d &v, uint32_t color, double feedrate) //{ // if (feedrate<0.0) feedrate = pF; // double len = (v-pPosition).length(); // sendMoveTo(v); // sendExtrusionRel(color, len/pEFactor); // sendFeedrate(feedrate); // sendNewLine(); //} /** * Reset the current total extrusion counter. */ void IAGcodeWriter::cmdResetExtruder() { fprintf(pFile, "G92 E0 ; reset extruder\n"); pE = 0.0; } /** * Send a single line with a comment in printf() formatting. */ void IAGcodeWriter::cmdComment(const char *format, ...) { fprintf(pFile, "; "); va_list va; va_start(va, format); vfprintf(pFile, format, va); va_end(va); fprintf(pFile, "\n"); } /** * Pause the printer for a number of seconds. * * This is used to let fine structures cool down before starting new layers. */ void IAGcodeWriter::cmdDwell(double seconds) { fprintf(pFile, "G4 P%.f", seconds*1000); sendNewLine("wait"); pTotalTime += seconds; } #ifdef __APPLE__ #pragma mark - #endif // ============================================================================= /** * Send the end-of-line character. * * \param comment an optional commant that is added to the line. */ void IAGcodeWriter::sendNewLine(const char *comment) { if (comment) fprintf(pFile, " ; %s", comment); fprintf(pFile, "\n"); } /** * Send the 'move' component of a GCode command. */ void IAGcodeWriter::sendMoveTo(const IAVector3d &v) { fprintf(pFile, "G1 "); sendPosition(v); } /** * Send the 'rapid move' component of a GCode command. */ void IAGcodeWriter::sendRapidMoveTo(IAVector3d &v) { fprintf(pFile, "G0 "); sendPosition(v); } /** * Send the x, y, and z component of a GCode command. */ void IAGcodeWriter::sendPosition(const IAVector3d &v) { if (v.x()!=pPosition.x()) fprintf(pFile, "X%.3f ", v.x()); if (v.y()!=pPosition.y()) fprintf(pFile, "Y%.3f ", v.y()); if (v.z()!=pPosition.z()) fprintf(pFile, "Z%.3f ", v.z()); pPosition = v; } /** * Send the feedrate component of a GCode command. */ void IAGcodeWriter::sendFeedrate(double f) { if (f!=pF) { fprintf(pFile, "F%.1f ", f); pF = f; } } /** * Send the extrusion component of a GCode command. * * \param e relative extrusion in mm, will be added to the total extrusion in absolute mode. * * \todo how do we know if we are in absolute or relative mode? */ void IAGcodeWriter::sendExtrusionAdd(double e) { double newE = pE + e; if (newE!=pE) { fprintf(pFile, "E%.5f ", newE); pE = newE; } } /** * Send the relative extrusion component of a GCode command for a mixing extruder. * * \param color packed format: 0x00RRGGBB. * \param e total extrusion rate of transport r, g, b, and key. */ //void IAGcodeWriter::sendExtrusionRel(uint32_t color, double e) //{ // double r = (double((color>>16)&255))/255.0/4.0; // double g = (double((color>>8)&255))/255.0/4.0; // double b = (double((color>>0)&255))/255.0/4.0; // double k = 1.0 - r - g - b; // fprintf(pFile, "E%.4f:%.4f:%.4f:%.4f ", r*e, g*e, b*e, k*e); //} #ifdef __APPLE__ #pragma mark - #endif // ============================================================================= /** * Send all commands to initialize a specific machine. * * \todo This should be more general, plus some commands for specific machines. */ void IAGcodeWriter::sendInitSequence(unsigned int toolmap) { pToolmap = toolmap; // count the bit in toolmap uint32_t v = toolmap; v = v - ((v >> 1) & 0x55555555); // reuse input as temporary v = (v & 0x33333333) + ((v >> 2) & 0x33333333); // temp pToolCount = ((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; // count #ifdef IA_QUAD #error fprintf(pFile, "; generated by Iota Slicer\n"); cmdComment(""); cmdComment("==== Macro Init"); fprintf(pFile, "G21 ; set units to millimeters\n"); fprintf(pFile, "G90 ; use absolute coordinates\n"); fprintf(pFile, "G28 ; home all axes\n"); fprintf(pFile, "G1 Z5 F5000 ; lift nozzle\n"); fprintf(pFile, "M140 S60 ; set bed temperature\n"); fprintf(pFile, "M563 P0 D0:1:2:3 H0 F0 ; set tool 0 as full color on quad\n"); fprintf(pFile, "T0\n"); // Using relative distances for extrusion is a very bad idea, but we nned to know how the Quad board behave before we can fix this fprintf(pFile, "M83 ; use relative distances for extrusion\n"); fprintf(pFile, "M104 S230 ; set extruder temperature\n"); fprintf(pFile, "M109 S230 ; set temperature and wait for it to be reached\n"); fprintf(pFile, "M190 S60 ; wait for bed temperature\n"); cmdResetExtruder(); fprintf(pFile, "G1 F800 E3:0:0:0 ; purge\n"); fprintf(pFile, "G1 F800 E0:3:0:0 ; purge\n"); fprintf(pFile, "G1 F800 E0:0:3:0 ; purge\n"); fprintf(pFile, "G1 F800 E0:0:0:3 ; purge\n"); fprintf(pFile, "M106 S255 P0 ; fan on\n"); fprintf(pFile, "M106 S255 P1 ; fan on\n"); fprintf(pFile, "M106 S255 P2 ; fan on\n"); fprintf(pFile, "G4 S0.1 ; dwell\n"); // C=523.251, D=587.330, E=659.255, F=698.456, G=783.991, A=880, B=987.767, C=1046.50 fprintf(pFile, "M300 S523.251 P100 ; beep\n"); fprintf(pFile, "M300 S587.330 P100 ; beep\n"); fprintf(pFile, "M300 S659.255 P100 ; beep\n"); fprintf(pFile, "M300 S698.456 P100 ; beep\n"); fprintf(pFile, "M300 S783.991 P100 ; beep\n"); #else fprintf(pFile, "; generated by Iota Slicer\n"); cmdComment(""); cmdComment("==== Macro Init"); fprintf(pFile, "G21 ; set units to millimeters\n"); fprintf(pFile, "G90 ; use absolute coordinates\n"); fprintf(pFile, "G28 ; home all axes\n"); fprintf(pFile, "G1 Z5 F5000 ; lift nozzle\n"); fprintf(pFile, "M140 S60 ; set bed temperature\n"); // fprintf(pFile, "T1\n"); // fprintf(pFile, "M82 ; use absolute distances for extrusion\n"); // fprintf(pFile, "M104 S230 ; set extruder temperature\n"); if (pToolmap&1) { fprintf(pFile, "T0\n"); fprintf(pFile, "M82 ; use absolute distances for extrusion\n"); fprintf(pFile, "M104 S%d ; set extruder temperature\n", pExtruderStandbyTemp); } if (pToolmap&2) { fprintf(pFile, "T1\n"); fprintf(pFile, "M82 ; use absolute distances for extrusion\n"); fprintf(pFile, "M104 S%d ; set extruder temperature\n", pExtruderStandbyTemp); } if (pToolmap&1) { fprintf(pFile, "T0\n"); fprintf(pFile, "M109 S%d ; set temperature and wait for it to be reached\n", pExtruderStandbyTemp); } if (pToolmap&2) { fprintf(pFile, "T1\n"); fprintf(pFile, "M109 S%d ; set temperature and wait for it to be reached\n", pExtruderStandbyTemp); } fprintf(pFile, "M190 S60 ; wait for bed temperature\n"); cmdResetExtruder(); sendMoveTo(pPosition); sendExtrusionAdd(-1.0); sendFeedrate(1800.0); sendNewLine("retract extruder"); fprintf(pFile, "M106 S255 P0 ; fan on\n"); fprintf(pFile, "M106 S255 P1 ; fan on\n"); fprintf(pFile, "M106 S255 P2 ; fan on\n"); fprintf(pFile, "G4 S0.1 ; dwell\n"); // C=523.251, D=587.330, E=659.255, F=698.456, G=783.991, A=880, B=987.767, C=1046.50 fprintf(pFile, "M300 S523.251 P100 ; beep\n"); fprintf(pFile, "M300 S587.330 P100 ; beep\n"); fprintf(pFile, "M300 S659.255 P100 ; beep\n"); fprintf(pFile, "M300 S698.456 P100 ; beep\n"); fprintf(pFile, "M300 S783.991 P100 ; beep\n"); #if 0 sendMoveTo(pPosition); sendExtrusionAdd(8); sendFeedrate(1800); sendNewLine("purge some filament"); #elif 1 // do nothing #else macroPurgeExtruder(0); macroPurgeExtruder(1); #endif IAVector3d vec = { 0.0, 0.0, 0.2 }; cmdRapidMove(vec); cmdComment(""); #endif } /** * Send the commands needed to end printing. * * \todo This should be more general, plus some commands for specific machines. */ void IAGcodeWriter::sendShutdownSequence() { cmdComment(""); cmdComment("==== Macro Shutdown"); cmdResetExtruder(); // fprintf(pFile, "T1 M104 S0 ; set extruder temperature\n"); if (pToolmap&1) { fprintf(pFile, "T0\n"); fprintf(pFile, "M104 S0 ; set extruder temperature\n"); } if (pToolmap&2) { fprintf(pFile, "T1\n"); fprintf(pFile, "M104 S0 ; set extruder temperature\n"); } fprintf(pFile, "M140 S0 ; set bed temperature\n"); fprintf(pFile, "M106 S0 P0 ; fan off\n"); fprintf(pFile, "M106 S0 P1 ; fan off\n"); fprintf(pFile, "M106 S0 P2 ; fan off\n"); fprintf(pFile, "G28 X0 Y0 ; home X and Y axis\n"); fprintf(pFile, "M84 ; disable motors\n"); fprintf(pFile, "G4 S0.1 ; dwell\n"); fprintf(pFile, "M300 S783.991 P100 ; beep\n"); fprintf(pFile, "M300 S698.456 P100 ; beep\n"); fprintf(pFile, "M300 S659.255 P100 ; beep\n"); fprintf(pFile, "M300 S587.330 P100 ; beep\n"); fprintf(pFile, "M300 S523.251 P100 ; beep\n"); cmdComment(""); } void IAGcodeWriter::requestTool(int t) { if (pT!=t) { /// \todo there will be a whole bunch of extruder change strategies // --- This is the strategy for multiple hotends with one feed each // We are creating wasted plastic in the park position, which is later // missing in the build. Some of this may be reduced by retracting much // further, bu I assume, some kind of minimal waste tower // is unavaoidable. if (pT!=-1) { fprintf(pFile, "T%d\n", pT); fprintf(pFile, "M104 S%d ; standby temperature\n", pExtruderStandbyTemp); cmdExtrude(-4.0); // pull the filament 4mm in in the hopes it will stop oozing } if (t!=-1) { // -- select the new extruder fprintf(pFile, "T%d\n", t); // -- move out of the way of the model IAVector3d pause = Iota.pMesh->pMin - IAVector3d(10.0, 10.0, 0.0) + Iota.pMesh->position(); /** \bug in world coordinates */ pause.setMax(IAVector3d(0.0, 0.0, 0.0)); /** \bug back-right of the bed (or beyond) */ pause.z( pPosition.z() ); cmdRapidMove(pause); // -- wait for printing temperature fprintf(pFile, "M109 S%d ; printing temperature and wait\n", pExtruderPrintTemp); // -- or purge, or print outline, or print waste tower, or ... cmdExtrude(4.0); // unretract the filament 4mm in in the hopes it will continue printing without gap pTotalTime += abs(t-pT)/1.5; // we assume 1.5 deg C per seconds heating rate if (pToolCount && pPrinter->toolChangeStrategy()==3) { // prime tower /// \bug the prime tower must ALWAYS be built, or a few layers without a toolchange will disrupt the tower double tw = 13.0, td = 13.0; double dx = (tw + 1.0) * t; // snake lines for (double i=1; i<=tw-1; i++) { cmdRapidMove(pause.x()+dx+i, pause.y()-0.5); cmdPrintMove(pause.x()+dx+i, pause.y()-td+0.5); cmdPrintMove(pause.x()+dx+i+0.5, pause.y()-td+0.5); cmdPrintMove(pause.x()+dx+i+0.5, pause.y()-0.5); } // a rectangle around the prime tower cmdRapidMove(pause.x()+dx, pause.y()); cmdPrintMove(pause.x()+dx+tw, pause.y()); cmdPrintMove(pause.x()+dx+tw, pause.y()-td); cmdPrintMove(pause.x()+dx, pause.y()-td); cmdPrintMove(pause.x()+dx, pause.y()); /// \todo generate a prime tower to ensure a steady flow of filament. /// \todo what's with collisions? Printing outside of the bed? Manually positioning towers? // we may also use an ooze shild or the infill for priming } } pT = t; } } /** * Send the commands to purge some extruder and make it ready for printing. * * \param t tool number for the extruder that we want to purge. * * \todo This should be more general, plus some commands for specific machines. */ void IAGcodeWriter::sendPurgeExtruderSequence(int t) { cmdComment(""); cmdComment("==== Macro Purge Extruder %d", t); if (t==0) { // The tool 0 box is mounted in a very bad place and can just barely be reached. // We need to drive the head in a circle to actually wipe, and make a bee line // so that waste goes into the waste box. Phew. Also, when usug repetier FW, the // width needs to be corrected so that we reach the waste container at all. // Wipe tool 0 // Box: 200, 0, 10 // Wipe: 180, 0, 10 cmdRapidMove(90, 0); cmdSelectExtruder(t); cmdResetExtruder(); cmdRapidMove(180, 0); cmdRapidMove(180, 20); cmdRapidMove(199, 20); cmdRapidMove(199, 0); cmdRapidMove(180, 0); cmdRapidMove(180, 20); cmdRapidMove(199, 20); cmdRapidMove(199, 0); cmdExtrude(30); cmdRapidMove(180, 0); cmdRapidMove(180, 20); cmdRapidMove(199, 20); cmdRapidMove(199, 0); cmdRapidMove(180, 0); cmdRapidMove(180, 20); cmdRapidMove(199, 20); cmdRapidMove(199, 0); cmdRapidMove(180, 0); cmdRapidMove(180, 20); cmdResetExtruder(); } else if (t==1) { // The tool 1 box is located a little bit better, but in order to reach it, // tool 0 must be active. I am not even sure if we can send a command to extrude // to head 1 without changing the position back onto the bed. In effect, we would // have change the minimum position for x to minus whatever the offest is between heads. // Maybe that's why in the original firmware, the *right* head is tool 0, and // the *left* head ist tool 1? // Wipe tool 1 // Box: T0! 0, 0, 10 // Wipe: T0! 0, 20, 10 // but can we extrude T1 without changing the position? Maybe by using relative // positioning? cmdRapidMove(90, 0); cmdSelectExtruder(t); cmdResetExtruder(); cmdRapidMove( 0, 0); cmdRapidMove( 0, 20); cmdRapidMove(20, 20); cmdRapidMove(20, 0); cmdRapidMove( 0, 0); cmdExtrude(30); cmdRapidMove( 0, 20); cmdRapidMove(20, 20); cmdRapidMove(20, 0); cmdRapidMove( 0, 0); cmdRapidMove( 0, 20); cmdRapidMove(20, 20); cmdRapidMove(20, 0); cmdRapidMove( 0, 0); cmdRapidMove( 0, 20); cmdRapidMove(20, 20); cmdRapidMove(20, 0); cmdResetExtruder(); } cmdComment(""); }
29.647482
134
0.611866
[ "vector", "model" ]
a54331dba8eb889e3b06840a425d17d02ec1abab
4,712
cpp
C++
src/TicTacView.cpp
saffarpour/SimpleMVCTicTacToe
92a38596519545e1107ffeb1b8b7f6f8f9d42317
[ "MIT" ]
null
null
null
src/TicTacView.cpp
saffarpour/SimpleMVCTicTacToe
92a38596519545e1107ffeb1b8b7f6f8f9d42317
[ "MIT" ]
null
null
null
src/TicTacView.cpp
saffarpour/SimpleMVCTicTacToe
92a38596519545e1107ffeb1b8b7f6f8f9d42317
[ "MIT" ]
null
null
null
/* File: TicTacView.cpp Copyright (c) 2020-Present Reza Saffarpour Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Licensed under the MIT License, you may not use this file except in compliance with the License. You may obtain a copy of the License at https://mit-license.org/ */ #include "TicTacView.h" #include <conio.h> TicTacView::TicTacView() { } TicTacView::~TicTacView() { } /** * Draws a line of board * @param boardStatus * @param lastRowNum */ void TicTacView::drawBoardLine(char * boardStatus, int lastRowNum) { if (((lastRowNum + 1) % ROWCOUNT) == 0) return; string noDataLine = ""; for (int j = 0; j < COLUMNCOUNT; j++) { noDataLine += "---"; if (((j + 1) % COLUMNCOUNT) != 0) noDataLine += "|"; } cout << noDataLine << "\n"; } /** * * @param dataArray * @param lastRowNum */ void TicTacView::drawBoardCellRow(char * dataArray, int lastRowNum) { string boardRow = ""; string s; for (int j = 0; j < COLUMNCOUNT; j++) { s = dataArray[lastRowNum * 3 + j]; boardRow += " " + s + " "; if (((j + 1) % COLUMNCOUNT) != 0) boardRow += "|"; } cout << boardRow << "\n"; } void TicTacView::drawBoard(char * boardDataArray) { for (int i = 0; i < ROWCOUNT; i++) { drawBoardCellRow(boardDataArray, i); drawBoardLine(boardDataArray, i); } } /** * * @param boardStatus */ void TicTacView::showGameBoard(char * boardStatus) { cout << "============\n"; cout << " Computer: X \n"; cout << " Player: O \n"; cout << "============\n"; cout << " Game Board \n"; cout << "============\n"; drawBoard(boardStatus); cout << "\n\n"; } void TicTacView::drawGameBoardHint(char * boardStatus) { char boardHintData[9]; int dataArraySize = ROWCOUNT * COLUMNCOUNT; cout << "\n\n"; cout << "===============\n"; cout << "Game Board Map \n"; cout << "===============\n"; for (int i = 0; i < dataArraySize; i++) { if (boardStatus[i] == ' ') boardHintData[i] = to_string(i + 1)[0]; else boardHintData[i] = ' '; } drawBoard(boardHintData); cout << "\n\n"; } /** * Shows game on screen * @param char * boardStatus a copy of boardStatus from Model * @param bool drawHint true means hint should be drawn */ void TicTacView::renderGameScreen(char * boardStatus, bool drawHint) { system("cls"); /** System call */ showGameBoard(boardStatus); if (drawHint) drawGameBoardHint(boardStatus); } void TicTacView::preparePlayerMoveQuestion(string freeCellNumber) { cout << "Select a cell number " << freeCellNumber <<" for your next move -> "; } void TicTacView::prepareAskToPlayAgainQuestion() { cout << "Do you want to play again? (Y or N) "; } /** * Gets user next move by asking cell number * @return int selected CellIndex, which is equal to playerNextCellNumber - 1 */ int TicTacView::getUserNextMove(){ int playerNextCellNumber; cin >> playerNextCellNumber; return playerNextCellNumber - 1; } void TicTacView::announceWinner(char winnerID, string winnerName) { char noUseChar; cout << "\n*******************************\n"; cout << "*** " << winnerName << " (" << winnerID << ") is winner! ***\n"; cout << "*******************************\n\n"; } void TicTacView::announceNoWinner() { char noUseChar; cout << "\n ------------------------\n"; cout << " Tie! No one is winner!\n"; cout << " ------------------------\n"; }
29.08642
83
0.593379
[ "model" ]
a54ccbc0064b034364049ee047aca7a3042d0446
10,124
cc
C++
pre_processors/filter_range_image.cc
Gatsby23/StaticMapping
71bb3bedfb116c4ea0ad82ab0cdf146f6a9df024
[ "MIT" ]
264
2019-08-08T08:39:39.000Z
2022-03-27T09:46:42.000Z
pre_processors/filter_range_image.cc
Gatsby23/StaticMapping
71bb3bedfb116c4ea0ad82ab0cdf146f6a9df024
[ "MIT" ]
26
2019-08-26T13:35:05.000Z
2022-03-14T10:16:55.000Z
pre_processors/filter_range_image.cc
Gatsby23/StaticMapping
71bb3bedfb116c4ea0ad82ab0cdf146f6a9df024
[ "MIT" ]
62
2019-08-20T17:14:14.000Z
2022-03-16T12:18:35.000Z
// MIT License // Copyright (c) 2019 Edward Liu // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #include "pre_processors/filter_range_image.h" namespace static_map { namespace pre_processers { namespace filter { RangeImage::RangeImage() : Interface(), top_angle_(30.), btm_angle_(-15.), offset_x_(0.f), offset_y_(0.f), offset_z_(0.f), vertical_line_num_(40), horizontal_line_num_(1800) { neighbors_.push_back(Index(0, 1)); neighbors_.push_back(Index(0, -1)); neighbors_.push_back(Index(0, 2)); neighbors_.push_back(Index(0, -2)); neighbors_.push_back(Index(1, 0)); neighbors_.push_back(Index(-1, 0)); // float params INIT_FLOAT_PARAM("top_angle", top_angle_); INIT_FLOAT_PARAM("btm_angle", btm_angle_); INIT_FLOAT_PARAM("offset_x", offset_x_); INIT_FLOAT_PARAM("offset_y", offset_y_); INIT_FLOAT_PARAM("offset_z", offset_z_); // int32_t params INIT_INT32_PARAM("vertical_line_num", vertical_line_num_); INIT_INT32_PARAM("horizontal_line_num", horizontal_line_num_); } void RangeImage::DisplayAllParams() { PARAM_INFO(top_angle_); PARAM_INFO(btm_angle_); PARAM_INFO(offset_x_); PARAM_INFO(offset_y_); PARAM_INFO(offset_z_); PARAM_INFO(vertical_line_num_); PARAM_INFO(horizontal_line_num_); } void RangeImage::SetInputCloud(const data::InnerCloudType::Ptr &cloud) { if (cloud == nullptr || cloud->points.empty()) { LOG(WARNING) << "cloud empty, do nothing!" << std::endl; this->inner_cloud_ = nullptr; return; } if (vertical_line_num_ <= 0 || horizontal_line_num_ <= 0) { return; } this->inner_cloud_ = cloud; map_image_.clear(); matrix_image_.resize(vertical_line_num_, horizontal_line_num_); matrix_image_.setZero(); } void RangeImage::Filter(const data::InnerCloudType::Ptr &cloud) { if (!cloud || !Interface::inner_cloud_) { LOG(WARNING) << "nullptr cloud, do nothing!" << std::endl; return; } this->FilterPrepare(cloud); const float image_horizontal_res = M_PI * 2 / static_cast<float>(horizontal_line_num_); const float image_vertical_res = (top_angle_ - btm_angle_) / static_cast<float>(vertical_line_num_) / 180.f * M_PI; int row_index = 0; int col_index = 0; float vertical_rad = 0.; float horizontal_rad = 0.; float range = 0.; const auto &input_cloud = this->inner_cloud_; for (int i = 0; i < input_cloud->points.size(); ++i) { auto point = input_cloud->points[i]; point.x += offset_x_; point.y += offset_y_; point.z += offset_z_; float distance_in_xy = std::sqrt(point.x * point.x + point.y * point.y); if (distance_in_xy < 0.01f) { this->outliers_.push_back(i); continue; } vertical_rad = std::atan2(point.z, distance_in_xy); row_index = (vertical_rad - btm_angle_ / 180.f * M_PI) / image_vertical_res; if (row_index < 0 || row_index >= vertical_line_num_) { this->outliers_.push_back(i); continue; } horizontal_rad = std::atan2(point.y, point.x); if (horizontal_rad < 0.f) { horizontal_rad += M_PI * 2; } col_index = std::lround(horizontal_rad / image_horizontal_res); if (col_index >= horizontal_line_num_) col_index -= horizontal_line_num_; if (col_index < 0 || col_index >= horizontal_line_num_) { this->outliers_.push_back(i); continue; } if (matrix_image_(row_index, col_index) < 1.e-6) { range = std::sqrt(point.x * point.x + point.y * point.y + point.z * point.z); matrix_image_(row_index, col_index) = range; map_image_[Index(row_index, col_index)] = Pixel(range, i); this->inliers_.push_back(i); } else { this->outliers_.push_back(i); } } for (auto &i : this->inliers_) { cloud->points.push_back(input_cloud->points[i]); } } void RangeImage::DepthCluster(const LabeledPointCloudPtr &cloud) { CHECK(this->inner_cloud_ != nullptr); LabelT label = 1; for (int row = 0; row < vertical_line_num_; ++row) { for (int col = 0; col < horizontal_line_num_; ++col) { if (matrix_image_(row, col) < 1.e-6) { continue; } if (map_image_.at(Index(row, col)).label > 0) { continue; } LabelOneComponent(label, Index(row, col)); label++; max_label_ = label; } } if (cloud) { for (auto &cluster : clusters_) { auto &indices = cluster.second; for (auto i : indices) { LabeledPointType point; point.x = this->inner_cloud_->points[i].x; point.y = this->inner_cloud_->points[i].y; point.z = this->inner_cloud_->points[i].z; point.label = cluster.first; cloud->push_back(point); } } } } void RangeImage::ToPng(const float &max_range, const char *filename, bool colorful) { CHECK(matrix_image_.rows() > 0 && matrix_image_.cols() > 0); FILE *fp = fopen(filename, "wb"); if (!fp) { LOG(ERROR) << "Can not open file " << filename << std::endl; return; } png_uint_32 width = matrix_image_.cols(); png_uint_32 height = matrix_image_.rows(); png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (!png_ptr) { LOG(ERROR) << "Could not allocate write struct" << std::endl; return; } png_infop info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { LOG(ERROR) << "Could not allocate info struct" << std::endl; png_destroy_write_struct(&png_ptr, (png_infopp)NULL); return; } LOG(INFO) << "Write range image file: " << filename << std::endl; png_init_io(png_ptr, fp); png_set_IHDR(png_ptr, info_ptr, width, height, 8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); png_write_info(png_ptr, info_ptr); png_bytep row = (png_bytep)malloc(3 * width * sizeof(png_byte)); for (png_uint_32 y = 0; y < height; ++y) { for (png_uint_32 x = 0; x < width; ++x) { if (matrix_image_(y, x) > max_range) { continue; } if (colorful) { png_byte value = matrix_image_(y, x) / max_range * 255; if (matrix_image_(y, x) < 1.e-6) { row[x * 3] = 0; row[x * 3 + 1] = 255; row[x * 3 + 2] = 0; } else { row[x * 3] = value; row[x * 3 + 1] = value; row[x * 3 + 2] = value; } } else { png_byte value = matrix_image_(y, x) / max_range * 255; row[x * 3] = value; row[x * 3 + 1] = value; row[x * 3 + 2] = value; } } png_write_row(png_ptr, row); } png_write_end(png_ptr, NULL); if (fp != NULL) { fclose(fp); } if (info_ptr != NULL) { png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1); } if (png_ptr != NULL) { png_destroy_write_struct(&png_ptr, (png_infopp)NULL); } } void RangeImage::LabelOneComponent(LabelT label, Index index) { std::queue<Index> labeling_queue; std::vector<int> indices; labeling_queue.push(index); int row_num = matrix_image_.rows(); int col_num = matrix_image_.cols(); CHECK_EQ(row_num, vertical_line_num_); CHECK_EQ(col_num, horizontal_line_num_); const float image_horizontal_res = M_PI * 2 / static_cast<float>(horizontal_line_num_); const float image_vertical_res = (top_angle_ - btm_angle_) / static_cast<float>(vertical_line_num_) / 180. * M_PI; while (!labeling_queue.empty()) { const Index current = labeling_queue.front(); labeling_queue.pop(); if (matrix_image_(current[0], current[1]) < 1.e-6 || map_image_.at(current).label > 0) { continue; } map_image_.at(current).label = label; CHECK_GE(map_image_.at(current).index, 0); indices.push_back(map_image_.at(current).index); for (const auto &step : neighbors_) { Index neighbor = current + step; if (neighbor[0] < 0 || neighbor[0] >= row_num) { continue; } if (neighbor[1] < 0) { neighbor[1] += col_num; } else if (neighbor[1] >= col_num) { neighbor[1] -= col_num; } if (matrix_image_(neighbor[0], neighbor[1]) < 1.e-6 || map_image_.at(neighbor).label > 0) { continue; } float d1 = std::max(matrix_image_(current[0], current[1]), matrix_image_(neighbor[0], neighbor[1])); float d2 = std::min(matrix_image_(current[0], current[1]), matrix_image_(neighbor[0], neighbor[1])); float alpha = 0.; if (step[0] == 0) { alpha = image_horizontal_res; } else { alpha = image_vertical_res; } float beta = std::atan2(d2 * std::sin(alpha), (d1 - d2 * std::cos(alpha))); if (beta > segmentation_rad_threshold_) { labeling_queue.push(neighbor); } } } if (indices.size() >= 20) { clusters_[label] = std::move(indices); } } } // namespace filter } // namespace pre_processers } // namespace static_map
32.242038
80
0.631865
[ "vector" ]
a550fadd84573d55292f5b6aa6b671e53f925a4b
2,392
cpp
C++
CIM_Framework/CIMFramework/CPPClasses/Src/CIM_UseOfLog.cpp
rgl/lms
cda6a25e0f39b2a18f10415560ee6a2cfc5fbbcb
[ "Apache-2.0" ]
18
2019-04-17T10:43:35.000Z
2022-03-22T22:30:39.000Z
CIM_Framework/CIMFramework/CPPClasses/Src/CIM_UseOfLog.cpp
rgl/lms
cda6a25e0f39b2a18f10415560ee6a2cfc5fbbcb
[ "Apache-2.0" ]
9
2019-10-03T15:29:51.000Z
2021-12-27T14:03:33.000Z
CIM_Framework/CIMFramework/CPPClasses/Src/CIM_UseOfLog.cpp
isabella232/lms
50d16f81b49aba6007388c001e8137352c5eb42e
[ "Apache-2.0" ]
8
2019-06-13T23:30:50.000Z
2021-06-25T15:51:59.000Z
//---------------------------------------------------------------------------- // // Copyright (c) Intel Corporation, 2003 - 2012 All Rights Reserved. // // File: CIM_UseOfLog.cpp // // Contents: ManagedSystemElements may record their event, error or informational data within Logs. The use of a Log to hold a ManagedSystemElement's data is described by this association. The type of Element data captured by the Log can be specified using the RecordedData string property. // // This file was automatically generated from CIM_UseOfLog.mof, version: 2.9.0 // //---------------------------------------------------------------------------- #include "CIM_UseOfLog.h" namespace Intel { namespace Manageability { namespace Cim { namespace Typed { const CimFieldAttribute CIM_UseOfLog::_metadata[] = { {"Antecedent", true, false, true }, {"Dependent", true, false, true }, {"RecordedData", false, false, false }, }; // class fields const string CIM_UseOfLog::RecordedData() const { return GetField("RecordedData")[0]; } void CIM_UseOfLog::RecordedData(const string &value) { SetOrAddField("RecordedData", value); } bool CIM_UseOfLog::RecordedDataExists() const { return ContainsField("RecordedData"); } void CIM_UseOfLog::RemoveRecordedData() { RemoveField("RecordedData"); } CimBase *CIM_UseOfLog::CreateFromCimObject(const CimObject &object) { CIM_UseOfLog *ret = NULL; if(object.ObjectType() != CLASS_NAME) { ret = new CimExtended<CIM_UseOfLog>(object); } else { ret = new CIM_UseOfLog(object); } return ret; } vector<shared_ptr<CIM_UseOfLog> > CIM_UseOfLog::Enumerate(ICimWsmanClient *client, const CimKeys &keys) { return CimBase::Enumerate<CIM_UseOfLog>(client, keys); } void CIM_UseOfLog::Delete(ICimWsmanClient *client, const CimKeys &keys) { CimBase::Delete(client, CLASS_URI, keys); } const vector<CimFieldAttribute> &CIM_UseOfLog::GetMetaData() const { return _classMetaData; } const string CIM_UseOfLog::CLASS_NAME = "CIM_UseOfLog"; const string CIM_UseOfLog::CLASS_URI = "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_UseOfLog"; const string CIM_UseOfLog::CLASS_NS = "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_UseOfLog"; const string CIM_UseOfLog::CLASS_NS_PREFIX = "AUs594"; CIMFRAMEWORK_API vector <CimFieldAttribute> CIM_UseOfLog::_classMetaData; } } } }
29.530864
293
0.684365
[ "object", "vector" ]
a22383f4caf419547cfb306533d3e5e78fd146bc
25,132
cpp
C++
SixthLabCMA/SixthLabCMA/SixthLabCMA.cpp
Hramkanvas/needandnotneed
f28ef4a4be428370e2148883c06126f5be9ccd4e
[ "MIT" ]
1
2019-12-28T13:57:09.000Z
2019-12-28T13:57:09.000Z
SixthLabCMA/SixthLabCMA/SixthLabCMA.cpp
Hramkanvas/needandnotneed
f28ef4a4be428370e2148883c06126f5be9ccd4e
[ "MIT" ]
null
null
null
SixthLabCMA/SixthLabCMA/SixthLabCMA.cpp
Hramkanvas/needandnotneed
f28ef4a4be428370e2148883c06126f5be9ccd4e
[ "MIT" ]
null
null
null
#include "stdafx.h" #include <vector> #include <cmath> #include <ctime> #include <iostream> #include <iomanip> #include <string> #include <algorithm> #include <fstream> using namespace std; class Matrix { public: vector<vector<double>> Mat; vector<vector<double>> IMat; vector<double> VSol; vector<double> VSolN; vector<double> Roots; vector<double> errorsVector; vector<int> rowPivoting; vector<vector<double>> LU; vector<int> pivotingVector; vector<double> minEigenVec; vector<double> residualVector; vector<double> frobeniusVector; void LUSolver(); void Danilevski(); void eigenvalueTest(); void showResidualVector(); void fixResidualVector(); void InvertIteration(); void showMinEigenVal(); void showMinEigVec(); void getIterationInf(); void readMat(); void writeMat(); virtual void genMat(); void genVSol(); void rotation(); void showLUDecomposition(); double getNorm(vector<double> &v1, vector <double> &v2); void residual(); void Jacobi(); void rootVSol(); virtual void showMat(); void showRoots(); void showVSol(); double scalarProduct(vector<double> &v1, vector<double> &v2); void showRowPivoting(); void createMatrix(); void createVSol(); void gaussianElemPiv(); void LUDecomposotion(); void getLUDeterminant(); void invertLU(); void showInvertMatrix(); int getOrder() { return order; } protected: int order = 0; int pivotingNumber = 0; double maxEigevalue; double minEigenvalue; string FName; }; class SymMatrix : public Matrix { public: void genMat(); vector<vector<double>> S; vector<double> D; void chol(); void showChol(); void SDSDec(); vector<vector<double>> ST1; vector<vector<double>> S1; vector<vector<double>> S1D; }; class ThridiagMatrix : public Matrix { public: void genMat(); vector<double> Rootsy; vector<double> Rootsz; vector<double> abc; vector<double> alpha; vector<double> beta; vector<double> gamma; void Thomas(); void createMat(); void showMat(); protected: int bStart; int aStart; int aEnd; int bEnd; }; class XMatrix : public Matrix { public: vector<double> Mat; void gmres(); void getInfIteration(); void genMat(); void showMat(); void showBackMat(); void getBackNorm(); double getTau(vector<double> &v1, vector<double> &v2); double getResidual(vector<double> &v1, vector<double> &v2); private: double x, y; }; int my_random(int min, int max) { return min + (rand() % static_cast<int>(max - min + 1)); } struct myclass { bool operator() (int i, int j) { return abs(i) < abs(j); } } myobj; double fRand(double fMin, double fMax) { double f = (double)rand() / RAND_MAX; return fMin + f * (fMax - fMin); } ostream& operator << (ostream &s, const vector<vector<double>> &Mat) { s << endl << "___________________________________________" << endl << endl; for (int i = 0, e = Mat.size(); i < e; i++) { for (int j = 0; j < e; j++) { s << fixed; s << setw(10) << right << setprecision(4) << Mat[i][j]; } s << endl << endl; } s << "___________________________________________" << endl; return s; } ostream& operator << (ostream &s, const vector<double> &Vec) { s << endl << "____________" << endl << endl; int dopLength = to_string((int)Vec[0]).length(); for (int i = 0, e = Vec.size(); i < e; i++) { s << fixed; s << setw(6 + dopLength) << right << setprecision(8) << Vec[i] << endl; } s << "____________" << endl; return s; } ostream& operator << (ostream &s, const vector<int> &Vec) { s << "____________" << endl << endl; int dopLength = to_string(Vec[0]).length(); for (int i = 0, e = Vec.size(); i < e; i++) { s << setw(2 + dopLength) << right << Vec[i] << endl; } s << "____________" << endl; return s; } int sgn(double var) { if (var < 0) return -1; else if (var > 0) return 1; else return 0; } void Matrix::genMat() { srand(time(NULL)); cout << "Enter the matrix order: "; cin >> order; vector<double> row; for (int i = 0; i < order; i++) { for (int j = 0; j < order; j++) { row.push_back(my_random(-5, 5)); } Mat.push_back(row); row.clear(); } } void SymMatrix::genMat() { srand(time(NULL)); cout << "Enter the matrix order: "; cin >> order; vector<double> row; double out = 0; for (int i = 0; i < order; i++) { for (int j = 0; j < order; j++) { if (j < i) { row.push_back(Mat[j][i]); } else { row.push_back(fRand(-5.0, 5.0)); } } Mat.push_back(row); row.clear(); } } void Matrix::showMat() { cout << Mat; } void Matrix::genVSol() { srand(time(NULL)); for (int i = 0; i < order; i++) { VSol.push_back(fRand(-5, 5)); } } void SymMatrix::chol() { double start = clock(); vector<double> row; double sum = 0; for (int i = 0; i < order; i++) { for (int j = 0; j < order; j++) { if (j < i) { row.push_back(0); } else if (j == i) { sum = 0; for (int k = 0; k < i; k++) sum += pow(S[k][i], 2) * D[k]; row.push_back(sqrt(abs(Mat[i][i] - sum))); D.push_back(sgn(Mat[i][i] - sum)); } else if (j > i) { sum = 0; for (int k = 0; k < i; k++) sum += S[k][i] * D[k] * S[k][j]; row.push_back((Mat[i][j] - sum) / (D[i] * row[i])); } } S.push_back(row); row.clear(); } double end = clock(); start = end - start; printf("It took me %d clicks (%f seconds).\n", start, ((float)start) / CLOCKS_PER_SEC); } void Matrix::rootVSol() { double element = 0; for (int i = 0; i < order; i++) { for (int j = 0; j < order; j++) { element += Mat[i][j]; } VSol.push_back(element); element = 0; } } void Matrix::residual() { vector<double> dt(order, 0); for (int i = 0; i < order; i++) { dt[i] = (1. - Roots[i]); } cout << endl << "residual = " << abs(*max_element(dt.begin(), dt.end(), myobj)) << endl; } void SymMatrix::showChol() { cout << "S matrix: " << endl; cout << S; cout << "D matrix: " << endl; cout << D; } void Matrix::showRoots() { cout << "Roots: " << endl; cout << Roots; }; void Matrix::showVSol() { cout << "Function dec: " << endl; cout << VSol; } double Matrix::scalarProduct(vector<double>& v1, vector<double>& v2) { double product = 0; for (int i = 0; i < order; i++) { product += v1[i] * v2[i]; } return product; } ; void Matrix::createVSol() { double element = 0; cout << "Enter Dec vector" << endl; for (int i = 0; i < order; i++) { cout << "Dec[" << i << "] = "; cin >> element; VSol.push_back(element); } } void Matrix::createMatrix() { double element = 0; vector<double> row; cout << "Enter the order of your matrix: "; cin >> order; cout << "Enter yout matrix: " << endl; for (int i = 0; i < order; i++) { for (int j = 0; j < order; j++) { cout << "Mat[" << i << "][" << j << "] = "; cin >> element; row.push_back(element); } Mat.push_back(row); row.clear(); } } void SymMatrix::SDSDec() { vector<vector<double>> ST = S; vector<double> y; double tmp = 0; double sum = 0; for (int i = 0; i < order; i++) { for (int j = i + 1; j < order; j++) { tmp = ST[i][j]; ST[i][j] = ST[j][i]; ST[j][i] = tmp; } } for (int i = 0; i < order; i++) { for (int k = 0; k < i; k++) sum += y[k] * ST[i][k]; y.push_back((VSol[i] - sum) / ST[i][i]); sum = 0; } Roots.clear(); Roots = y; for (int i = order - 1; i > -1; i--) { Roots[i] = D[i] * y[i]; for (int k = i + 1; k < order; k++) Roots[i] -= Roots[k] * S[i][k]; Roots[i] /= S[i][i]; sum = 0; } } void ThridiagMatrix::genMat() { srand(time(NULL)); cout << "Enter the matrix order: "; cin >> order; bStart = order; aStart = 2 * order; aEnd = 3 * order - 1; bEnd = bStart + order - 1; for (int i = 0; i < aEnd + 1; i++) { abc.push_back(fRand(-5, 5)); } } void ThridiagMatrix::createMat() { srand(time(NULL)); cout << "Enter the matrix order: "; cin >> order; double el = 0; bStart = order; aStart = 2 * order; aEnd = 3 * order - 1; bEnd = bStart + order - 1; for (int i = 0; i < aEnd + 1; i++) { if (i < bStart) { cout << endl << "c[" << i << "]"; cin >> el; abc.push_back(el); } else if (i >= bStart && i < aStart) { cout << endl << "b[" << i - bStart << "]"; cin >> el; abc.push_back(el); } else { cout << endl << "a[" << i - aStart << "]"; cin >> el; abc.push_back(el); } } } void ThridiagMatrix::showMat() { cout << endl << "Your thridiagonal matrix:" << endl; for (int i = 0; i < order; i++) { for (int j = 0; j < order; j++) { if (i == j) { cout << setw(10) << left << setprecision(4) << abc[i]; } else if (i == j - 1) { cout << setw(10) << left << setprecision(4) << abc[bStart + i]; } else if (i == j + 1) { cout << setw(10) << left << setprecision(4) << abc[aStart + i]; } else if (i == order - 1 && j == 0) { cout << setw(10) << left << setprecision(4) << abc[bStart + order - 1]; } else if (i == 0 && j == order - 1) { cout << setw(10) << left << setprecision(4) << abc[aStart]; } else { cout << setw(10) << left << setprecision(4) << 0; } } cout << endl; } } void ThridiagMatrix::Thomas() { clock_t start = clock(); alpha.push_back(0); beta.push_back(0); gamma.push_back(1); double eltm = 0; for (int i = 1; i < order + 1; i++) { if (i == order) { eltm = (abc[0] + alpha[i - 1] * abc[aStart]); alpha.push_back(-abc[bStart] / eltm); beta.push_back((VSol[0] - beta[i - 1] * abc[aStart]) / eltm); gamma.push_back(-gamma[i - 1] * abc[aStart] / eltm); } else { eltm = (abc[i] + alpha[i - 1] * abc[aStart + i]); alpha.push_back(-abc[bStart + i] / eltm); beta.push_back((VSol[i] - beta[i - 1] * abc[aStart + i]) / eltm); gamma.push_back(-gamma[i - 1] * abc[aStart + i] / eltm); } } Rootsy.push_back(0); Rootsz.push_back(1); int root = 0; for (int i = order - 1; i > 0; i--) { Rootsy.push_back(alpha[i] * Rootsy[root] + beta[i]); Rootsz.push_back(alpha[i] * Rootsz[root] + gamma[i]); root++; } Rootsy.push_back(0); Rootsz.push_back(1); reverse(Rootsz.begin(), Rootsz.end()); reverse(Rootsy.begin(), Rootsy.end()); Roots.push_back((beta[order] + alpha[order] * Rootsy[1]) / (1 - gamma[order] - alpha[order] * Rootsz[1])); for (int i = 1; i < order; i++) { Roots.push_back(Rootsy[i] + Roots[0] * Rootsz[i]); } start = clock() - start; printf("It took me %f seconds.\n", start / CLOCKS_PER_SEC); } class GilbertMatrix : public SymMatrix { public: void genMat(); }; void GilbertMatrix::genMat() { vector<double> row; cout << "Enter the order of your gilbert matrix: " << endl; cin >> order; for (int i = 1; i <= order; i++) { for (int j = 1; j <= order; j++) { row.push_back(1. / (j + i - 1)); } Mat.push_back(row); row.clear(); } } void Matrix::LUSolver() { Roots = vector<double>(order, 0); for (int i = 0; i < order; i++) { Roots[i] = VSol[pivotingVector[i]]; for (int j = 0; j < i; j++) { Roots[i] -= LU[i][j] * Roots[j]; } } for (int i = order - 1; i >= 0; i--) { for (int j = i + 1; j < order; j++) { Roots[i] -= LU[i][j] * Roots[j]; } Roots[i] /= LU[i][i]; } } void ImprDanilStability(vector<vector<double>> &matrix, vector<int> &pivot, int stepNumber) { double maxElement = matrix[stepNumber][stepNumber + 1], element, nrow = stepNumber; for (int i = stepNumber + 2; i < matrix.size(); i++) { if (fabs(element = matrix[stepNumber][i]) > fabs(maxElement)) { nrow = i; cout << "max" << maxElement; cout << "el" << element; maxElement = element; } } if (nrow != stepNumber) { swap(matrix[stepNumber + 1], matrix[nrow]); swap(pivot[stepNumber + 1], pivot[nrow]); for_each(matrix.begin(), matrix.end(), [&](vector<double> &item) {swap(item[stepNumber + 1], item[nrow]) ; }); } } void Matrix::Danilevski() { double sum = 0; vector<vector<double>> A = Mat; vector<vector<double>> B = Mat; frobeniusVector = vector<double>(order, 0); pivotingVector = vector<int>(order); for (int i = 0; i < order; i++) { pivotingVector[i] = i; } for (int k = 0; k < order - 1; k++) { if (k != order - 2)ImprDanilStability(A, pivotingVector, k); for (int i = 0; i < order; i++) { B[i][k + 1] = A[i][k + 1] / A[k][k + 1]; } for (int i = 0; i < order; i++) { for (int j = 0; j < order; j++) { if (j != k + 1) { B[i][j] = A[i][j] - A[k][j] * B[i][k + 1]; } } } for (int j = 0; j < order; j++) { sum = 0; for (int i = 0; i < order; i++) { sum += A[k][i] * B[i][j]; } A[k + 1][j] = sum; } for (int i = 0; i < order; i++) { if (i != k + 1) { for (int j = 0; j < order; j++) { A[i][j] = B[i][j]; } } } } for (int i = 0; i < order; i++) { frobeniusVector[i] = A[order - 1][i]; } cout << "\nFrobenius matrix :\n" << A; cout << "\ncoefficients vector\n" << frobeniusVector; } void Matrix::eigenvalueTest() { double result = 0; result = pow(minEigenvalue, order); for (int i = order -1; i >= 0; i--) { result -= frobeniusVector[i] * pow(minEigenvalue, i); } cout << "\n result of P(v(min)) = \n" << result << endl; } void Matrix::showResidualVector() { cout << "\n A*x - lambda*x vector:\n" << residualVector; } void Normalization(vector<double> &vect) { double firstNorm = *max_element(vect.begin(), vect.end()); for_each(vect.begin(), vect.end(), [&](double &item) {item /= firstNorm; }); } void TwoVecDivision(vector<double> &vect1, vector<double> &vect2, double &error, double &eigenvalue) { int dimension = vect1.size(); vector<double> result(dimension, 0); for (int i = 0; i < dimension; i++) { result[i] = vect1[i] / vect2[i]; } eigenvalue = *max_element(result.begin(), result.end()); error = fabs(eigenvalue - *min_element(result.begin(), result.end())); } void Matrix::fixResidualVector() { residualVector = vector<double>(order); for (int i = 0; i < order; i++) { residualVector[i] = Roots[i] - VSol[i]*minEigenvalue; } } void Matrix::InvertIteration() { double tol, error, iterationNumber = 0; cout << "Enter a tolerance: "; cin >> tol; VSol = vector<double>(order, 1); minEigenvalue = 1; this->LUDecomposotion(); cout << "Error on k'th step:\n"; while(true){ iterationNumber++; this->LUSolver(); TwoVecDivision(Roots, VSol, error, minEigenvalue); cout << error << endl; if (error <= tol) break; VSol = Roots; Normalization(VSol); } fixResidualVector(); minEigenvalue = 1 / minEigenvalue; minEigenVec = VSol; } void Matrix::showMinEigenVal() { cout << "\n Minimal eigenvalue of your matrix = " << minEigenvalue << endl; } void Matrix::showMinEigVec() { cout << "\n Eigenvector of min eigenvalue:"; cout << minEigenVec; } void Matrix::getIterationInf() { cout << "\n~`!@#$%^&*()_+/*-+?][{}!@#$%^&*()_!@#$%^&*()!@#$%^&*(\nNumber of iterations = " << errorsVector.size() << endl << "errors table: {\n"; for (int i = 0; i < errorsVector.size(); i++) { cout << "\t" << setprecision(17) << errorsVector[i] << endl; } cout << "}\n"; cout << "\n~`!@#$%^&*()_ +/*-+?][{}!@#$%^&*()_!@#$%^&*()!@#$%^&*(\n"; } void Matrix::readMat() { cout << "Type the name of the matrix-file you want to open:\n"; cin >> FName;//*********** FName += ".txt"; ifstream MFile(FName); while (!MFile.is_open()) { cout << endl << "There're some problems with your file, try again, type the name:\n"; cin >> FName; FName += ".txt"; ifstream MFile(FName); } vector <double> Row; string TStr; string TTT; while (getline(MFile, TStr)) { order++; string::iterator it = TStr.begin(); string::iterator itt = TStr.begin() + TStr.find(' '); string::iterator end = TStr.end(); while (it != end) { for (itt = TStr.begin() + TStr.find(' '); it != itt; ++it) { TTT.push_back(*it); } Row.push_back(stod(TTT)); TStr.erase(TStr.begin(), TStr.begin() + TStr.find(' ') + 1); TTT.clear(); it = TStr.begin(); end = TStr.end(); } Mat.push_back(Row); Row.clear(); } MFile.close(); } void Matrix::writeMat() { string FName1; cout << "Your matrix will be saved in file, please type the name of the new file: "; cin >> FName1; FName1 + ".txt"; ofstream MFile1(FName1); for (vector<vector<double>>::iterator it = Mat.begin(); it != Mat.end(); ++it) { for (vector<double>::iterator jt = (*it).begin(); jt != (*it).end(); ++jt) { MFile1 << *jt << " "; } MFile1 << endl; } MFile1.close(); } void Matrix::rotation() { double start = clock(); double cos = 0; double sin = 0; double zn = 0; double ch = 0; double a, b; double apast; double fpast; for (int i = 0; i < order - 1; i++) { for (int k = i + 1; k < order; k++) { b = Mat[k][i]; a = Mat[i][i]; zn = sqrt(a * a + b * b); cos = a / zn; sin = -b / zn; for (int j = i; j < order; j++) { apast = Mat[i][j]; Mat[i][j] = cos * apast - sin * Mat[k][j]; Mat[k][j] = sin * apast + cos * Mat[k][j]; } fpast = VSol[i]; VSol[i] = cos * fpast - sin * VSol[k]; VSol[k] = sin * fpast + cos * VSol[k]; } } Roots = VSol; for (int i = order - 1; i >= 0; i--) { Roots[i] = VSol[i]; for (int j = i + 1; j < order; j++) { Roots[i] -= Mat[i][j] * Roots[j]; } Roots[i] /= Mat[i][i]; } start = clock() - start; printf("\nIt took me %f seconds.\n", start / 1000); } void Matrix::showLUDecomposition() { cout << "\nLU Decomposition; LU-matrix\n" << LU; cout << "Pivoting vector:\n" << pivotingVector; } double Matrix::getNorm(vector<double> &v1, vector<double> &v2) { double result = abs(v1[0] - v2[0]); double element; for (int i = 1; i < order; i++) { element = abs(v1[i] - v2[i]); if (element > result) { result = element; } } return result; } void Matrix::gaussianElemPiv() { double start = clock(); double max = 0; double newRow = 0; double newCol = 0; double element = 0; const double SGL = 1e-6; //pivoting vector initialization for (int i = 0; i < order; i++) { rowPivoting.push_back(i); } //gauss upward for (unsigned int i = 0; i < order; i++) { max = Mat[i][i]; newRow = i; newCol = i; //looking for max element for (unsigned int it = i; it < order; it++) { for (unsigned int jt = i; jt < order; jt++) { if (abs(max) < abs(Mat[it][jt])) { max = Mat[it][jt]; newRow = it; newCol = jt; } } } if (abs(max) <= SGL) { cerr << "Matrix is singular"; exit(1); } if (newRow != i) { swap(Mat[i], Mat[newRow]); swap(VSol[i], VSol[newRow]); } if (newCol != i) { for (int it = 0; it < order; it++) { swap(Mat[it][i], Mat[it][newCol]); } } for (int it = i + 1; it < order; it++) { element = Mat[it][i] / Mat[i][i]; for (int j = i + 1; j < order; j++) { Mat[it][j] -= Mat[i][j] * element; } VSol[it] -= VSol[i] * element; Mat[it][i] = 0; } } int n = 9; int *arr = new int[n]; int *arr2 = new int[n]; arr = arr2; //backward Roots = VSol; for (int i = order - 1; i >= 0; i--) { Roots[i] = VSol[i]; for (int j = i + 1; j < order; j++) { Roots[i] -= Mat[i][j] * Roots[j]; } Roots[i] /= Mat[i][i]; } start = clock() - start; printf("\nIt took me %f seconds.\n", start / 1000); } void Matrix::LUDecomposotion() { double start = clock(); int nrow; double maxColEl; pivotingVector = vector<int>(order, 0); LU = Mat; for (int i = 0; i < order; i++) { pivotingVector[i] = i; } for (int i = 0; i < order - 1; i++) { nrow = i; maxColEl = LU[i][i]; for (int t = i + 1; t < order; t++) { if (fabs(maxColEl) < fabs(LU[t][i])) { nrow = t; } } if (fabs(LU[nrow][i]) < 1e-15) { cerr << "singular matrix"; exit(1); } if (nrow != i) { pivotingNumber++; swap(LU[i], LU[nrow]); swap(pivotingVector[i], pivotingVector[nrow]); } for (int j = i + 1; j < order; j++) { LU[j][i] /= LU[i][i]; for (int k = i + 1; k < order; k++) { LU[j][k] -= LU[j][i] * LU[i][k]; } } } start = clock() - start; printf("\nIt took me %f seconds.\n", start / 1000); /*double sum = 0; vector<double> row(order,0); U = vector<vector<double>>(order, row); L = vector<vector<double>>(order, row); double maxInColomn; for (int i = 0; i < order; i++) { for (int j = 0; j < order; j++) { U[0][i] = Mat[0][i]; L[i][0] = Mat[i][0] / U[0][0]; sum = 0; for (int k = 0; k < i; k++) sum += L[i][k] * U[k][j]; U[i][j] = Mat[i][j] - sum; if (i <= j) { sum = 0; for (int k = 0; k < i; k++) sum += L[j][k] * U[k][i]; L[j][i] = (Mat[j][i] - sum) / U[i][i]; } } cout << endl << L << endl << U; }*/ } void Matrix::getLUDeterminant() { double result = 1; for (int i = 0; i < order; i++) { result *= LU[i][i]; } if (pivotingNumber & 1) result *= -1; cout << "\n Determinant of your matrix = " << setprecision(8) << result << endl; } void Matrix::invertLU() { IMat = vector < vector < double>>(order, vector<double>(order, 0)); for (int j = 0; j < order; j++) { for (int i = 0; i < order; i++) { if (pivotingVector[i] == j) { IMat[i][j] = 1; } else { IMat[i][j] = 0; } for (int k = 0; k < i; k++) { IMat[i][j] -= LU[i][k] * IMat[k][j]; } } for (int i = order - 1; i >= 0; i--) { for (int k = i + 1; k < order; k++) { IMat[i][j] -= LU[i][k] * IMat[k][j]; } IMat[i][j] = IMat[i][j] / LU[i][i]; } } } void Matrix::showInvertMatrix() { cout << "\nInvert Matrix:\n"; cout << IMat; } void Matrix::showRowPivoting() { cout << "\n roots pivoting"; cout << rowPivoting; } void Matrix::Jacobi(){ vector<double> PRoots(order, 0); Roots = PRoots; double error, eps, elem; cout << "Please, enter precision: "; cin >> eps; vector<vector<double>> B = Mat; VSol[0] += VSol[1]; for (int i = 0; i < order; i++) { elem = B[i][i]; B[i][i] = 0; VSol[i] /= elem; for (int j = 0; j < order; j++) { if (i != j) { B[i][j] /= -elem; } } } PRoots = VSol; do { for (int i = 0; i < order; i++) { Roots[i] = VSol[i]; for (int j = 0; j < order; j++) { if (j != i) { Roots[i] += PRoots[j] * B[i][j]; } } } error = getNorm(Roots, PRoots); errorsVector.push_back(error); PRoots = Roots; } while (error > eps); } void XMatrix::genMat() { cout << "\nPlease, enter the order of yout matrix: "; cin >> order; cout << "\nEnter the main diagonal element: "; cin >> x; cout << "\nEnter the secondary diagonal element: "; cin >> y; } void XMatrix::showMat() { for (int i = 0; i < order; i++) { for (int j = 0; j < order; j++) { if (i == j)cout << left << setw(4) << setprecision(5) << x; else if(i == order - j - 1) cout << left << setw(4) << setprecision(5) << y; else cout << left << setw(4) << 0; } cout << endl; } } void XMatrix::showBackMat() { if (order % 2 == 0) { for (int i = 0; i < order; i++) { for (int j = 0; j < order; j++) { if (i == j)cout << left << setw(9) << setprecision(5) << Roots[0]; else if (i == order - j - 1) cout << left << setw(9) << setprecision(5) << Roots[1]; else cout << left << setw(9) << 0; } cout << endl; } } else { for (int i = 0; i < order; i++) { for (int j = 0; j < order; j++) { if(i == (order) / 2 && i == j)cout << left << setw(9) << setprecision(5) << 1/x; else if (i == j)cout << left << setw(9) << setprecision(5) << Roots[0]; else if (i == order - j - 1) cout << left << setw(9) << setprecision(5) << Roots[1]; else cout << left << setw(9) << 0; } cout << endl; } } } void XMatrix::getBackNorm() { cout << "\n Our norm ||A*A^(-1) - I|| = " << abs(x*Roots[0] + y*Roots[1] - 1) + abs(x*Roots[1] + y*Roots[0]) << endl; } double XMatrix::getTau(vector<double>& v1, vector<double>& v2) { double tau1 = 0, tau2 = 0, el1, el2; for (int i = 0; i < 2; i++) { el1 = v1[i]; el2 = v2[i]; tau1 += el1 * el2; tau2 += el1 * el1; } return tau1/tau2; } double XMatrix::getResidual(vector<double> &v1, vector<double> &v2) { double residual = abs(v1[0] - v2[0]), element; for (int i = 1; i < 2; i++) { element = abs(v1[i] - v2[i]); if (element > residual) residual = element; } return residual; } void XMatrix::gmres() { double eps = 0.1; cout << "Please, enter precision: "; cin >> eps; double tau = 0; double residual = 0; vector<double> rv(2, 1); Roots = rv; VSol = rv; VSol[1] = 0; Roots[0] = 1; vector<double> PRoots = Roots; vector<double> Arv(2, 0); vector<double> Ax(2, 0); do { //getting rv for (int i = 0; i < 2; i++) { Ax[i] = x*PRoots[i] + y*PRoots[2 - i - 1]; rv[i] = Ax[i] - VSol[i]; } //getting Arv for (int i = 0; i < 2; i++) { Arv[i] = x*rv[i] + y*rv[2 - i - 1]; } //getting tau tau = getTau(Arv, rv); for (int i = 0; i < 2; i++) { Roots[i] = PRoots[i] - tau*rv[i]; } residual = getResidual(Ax, VSol); PRoots = Roots; errorsVector.push_back(residual); } while (residual > eps); } void XMatrix::getInfIteration() { cout << "\n~`!@#$%^&*()_+/*-+?][{}!@#$%^&*()_!@#$%^&*()!@#$%^&*(\nNumber of iterations = " << errorsVector.size() << endl << "errors table: {\n"; for (int i = 0; i < errorsVector.size(); i++) { cout << "\t" << setprecision(17) << errorsVector[i] << endl; } cout << "}\n"; cout << "\n~`!@#$%^&*()_ +/*-+?][{}!@#$%^&*()_!@#$%^&*()!@#$%^&*(\n"; } int main() { ThridiagMatrix matrix; matrix.genMat(); matrix.showMat(); matrix.genVSol(); matrix.Thomas(); system("pause"); return 0; }
24.072797
118
0.549737
[ "vector" ]
a22fc6136dc1016e706df8da9ad3628b5aa2596a
5,208
cpp
C++
Vigilant/Vigilant.cpp
hardikphalet/vigilant-engine
ffffdad68d3f1fe05872aa8a6236ad2f327e9d65
[ "Apache-2.0" ]
1
2021-01-12T07:12:53.000Z
2021-01-12T07:12:53.000Z
Vigilant/Vigilant.cpp
hardikphalet/vigilant-engine
ffffdad68d3f1fe05872aa8a6236ad2f327e9d65
[ "Apache-2.0" ]
null
null
null
Vigilant/Vigilant.cpp
hardikphalet/vigilant-engine
ffffdad68d3f1fe05872aa8a6236ad2f327e9d65
[ "Apache-2.0" ]
null
null
null
#include "Polynomial.h" #include <iostream> #include <SDL.h> #include <SDL_image.h> //Screen dimension constants const int SCREEN_HEIGHT = 480; const int SCREEN_WIDTH = 640; //setting the screen size bool init(); //Starts up SDL and creates window bool loadMedia(); //Loads media void close(); //Frees media and shuts down SDL SDL_Window* gWindow = NULL; //The window we'll be rendering to SDL_Renderer* gRenderer = NULL; //The window renderer bool init() { //Initialization flag bool success = true; //Initialize SDL if (SDL_Init(SDL_INIT_VIDEO) < 0) { std::cout << "SDL could not initialise ! SDL Error: " << SDL_GetError() << std::endl; success = false; } else { //Set texture filtering to linear if (!SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "1")) { std::cout << "Warning: Linear texture filtering not enabled." << std::endl; } //Create window gWindow = SDL_CreateWindow("Vigilant-Window", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN); if (gWindow == NULL) { std::cout << "Window could not be created! SDL Error: " << SDL_GetError() << std::endl; success = false; } else { //Create renderer for window gRenderer = SDL_CreateRenderer(gWindow, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if (gRenderer == NULL) { std::cout << "Renderer could not be created! SDL_Error :: " << SDL_GetError() << std::endl; success = false; } else { //Initialize renderer color SDL_SetRenderDrawColor(gRenderer, 0xFF, 0xFF, 0xFF, 0xFF); //Initialize PNG loading int imgFlags = IMG_INIT_PNG; if (!(IMG_Init(imgFlags) & imgFlags)) { std::cout << "SDL_image could not initialize! SDL_image error: " << IMG_GetError() << std::endl; success = false; } } } } return success; } bool loadMedia() { bool success = true; // Nothing to load :/ return success; } void close() { //Destroy window SDL_DestroyRenderer(gRenderer); SDL_DestroyWindow(gWindow); gWindow = NULL; gRenderer = NULL; //Quitting SDL subsystems IMG_Quit(); SDL_Quit(); } SDL_Texture* loadTexture(std::string path) { //The final texture SDL_Texture* newTexture = NULL; //Load image at specified path SDL_Surface* loadedSurface = IMG_Load(path.c_str()); if (loadedSurface == NULL) { printf("Unable to load image %s! SDL_image Error: %s\n", path.c_str(), IMG_GetError()); } else { //Create texture from surface pixels newTexture = SDL_CreateTextureFromSurface(gRenderer, loadedSurface); if (newTexture == NULL) { printf("Unable to create texture from %s! SDL Error: %s\n", path.c_str(), SDL_GetError()); } //Get rid of old loaded surface SDL_FreeSurface(loadedSurface); } return newTexture; } int main(int argc, char* args[]) { std::cout << "Vigilant starting..." << std::endl; Polynomial poly(2); double arr[] = { 1.0, -2.0, 1.0 }; poly.setCoeff(arr); std::cout << "Value of polynomial at 1 is " << poly.valueAt(1.1) << std::endl; std::cout << "Value of polynomial at 1 is " << poly.valueAt(2) << std::endl; std::cout << "Value of derivative at 1 is " << poly.derivative().valueAt(1) << std::endl; std::cout << "Value of derivative at 1 is " << poly.derivative().valueAt(2) << std::endl; std::cout << "Zero of the given Polynomial is " << poly.newtonRaphson(1.1) << std::endl; std::cout << "Program has ended. Please press enter to exit." << std::endl; std::cin.get(); if (!init()) { std::cout << "Failed to initialise!\n"; } else { //Load Media if (!loadMedia()) { std::cout << "Failed to load media!\n"; } else { // Main loop flag bool quit = false; //Event handler SDL_Event e; while (!quit) { while (SDL_PollEvent(&e) != 0) { if (e.type == SDL_QUIT) { quit = true; } } //Clear screen after every render SDL_SetRenderDrawColor(gRenderer, 0xFF, 0xFF, 0xFF, 0xFF); SDL_RenderClear(gRenderer); //Render sample SDL_SetRenderDrawColor(gRenderer, 0, 0, 0, 0xFF); SDL_RenderDrawLine(gRenderer, SCREEN_WIDTH / 2, 0, SCREEN_WIDTH / 2, SCREEN_HEIGHT); SDL_RenderDrawLine(gRenderer, 0, SCREEN_HEIGHT / 2, SCREEN_WIDTH, SCREEN_HEIGHT / 2); SDL_RenderPresent(gRenderer); } } } return 0; }
28.773481
151
0.544547
[ "render" ]
a2327ed958e4ee6b9a2074799374b5074ca7190c
13,773
cpp
C++
basic_culling.cpp
Yours3lf/basic_culling
d82f8fc85a9f5291dfcffac66e3cd04027554f79
[ "MIT" ]
null
null
null
basic_culling.cpp
Yours3lf/basic_culling
d82f8fc85a9f5291dfcffac66e3cd04027554f79
[ "MIT" ]
null
null
null
basic_culling.cpp
Yours3lf/basic_culling
d82f8fc85a9f5291dfcffac66e3cd04027554f79
[ "MIT" ]
null
null
null
#include "intersection.h" #include "framework.h" using namespace prototyper; int main( int argc, char** argv ) { shape::set_up_intersection(); map<string, string> args; for( int c = 1; c < argc; ++c ) { args[argv[c]] = c + 1 < argc ? argv[c + 1] : ""; ++c; } cout << "Arguments: " << endl; for_each( args.begin(), args.end(), []( pair<string, string> p ) { cout << p.first << " " << p.second << endl; } ); uvec2 screen( 0 ); bool fullscreen = false; bool silent = false; string title = "Culling poc"; /* * Process program arguments */ stringstream ss; ss.str( args["--screenx"] ); ss >> screen.x; ss.clear(); ss.str( args["--screeny"] ); ss >> screen.y; ss.clear(); if( screen.x == 0 ) { screen.x = 1280; } if( screen.y == 0 ) { screen.y = 720; } try { args.at( "--fullscreen" ); fullscreen = true; } catch( ... ) {} try { args.at( "--help" ); cout << title << ", written by Marton Tamas." << endl << "Usage: --silent //don't display FPS info in the terminal" << endl << " --screenx num //set screen width (default:1280)" << endl << " --screeny num //set screen height (default:720)" << endl << " --fullscreen //set fullscreen, windowed by default" << endl << " --help //display this information" << endl; return 0; } catch( ... ) {} try { args.at( "--silent" ); silent = true; } catch( ... ) {} /* * Initialize the OpenGL context */ framework frm; frm.init( screen, title, fullscreen ); //set opengl settings glEnable( GL_DEPTH_TEST ); glDepthFunc( GL_LEQUAL ); glFrontFace( GL_CCW ); glEnable( GL_CULL_FACE ); glClearColor( 0.0f, 0.0f, 0.0f, 0.0f ); glClearDepth( 1.0f ); frm.get_opengl_error(); /* * Set up mymath */ camera<float> cam; frame<float> the_frame; float cam_fov = 58.7f; float cam_near = 1.0f; float cam_far = 1000.0f; /** //small camera cam_fov = 20.0f; cam_far = 10.0f; /**/ the_frame.set_perspective( radians( cam_fov ), ( float )screen.x / ( float )screen.y, cam_near, cam_far ); frame<float> top_frame; camera<float> cam_top; top_frame.set_perspective( radians( 58.7f ), ( float )screen.x / ( float )screen.y, 1, 100 ); cam_top.rotate_x( radians( -90.0f ) ); cam_top.move_forward( -70.0f ); glViewport( 0, 0, screen.x, screen.y ); /* * Set up the scene */ float move_amount = 5; float cam_rotation_amount = 5.0; //set up boxes GLuint box = frm.create_box(); int size = 100; //number of boxes to render cout << "Rendering: " << size* size << " cubes" << endl; vector<mat4> positions; positions.resize( size * size ); for( int c = 0; c < size; ++c ) { for( int d = 0; d < size; ++d ) { positions[c * size + d] = mm::create_translation( mm::vec3( c * 30 - size, -20, -d * 30 ) ) * mm::create_scale(mm::vec3(10)); } } /* * Set up the shaders */ GLuint debug_shader = 0; frm.load_shader( debug_shader, GL_VERTEX_SHADER, "../shaders/culling/debug.vs" ); frm.load_shader( debug_shader, GL_FRAGMENT_SHADER, "../shaders/culling/debug.ps" ); GLint debug_proj_mat_loc = glGetUniformLocation( debug_shader, "proj" ); GLint debug_view_mat_loc = glGetUniformLocation( debug_shader, "view" ); GLint debug_model_mat_loc = glGetUniformLocation( debug_shader, "model" ); GLint debug_light_loc = glGetUniformLocation( debug_shader, "light" ); /* * Set up culling */ bool cull = true; /**/ //calculate camera and box bounding volumes vec4 box_center = vec4( vec3( 0 ), 1 ); float box_radius = length( vec3( 2, 2, 2 ) ) * 0.5f; /**/ vector<shape*> bvs; bvs.resize( size * size ); for( int c = 0; c < size; ++c ) { for( int d = 0; d < size; ++d ) { vec4 model_box_center = positions[c * size + d] * box_center; //represent boxes as aabbs or spheres //spheres are a tiny bit faster bvs[c * size + d] = new aabb( model_box_center.xyz, vec3( 10 ) ); //bvs[c * size + d] = new sphere( model_box_center.xyz, box_radius ); } } shape* cam_sphere = new sphere( vec3(0), float(0) ); shape* cam_frustum = new frustum(); /* * Handle events */ //allows to switch between the topdown and normal camera camera<float>* cam_ptr = &cam; bool warped = false, ignore = true; vec2 movement_speed = vec2(0); auto event_handler = [&]( const sf::Event & ev ) { switch( ev.type ) { case sf::Event::MouseMoved: { vec2 mpos( ev.mouseMove.x / float( screen.x ), ev.mouseMove.y / float( screen.y ) ); if( warped ) { ignore = false; } else { frm.set_mouse_pos( ivec2( screen.x / 2.0f, screen.y / 2.0f ) ); warped = true; ignore = true; } if( !ignore && all( notEqual( mpos, vec2( 0.5 ) ) ) ) { cam.rotate( radians( -180.0f * ( mpos.x - 0.5f ) ), vec3( 0.0f, 1.0f, 0.0f ) ); cam.rotate_x( radians( -180.0f * ( mpos.y - 0.5f ) ) ); frm.set_mouse_pos( ivec2( screen.x / 2.0f, screen.y / 2.0f ) ); warped = true; } break; } case sf::Event::KeyPressed: {/* if( ev.key.code == sf::Keyboard::A ) { if( cam_ptr == &cam ) cam_ptr->rotate_y( radians( cam_rotation_amount ) ); else if( cam_ptr == &cam_top ) cam_ptr->rotate_z( radians( -cam_rotation_amount ) ); } if( ev.key.code == sf::Keyboard::D ) { if( cam_ptr == &cam ) cam_ptr->rotate_y( radians( -cam_rotation_amount ) ); else if( cam_ptr == &cam_top ) cam_ptr->rotate_z( radians( cam_rotation_amount ) ); } if( ev.key.code == sf::Keyboard::W ) { if( cam_ptr == &cam ) cam_ptr->move_forward( move_amount ); else if( cam_ptr == &cam_top ) cam_ptr->move_up( move_amount ); } if( ev.key.code == sf::Keyboard::S ) { if( cam_ptr == &cam ) cam_ptr->move_forward( -move_amount ); else if( cam_ptr == &cam_top ) cam_ptr->move_up( -move_amount ); }*/ if( ev.key.code == sf::Keyboard::Space ) { cull = !cull; } if( ev.key.code == sf::Keyboard::C ) { cam_ptr = &cam; } if( ev.key.code == sf::Keyboard::X ) { cam_ptr = &cam_top; } break; } default: break; } }; /* * Render */ sf::Clock timer; timer.restart(); ss.clear(); int draw_count = 0; int intersection_count = 0; int frame_count = 0; sf::Clock movement_timer; movement_timer.restart(); frm.display( [&] { frm.handle_events( event_handler ); float seconds = movement_timer.getElapsedTime().asMilliseconds() / 1000.0f; if( seconds > 0.01667 ) { //move camera if( sf::Keyboard::isKeyPressed( sf::Keyboard::A ) ) { movement_speed.x -= move_amount; } if( sf::Keyboard::isKeyPressed( sf::Keyboard::D ) ) { movement_speed.x += move_amount; } if( sf::Keyboard::isKeyPressed( sf::Keyboard::W ) ) { movement_speed.y += move_amount; } if( sf::Keyboard::isKeyPressed( sf::Keyboard::S ) ) { movement_speed.y -= move_amount; } cam.move_forward( movement_speed.y * seconds ); cam.move_right( movement_speed.x * seconds ); movement_speed *= 0.5; movement_timer.restart(); } glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); glUseProgram( debug_shader ); glUniformMatrix4fv( debug_proj_mat_loc, 1, false, &the_frame.projection_matrix[0][0] ); mat4 view = cam_ptr->get_matrix(); glUniformMatrix4fv( debug_view_mat_loc, 1, false, &view[0][0] ); glBindVertexArray( box ); //set up camera //need to set up per change (per frame for now) static_cast<frustum*>( cam_frustum )->set_up( cam, the_frame ); vec3 cam_center = cam.pos + cam.view_dir * ( ( cam_far - cam_near ) * 0.5f ) + cam_near; float cam_radius = length( //far top right apex ( ( cam.pos - cam.view_dir* the_frame.far_ll.z ) + cam.up_vector * ( the_frame.far_ul.y - the_frame.far_ll.y ) - -normalize( cross( cam.up_vector, cam.view_dir ) ) * ( the_frame.far_lr.x - the_frame.far_ll.x ) ) - cam_center ); //center of the circle around the camera static_cast<sphere*>( cam_sphere )->set_center( cam_center ); static_cast<sphere*>( cam_sphere )->set_radius( cam_radius ); //contains the IDs and state (culled or not) of the cubes static vector< pair< int, bool > > in_view; for( int c = 0; c < size; ++c ) { for( int d = 0; d < size; ++d ) { bool culled = false; if( cull ) { /** //camera is approximated by a sphere if( !culled ) { ++intersection_count; if( !shape::intersects.go( cam_sphere, bvs[c * size + d] ) ) culled = true; } /**/ /**/ //camera is a frustum //precise intersection if( !culled ) { intersection_count += 6; if( !cam_frustum->is_intersecting( bvs[c * size + d] ) ) culled = true; } /**/ } /**/ //comment out to see coloring if( culled ) continue; /**/ in_view.push_back( make_pair( c * size + d, culled ) ); } } for( auto c = in_view.begin(); c != in_view.end(); ++c ) { vec3 red( 1, 0, 0 ); vec3 green( 0, 1, 0 ); if( c->second ) glUniform3fv( debug_light_loc, 1, &red.x ); else glUniform3fv( debug_light_loc, 1, &green.x ); glUniformMatrix4fv( debug_model_mat_loc, 1, false, &positions[c->first][0][0] ); glDrawElements( GL_TRIANGLES, 36, GL_UNSIGNED_INT, 0 ); ++draw_count; } in_view.clear(); /**/ if( cam_ptr == &cam_top ) { //draw camera vec3 blue( 1, 1, 1 ); glUniform3fv( debug_light_loc, 1, &blue.x ); mat4 m = mat4::identity; glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glDisable(GL_TEXTURE_2D); glDisable(GL_CULL_FACE); glUniformMatrix4fv( debug_model_mat_loc, 1, false, &m[0][0] ); vec3 cam_base = cam.pos; //m = create_translation( cam.pos + vec3( 0, 1, 0 ) ); //glUniformMatrix4fv( debug_model_mat_loc, 1, false, &m[0][0] ); //glDrawElements( GL_TRIANGLES, 36, GL_UNSIGNED_INT, 0 ); glBegin(GL_TRIANGLES); float nw = the_frame.near_lr.x - the_frame.near_ll.x; float nh = the_frame.near_ul.y - the_frame.near_ll.y; float fw = the_frame.far_lr.x - the_frame.far_ll.x; float fh = the_frame.far_ul.y - the_frame.far_ll.y; vec3 nc = cam.pos - cam.view_dir * the_frame.near_ll.z; vec3 fc = cam.pos - cam.view_dir * the_frame.far_ll.z; vec3 right = -normalize( cross( cam.up_vector, cam.view_dir ) ); //near top left vec3 ntl = nc + cam.up_vector * nh - right * nw; vec3 ntr = nc + cam.up_vector * nh + right * nw; vec3 nbl = nc - cam.up_vector * nh - right * nw; vec3 nbr = nc - cam.up_vector * nh + right * nw; vec3 ftl = fc + cam.up_vector * fh - right * fw; vec3 ftr = fc + cam.up_vector * fh + right * fw; vec3 fbl = fc - cam.up_vector * fh - right * fw; vec3 fbr = fc - cam.up_vector * fh + right * fw; glVertex3fv((GLfloat*)&cam_base); glVertex3fv((GLfloat*)&ftl); glVertex3fv((GLfloat*)&fbl); glVertex3fv((GLfloat*)&cam_base); glVertex3fv((GLfloat*)&ftr); glVertex3fv((GLfloat*)&fbr); glVertex3fv((GLfloat*)&cam_base); glVertex3fv((GLfloat*)&ftl); glVertex3fv((GLfloat*)&ftr); glVertex3fv((GLfloat*)&cam_base); glVertex3fv((GLfloat*)&fbl); glVertex3fv((GLfloat*)&fbr); //far plane //m = create_translation( vec3( ntl.x, 1, ntl.z ) ); //glUniformMatrix4fv( debug_model_mat_loc, 1, false, &m[0][0] ); //glDrawElements( GL_TRIANGLES, 36, GL_UNSIGNED_INT, 0 ); //m = create_translation( vec3( ntr.x, 1, ntr.z ) ); //glUniformMatrix4fv( debug_model_mat_loc, 1, false, &m[0][0] ); //glDrawElements( GL_TRIANGLES, 36, GL_UNSIGNED_INT, 0 ); //near plane //m = create_translation( vec3( ftl.x, 1, ftl.z ) ); //glUniformMatrix4fv( debug_model_mat_loc, 1, false, &m[0][0] ); //glDrawElements( GL_TRIANGLES, 36, GL_UNSIGNED_INT, 0 ); //m = create_translation( vec3( ftr.x, 1, ftr.z ) ); //glUniformMatrix4fv( debug_model_mat_loc, 1, false, &m[0][0] ); //glDrawElements( GL_TRIANGLES, 36, GL_UNSIGNED_INT, 0 ); glEnd(); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glEnable(GL_TEXTURE_2D); glEnable(GL_CULL_FACE); } /**/ ++frame_count; if( timer.getElapsedTime().asMilliseconds() > 1000 && !silent ) { int timepassed = timer.getElapsedTime().asMilliseconds(); int fps = 1000.0f / ( ( float ) timepassed / ( float ) frame_count ); string ttl = title; ss << " - FPS: " << fps << " - Time: " << ( float ) timepassed / ( float ) frame_count << " - Draw calls: " << ( draw_count / frame_count ) << " - Intersections: " << ( intersection_count / frame_count ); ttl += ss.str(); ss.str( "" ); frm.set_title( ttl ); intersection_count = 0; draw_count = 0; frame_count = 0; timer.restart(); } frm.get_opengl_error(); }, silent ); return 0; }
25.225275
131
0.561679
[ "render", "shape", "vector", "model" ]
a237730667122a0c529ec85369f1be63a7fab835
5,998
cpp
C++
xdl-algorithm-solution/TDMServing/tdm-serving/index/index_unit.cpp
Ru-Xiang/x-deeplearning
04cc0497150920c64b06bb8c314ef89977a3427a
[ "Apache-2.0" ]
4,071
2018-12-13T04:17:38.000Z
2022-03-30T03:29:35.000Z
xdl-algorithm-solution/TDMServing/tdm-serving/index/index_unit.cpp
laozhuang727/x-deeplearning
781545783a4e2bbbda48fc64318fb2c6d8bbb3cc
[ "Apache-2.0" ]
359
2018-12-21T01:14:57.000Z
2022-02-15T07:18:02.000Z
xdl-algorithm-solution/TDMServing/tdm-serving/index/index_unit.cpp
laozhuang727/x-deeplearning
781545783a4e2bbbda48fc64318fb2c6d8bbb3cc
[ "Apache-2.0" ]
1,054
2018-12-20T09:57:42.000Z
2022-03-29T07:16:53.000Z
/* Copyright (C) 2016-2018 Alibaba Group Holding Limited Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "index/index_unit.h" #include <utime.h> #include <fstream> #include "common/common_def.h" #include "index/index.h" #include "model/model_manager.h" #include "util/file_monitor.h" #include "util/log.h" namespace tdm_serving { IndexUnit::IndexUnit() : enable_(true) { } IndexUnit::~IndexUnit() { for (uint32_t i = 0; i < index_datas_.size(); ++i) { DELETE_AND_SET_NULL(index_datas_[i]); } index_datas_.clear(); if (!version_file_path_.empty()) { util::FileMonitor::UnWatch(version_file_path_); } } void IndexReloadAction(const std::string& file, util::WatchEvent ev, void* args) { (void)file; (void)ev; if (NULL == args) { LOG_ERROR << "Relaod action args is NULL"; return; } IndexUnit* index_unit = reinterpret_cast<IndexUnit*>(args); if (NULL == index_unit) { LOG_ERROR << "Index Unit ptr is NULL"; return; } // wait for model to update if (!index_unit->CheckModelVersion()) { LOG_WARN << "Index Unit check model version failed"; utime(file.c_str(), NULL); sleep(1); return; } if (!index_unit->Reload()) { LOG_ERROR << "Index Unit reload failed"; } } bool IndexUnit::Init(const std::string& section, const std::string& conf_path) { section_ = section; conf_path_ = conf_path; if (!conf_parser_.Init(conf_path_)) { LOG_ERROR << "Load conf from " << conf_path << " failed"; return false; } if (!conf_parser_.GetValue<bool>(section_, kConfigEnable, &enable_)) { LOG_ERROR << "[" << section_ << "] get " << kConfigEnable << " failed"; return false; } if (!enable_) { LOG_INFO << "[" << section_ << "] is disable"; return true; } if (!conf_parser_.GetValue<std::string>(section_, kConfigIndexType, &index_type_) || index_type_.empty()) { LOG_ERROR << "[" << section_ << "] get " << kConfigIndexType << " failed"; return false; } LOG_INFO << "[" << section_ << "] " << kConfigIndexType << ": "<< index_type_; for (uint32_t i = 0; i < kIndexInstanceNum; ++i) { index_datas_.push_back(NULL); } if (!Reload()) { LOG_ERROR << "init unit init to reload failed"; return false; } // register file monitor version_file_path_ = index_datas_[idx_]->version_file_path(); if (version_file_path_.empty()) { LOG_INFO << "[" << section_ << "] need not reload index"; } else { util::FileMonitor::Watch(version_file_path_, IndexReloadAction, reinterpret_cast<bool *>(this)); LOG_INFO << "[" << section_ << "] file_monitor register at: " << version_file_path_; } return true; } bool IndexUnit::Reload() { LOG_INFO << "[" << section_ << "] begin reload"; Index* index = IndexRegisterer::GetInstanceByTitle(index_type_); if (index == NULL) { LOG_ERROR << "[" << section_ << "] get index by type: " << index_type_ << " failed"; return false; } if (!index->Init(section_, conf_parser_)) { LOG_ERROR << "[" << section_ << "] init index failed"; return false; } // switch uint32_t new_idx = (idx_ + 1) % kIndexInstanceNum; Index* old_index = index_datas_[new_idx]; index_datas_[new_idx] = index; idx_ = new_idx; if (old_index != NULL) { LOG_INFO << "[" << section_ << "] release old index"; delete old_index; } LOG_INFO << "[" << section_ << "] new index switch success"; return true; } Index* IndexUnit::GetIndex() { return index_datas_[idx_]; } bool IndexUnit::is_enabled() { return enable_; } bool IndexUnit::CheckModelVersion() { std::ifstream version_file_handler(version_file_path_.c_str()); if (!version_file_handler) { LOG_DEBUG << "Check model version, open " << version_file_path_ << " failed, need no check"; return true; } std::string model_name = GetIndex()->model_name(); if (model_name.empty()) { LOG_DEBUG << "Check model version, model name is empty, " << "do not need model"; return true; } // get model version for index std::string line; size_t pos = 0; std::string model_version; while (std::getline(version_file_handler, line)) { util::StrUtil::Trim(line); if ((pos = line.find(kModelVersionTag)) != std::string::npos) { model_version = line.substr(pos + kModelVersionTag.length()); util::StrUtil::Trim(model_version); } } if (model_version == "") { LOG_ERROR << "Check model version, has version file, " << "but has no version, need no check"; return true; } // check if model version is valid if (!ModelManager::Instance().HasModel(model_name, model_version)) { LOG_WARN << "Check model version, " << "model manager does not have model with " << "model_name: " << model_name << ", model_version: " << model_version << ", wait for model updating"; return false; } LOG_DEBUG << "Check model version, " << "model manager has model with " << "model_name: " << model_name << ", model_version: " << model_version << ", pass"; return true; } } // namespace tdm_serving
28.292453
80
0.604201
[ "model" ]
a23863f6136a7da0bbe765fe8bdc0f7e28b94bec
3,676
cpp
C++
build/main/RoninManager.cpp
walthill/final-crusade
4533651b6a4cf55665ea864cb1cb2d40beaf4ee3
[ "Apache-2.0" ]
null
null
null
build/main/RoninManager.cpp
walthill/final-crusade
4533651b6a4cf55665ea864cb1cb2d40beaf4ee3
[ "Apache-2.0" ]
null
null
null
build/main/RoninManager.cpp
walthill/final-crusade
4533651b6a4cf55665ea864cb1cb2d40beaf4ee3
[ "Apache-2.0" ]
null
null
null
#include "RoninManager.h" RoninManager::RoninManager() { } RoninManager::~RoninManager() { clearManager(); } void RoninManager::clearManager() { for (unsigned int i = 0; i < mRoninList.size(); i++) { Ronin* tmp = mRoninList[i]; Collider* tmpCol = mColliderList[i]; if (tmp != NULL) delete tmp; //if (tmpCol != NULL) // delete tmpCol; } mRoninList.clear(); mColliderList.clear(); /* map<EntityId, Ronin*>::iterator iter; for (iter = mEntityMap.begin(); iter != mEntityMap.end(); iter++) { Ronin* tmp = iter->second; if (tmp != NULL) delete tmp; } mEntityMap.clear();*/ } void RoninManager::update(double elapsedTime) { for (unsigned int i = 0; i < mRoninList.size(); i++) { mRoninList[i]->update(elapsedTime); } /* map<EntityId, Ronin*>::iterator iter; for (iter = mEntityMap.begin(); iter != mEntityMap.end(); iter++) iter->second->update(elapsedTime);*/ } void RoninManager::draw(GraphicsSystem *system) { for (unsigned int i = 0; i < mRoninList.size(); i++) { mRoninList[i]->draw(system); } /*map<EntityId, Ronin*>::iterator iter; for (iter = mEntityMap.begin(); iter != mEntityMap.end(); iter++) iter->second->draw(system);*/ } void RoninManager::draw(GraphicsSystem *system, int camX, int camY) { for (unsigned int i = 0; i < mRoninList.size(); i++) { mRoninList[i]->draw(system, camX, camY); } /* map<EntityId, Ronin*>::iterator iter; for (iter = mEntityMap.begin(); iter != mEntityMap.end(); iter++) iter->second->draw(system, camX, camY);*/ } void RoninManager::createAndAddEntity(EntityId key, int x, int y, Animation anim) { //pass in the animation, location // map<EntityId, Ronin*>::iterator iter = mEntityMap.find(key); //if (iter == mEntityMap.end()) //{ Ronin *newEntity = new Ronin; newEntity->setAnimation(anim); newEntity->setLoc(x, y); newEntity->setCollider("ronin"); mRoninList.push_back(newEntity); mColliderList.push_back(newEntity->getCollider()); //mEntityMap[key] = newEntity; newEntity = NULL; cout << "NEW SPRITE" << endl; //} } void RoninManager::createAndAddEntity(EntityId key, int x, int y, Animation anim, int amount) { /*//pass in the animation, location map<EntityId, Ronin*>::iterator iter = mEntityMap.find(key); srand(unsigned(time(NULL))); for (int i = 0; i < amount; i++) { int randX = rand() % 1500; int randY = rand() % 1100; if (iter == mEntityMap.end()) { Ronin *newEntity = new Ronin; newEntity->setAnimation(anim); newEntity->setLoc(randX, randY); mEntityMap[key] = newEntity; newEntity = NULL; cout << "NEW SPRITE" << endl; } }*/ } void RoninManager::addEntity(EntityId key, Ronin *objToAdd) { mRoninList.push_back(objToAdd); mColliderList.push_back(objToAdd->getCollider()); /*map<EntityId, Ronin*>::iterator iter = mEntityMap.find(key); if (iter == mEntityMap.end()) mEntityMap[key] = objToAdd;*/ } void RoninManager::removeEntity(int index) { mRoninList.erase(mRoninList.begin() + index); mColliderList.erase(mColliderList.begin() + index); /*map<EntityId, Ronin*>::iterator iter = mEntityMap.find(key); if (iter != mEntityMap.end()) mEntityMap.erase(key);*/ } void RoninManager::removeEntity(Ronin *objToRemove) { /* map<EntityId, Ronin*>::iterator iter; for (iter = mEntityMap.begin(); iter != mEntityMap.end(); iter++) { if (objToRemove == iter->second) { delete objToRemove; mEntityMap.erase(iter); return; } }*/ } Ronin* RoninManager::getEntity(int index) { return mRoninList[index]; } int RoninManager::getCount() { return mRoninList.size(); } vector<Collider*> RoninManager::getColliderList() { return mColliderList; }
18.948454
93
0.663221
[ "vector" ]
a24b43e7738ae02b17fb78edaad89d3ad29acc43
7,230
cc
C++
chrome/test/webdriver/dispatch.cc
Gitman1989/chromium
2b1cceae1075ef012fb225deec8b4c8bbe4bc897
[ "BSD-3-Clause" ]
2
2017-09-02T19:08:28.000Z
2021-11-15T15:15:14.000Z
chrome/test/webdriver/dispatch.cc
Gitman1989/chromium
2b1cceae1075ef012fb225deec8b4c8bbe4bc897
[ "BSD-3-Clause" ]
null
null
null
chrome/test/webdriver/dispatch.cc
Gitman1989/chromium
2b1cceae1075ef012fb225deec8b4c8bbe4bc897
[ "BSD-3-Clause" ]
1
2020-04-13T05:45:10.000Z
2020-04-13T05:45:10.000Z
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/test/webdriver/dispatch.h" #include <sstream> #include <string> #include "base/json/json_writer.h" #include "chrome/test/webdriver/commands/command.h" namespace webdriver { // The standard HTTP Status codes are implemented below. Chrome uses // OK, See Other, Not Found, Method Not Allowed, and Internal Error. // Internal Error, HTTP 500, is used as a catch all for any issue // not covered in the JSON protocol. void SendHttpOk(struct mg_connection* const connection, const struct mg_request_info* const request_info, const Response& response) { const std::string json = response.ToJSON(); std::ostringstream out; out << "HTTP/1.1 200 OK\r\n" << "Content-Length: " << strlen(json.c_str()) << "\r\n" << "Content-Type: application/json; charset=UTF-8\r\n" << "Vary: Accept-Charset, Accept-Encoding, Accept-Language, Accept\r\n" << "Accept-Ranges: bytes\r\n" << "Connection: close\r\n\r\n"; if (strcmp(request_info->request_method, "HEAD") != 0) out << json << "\r\n"; VLOG(1) << out.str(); mg_printf(connection, "%s", out.str().c_str()); } void SendHttpSeeOther(struct mg_connection* const connection, const struct mg_request_info* const request_info, const Response& response) { const Value* value = response.value(); CheckValueType(Value::TYPE_STRING, value); std::string location; if (!value->GetAsString(&location)) { NOTREACHED(); } std::ostringstream out; out << "HTTP/1.1 303 See Other\r\n" << "Location: " << location << "\r\n" << "Content-Type: text/html\r\n" << "Content-Length: 0\r\n\r\n"; VLOG(1) << out.str(); mg_printf(connection, "%s", out.str().c_str()); } void SendHttpBadRequest(struct mg_connection* const connection, const struct mg_request_info* const request_info, const Response& response) { const std::string json = response.ToJSON(); std::ostringstream out; out << "HTTP/1.1 400 Bad Request\r\n" << "Content-Length: " << strlen(json.c_str()) << "\r\n" << "Content-Type: application/json; charset=UTF-8\r\n" << "Vary: Accept-Charset, Accept-Encoding, Accept-Language, Accept\r\n" << "Accept-Ranges: bytes\r\n" << "Connection: close\r\n\r\n"; if (strcmp(request_info->request_method, "HEAD") != 0) out << json << "\r\n"; VLOG(1) << out.str(); mg_printf(connection, "%s", out.str().c_str()); } void SendHttpNotFound(struct mg_connection* const connection, const struct mg_request_info* const request_info, const Response& response) { const std::string json = response.ToJSON(); std::ostringstream out; out << "HTTP/1.1 404 Not Found\r\n" << "Content-Length: " << strlen(json.c_str()) << "\r\n" << "Content-Type: application/json; charset=UTF-8\r\n" << "Vary: Accept-Charset, Accept-Encoding, Accept-Language, Accept\r\n" << "Accept-Ranges: bytes\r\n" << "Connection: close\r\n\r\n"; if (strcmp(request_info->request_method, "HEAD") != 0) out << json << "\r\n"; VLOG(1) << out.str(); mg_printf(connection, "%s", out.str().c_str()); } void SendHttpMethodNotAllowed(struct mg_connection* const connection, const struct mg_request_info* const request_info, const Response& response) { const Value* value = response.value(); CheckValueType(Value::TYPE_LIST, value); std::vector<std::string> allowed_methods; const ListValue* list_value = static_cast<const ListValue*>(value); for (size_t i = 0; i < list_value->GetSize(); ++i) { std::string method; LOG_IF(WARNING, list_value->GetString(i, &method)) << "Ignoring non-string value at index " << i; allowed_methods.push_back(method); } std::ostringstream out; out << "HTTP/1.1 405 Method Not Allowed\r\n" << "Content-Type: text/html\r\n" << "Content-Length: 0\r\n" << "Allow: " << JoinString(allowed_methods, ',') << "\r\n\r\n"; VLOG(1) << out.str(); mg_printf(connection, "%s", out.str().c_str()); } void SendHttpInternalError(struct mg_connection* const connection, const struct mg_request_info* const request_info, const Response& response) { const std::string json = response.ToJSON(); std::ostringstream out; out << "HTTP/1.1 500 Internal Server Error\r\n" << "Content-Length: " << strlen(json.c_str()) << "\r\n" << "Content-Type: application/json; charset=UTF-8\r\n" << "Vary: Accept-Charset, Accept-Encoding, Accept-Language, Accept\r\n" << "Accept-Ranges: bytes\r\n" << "Connection: close\r\n\r\n"; if (strcmp(request_info->request_method, "HEAD") != 0) out << json << "\r\n"; VLOG(1) << out.str(); mg_printf(connection, "%s", out.str().c_str()); } // For every HTTP request from the mongoode server DispatchCommand will // inspect the HTTP method call requested and execute the proper function // mapped from the class Command. void DispatchCommand(Command* const command, const std::string& method, Response* response) { if (command->DoesPost() && method == "POST") { if (command->Init(response)) command->ExecutePost(response); } else if (command->DoesGet() && method == "GET") { if (command->Init(response)) command->ExecuteGet(response); } else if (command->DoesDelete() && method == "DELETE") { if (command->Init(response)) command->ExecuteDelete(response); } else { ListValue* methods = new ListValue; if (command->DoesPost()) methods->Append(Value::CreateStringValue("POST")); if (command->DoesGet()) { methods->Append(Value::CreateStringValue("GET")); methods->Append(Value::CreateStringValue("HEAD")); } if (command->DoesDelete()) methods->Append(Value::CreateStringValue("DELETE")); response->set_status(kMethodNotAllowed); response->set_value(methods); // Assumes ownership. } } void SendResponse(struct mg_connection* const connection, const struct mg_request_info* const request_info, const Response& response) { switch (response.status()) { case kSuccess: SendHttpOk(connection, request_info, response); break; case kSeeOther: SendHttpSeeOther(connection, request_info, response); break; case kBadRequest: SendHttpBadRequest(connection, request_info, response); break; case kSessionNotFound: SendHttpNotFound(connection, request_info, response); break; case kMethodNotAllowed: SendHttpMethodNotAllowed(connection, request_info, response); break; // All other errors should be treated as generic 500s. The client will be // responsible for inspecting the message body for details. case kInternalServerError: default: SendHttpInternalError(connection, request_info, response); break; } } } // namespace webdriver
37.46114
79
0.640664
[ "vector" ]
a24f848141375fdd093926e8eab54e747354d0f9
1,139
cpp
C++
p3iv_utils_polyvision/test/cgal_convex_hull.cpp
fzi-forschungszentrum-informatik/P3IV
51784e6dc03dcaa0ad58a5078475fa4daec774bd
[ "BSD-3-Clause" ]
4
2021-07-27T06:56:22.000Z
2022-03-22T11:21:30.000Z
p3iv_utils_polyvision/test/cgal_convex_hull.cpp
fzi-forschungszentrum-informatik/P3IV
51784e6dc03dcaa0ad58a5078475fa4daec774bd
[ "BSD-3-Clause" ]
null
null
null
p3iv_utils_polyvision/test/cgal_convex_hull.cpp
fzi-forschungszentrum-informatik/P3IV
51784e6dc03dcaa0ad58a5078475fa4daec774bd
[ "BSD-3-Clause" ]
1
2021-10-10T01:56:44.000Z
2021-10-10T01:56:44.000Z
#include <iostream> #include <CGAL/Exact_predicates_inexact_constructions_kernel.h> #include <CGAL/convex_hull_2.h> #include "gtest/gtest.h" typedef CGAL::Exact_predicates_inexact_constructions_kernel K; typedef K::Point_2 Point_2; typedef std::vector<Point_2> Points; TEST(CGALTest, ConvexHull) { // array_convex_hull.cpp Point_2 points[5] = {Point_2(0, 0), Point_2(10, 0), Point_2(10, 10), Point_2(6, 5), Point_2(4, 1)}; Point_2 result[5]; Point_2* ptr = CGAL::convex_hull_2(points, points + 5, result); std::cout << ptr - result << " points on the convex hull:" << std::endl; for (int i = 0; i < ptr - result; i++) { std::cout << result[i] << std::endl; } // vector_convex_hull.cpp Points pointsVec, resultVec; pointsVec.push_back(Point_2(0, 0)); pointsVec.push_back(Point_2(10, 0)); pointsVec.push_back(Point_2(10, 10)); pointsVec.push_back(Point_2(6, 5)); pointsVec.push_back(Point_2(4, 1)); CGAL::convex_hull_2(pointsVec.begin(), pointsVec.end(), std::back_inserter(resultVec)); std::cout << resultVec.size() << " points on the convex hull" << std::endl; }
36.741935
103
0.676032
[ "vector" ]
a254140e75410a1e60d9db2fe6751a91b5c0b9d2
6,672
hpp
C++
Gui/pagmo/utils/hv_algos/hv_hv2d.hpp
haisenzhao/CarpentryCompiler
c9714310b7ce7523a25becd397265bfaa3ab7ea3
[ "FSFAP" ]
21
2019-12-06T09:57:10.000Z
2021-09-22T12:58:09.000Z
Gui/pagmo/utils/hv_algos/hv_hv2d.hpp
haisenzhao/CarpentryCompiler
c9714310b7ce7523a25becd397265bfaa3ab7ea3
[ "FSFAP" ]
null
null
null
Gui/pagmo/utils/hv_algos/hv_hv2d.hpp
haisenzhao/CarpentryCompiler
c9714310b7ce7523a25becd397265bfaa3ab7ea3
[ "FSFAP" ]
5
2020-11-18T00:09:30.000Z
2021-01-13T04:40:47.000Z
/* Copyright 2017-2018 PaGMO development team This file is part of the PaGMO library. The PaGMO library is free software; you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or both in parallel, as here. The PaGMO 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 General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with the PaGMO library. If not, see https://www.gnu.org/licenses/. */ #ifndef PAGMO_UTIL_hv2d_H #define PAGMO_UTIL_hv2d_H #include <cmath> #include <iostream> #include <stdexcept> #include <string> #include <vector> #include <pagmo/exceptions.hpp> #include <pagmo/io.hpp> #include <pagmo/population.hpp> #include <pagmo/types.hpp> #include <pagmo/utils/hv_algos/hv_algorithm.hpp> #include <pagmo/utils/hypervolume.hpp> namespace pagmo { /// hv2d hypervolume algorithm class /** * This is the class containing the implementation of the hypervolume algorithm for the 2-dimensional fronts. * This method achieves the lower bound of n*log(n) time by sorting the initial set of points and then computing the * partial areas linearly. * */ class hv2d final : public hv_algorithm { public: /// Constructor /** * @param initial_sorting Turn initial sorting on-off */ hv2d(const bool initial_sorting = true) : m_initial_sorting(initial_sorting) {} /// Compute hypervolume method. /** * This method should be used both as a solution to 2-dimensional cases, and as a general termination method for * algorithms that reduce n-dimensional problem to 2D. * * Computational complexity: n*log(n) * * @param points vector of points containing the 2-dimensional points for which we compute the hypervolume * @param r_point reference point for the points * * @return hypervolume */ double compute(std::vector<vector_double> &points, const vector_double &r_point) const override { if (points.size() == 0u) { return 0.0; } else if (points.size() == 1u) { return hv_algorithm::volume_between(points[0], r_point); } if (m_initial_sorting) { sort(points.begin(), points.end(), [](const vector_double &v1, const vector_double &v2) { return v1[1] < v2[1]; }); } double hypervolume = 0.0; // width of the sweeping line double w = r_point[0] - points[0][0]; for (decltype(points.size()) idx = 0u; idx < points.size() - 1u; ++idx) { hypervolume += (points[idx + 1u][1] - points[idx][1]) * w; w = std::max(w, r_point[0] - points[idx + 1u][0]); } hypervolume += (r_point[1] - points[points.size() - 1u][1]) * w; return hypervolume; } /// Compute hypervolume method. /** * This method should be used both as a solution to 2-dimensional cases, and as a general termination method for * algorithms that reduce n-dimensional problem to 2d. * This method is overloaded to work with arrays of double, in order to provide other algorithms that internally * work with arrays (such as hv_algorithm::wfg) with an efficient computation. * * Computational complexity: n*log(n) * * @param points array of 2-dimensional points * @param n_points number of points * @param r_point 2-dimensional reference point for the points * * @return hypervolume */ double compute(double **points, vector_double::size_type n_points, double *r_point) const { if (n_points == 0u) { return 0.0; } else if (n_points == 1u) { return volume_between(points[0], r_point, 2); } if (m_initial_sorting) { std::sort(points, points + n_points, [](double *a, double *b) { return a[1] < b[1]; }); } double hypervolume = 0.0; // width of the sweeping line double w = r_point[0] - points[0][0]; for (decltype(n_points) idx = 0; idx < n_points - 1u; ++idx) { hypervolume += (points[idx + 1u][1] - points[idx][1]) * w; w = std::max(w, r_point[0] - points[idx + 1u][0]); } hypervolume += (r_point[1] - points[n_points - 1u][1]) * w; return hypervolume; } /// Contributions method /** * Computes the contributions of each point by invoking the HV3D algorithm with mock third dimension. * * @param points vector of points containing the 2-dimensional points for which we compute the hypervolume * @param r_point reference point for the points * @return vector of exclusive contributions by every point */ std::vector<double> contributions(std::vector<vector_double> &points, const vector_double &r_point) const override; /// Clone method. /** * @return a pointer to a new object cloning this */ std::shared_ptr<hv_algorithm> clone() const override { return std::shared_ptr<hv_algorithm>(new hv2d(*this)); } /// Verify input method. /** * Verifies whether the requested data suits the hv2d algorithm. * * @param points vector of points containing the d dimensional points for which we compute the hypervolume * @param r_point reference point for the vector of points * * @throws value_error when trying to compute the hypervolume for the dimension other than 3 or non-maximal * reference point */ void verify_before_compute(const std::vector<vector_double> &points, const vector_double &r_point) const override { if (r_point.size() != 2u) { pagmo_throw(std::invalid_argument, "Algorithm hv2d works only for 2-dimensional cases."); } hv_algorithm::assert_minimisation(points, r_point); } /// Algorithm name /** * @return The name of this particular algorithm */ std::string get_name() const override { return "hv2d algorithm"; } private: // Flag stating whether the points should be sorted in the first step of the algorithm. const bool m_initial_sorting; }; } // namespace pagmo #endif
34.040816
119
0.658723
[ "object", "vector" ]
a262366c9289486fa1084e28872a9e3650d8362f
3,493
cpp
C++
multithreaded/thread_pool.cpp
kzhereb/knu-is-ooop2019
bd0d25b8f42fa00ddbe4cd0a2a477f790cca5ffe
[ "MIT" ]
4
2019-09-30T14:58:40.000Z
2021-03-25T10:11:03.000Z
multithreaded/thread_pool.cpp
kzhereb/knu-is-ooop2019
bd0d25b8f42fa00ddbe4cd0a2a477f790cca5ffe
[ "MIT" ]
143
2019-12-07T14:30:00.000Z
2020-05-18T09:40:10.000Z
multithreaded/thread_pool.cpp
kzhereb/knu-is-ooop2019
bd0d25b8f42fa00ddbe4cd0a2a477f790cca5ffe
[ "MIT" ]
4
2019-09-17T11:39:06.000Z
2019-12-11T18:41:22.000Z
/* * thread_pool.cpp * * Created on: May 29, 2020 * Author: KZ */ #include "../unit-testing/catch.hpp" #include <vector> #include <queue> #include <memory> #include <thread> #include <mutex> #include <condition_variable> #include <future> #include <functional> #include <stdexcept> #include <iostream> class ThreadPool { public: ThreadPool(size_t); template<class F, class... Args> auto enqueue(F&& f, Args&&... args) -> std::future<typename std::result_of<F(Args...)>::type>; ~ThreadPool(); private: // need to keep track of threads so we can join them std::vector< std::thread > workers; // the task queue std::queue< std::function<void()> > tasks; // synchronization std::mutex queue_mutex; std::condition_variable condition; bool stop; }; // the constructor just launches some amount of workers inline ThreadPool::ThreadPool(size_t threads) : stop(false) { for(size_t i = 0;i<threads;++i) workers.emplace_back( [this] { for(;;) { std::function<void()> task; { std::unique_lock<std::mutex> lock(this->queue_mutex); this->condition.wait(lock, [this]{ return this->stop || !this->tasks.empty(); }); if(this->stop && this->tasks.empty()) return; task = std::move(this->tasks.front()); this->tasks.pop(); } task(); } } ); } // add new work item to the pool template<class F, class... Args> auto ThreadPool::enqueue(F&& f, Args&&... args) -> std::future<typename std::result_of<F(Args...)>::type> { using return_type = typename std::result_of<F(Args...)>::type; auto task = std::make_shared< std::packaged_task<return_type()> >( std::bind(std::forward<F>(f), std::forward<Args>(args)...) ); std::future<return_type> res = task->get_future(); { std::unique_lock<std::mutex> lock(queue_mutex); // don't allow enqueueing after stopping the pool if(stop) throw std::runtime_error("enqueue on stopped ThreadPool"); tasks.emplace([task](){ (*task)(); }); } condition.notify_one(); return res; } // the destructor joins all threads inline ThreadPool::~ThreadPool() { { std::unique_lock<std::mutex> lock(queue_mutex); stop = true; } condition.notify_all(); for(std::thread &worker: workers) worker.join(); } TEST_CASE("example from ThreadPool", "[threads]") { ThreadPool pool(4); std::vector< std::future<int> > results; for(int i = 0; i < 8; ++i) { results.emplace_back( pool.enqueue([i] { std::cout << "hello " << i << std::endl; std::this_thread::sleep_for(std::chrono::milliseconds(100*i+300)); std::cout << "world " << i << std::endl; return i*i; }) ); } int i = 0; for(auto && result: results) { int val = result.get(); std::cout << val << ' '; REQUIRE(val == i*i); i++; } std::cout << std::endl; }
25.129496
83
0.504151
[ "vector" ]
a267cf5c827291d9dae95846bd3c8b6866c96acd
1,732
cpp
C++
cpp/249.cpp
kylekanos/project-euler-1
af7089356a4cea90f8ef331cfdc65e696def6140
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
cpp/249.cpp
kylekanos/project-euler-1
af7089356a4cea90f8ef331cfdc65e696def6140
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
cpp/249.cpp
kylekanos/project-euler-1
af7089356a4cea90f8ef331cfdc65e696def6140
[ "BSD-2-Clause-FreeBSD" ]
1
2019-09-17T00:55:58.000Z
2019-09-17T00:55:58.000Z
#include <algorithm> #include <iostream> #include <sstream> #include <cstring> #include <cstdlib> #include <climits> #include <cmath> #include <bitset> #include <vector> #include <queue> #include <stack> #include <set> #include <map> #define REP(i,a) for(int i=0;i<(a);i++) #define FOR(i,a,b) for(int i=(a);i<(b);i++) #define MAX(a,b) ((a)>(b)?(a):(b)) #define MAX3(a,b,c) MAX(MAX(a,b),c) #define MAX4(a,b,c,d) MAX(MAX3(a,b,c),d) #define MIN(a,b) ((a)<(b)?(a):(b)) #define MIN3(a,b,c) MIN(MIN(a,b),c) #define MIN4(a,b,c,d) MIN(MIN3(a,b,c),d) #define SZ size() #define PB push_back const int oo = INT_MAX>>1; using namespace std; typedef vector<int> VE; typedef unsigned long long ull; ull mod = pow(10,16); const int M=5000; ull *mem[M]; inline int modn(int n, int m) { return n>=0 ? n%m : (n%m)+m; } int main() { VE parr; vector<bool> prime(M,true); prime[0]=prime[1]=false; for (int i=2; i*i<M; i++) { if (!prime[i]) continue; for (int j=i<<1; j<M; j+=i) prime[j]=false; } REP(i,M) if (prime[i]) parr.PB(i); int n = parr.SZ; int total=0; REP(i,n) total+=parr[i]; REP(i,M) mem[i] = new ull[n+1]; prime = vector<bool>(total+1,true); prime[0]=prime[1]=false; for (int i=2; i*i<=total; i++) { if (!prime[i]) continue; for (int j=i<<1; j<=total; j+=i) prime[j]=false; } ull ans = 0; fill(mem[0],mem[0]+n+1,1); FOR(i,1,M) fill(mem[i],mem[i]+n+1,0); FOR(i,2,total+1) { int num=i%M; mem[num][n]=0; for (int j=n-1; j>=0; j--) mem[num][j] = (mem[modn(num-parr[j],M)][j+1] + mem[num][j+1])%mod; if (prime[i]) ans = (ans+mem[num][0])%mod; } cout << ans << endl; return 0; }
24.742857
78
0.547344
[ "vector" ]
a2738fb11f517ea294b9c2fff896c364c4cbd1b5
1,442
cpp
C++
ftsoftds_vc6/ch13/prg13_5a.cpp
guarana-x/fwg
5a56dcb4caee5dca6744fca8e21b987b07106513
[ "MIT" ]
null
null
null
ftsoftds_vc6/ch13/prg13_5a.cpp
guarana-x/fwg
5a56dcb4caee5dca6744fca8e21b987b07106513
[ "MIT" ]
null
null
null
ftsoftds_vc6/ch13/prg13_5a.cpp
guarana-x/fwg
5a56dcb4caee5dca6744fca8e21b987b07106513
[ "MIT" ]
null
null
null
// File: prg13_5a.cpp // the program demonstrates the need for a virtual destructor // in the base class. the base class, baseCL, does not declare // a virtual destructor, and the derived class, dynDerived, // allocates dynamic memory. after allocating a dynDerived object // and storing the pointer in a baseCL pointer, the program calls // delete which causes only the base class destructor to execute. the // dynamic memory allocated by the derived object is not removed, // causing a memory leak #include <iostream> using namespace std; class baseCL { public: baseCL() { cout << "baseCL constructor - no action" << endl;} ~baseCL() // not a virtual destructor { cout << "baseCL destructor - no action" << endl; } }; class dynDerived: public baseCL { public: dynDerived() : baseCL() { cout << "dynDerived constructor - allocate 4-element array" << endl; dArr = new int [4]; } ~dynDerived() { cout << "dynDerived destructor - deallocate 4-element array" << endl; delete [] dArr; } private: int *dArr; // pointer to derived class dynamic array }; int main() { baseCL *basePtr = new dynDerived; delete basePtr; return 0; } /* Run: (baseCL destructor is not virtual): In baseCL constructor - no action In dynDerived constructor - allocate 4-element array In baseCL destructor - no action */
23.639344
70
0.653953
[ "object" ]
a2782f1059b76bd57b85d8575a0a8b8e86892c1e
1,728
cpp
C++
201610_12/1127_cf16-relay/G.cpp
kazunetakahashi/atcoder
16ce65829ccc180260b19316e276c2fcf6606c53
[ "MIT" ]
7
2019-03-24T14:06:29.000Z
2020-09-17T21:16:36.000Z
201610_12/1127_cf16-relay/G.cpp
kazunetakahashi/atcoder
16ce65829ccc180260b19316e276c2fcf6606c53
[ "MIT" ]
null
null
null
201610_12/1127_cf16-relay/G.cpp
kazunetakahashi/atcoder
16ce65829ccc180260b19316e276c2fcf6606c53
[ "MIT" ]
1
2020-07-22T17:27:09.000Z
2020-07-22T17:27:09.000Z
#include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> // get<n>(xxx) #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> // S.insert(M); // if (S.find(key) != S.end()) { } // for (auto it=S.begin(); it != S.end(); it++) { } // auto it = S.lower_bound(M); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> // atoi(xxx) using namespace std; typedef long long ll; //const int dx[4] = {1, 0, -1, 0}; //const int dy[4] = {0, 1, 0, -1}; // const int C ; // const int M = 1000000007; int N, Q; int A[100010], B[100010]; int h[100010]; bool visited[100010]; int main () { cin >> N >> Q; for (auto i = 0; i < Q; i++) { cin >> A[i] >> B[i]; A[i]--; B[i]--; } h[0] = 0; for (auto i = 0; i < Q; i++) { if (A[i] == h[i]) { h[i+1] = B[i]; } else if (B[i] == h[i]) { h[i+1] = A[i]; } else { h[i+1] = h[i]; } //cerr << "h[" << i+1 << "] = " << h[i+1] << endl; } fill(visited, visited+100010, false); visited[0] = true; visited[1] = true; for (auto i = 0; i < Q; i++) { swap(visited[A[i]], visited[B[i]]); if (0 <= h[i+1]-1 && h[i+1]-1 < N) { visited[h[i+1]-1] = true; } if (0 <= h[i+1]+1 && h[i+1]+1 < N) { visited[h[i+1]+1] = true; } for (auto j = 0; j < N; j++) { //cerr << (visited[j] ? "x" : "."); } //cerr << endl; } int ans = 0; for (auto i = 0; i < N; i++) { if (visited[i]) ans++; } cout << ans << endl; }
23.351351
69
0.480903
[ "vector" ]
a27c7bd195db8ed3c85608a2be06d7c7d98ddc23
606
hpp
C++
code/stable/dblpendulum/src/cpp/Calculations.hpp
JacquesCarette/literate-scientific-software
ba461947c2f1f81c76adce95f05e65edd86b8390
[ "BSD-2-Clause" ]
null
null
null
code/stable/dblpendulum/src/cpp/Calculations.hpp
JacquesCarette/literate-scientific-software
ba461947c2f1f81c76adce95f05e65edd86b8390
[ "BSD-2-Clause" ]
442
2016-05-18T19:11:00.000Z
2017-12-02T14:37:06.000Z
code/stable/dblpendulum/src/cpp/Calculations.hpp
JacquesCarette/literate-scientific-software
ba461947c2f1f81c76adce95f05e65edd86b8390
[ "BSD-2-Clause" ]
null
null
null
/** \file Calculations.hpp \author Dong Chen \brief Provides functions for calculating the outputs */ #ifndef Calculations_h #define Calculations_h #include <vector> #include "ODE.hpp" #include "Populate.hpp" using std::vector; /** \brief Calculates dependent variables (rad) \param m_1 the mass of the first object (kg) \param m_2 the mass of the second object (kg) \param L_2 the length of the second rod (m) \param L_1 the length of the first rod (m) \return dependent variables (rad) */ vector<double> func_theta(double m_1, double m_2, double L_2, double L_1); #endif
24.24
74
0.714521
[ "object", "vector" ]
a28804c117952476dfcf69fb688492a5f88b961e
1,655
cpp
C++
src/1.cpp
zzlai/leetcode-solution
68d35d4f3def6c3f0362bfcc74cb0060291649b3
[ "MIT" ]
null
null
null
src/1.cpp
zzlai/leetcode-solution
68d35d4f3def6c3f0362bfcc74cb0060291649b3
[ "MIT" ]
null
null
null
src/1.cpp
zzlai/leetcode-solution
68d35d4f3def6c3f0362bfcc74cb0060291649b3
[ "MIT" ]
null
null
null
#include <vector> #include <iostream> #include <unordered_map> using namespace std; #if 0 class Solution { public: // brute force // time and space complexity : O(N^2), O(N) vector<int> twoSum(vector<int>& nums, int target) { int sz = nums.size(); for (int i = 0; i < sz; ++i) { for (int j = i + 1; j < sz; ++j) { if (nums[i] + nums[j] == target) { return {i, j}; } } } return {-1, -1}; } }; #endif #if 0 class Solution { public: // hash // time and space complexity : O(N), O(N) vector<int> twoSum(vector<int>& nums, int target) { int sz = nums.size(); unordered_map<int, int> dict; // <nums[i], i> for (int i = 0; i < sz; ++i) { dict.insert(make_pair(nums[i], i)); } for (int i = 0; i < sz; ++i) { auto iter = dict.find(target - nums[i]); if (iter != dict.end() && iter->second != i) return vector<int>{i, iter->second}; } return vector<int>{-1, -1}; } }; #endif class Solution { public: // hash // time and space complexity : O(N), O(N) vector<int> twoSum(vector<int>& nums, int target) { int sz = nums.size(); unordered_map<int, int> dict; // <nums[i], i> for (int i = 0; i < sz; ++i) { auto iter = dict.find(target - nums[i]); if (iter != dict.end() && iter->second != i) return vector<int>{iter->second, i}; dict.insert(make_pair(nums[i], i)); } return vector<int>{-1, -1}; } };
23.985507
56
0.468882
[ "vector" ]
a28fb24d95cbb3b4bd1811cec42f96cca5df324c
7,185
cpp
C++
ext/include/osgEarthDrivers/label_overlay/OverlayLabelSource.cpp
energonQuest/dtEarth
47b04bb272ec8781702dea46f5ee9a03d4a22196
[ "MIT" ]
6
2015-09-26T15:33:41.000Z
2021-06-13T13:21:50.000Z
ext/include/osgEarthDrivers/label_overlay/OverlayLabelSource.cpp
energonQuest/dtEarth
47b04bb272ec8781702dea46f5ee9a03d4a22196
[ "MIT" ]
null
null
null
ext/include/osgEarthDrivers/label_overlay/OverlayLabelSource.cpp
energonQuest/dtEarth
47b04bb272ec8781702dea46f5ee9a03d4a22196
[ "MIT" ]
5
2015-05-04T09:02:23.000Z
2019-06-17T11:34:12.000Z
/* -*-c++-*- */ /* osgEarth - Dynamic map generation toolkit for OpenSceneGraph * Copyright 2008-2013 Pelican Mapping * http://osgearth.org * * osgEarth 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 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ #include <osgEarthFeatures/LabelSource> #include <osgEarthSymbology/Expression> #include <osgEarthUtil/Controls> #include <osgEarth/CullingUtils> #include <osgEarth/ECEF> #include <osg/ClusterCullingCallback> #include <osg/MatrixTransform> #include <osgDB/FileNameUtils> #include <set> using namespace osgEarth; using namespace osgEarth::Features; using namespace osgEarth::Symbology; using namespace osgEarth::Util; /******* Deprecated ---- please use AnnotationLabelSource instead *************/ class OverlayLabelSource : public LabelSource { public: OverlayLabelSource( const LabelSourceOptions& options ) : LabelSource( options ) { //nop } /** * Creates a simple label. The caller is responsible for placing it in the scene. */ osg::Node* createNode( const std::string& text, const Style& style ) { const TextSymbol* symbol = style.get<TextSymbol>(); Controls::LabelControl* label = new Controls::LabelControl( text ); if ( symbol ) { if ( symbol->fill().isSet() ) label->setForeColor( symbol->fill()->color() ); if ( symbol->halo().isSet() ) label->setHaloColor( symbol->halo()->color() ); if ( symbol->size().isSet() ) label->setFontSize( *symbol->size() ); if ( symbol->font().isSet() ) label->setFont( osgText::readFontFile(*symbol->font()) ); if ( symbol->encoding().isSet() ) { osgText::String::Encoding enc; switch(symbol->encoding().value()) { case TextSymbol::ENCODING_ASCII: enc = osgText::String::ENCODING_ASCII; break; case TextSymbol::ENCODING_UTF8: enc = osgText::String::ENCODING_UTF8; break; case TextSymbol::ENCODING_UTF16: enc = osgText::String::ENCODING_UTF16; break; case TextSymbol::ENCODING_UTF32: enc = osgText::String::ENCODING_UTF32; break; default: enc = osgText::String::ENCODING_UNDEFINED; break; } label->setEncoding( enc ); } } Controls::ControlNode* node = new Controls::ControlNode( label ); return node; } /** * Creates a complete set of positioned label nodes from a feature list. */ osg::Node* createNode( const FeatureList& input, const Style& style, const FilterContext& context ) { const TextSymbol* text = style.get<TextSymbol>(); osg::Group* group = 0L; std::set<std::string> used; // to prevent dupes bool skipDupes = (text->removeDuplicateLabels() == true); StringExpression contentExpr ( *text->content() ); NumericExpression priorityExpr( *text->priority() ); //bool makeECEF = false; const SpatialReference* ecef = 0L; if ( context.isGeoreferenced() ) { //makeECEF = context.getSession()->getMapInfo().isGeocentric(); ecef = context.getSession()->getMapSRS()->getECEF(); } for( FeatureList::const_iterator i = input.begin(); i != input.end(); ++i ) { const Feature* feature = i->get(); if ( !feature ) continue; const Geometry* geom = feature->getGeometry(); if ( !geom ) continue; osg::Vec3d centroid = geom->getBounds().center(); if ( ecef ) { context.profile()->getSRS()->transform( centroid, ecef, centroid ); //context.profile()->getSRS()->transformToECEF( centroid, centroid ); } const std::string& value = feature->eval( contentExpr, &context ); if ( !value.empty() && (!skipDupes || used.find(value) == used.end()) ) { if ( !group ) { group = new osg::Group(); } double priority = feature->eval( priorityExpr, &context ); Controls::LabelControl* label = new Controls::LabelControl( value ); if ( text->fill().isSet() ) label->setForeColor( text->fill()->color() ); if ( text->halo().isSet() ) label->setHaloColor( text->halo()->color() ); if ( text->size().isSet() ) label->setFontSize( *text->size() ); if ( text->font().isSet() ) label->setFont( osgText::readFontFile(*text->font()) ); Controls::ControlNode* node = new Controls::ControlNode( label, priority ); osg::MatrixTransform* xform = new osg::MatrixTransform( osg::Matrixd::translate(centroid) ); xform->addChild( node ); // for a geocentric map, do a simple dot product cull. if ( ecef ) { xform->setCullCallback( new CullNodeByHorizon( centroid, ecef->getEllipsoid() ) ); //context.getSession()->getMapSRS()->getEllipsoid() ) ); //getMapInfo().getProfile()->getSRS()->getEllipsoid()) ); group->addChild( xform ); } else { group->addChild( xform ); } if ( skipDupes ) { used.insert( value ); } } } return group; } }; //------------------------------------------------------------------------ class OverlayLabelSourceDriver : public LabelSourceDriver { public: OverlayLabelSourceDriver() { supportsExtension( "osgearth_label_overlay", "osgEarth overlay label plugin" ); } virtual const char* className() { return "osgEarth Overlay Label Plugin"; } virtual ReadResult readObject(const std::string& file_name, const Options* options) const { if ( !acceptsExtension(osgDB::getLowerCaseFileExtension( file_name ))) return ReadResult::FILE_NOT_HANDLED; return new OverlayLabelSource( getLabelSourceOptions(options) ); } }; REGISTER_OSGPLUGIN(osgearth_label_overlay, OverlayLabelSourceDriver)
35.220588
138
0.55936
[ "geometry", "transform" ]
a297b52b66a7f002192a9956a9080cc18af95e4d
2,140
cpp
C++
Online-Judges/CodeForces/800/1627A.Not_Shading.cpp
shihab4t/Competitive-Programming
e8eec7d4f7d86bfa1c00b7fbbedfd6a1518f19be
[ "Unlicense" ]
3
2021-06-15T01:19:23.000Z
2022-03-16T18:23:53.000Z
Online-Judges/CodeForces/800/1627A.Not_Shading.cpp
shihab4t/Competitive-Programming
e8eec7d4f7d86bfa1c00b7fbbedfd6a1518f19be
[ "Unlicense" ]
null
null
null
Online-Judges/CodeForces/800/1627A.Not_Shading.cpp
shihab4t/Competitive-Programming
e8eec7d4f7d86bfa1c00b7fbbedfd6a1518f19be
[ "Unlicense" ]
null
null
null
#include <bits/stdc++.h> using namespace std; using lli = long long int; using str = string; #define vec vector #define endn '\n' #define loop(i, a, b) for (i = a; i < b; i++) #define first_io \ ios_base::sync_with_stdio(false); \ cin.tie(NULL); #define file_io \ freopen("input.txt", "r", stdin); \ freopen("output.txt", "w", stdout); #define debug(...) __f(#__VA_ARGS__, __VA_ARGS__) template <typename Arg1> void __f(const char *name, Arg1 &&arg1) { cout << name << " = " << arg1 << std::endl; } template <typename Arg1, typename... Args> void __f(const char *names, Arg1 &&arg1, Args &&...args) { const char *comma = strchr(names + 1, ','); cout.write(names, comma - names) << " = " << arg1 << " | "; __f(comma + 1, args...); } template <typename Tp> void print(Tp arr[], int n) { for (int i = 0; i < n; i++) cout << arr[i] << " "; cout << '\n'; } template <typename Tp> void print(vector<Tp> &vc) { for (auto &ith : vc) cout << ith << " "; cout << '\n'; } #define PI acos(-1.0) #define EPS 1e-9 #define MOD 1000000007 void test_case() { int n, m; cin >> n >> m; int r, c; cin >> r >> c; char a[55][55], i, j; bool is_got = false; vector<pair<int, int>> indexs; for (i = 1; i <= n; i++) { for (j = 1; j <= m; j++) { cin >> a[i][j]; if (a[i][j] == 'B') { is_got = true; indexs.push_back({i, j}); } } } if (is_got == false) { cout << -1 << endn; return; } if (a[r][c] == 'B') { cout << 0 << endn; return; } for (i = 1; i <= m; i++) { if (a[r][i] == 'B') { cout << 1 << endn; return; } } for (i = 1; i <= n; i++) { if (a[i][c] == 'B') { cout << 1 << endn; return; } } cout << 2 << endn; } int main(void) { first_io; int t; cin >> t; while (t--) { test_case(); } return 0; } // Solved by: Shihab Mahamud (github.com/shihab4t)
22.061856
63
0.451402
[ "vector" ]
a29e86b9837e918ca88cb12ed54cf785b499452d
831
cc
C++
src/tools/dump_graph_main.cc
ishine/deepx_core
a71fa4b5fec5cf5d83da04cbb9ee437d0c8b6e05
[ "BSD-2-Clause" ]
309
2021-03-24T03:00:19.000Z
2022-03-31T16:17:46.000Z
src/tools/dump_graph_main.cc
ishine/deepx_core
a71fa4b5fec5cf5d83da04cbb9ee437d0c8b6e05
[ "BSD-2-Clause" ]
4
2021-03-30T01:46:32.000Z
2021-04-06T12:22:18.000Z
src/tools/dump_graph_main.cc
ishine/deepx_core
a71fa4b5fec5cf5d83da04cbb9ee437d0c8b6e05
[ "BSD-2-Clause" ]
45
2021-03-29T06:12:17.000Z
2022-03-04T05:19:46.000Z
// Copyright 2021 the deepx authors. // Author: Yafei Zhang (kimmyzhang@tencent.com) // #include <deepx_core/graph/graph.h> #include <gflags/gflags.h> #include <iostream> DEFINE_string(in, "", "input model dir/graph file"); namespace deepx_core { namespace { int main(int argc, char** argv) { google::SetUsageMessage("Usage: [Options]"); #if HAVE_COMPILE_FLAGS_H == 1 google::SetVersionString("\n\n" #include "compile_flags.h" ); #endif google::ParseCommandLineFlags(&argc, &argv, true); DXCHECK_THROW(!FLAGS_in.empty()); Graph graph; if (LoadGraph(FLAGS_in, &graph) || graph.Load(FLAGS_in)) { std::cout << graph.Dot() << std::endl; } google::ShutDownCommandLineFlags(); return 0; } } // namespace } // namespace deepx_core int main(int argc, char** argv) { return deepx_core::main(argc, argv); }
22.459459
72
0.689531
[ "model" ]
94759830de98d928b6c6eb81567cffbacfaf25d6
2,165
cpp
C++
src/c++/methods/callbacks/MetadataKVPInstanceCallbacks.cpp
leo-polymorph/modioSDK
4e1b1d4baa17d3690f9520484fa58ea466818c2a
[ "MIT" ]
1
2018-10-05T15:59:04.000Z
2018-10-05T15:59:04.000Z
src/c++/methods/callbacks/MetadataKVPInstanceCallbacks.cpp
PyrokinesisStudio/modioSDK
951de6d90806794b5f86f82a1bbfda3e0ba0b65f
[ "MIT" ]
null
null
null
src/c++/methods/callbacks/MetadataKVPInstanceCallbacks.cpp
PyrokinesisStudio/modioSDK
951de6d90806794b5f86f82a1bbfda3e0ba0b65f
[ "MIT" ]
null
null
null
#include "c++/ModIOInstance.h" namespace modio { std::map<u32, GetAllMetadataKVPCall*> get_all_metadata_kvp_calls; std::map<u32, AddMetadataKVPCall*> add_metadata_kvp_calls; std::map<u32, DeleteMetadataKVPCall*> delete_metadata_kvp_calls; void onGetAllMetadataKVP(void* object, ModioResponse modio_response, ModioMetadataKVP* metadata_kvp_array, u32 metadata_kvp_array_size) { u32 call_id = *((u32*)object); modio::Response response; response.initialize(modio_response); std::vector<modio::MetadataKVP> metadata_kvp_vector; metadata_kvp_vector.resize(metadata_kvp_array_size); for(u32 i=0; i < metadata_kvp_array_size; i++) { metadata_kvp_vector[i].initialize(metadata_kvp_array[i]); } get_all_metadata_kvp_calls[call_id]->callback((const Response&)response, metadata_kvp_vector); delete get_all_metadata_kvp_calls[call_id]; delete (u32*)object; get_all_metadata_kvp_calls.erase(call_id); } void onAddMetadataKVP(void* object, ModioResponse modio_response) { u32 call_id = *((u32*)object); modio::Response response; response.initialize(modio_response); add_metadata_kvp_calls[call_id]->callback((const Response&)response); for(u32 i=0; i<add_metadata_kvp_calls[call_id]->metadata_kvp_array_size; i++) delete[] add_metadata_kvp_calls[call_id]->metadata_kvp_array[i]; delete[] add_metadata_kvp_calls[call_id]->metadata_kvp_array; delete add_metadata_kvp_calls[call_id]; delete (u32*)object; add_metadata_kvp_calls.erase(call_id); } void onDeleteMetadataKVP(void* object, ModioResponse modio_response) { u32 call_id = *((u32*)object); modio::Response response; response.initialize(modio_response); delete_metadata_kvp_calls[call_id]->callback((const Response&)response); for(u32 i=0; i<delete_metadata_kvp_calls[call_id]->metadata_kvp_array_size; i++) delete[] delete_metadata_kvp_calls[call_id]->metadata_kvp_array[i]; delete[] delete_metadata_kvp_calls[call_id]->metadata_kvp_array; delete delete_metadata_kvp_calls[call_id]; delete (u32*)object; delete_metadata_kvp_calls.erase(call_id); } }
35.491803
137
0.755658
[ "object", "vector" ]
947681a4fec2cd676e4b4ae425e6e7d16c1f0cf7
6,464
cpp
C++
Chapter_5_Image_Restroration_and_Reconstruction/Section_5_7.cpp
AlazzR/Digital-Image-Processing-Cpp
22573ff1aa2c8c8cc3dd6fb4ffaea07241aec47a
[ "CC0-1.0" ]
null
null
null
Chapter_5_Image_Restroration_and_Reconstruction/Section_5_7.cpp
AlazzR/Digital-Image-Processing-Cpp
22573ff1aa2c8c8cc3dd6fb4ffaea07241aec47a
[ "CC0-1.0" ]
null
null
null
Chapter_5_Image_Restroration_and_Reconstruction/Section_5_7.cpp
AlazzR/Digital-Image-Processing-Cpp
22573ff1aa2c8c8cc3dd6fb4ffaea07241aec47a
[ "CC0-1.0" ]
null
null
null
#include "Section_5_7_H_.h" void rescaling_intensities(cv::Mat& tempImage) { //Rescalling the values of the image to be non-negative cv::Mat gm = cv::Mat::zeros(tempImage.rows, tempImage.cols, CV_32FC1); cv::Mat gs = cv::Mat::zeros(tempImage.rows, tempImage.cols, CV_32FC1); std::vector<float> min_vector; auto f = [](const cv::Mat& a, std::vector<float>& vector)->void { const float* ptrM; for (int i = 0; i < a.rows; i++) { ptrM = a.ptr<float>(i); for (int j = 0; j < a.cols; j++) vector.push_back(ptrM[i]); } }; f(tempImage, min_vector); float min = *std::min_element(min_vector.begin(), min_vector.end()); const float* ptrTempT; float* ptrTempT1; for (int i = 0; i < gm.rows; i++) { ptrTempT = tempImage.ptr<float>(i); ptrTempT1 = gm.ptr<float>(i); for (int j = 0; j < gm.cols; j++) ptrTempT1[j] = ptrTempT[j] - min; } std::vector<float> max_vector; f(gm, max_vector); float max = *std::max_element(max_vector.begin(), max_vector.end()); for (int i = 0; i < gm.rows; i++) { ptrTempT = gm.ptr<float>(i); ptrTempT1 = gs.ptr<float>(i); for (int j = 0; j < gm.cols; j++) ptrTempT1[j] = 255.0F * (ptrTempT[j] / max); } gs.copyTo(tempImage); } cv::Mat creating_Butterworth_LPF(int P, int Q, float D0, int n) { cv::Mat butter = cv::Mat::zeros(P, Q, CV_32FC1); std::cout << "Filter size:\t" << butter.size() << std::endl; float t1; float t2; float D; float* ptr; for (int i = 0; i < P; i++) { ptr = butter.ptr<float>(i); for (int j = 0; j < Q; j++) { t1 = std::pow(i - P / 2.0F, 2); t2 = std::pow(j - Q / 2.0F, 2); D = std::sqrt(t1 + t2); ptr[j] = 1.0F / (1.0F + std::pow(D / D0, 2 * n)); } } auto f = [](cv::Mat& A, cv::Mat& B) {cv::Mat temp; cv::multiply(A, B, temp); return temp; }; cv::imwrite("../bin/Section_5_7/Butterworth_radii" + std::to_string(D0) + "_n_" + std::to_string(n) + ".jpg", f(butter, cv::Mat(butter.rows, butter.cols, CV_32FC1, cv::Scalar(255)))); return butter; } void centering_image(cv::Mat& img) { float* ptr; for (int i = 0; i < img.rows; i++) { ptr = img.ptr<float>(i); for (int j = 0; j < img.cols; j++) ptr[j] = ptr[j] * std::pow(-1, i + j); } } cv::Mat creating_H_atmospheric(float k, int M, int N) { cv::Mat kernel[2] = { cv::Mat::zeros(M, N, CV_32FC1), cv::Mat::zeros(M, N, CV_32FC1) }; float* ptr; for (int i = 0; i < kernel[0].rows; i++) { ptr = kernel[0].ptr<float>(i); for (int j = 0; j < kernel[0].cols; j++) { float t1 = std::pow((float)i - M/2.0F , 2) + std::pow((float)j - N / 2.0F, 2); //std::cout << 5 / 6 << std::endl; //std::cout << 5.0F/6.0F << std::endl; float t2 = std::pow(t1, 0.5F); ptr[j] = std::exp(-1.0F * k * t2); } } cv::Mat finalKernel = cv::Mat(M, N, CV_32FC2); cv::merge(kernel, 2, finalKernel); return finalKernel; } cv::Mat creating_H_motion(float a, float b, float T, int M, int N) { cv::Mat kernel[2] = { cv::Mat::zeros(M, N, CV_32FC1), cv::Mat::zeros(M, N, CV_32FC1)}; float* ptr1; float* ptr2; for (int i = 0; i < kernel[0].rows; i++) { ptr1 = kernel[0].ptr<float>(i); ptr2 = kernel[1].ptr<float>(i); for (int j = 0; j < kernel[0].cols; j++) { //float u = (float)i - M / 2.0F; //float v = (float)j - N / 2.0F; float u = (float)i; float v = (float)j; float t = (a * u + b * v); float t1 = std::sin(PI * t); float t2 = T / (PI * t); float treal = std::cos(-1.0F * PI * t); float timg = std::sin(-1.0F * PI * t); ptr1[j] = t2 * t1 * treal; ptr2[j] = t2 * t1 * timg; } } cv::Mat finalKernel = cv::Mat(M, N, CV_32FC2); cv::merge(kernel, 2, finalKernel); return finalKernel; } void inverse_filtering(const cv::Mat& img, std::string type, float D0, int n, float k, float a, float b, float T, std::string imageName) { cv::Mat kernel; if (type == "Atmospheric") kernel = creating_H_atmospheric(k, img.rows, img.cols); else kernel = creating_H_motion(a, b, T, img.rows, img.cols); cv::Mat ker[2] = { cv::Mat::zeros(img.rows, img.cols, CV_32FC1), cv::Mat::zeros(img.rows, img.cols, CV_32FC1) }; cv::split(kernel, ker); cv::Mat imgcentered = img.clone(); imgcentered.convertTo(imgcentered, CV_32FC1); centering_image(imgcentered); cv::Mat complex[2] = { imgcentered, cv::Mat::zeros(img.rows, img.cols, CV_32FC1) }; cv::Mat dftimg; cv::merge(complex, 2, dftimg); cv::dft(dftimg, dftimg); cv::split(dftimg, complex); std::cout << "*******************************" << std::endl; //(a+jb)/ (c + jd) = mag(a,b)/mag(c,d) < atan(b/a) - atan(d/c) cv::Mat magTemp[2] = { complex[0].clone(), complex[1].clone()}; cv::Mat phaseTemp = complex[0].clone(); cv::magnitude(magTemp[0], magTemp[1], magTemp[0]); cv::magnitude(ker[0], ker[1], magTemp[1]); cv::divide(magTemp[0], magTemp[1], magTemp[0]); float* ptrMag1; float* ptrMag2; float* ptrPhase; const float* ptrC1; const float* ptrC2; const float* ptrK1; const float* ptrK2; for (int row = 0; row < img.rows; row++) { ptrPhase = phaseTemp.ptr<float>(row); ptrC1 = complex[0].ptr<float>(row); ptrC2 = complex[1].ptr<float>(row); ptrK1 = ker[0].ptr<float>(row); ptrK2 = ker[1].ptr<float>(row); for (int col = 0; col < img.cols; col++) { ptrPhase[col] =std::atan2(ptrC2[col], ptrC1[col]) - std::atan2(ptrK2[col], ptrK1[col]); } } magTemp[1] = magTemp[0].clone();//To equate them and this will mitigate the issue of creating another Mat object for (int row = 0; row < img.rows; row++) { ptrMag1 = magTemp[0].ptr<float>(row); ptrMag2 = magTemp[1].ptr<float>(row); ptrPhase = phaseTemp.ptr<float>(row); for (int col = 0; col < img.cols; col++) { ptrMag1[col] = ptrMag1[col] * std::cos(ptrPhase[col]);//real ptrMag2[col] = ptrMag2[col] * std::sin(ptrPhase[col]);//imaginary } } complex[0] = magTemp[0].clone(); complex[1] = magTemp[1].clone(); cv::Mat LPF = creating_Butterworth_LPF(img.rows, img.cols, D0, n); cv::multiply(complex[0], LPF, complex[0]); cv::multiply(complex[1], LPF, complex[1]); cv::merge(complex, 2, dftimg); cv::dft(dftimg, dftimg, cv::DFT_INVERSE | cv::DFT_REAL_OUTPUT | cv::DFT_SCALE); cv::Mat finalImg; finalImg = dftimg.clone(); centering_image(finalImg); //rescaling_intensities(finalImg); finalImg.convertTo(finalImg, CV_8UC1); cv::imwrite("../bin/Section_5_7/Origina_Inverse_Filtering_" + imageName + "_noiseType_BY_" + type + ".jpg", img); cv::imwrite("../bin/Section_5_7/Image__After_Inverse_Filtering_" + imageName + "_noiseType_BY_" + type + ".jpg", finalImg); }
31.227053
184
0.606745
[ "object", "vector" ]
947811b1dc821a01b7019563731a62615adaa69c
4,765
cpp
C++
sdk/cpp/core/src/crud_service.cpp
YDK-Solutions/ydk
7ab961284cdc82de8828e53fa4870d3204d7730e
[ "ECL-2.0", "Apache-2.0" ]
125
2016-03-15T17:04:13.000Z
2022-03-22T02:46:17.000Z
sdk/cpp/core/src/crud_service.cpp
YDK-Solutions/ydk
7ab961284cdc82de8828e53fa4870d3204d7730e
[ "ECL-2.0", "Apache-2.0" ]
818
2016-03-17T17:06:00.000Z
2022-03-28T03:56:17.000Z
sdk/cpp/core/src/crud_service.cpp
YDK-Solutions/ydk
7ab961284cdc82de8828e53fa4870d3204d7730e
[ "ECL-2.0", "Apache-2.0" ]
93
2016-03-15T19:18:55.000Z
2022-02-24T13:55:07.000Z
/// YANG Development Kit // Copyright 2016 Cisco Systems. All rights reserved // //////////////////////////////////////////////////////////////// // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // ////////////////////////////////////////////////////////////////// #include "crud_service.hpp" #include "logger.hpp" #include "common_utilities.hpp" using namespace std; namespace ydk { static bool operation_succeeded(shared_ptr<Entity> entity) { YLOG_INFO("Operation {}", ((entity == nullptr)?"succeeded":"failed")); return entity == nullptr; } static bool operation_succeeded(vector<shared_ptr<Entity>> entity_list) { YLOG_INFO("Operation {}", (entity_list.size() == 0) ? "succeeded" : "failed"); return entity_list.size() == 0; } // Class CrudService implementation // CrudService::CrudService() { } CrudService::~CrudService() { } bool CrudService::create(ydk::ServiceProvider & provider, Entity & entity) { YLOG_INFO("Executing CRUD create operation on [{}]", entity.get_segment_path()); map<string,string> params; return operation_succeeded( provider.execute_operation("create", entity, params) ); } bool CrudService::create(ydk::ServiceProvider & provider, vector<Entity*> & entity_list) { YLOG_INFO("Executing CRUD create operation on {}", entity_vector_to_string(entity_list)); map<string,string> params; return operation_succeeded( provider.execute_operation("create", entity_list, params) ); } bool CrudService::update(ydk::ServiceProvider & provider, Entity & entity) { YLOG_INFO("Executing CRUD update operation on [{}]", entity.get_segment_path()); map<string,string> params; return operation_succeeded( provider.execute_operation("update", entity, params) ); } bool CrudService::update(ydk::ServiceProvider & provider, vector<Entity*> & entity_list) { YLOG_INFO("Executing CRUD create operation on {}", entity_vector_to_string(entity_list)); map<string,string> params; return operation_succeeded( provider.execute_operation("update", entity_list, params) ); } bool CrudService::delete_(ydk::ServiceProvider & provider, Entity & entity) { YLOG_INFO("Executing CRUD delete operation on [{}]", entity.get_segment_path()); map<string,string> params; return operation_succeeded( provider.execute_operation("delete", entity, params) ); } bool CrudService::delete_(ydk::ServiceProvider & provider, vector<Entity*> & entity_list) { YLOG_INFO("Executing CRUD delete operation on {}", entity_vector_to_string(entity_list)); map<string,string> params; return operation_succeeded( provider.execute_operation("delete", entity_list, params) ); } shared_ptr<Entity> CrudService::read(ydk::ServiceProvider & provider, Entity & filter) { YLOG_INFO("Executing CRUD read operation on [{}]", filter.get_segment_path()); map<string,string> params; params["mode"] = "all"; return provider.execute_operation("read", filter, params); } vector<shared_ptr<Entity>> CrudService::read(ydk::ServiceProvider & provider, vector<Entity*> & filter_list) { YLOG_INFO("Executing CRUD read operation on {}", entity_vector_to_string(filter_list)); map<string,string> params; params["mode"] = "all"; return provider.execute_operation("read", filter_list, params); } shared_ptr<Entity> CrudService::read_config(ydk::ServiceProvider & provider, Entity & filter) { YLOG_INFO("Executing CRUD read_config operation on [{}]", filter.get_segment_path()); map<string,string> params; params["mode"] = "config"; return provider.execute_operation("read", filter, params); } vector<shared_ptr<Entity>> CrudService::read_config(ydk::ServiceProvider & provider, vector<Entity*> & filter_list) { YLOG_INFO("Executing CRUD read operation on {}", entity_vector_to_string(filter_list)); map<string,string> params; params["mode"] = "config"; return provider.execute_operation("read", filter_list, params); } }
32.195946
93
0.703882
[ "vector" ]
947c73a6508b1f8683daa28613cc9ac8a71c8562
2,541
hpp
C++
viennamini/stepper.hpp
viennamini/viennamini-dev
0737b8010cce097b5df17d0f6e99583f0055dd66
[ "MIT" ]
null
null
null
viennamini/stepper.hpp
viennamini/viennamini-dev
0737b8010cce097b5df17d0f6e99583f0055dd66
[ "MIT" ]
null
null
null
viennamini/stepper.hpp
viennamini/viennamini-dev
0737b8010cce097b5df17d0f6e99583f0055dd66
[ "MIT" ]
null
null
null
#ifndef VIENNAMINI_STEPPER_HPP #define VIENNAMINI_STEPPER_HPP /* ======================================================================= Copyright (c) 2011-2013, Institute for Microelectronics, TU Wien http://www.iue.tuwien.ac.at ----------------- ViennaMini - The Vienna Device Simulator ----------------- authors: Karl Rupp rupp@iue.tuwien.ac.at Josef Weinbub weinbub@iue.tuwien.ac.at (add your name here) license: see file LICENSE in the ViennaFVM base directory ======================================================================= */ #include <vector> #include <map> #include "viennamini/forwards.h" namespace viennamini { class stepper { private: typedef std::vector<numeric> ValuesType; typedef std::pair< std::size_t, numeric> StepEntryType; typedef std::vector< StepEntryType > StepSetupType; typedef std::vector< StepSetupType > StepValuesType; public: typedef ValuesType values_type; typedef StepEntryType step_entry_type; typedef StepSetupType step_setup_type; typedef StepValuesType step_values_type; stepper (); void add (std::size_t segment_index, numeric const& start, numeric const& end, numeric const& delta); void add (std::size_t segment_index, numeric const& value); values_type compute_value_range (numeric const& start, numeric const& end, numeric const& delta); void update (); bool apply_next (sparse_values& current_contact_potentials); std::size_t get_current_step_id (); step_setup_type& get_step_setup (std::size_t step_id); step_setup_type& get_current_step_setup (); void write (std::ostream& stream = std::cout); std::size_t size (); bool empty (); void clear (); private: void add_impl(std::size_t segment_index, ValuesType& values); StepValuesType step_values_; StepValuesType::iterator current_step_; }; } // viennamini #endif
39.092308
144
0.494687
[ "vector" ]
9487427fef5e3115f98048f7e8bdedeb5b60919f
2,379
cpp
C++
ext/emsdk_portable/clang/tag-e1.34.1/src/lib/Target/BPF/BPFTargetMachine.cpp
slightperturbation/Cobalt
7b398d155d28f7ddf4068a6c25c8aa6aaae486d4
[ "Apache-2.0" ]
null
null
null
ext/emsdk_portable/clang/tag-e1.34.1/src/lib/Target/BPF/BPFTargetMachine.cpp
slightperturbation/Cobalt
7b398d155d28f7ddf4068a6c25c8aa6aaae486d4
[ "Apache-2.0" ]
null
null
null
ext/emsdk_portable/clang/tag-e1.34.1/src/lib/Target/BPF/BPFTargetMachine.cpp
slightperturbation/Cobalt
7b398d155d28f7ddf4068a6c25c8aa6aaae486d4
[ "Apache-2.0" ]
null
null
null
//===-- BPFTargetMachine.cpp - Define TargetMachine for BPF ---------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Implements the info about BPF target spec. // //===----------------------------------------------------------------------===// #include "BPF.h" #include "BPFTargetMachine.h" #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h" #include "llvm/IR/LegacyPassManager.h" #include "llvm/CodeGen/Passes.h" #include "llvm/Support/FormattedStream.h" #include "llvm/Support/TargetRegistry.h" #include "llvm/Target/TargetOptions.h" using namespace llvm; extern "C" void LLVMInitializeBPFTarget() { // Register the target. RegisterTargetMachine<BPFTargetMachine> X(TheBPFTarget); } // DataLayout --> Little-endian, 64-bit pointer/ABI/alignment // The stack is always 8 byte aligned // On function prologue, the stack is created by decrementing // its pointer. Once decremented, all references are done with positive // offset from the stack/frame pointer. BPFTargetMachine::BPFTargetMachine(const Target &T, StringRef TT, StringRef CPU, StringRef FS, const TargetOptions &Options, Reloc::Model RM, CodeModel::Model CM, CodeGenOpt::Level OL) : LLVMTargetMachine(T, "e-m:e-p:64:64-i64:64-n32:64-S128", TT, CPU, FS, Options, RM, CM, OL), TLOF(make_unique<TargetLoweringObjectFileELF>()), Subtarget(TT, CPU, FS, *this) { initAsmInfo(); } namespace { // BPF Code Generator Pass Configuration Options. class BPFPassConfig : public TargetPassConfig { public: BPFPassConfig(BPFTargetMachine *TM, PassManagerBase &PM) : TargetPassConfig(TM, PM) {} BPFTargetMachine &getBPFTargetMachine() const { return getTM<BPFTargetMachine>(); } bool addInstSelector() override; }; } TargetPassConfig *BPFTargetMachine::createPassConfig(PassManagerBase &PM) { return new BPFPassConfig(this, PM); } // Install an instruction selector pass using // the ISelDag to gen BPF code. bool BPFPassConfig::addInstSelector() { addPass(createBPFISelDag(getBPFTargetMachine())); return false; }
33.985714
80
0.64607
[ "model" ]
948a3cc3aba55d9065bed6be2bc7f0e9cdcdb9d4
2,405
hpp
C++
include/Hry/SCSSDK/TrailerChannel.hpp
Hary309/hry-core
c6547983115d7a34711ce20607c359f4047ec61e
[ "MIT" ]
8
2020-11-13T23:50:16.000Z
2022-01-03T16:54:00.000Z
include/Hry/SCSSDK/TrailerChannel.hpp
Hary309/hry-core
c6547983115d7a34711ce20607c359f4047ec61e
[ "MIT" ]
1
2021-01-28T01:56:30.000Z
2021-04-07T21:45:52.000Z
include/Hry/SCSSDK/TrailerChannel.hpp
Hary309/hry-core
c6547983115d7a34711ce20607c359f4047ec61e
[ "MIT" ]
2
2021-05-30T18:42:20.000Z
2021-07-04T09:04:34.000Z
/** * This file is part of the hry-core project * @ Author: Piotr Krupa <piotrkrupa06@gmail.com> * @ License: MIT License * @ Documentation: SCS Software */ #pragma once #include "Hry/Math/SCSTypes.hpp" #include "Hry/Namespace.hpp" HRY_NS_BEGIN namespace scs { struct TrailerChannel { /** @brief Is the trailer connected to the truck? */ bool connected; /** @brief How much is the cargo damaged that is loaded to this trailer in <0.0, 1.0> range */ float cargoDamage; /** @brief Represents world space position and orientation of the truck */ PlacementD worldPlacement; /** @brief Represents vehicle space linear velocity of the truck measured in meters per second */ Vec3<float> localVelocityLinear; /** @brief Represents vehicle space angular velocity of the truck measured in rotations per second */ Vec3<float> localVelocityAngular; /** @brief Repreesnts vehicle space linear acceleration of the truck measured in meters per second^2 */ Vec3<float> localAccelerationLinear; /** @brief Represents vehicle space angular acceleration of the truck meassured in rotations per second^2 */ Vec3<float> localAccelerationAngular; /** @brief Wear of the chassis accessory as <0;1> */ float wearChassis; /** @brief Average wear across the wheel accessories as <0;1> */ float wearWheels; /** @brief Vertical displacement of the wheel from its axis in meters. */ std::vector<float> wheelSuspensionDeflection; /** @brief Is the wheel in contact with ground? */ std::vector<bool> wheelOnGround; /** @brief Substance below the whell */ std::vector<uint32_t> wheelSubstance; /** @brief Angular velocity of the wheel in rotations per second */ std::vector<float> wheelAngularVelocity; /** @brief Steering rotation of the wheel in rotations */ std::vector<float> wheelSteering; /** @brief Rolling rotation of the wheel in rotations */ std::vector<float> wheelRotation; /** @brief Lift state of the wheel <0;1> */ std::vector<float> wheelLift; /** @brief Vertical displacement of the wheel axle from its normal position in meters as result of lifting */ std::vector<float> wheelLiftOffset; }; } // namespace scs HRY_NS_END
40.083333
117
0.662786
[ "vector" ]
948c0fa99f59bd8d4d97822710227dd5f695d915
5,329
cc
C++
plugins/update/npapi/np_update.cc
rocious/omaha
44a58900e58979362ad18de6867d804bee0f1b91
[ "Apache-2.0" ]
34
2019-11-01T04:26:40.000Z
2022-03-29T03:00:40.000Z
plugins/update/npapi/np_update.cc
rocious/omaha
44a58900e58979362ad18de6867d804bee0f1b91
[ "Apache-2.0" ]
1
2015-06-15T06:26:34.000Z
2015-06-15T06:26:34.000Z
plugins/update/npapi/np_update.cc
rocious/omaha
44a58900e58979362ad18de6867d804bee0f1b91
[ "Apache-2.0" ]
8
2019-11-01T04:27:53.000Z
2022-03-16T22:17:12.000Z
// Copyright 2009 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ======================================================================== #include "omaha/plugins/update/npapi/np_update.h" #include <atlbase.h> #include <atlcom.h> #include "omaha/base/debug.h" #include "omaha/base/scope_guard.h" #include "omaha/base/string.h" #include "omaha/plugins/update/config.h" #include "omaha/plugins/update/npapi/dispatch_host.h" #include "omaha/plugins/update/npapi/urlpropbag.h" #include "plugins/update/activex/update_control_idl.h" NPError NS_PluginInitialize() { return NPERR_NO_ERROR; } void NS_PluginShutdown() { } nsPluginInstanceBase* NS_NewPluginInstance(nsPluginCreateData* data) { return new omaha::NPUpdate(data->instance, data->type); } void NS_DestroyPluginInstance(nsPluginInstanceBase* plugin) { delete plugin; } namespace omaha { NPUpdate::NPUpdate(NPP instance, const char* mime_type) : instance_(instance), is_initialized_(false), mime_type_(mime_type), scriptable_object_(NULL) { ASSERT1(instance); // TODO(omaha): initialize COM } NPUpdate::~NPUpdate() { if (scriptable_object_) { NPN_ReleaseObject(scriptable_object_); } } NPBool NPUpdate::init(NPWindow* np_window) { UNREFERENCED_PARAMETER(np_window); is_initialized_ = true; return TRUE; } void NPUpdate::shut() { is_initialized_ = false; } NPBool NPUpdate::isInitialized() { // TODO(omaha): figure the right boolean type to return here... return is_initialized_ ? TRUE : FALSE; } NPError NPUpdate::GetValue(NPPVariable variable, void* value) { if (!instance_) { return NPERR_INVALID_INSTANCE_ERROR; } if (NPPVpluginScriptableNPObject != variable || !value) { return NPERR_INVALID_PARAM; } CString url; if (!GetCurrentBrowserUrl(&url) || !site_lock_.InApprovedDomain(url)) { return NPERR_INVALID_URL; } if (!scriptable_object_) { CComPtr<IDispatch> p; CLSID clsid; if (!MapMimeTypeToClsid(&clsid)) { return NPERR_INVALID_PLUGIN_ERROR; } if (FAILED(p.CoCreateInstance(clsid))) { return NPERR_OUT_OF_MEMORY_ERROR; } // Store the current URL in a property bag and set it as the site of // the object. CComPtr<IPropertyBag> pb; if (FAILED(UrlPropertyBag::Create(url, &pb))) { return NPERR_GENERIC_ERROR; } CComPtr<IObjectWithSite> sited_obj; if (FAILED(p.QueryInterface(&sited_obj))) { return NPERR_GENERIC_ERROR; } if (FAILED(sited_obj->SetSite(pb))) { return NPERR_GENERIC_ERROR; } scriptable_object_ = DispatchHost::CreateInstance(instance_, p); } if (scriptable_object_) { NPN_RetainObject(scriptable_object_); } else { return NPERR_OUT_OF_MEMORY_ERROR; } *(reinterpret_cast<NPObject**>(value)) = scriptable_object_; return NPERR_NO_ERROR; } bool NPUpdate::MapMimeTypeToClsid(CLSID* clsid) { ASSERT1(clsid); // TODO(omaha): We could probably abstract this out to a map that can // have entries added to it at runtime, making this module fully generic. // We could also consider extracting the MIME_TYPE resource from the current // DLL and populating it from that. if (0 == mime_type_.CompareNoCase(CString(UPDATE3WEB_MIME_TYPE))) { *clsid = __uuidof(GoogleUpdate3WebControlCoClass); return true; } if (0 == mime_type_.CompareNoCase(CString(ONECLICK_MIME_TYPE))) { *clsid = __uuidof(GoogleUpdateOneClickControlCoClass); return true; } return false; } bool NPUpdate::GetCurrentBrowserUrl(CString* url) { ASSERT1(url); NPObject* window = NULL; NPError error = NPN_GetValue(instance_, NPNVWindowNPObject, &window); if (NPERR_NO_ERROR != error || !window) { ASSERT(false, (L"NPN_GetValue returned error %d", error)); return false; } ON_SCOPE_EXIT(NPN_ReleaseObject, window); NPIdentifier location_id = NPN_GetStringIdentifier("location"); NPVariant location; NULL_TO_NPVARIANT(location); if (!NPN_GetProperty(instance_, window, location_id, &location)) { ASSERT1(false); return false; } ON_SCOPE_EXIT(NPN_ReleaseVariantValue, &location); if (!NPVARIANT_IS_OBJECT(location)) { ASSERT(false, (L"Variant type: %d", location.type)); return false; } NPIdentifier href_id = NPN_GetStringIdentifier("href"); NPVariant href; NULL_TO_NPVARIANT(href); if (!NPN_GetProperty(instance_, NPVARIANT_TO_OBJECT(location), href_id, &href)) { ASSERT1(false); return false; } ON_SCOPE_EXIT(NPN_ReleaseVariantValue, &href); if (!NPVARIANT_IS_STRING(href)) { ASSERT(false, (L"Variant type: %d", href.type)); return false; } *url = Utf8ToWideChar(NPVARIANT_TO_STRING(href).UTF8Characters, NPVARIANT_TO_STRING(href).UTF8Length); return true; } } // namespace omaha
28.195767
78
0.705198
[ "object" ]
948d787c18a1fc9d8aeca8d8aaa172d834714661
5,246
cpp
C++
src/CodeGenerator.cpp
gauravahya/program-homework-solver
3f937e63d25f98990b9ceb5a0eb3b7d816d7e129
[ "MIT" ]
7
2019-04-01T05:45:48.000Z
2021-07-31T19:46:18.000Z
src/CodeGenerator.cpp
gauravahya/program-homework-solver
3f937e63d25f98990b9ceb5a0eb3b7d816d7e129
[ "MIT" ]
3
2018-09-30T17:11:30.000Z
2018-10-01T17:35:45.000Z
src/CodeGenerator.cpp
gauravahya/program-homework-solver
3f937e63d25f98990b9ceb5a0eb3b7d816d7e129
[ "MIT" ]
2
2018-11-26T19:52:56.000Z
2020-10-02T06:19:02.000Z
// // Created by junaidrahim on 19/9/18. // #include "../include/CodeGenerator.h" /* -> It takes the vector<element> as a constructor input and generates a string compatible with all the programming languages. -> vector<element> looks like { {4, {"x-3","x-4","x-5"} ,3}, {13, {"x-4","x-2","x-7"}, 4}, {3, {"x-6","x-1","x-9"}, 7} } -> The get_polynomial_string() converts that into something like: ((4*(x-3)*(x-4)*(x-5))/3)+((13*(x-4)*(x-2)*(x-7))/4)+((3*(x-6)*(x-1)*(x-9))/7) -> And then use the boilerplate code and that function to generate the source code in c cpp python js go java */ CodeGenerator::CodeGenerator(vector<LagrangePolynomial::element> p) { CodeGenerator::lagrange_polynomial = p; CodeGenerator::func = get_polynomial_string(); } string CodeGenerator::get_polynomial_string() { // 1 x-2 x-3 2 // 4 x-1 x-3 -1 => int f(int x) = ((1*(x-2)*(x-3))/2) + ((4*(x-1)*(x-3))/-1) + ((9*(x-1)*(x-2))/2) // 9 x-1 x-2 2 this can be used in each language's source string result; int lagrange_polynomial_size = CodeGenerator::lagrange_polynomial.size(); for(int i=0; i<lagrange_polynomial_size; i++){ string polynomial; //*(x-2)*(x-3) for(int j=0; j<lagrange_polynomial[i].p.size(); j++){ polynomial += "*(" + lagrange_polynomial[i].p[j] +")"; } string m = to_string(lagrange_polynomial[i].multiple); string d = to_string(lagrange_polynomial[i].denominator); // result will be something like ((1*(x-2)*(x-3))/2) => (m=1),(d=2) result += "((" + m + polynomial + ")/" + d + ")"; if(i!=lagrange_polynomial_size-1){ result += "+"; } } return result; } CodeGenerator::code_arr CodeGenerator::generate_all_lang_code() { code_arr result; result.languages = {"c","cpp","py","go","js","java"}; // keeping these the same as the extensions result.code.push_back(generate_c_code()); result.code.push_back(generate_cpp_code()); result.code.push_back(generate_python_code()); result.code.push_back(generate_go_code()); result.code.push_back(generate_js_code()); result.code.push_back(generate_java_code()); return result; } string CodeGenerator::generate_c_code() { string code = "// Generated by program-homework-solver\n\n" "#include <stdio.h>" "\n\n" "int f(int x){\n" "\tint answer = " + CodeGenerator::func + ";\n" "\treturn answer;\n" "}\n\n" "void main(){" "\n\n" "\tfor(int i=0; i<20; i++){\n" "\t\tprintf(\"%d \",f(i));\n" "\t}\n" "}"; return code; } string CodeGenerator::generate_cpp_code() { string code = "// Generated by program homework solver" "\n\n" "#include <iostream>\n\n" "using namespace std;\n\n" "int64_t f(int x) {\n" "\tint64_t answer =" + CodeGenerator::func + ";\n" "\treturn answer;\n" "}\n\n" "int main(){\n" "\tfor(int i=0; i<20; i++){\n" "\t\tcout << f(i) << endl;\n" "\t}\n" "\treturn 0;\n" "}"; return code; } string CodeGenerator::generate_python_code() { string code = "# Generated by program-homework-solver \n\n" "def f(x):\n" "\tanswer = " + CodeGenerator::func + "\n" "\treturn answer\n" "\nfor i in range(0,20):\n" "\tprint(f(i))\n"; return code; } string CodeGenerator::generate_go_code() { string code = "// Generated by program-homework-solvern\n\n" "package main" "\n\n" "import(\"fmt\")\n" "\nfunc f(x int64) int64 {\n" "\tanswer := " + CodeGenerator::func +"\n" "\treturn answer;\n" "}\n\n" "func main(){\n" "\n\tvar i int64;" "\n\tfor i=0; i<20; i++ {\n" "\t\tfmt.Println(f(i))\n" "\t}\n" "\n}"; return code; } string CodeGenerator::generate_js_code() { string code = "// Generated by program-homework-solver \n\n" "function f(x){\n" "\tlet answer = "+CodeGenerator::func+"\n" "\treturn answer\n" "}\n\n" "for(i=0; i<20; i++){\n" "\tconsole.log(f(i))\n" "}"; return code; } string CodeGenerator::generate_java_code() { string code = "// Generated by program-homework-solver \n\n" "class test{\n\n" "\tpublic int f(int x){\n" "\t\tint answer = " + CodeGenerator::func +";\n" "\t\treturn answer;\n" "}\n\n" "\tpublic static void main(String args[]){\n" "\t\ttest t = new test();\n" "\t\tfor(int i=0; i<20; i++){\n" "\t\t\tSystem.out.println(t.f(i));\n" "\t\t}\n" "\n\t}" "\n}"; return code; }
28.053476
107
0.494853
[ "vector" ]
94922feebdf1b9497640dca067876f5988664924
13,428
cxx
C++
MUON/MUONmapping/AliMpFastSegmentation.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
52
2016-12-11T13:04:01.000Z
2022-03-11T11:49:35.000Z
MUON/MUONmapping/AliMpFastSegmentation.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
1,388
2016-11-01T10:27:36.000Z
2022-03-30T15:26:09.000Z
MUON/MUONmapping/AliMpFastSegmentation.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
275
2016-06-21T20:24:05.000Z
2022-03-31T13:06:19.000Z
/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ // $Id$ /// \class AliMpFastSegmentation /// An implementation of AliMpVSegmentation, which uses /// some internal maps to speed up the (Has)PadByIndices and PadByLocation /// methods. /// /// L. Aphecetche, Subatech /// #include "AliMpFastSegmentation.h" #include "AliCodeTimer.h" #include "AliLog.h" #include "AliMpConnection.h" #include "AliMpConstants.h" #include "AliMpMotifMap.h" #include "AliMpMotifPosition.h" #include "AliMpMotifType.h" #include "AliMpPad.h" #include "AliMpSector.h" #include "AliMpSlat.h" #include "AliMpVPadIterator.h" #include "AliMpEncodePair.h" #include <TArrayI.h> /// \cond CLASSIMP ClassImp(AliMpFastSegmentation) /// \endcond //#define CHECK #ifdef CHECK #include <cassert> #endif namespace { /// /// The values in Encode and Encode2 are not exactly random. /// They are the result of a few "try and see" efforts to optimize the /// timing of the TExMap::GetValue (you should note that the TExMap implementation /// speed depends on the "non-uniformity" of the keys). /// /// So don't change those values w/o at least testing a bit the implications... /// But feel free to experiment though, in order to optimizer further ;-) /// Int_t Encode(Int_t a, Int_t b) { return a*1009 + b; } Int_t Encode2(Int_t a) { /// Ideally this method should be different for sectors and slats, as we have /// much less manus per DE for slats, and hence the "non-uniformity" is less... return ( a ^ (1<<10) ) << 16 ; } } //_____________________________________________________________________________ AliMpFastSegmentation::AliMpFastSegmentation(AliMpVSegmentation* vseg) : AliMpVSegmentation(), fHelper(vseg), fMotifPositions(), fIxIy(), fManuId(), fPositionX(0.), fPositionY(0.) { /// Ctor. We adopt vseg. if (!vseg) { AliError("Will get a hard time working with a NULL vseg !"); return; } AliCodeTimerAuto(vseg->ClassName(),0); fPositionX = vseg->GetPositionX(); fPositionY = vseg->GetPositionY(); TArrayI manus; vseg->GetAllElectronicCardIDs(manus); for ( Int_t i = 0; i < manus.GetSize(); ++i ) { Int_t manuId = manus[i]; AliMpMotifPosition* mp = vseg->MotifPosition(manuId); // Should never happen if ( ! mp ) { AliFatal("AliMpMotifPosition not found."); } Int_t index = 1 + fMotifPositions.GetLast(); fMotifPositions.AddLast(mp); fManuId.Add(Encode2(manuId),1+index); for ( Int_t manuChannel = 0; manuChannel < AliMpConstants::ManuNofChannels(); ++manuChannel ) { if ( vseg->HasPadByLocation(manuId,manuChannel) ) { AliMpPad pad = vseg->PadByLocation(manuId,manuChannel); fIxIy.Add(Encode(pad.GetIx(),pad.GetIy()),1+index); } } } } //_____________________________________________________________________________ AliMpFastSegmentation::~AliMpFastSegmentation() { /// dtor delete fHelper; } //_____________________________________________________________________________ AliMpVPadIterator* AliMpFastSegmentation::CreateIterator(const AliMpArea& area) const { /// Forward to our helper return fHelper->CreateIterator(area); } //_____________________________________________________________________________ AliMpVPadIterator* AliMpFastSegmentation::CreateIterator() const { /// Forward to our helper return fHelper->CreateIterator(); } //_____________________________________________________________________________ Int_t AliMpFastSegmentation::GetNeighbours(const AliMpPad& pad, TObjArray& neighbours, Bool_t includeSelf, Bool_t includeVoid) const { /// Use default implementation return AliMpVSegmentation::GetNeighbours(pad,neighbours,includeSelf,includeVoid); } //_____________________________________________________________________________ AliMpPad AliMpFastSegmentation::PadByLocation(Int_t manuId, Int_t manuChannel, Bool_t warning) const { /// Get the pad by location, using the manuid map. Int_t index = fManuId.GetValue(Encode2(manuId)); if (!index) { if (warning) { AliWarning(Form("Manu ID %d not found",manuId)); Print(); } return AliMpPad::Invalid(); } AliMpMotifPosition* motifPos = InternalMotifPosition(index); if (!motifPos) { AliError(Form("InternalMotifPosition(%d) failed",index)); Print(); return AliMpPad::Invalid(); } AliMpVMotif* motif = motifPos->GetMotif(); MpPair_t localIndices = motif->GetMotifType()->FindLocalIndicesByGassiNum(manuChannel); if ( localIndices < 0 ) { if (warning) { AliWarning(Form("The pad number %d doesn't exists", manuChannel)); Print(); } return AliMpPad::Invalid(); } #ifdef CHECK Double_t posx, posy; motif->PadPositionLocal(localIndices, posx, posy); posx += motifPos->GetPositionX() - fPositionX; posy += motifPos->GetPositionY() - fPositionY; Double_t dx, dy; motif->GetPadDimensionsByIndices(localIndices, dx, dy); AliMpPad pad1 = AliMpPad(manuId, manuChannel, motifPos->GlobalIndices(localIndices), posx, posy, dx, dy); AliMpPad pad2 = fHelper->PadByLocation(manuId, manuChannel,warning); if ( pad1 != pad2 ) { Print(); pad1.Print(); pad2.Print(); assert(pad1==pad2); } #endif Double_t posx, posy; motif->PadPositionLocal(localIndices, posx, posy); posx += motifPos->GetPositionX() - fPositionX; posy += motifPos->GetPositionY() - fPositionY; Double_t dx, dy; motif->GetPadDimensionsByIndices(localIndices, dx, dy); return AliMpPad(manuId, manuChannel, motifPos->GlobalIndices(localIndices), posx, posy, dx, dy); } //_____________________________________________________________________________ AliMpMotifPosition* AliMpFastSegmentation::InternalMotifPosition(Int_t index) const { /// Get the internal manu from the index return static_cast<AliMpMotifPosition*>(fMotifPositions.UncheckedAt(index-1)); } //_____________________________________________________________________________ AliMpPad AliMpFastSegmentation::PadByIndices (Int_t ix, Int_t iy, Bool_t warning) const { /// Get pad by indices Int_t index = fIxIy.GetValue(Encode(ix, iy)); if ( !index ) { if (warning) { AliWarning(Form("ManuID not found for pad indices (%d,%d)", ix, iy)); Print(); } return AliMpPad::Invalid(); } AliMpMotifPosition* motifPos = InternalMotifPosition(index); if (!motifPos) { AliError(Form("InternalMotifPosition(%d) failed",index)); Print(); return AliMpPad::Invalid(); } AliMpVMotif* motif = motifPos->GetMotif(); AliMpMotifType* motifType = motif->GetMotifType(); MpPair_t localIndices(AliMp::Pair(ix, iy) - motifPos->GetLowIndicesLimit()); AliMpConnection* connection = motifType->FindConnectionByLocalIndices(localIndices); if (!connection) { if ( warning ) { AliWarning(Form("No connection for pad indices (%d,%d)", ix, iy)); } return AliMpPad::Invalid(); } #ifdef CHECK AliMpPad pad2 = fHelper->PadByIndices(ix, iy, warning); Double_t posx, posy; motif->PadPositionLocal(localIndices, posx, posy); posx += motifPos->GetPositionX() - fPositionX; posy += motifPos->GetPositionY() - fPositionY; Double_t dx, dy; motif->GetPadDimensionsByIndices(localIndices, dx, dy); AliMpPad pad1 = AliMpPad(motifPos->GetID(),connection->GetManuChannel(), ix, iy, posx, posy, dx, dy); assert(pad1==pad2); #endif Double_t posx, posy; motif->PadPositionLocal(localIndices, posx, posy); posx += motifPos->GetPositionX() - fPositionX; posy += motifPos->GetPositionY() - fPositionY; Double_t dx, dy; motif->GetPadDimensionsByIndices(localIndices, dx, dy); return AliMpPad(motifPos->GetID(),connection->GetManuChannel(), ix, iy, posx, posy, dx, dy); } //_____________________________________________________________________________ AliMpPad AliMpFastSegmentation::PadByPosition(Double_t x, Double_t y, Bool_t warning ) const { /// Forward to our helper return fHelper->PadByPosition(x, y, warning); } //_____________________________________________________________________________ Int_t AliMpFastSegmentation::MaxPadIndexX() const { /// Forward to our helper return fHelper->MaxPadIndexX(); } //_____________________________________________________________________________ Int_t AliMpFastSegmentation::MaxPadIndexY() const { /// Forward to our helper return fHelper->MaxPadIndexY(); } //_____________________________________________________________________________ Int_t AliMpFastSegmentation::NofPads() const { /// Forward to our helper return fHelper->NofPads(); } //_____________________________________________________________________________ Int_t AliMpFastSegmentation::GetNofElectronicCards() const { /// Forward to our helper return fHelper->GetNofElectronicCards(); } //_____________________________________________________________________________ void AliMpFastSegmentation::GetAllElectronicCardIDs(TArrayI& ecn) const { /// Forward to our helper fHelper->GetAllElectronicCardIDs(ecn); } //_____________________________________________________________________________ Bool_t AliMpFastSegmentation::HasPadByIndices(Int_t ix, Int_t iy) const { /// Whether there is a pad at the given indices Int_t index = fIxIy.GetValue(Encode(ix, iy)); if ( !index ) return kFALSE; AliMpMotifPosition* mp = InternalMotifPosition(index); Bool_t r1 = mp->HasPadByIndices(AliMp::Pair(ix, iy)); #ifdef CHECK Bool_t r2 = fHelper->HasPadByIndices(ix, iy); assert(r1==r2); #endif return r1; } //_____________________________________________________________________________ Bool_t AliMpFastSegmentation::HasPadByLocation(Int_t manuId, Int_t manuChannel) const { /// Whether there is a pad at the given location (de,manuid) Int_t index = fManuId.GetValue(Encode2(manuId)); if (!index) return kFALSE; AliMpMotifPosition* mp = InternalMotifPosition(index); Bool_t r1 = mp->HasPadByManuChannel(manuChannel); #ifdef CHECK Bool_t r2 = fHelper->HasPadByLocation(manuId, manuChannel); assert(r1==r2); #endif return r1; } //_____________________________________________________________________________ void AliMpFastSegmentation::Print(Option_t* opt) const { /// Forward to our helper fHelper->Print(opt); } //_____________________________________________________________________________ AliMp::PlaneType AliMpFastSegmentation::PlaneType() const { /// Forward to our helper return fHelper->PlaneType(); } //_____________________________________________________________________________ Double_t AliMpFastSegmentation::GetDimensionX() const { /// Forward to our helper return fHelper->GetDimensionX(); } //_____________________________________________________________________________ Double_t AliMpFastSegmentation::GetDimensionY() const { /// Forward to our helper return fHelper->GetDimensionY(); } //_____________________________________________________________________________ Double_t AliMpFastSegmentation::GetPositionX() const { /// Forward to our helper return fHelper->GetPositionX(); } //_____________________________________________________________________________ Double_t AliMpFastSegmentation::GetPositionY() const { /// Forward to our helper return fHelper->GetPositionY(); } //_____________________________________________________________________________ Bool_t AliMpFastSegmentation::HasMotifPosition(Int_t manuId) const { /// Whether or not we have a given manu return ( fManuId.GetValue(Encode2(manuId)) != 0); } //_____________________________________________________________________________ AliMpMotifPosition* AliMpFastSegmentation::MotifPosition(Int_t manuId) const { /// Get the motifPosition object of a given manu Int_t index = fManuId.GetValue(Encode2(manuId)); if (!index) { AliMpVPadIterator* it = CreateIterator(); it->First(); AliMpPad pad = it->CurrentItem(); delete it; AliWarning(Form("DE %04d Manu ID %04d not found",pad.GetManuId(),manuId)); return 0x0; } return InternalMotifPosition(index); }
27.62963
97
0.704498
[ "object" ]
9492587ea0260f80293e7af6e8f583b39b5705db
7,382
hpp
C++
openbmc/build/tmp/deploy/sdk/witherspoon-2019-08-08/sysroots/armv6-openbmc-linux-gnueabi/usr/include/xyz/openbmc_project/Certs/CSR/Create/server.hpp
sotaoverride/backup
ca53a10b72295387ef4948a9289cb78ab70bc449
[ "Apache-2.0" ]
null
null
null
openbmc/build/tmp/deploy/sdk/witherspoon-2019-08-08/sysroots/armv6-openbmc-linux-gnueabi/usr/include/xyz/openbmc_project/Certs/CSR/Create/server.hpp
sotaoverride/backup
ca53a10b72295387ef4948a9289cb78ab70bc449
[ "Apache-2.0" ]
null
null
null
openbmc/build/tmp/deploy/sdk/witherspoon-2019-08-08/sysroots/armv6-openbmc-linux-gnueabi/usr/include/xyz/openbmc_project/Certs/CSR/Create/server.hpp
sotaoverride/backup
ca53a10b72295387ef4948a9289cb78ab70bc449
[ "Apache-2.0" ]
null
null
null
#pragma once #include <map> #include <string> #include <sdbusplus/sdbus.hpp> #include <sdbusplus/server.hpp> #include <systemd/sd-bus.h> #include <tuple> #include <variant> namespace sdbusplus { namespace xyz { namespace openbmc_project { namespace Certs { namespace CSR { namespace server { class Create { public: /* Define all of the basic class operations: * Not allowed: * - Default constructor to avoid nullptrs. * - Copy operations due to internal unique_ptr. * - Move operations due to 'this' being registered as the * 'context' with sdbus. * Allowed: * - Destructor. */ Create() = delete; Create(const Create&) = delete; Create& operator=(const Create&) = delete; Create(Create&&) = delete; Create& operator=(Create&&) = delete; virtual ~Create() = default; /** @brief Constructor to put object onto bus at a dbus path. * @param[in] bus - Bus to attach to. * @param[in] path - Path to attach at. */ Create(bus::bus& bus, const char* path); /** @brief Implementation for GenerateCSR * This command is used to initiate a certificate signing request. This command only returns the D-Bus path name for the new CSR object. User need to listen on InterfacesAdded signal emitted by /xyz/openbmc_project/Certs to retrieve the CSR string after successful CSR creation. Note: Following Parameters are mandatory or optional based on the Redfish documentation. Caller is responsible for the input parameter validation. If the caller does not wish a field to be included in the CSR Request, initialize the Parameter with blank for strings and zero for integers. * * @param[in] alternativeNames - Additional hostnames of the component that is being secured. * @param[in] challengePassword - The challenge password to be applied to the certificate for revocation requests. * @param[in] city - The city or locality of the organization making the request. For Example Austin This is a required parameter. * @param[in] commonName - The fully qualified domain name of the component that is being secured. This is a required parameter. * @param[in] contactPerson - The name of the user making the request. * @param[in] country - The country of the organization making the request. This is a required parameter. * @param[in] email - The email address of the contact within the organization making the request. * @param[in] givenName - The given name of the user making the request. * @param[in] initials - The initials of the user making the request. * @param[in] keyBitLength - The length of the key in bits, if needed based on the value of the KeyPairAlgorithm parameter. Refer https://www.openssl.org/docs/man1.0.2/man1/genpkey.html * @param[in] keyCurveId - The curve ID to be used with the key, if needed based on the value of the KeyPairAlgorithm parameter. Refer https://www.openssl.org/docs/man1.0.2/man1/genpkey.html * @param[in] keyPairAlgorithm - The type of key pair for use with signing algorithms. Valid built-in algorithm names for private key generation are RSA and EC. * @param[in] keyUsage - Key usage extensions define the purpose of the public key contained in a certificate. Valid Key usage extensions and its usage description. ClientAuthentication: The public key is used for TLS WWW client authentication. CodeSigning: The public key is used for the signing of executable code. CRLSigning: The public key is used for verifying signatures on certificate revocation lists (CLRs). DataEncipherment: The public key is used for directly enciphering raw user data without the use of an intermediate symmetric cipher. DecipherOnly: The public key could be used for deciphering data while performing key agreement. DigitalSignature: The public key is used for verifying digital signatures, other than signatures on certificates and CRLs. EmailProtection: The public key is used for email protection. EncipherOnly: The public key could be used for enciphering data while performing key agreement. KeyCertSign: The public key is used for verifying signatures on public key certificates. KeyEncipherment: The public key is used for enciphering private or secret keys. NonRepudiation: The public key is used to verify digital signatures, other than signatures on certificates and CRLs, and used to provide a non- repudiation service that protects against the signing entity falsely denying some action. OCSPSigning: The public key is used for signing OCSP responses. ServerAuthentication: The public key is used for TLS WWW server authentication. Timestamping: The public key is used for binding the hash of an object to a time. * @param[in] organization - The legal name of the organization. This should not be abbreviated and should include suffixes such as Inc, Corp, or LLC. For example, IBM Corp. This is a required parameter. * @param[in] organizationalUnit - The name of the unit or division of the organization making the request. This is a required parameter. * @param[in] state - The state or province where the organization is located. This should not be abbreviated. For example, Texas. This is a required parameter. * @param[in] surname - The surname of the user making the request. * @param[in] unstructuredName - The unstructured name of the subject. * * @return path[std::string] - The object path of the D-Bus object to be watch for retrieving the CSR string. */ virtual std::string generateCSR( std::vector<std::string> alternativeNames, std::string challengePassword, std::string city, std::string commonName, std::string contactPerson, std::string country, std::string email, std::string givenName, std::string initials, int64_t keyBitLength, std::string keyCurveId, std::string keyPairAlgorithm, std::vector<std::string> keyUsage, std::string organization, std::string organizationalUnit, std::string state, std::string surname, std::string unstructuredName) = 0; private: /** @brief sd-bus callback for GenerateCSR */ static int _callback_GenerateCSR( sd_bus_message*, void*, sd_bus_error*); static constexpr auto _interface = "xyz.openbmc_project.Certs.CSR.Create"; static const vtable::vtable_t _vtable[]; sdbusplus::server::interface::interface _xyz_openbmc_project_Certs_CSR_Create_interface; sdbusplus::SdBusInterface *_intf; }; } // namespace server } // namespace CSR } // namespace Certs } // namespace openbmc_project } // namespace xyz } // namespace sdbusplus
45.567901
287
0.666622
[ "object", "vector" ]
949603cdfbf7c2be44e627c271a9bff694fd236f
7,396
cpp
C++
barelymusician/engine/instrument.cpp
anokta/barelymusician
5e3485c80cc74c4bcbc0653c0eb8750ad44981d6
[ "MIT" ]
6
2021-11-25T17:40:21.000Z
2022-03-24T03:38:11.000Z
barelymusician/engine/instrument.cpp
anokta/barelymusician
5e3485c80cc74c4bcbc0653c0eb8750ad44981d6
[ "MIT" ]
17
2021-11-27T00:10:39.000Z
2022-03-30T00:33:51.000Z
barelymusician/engine/instrument.cpp
anokta/barelymusician
5e3485c80cc74c4bcbc0653c0eb8750ad44981d6
[ "MIT" ]
null
null
null
#include "barelymusician/engine/instrument.h" #include <cassert> #include <utility> #include <variant> #include "barelymusician/engine/event.h" namespace barelyapi { // NOLINTNEXTLINE(bugprone-exception-escape) Instrument::Instrument(const Definition& definition, int frame_rate) noexcept : destroy_callback_(definition.destroy_callback), process_callback_(definition.process_callback), set_data_callback_(definition.set_data_callback), set_note_off_callback_(definition.set_note_off_callback), set_note_on_callback_(definition.set_note_on_callback), set_parameter_callback_(definition.set_parameter_callback), frame_rate_(frame_rate) { assert(frame_rate >= 0); parameters_.reserve(definition.num_parameter_definitions); for (int index = 0; index < definition.num_parameter_definitions; ++index) { parameters_.emplace_back(definition.parameter_definitions[index]); } if (definition.create_callback) { definition.create_callback(&state_, frame_rate); } if (set_parameter_callback_) { for (int index = 0; index < definition.num_parameter_definitions; ++index) { set_parameter_callback_(&state_, index, parameters_[index].GetValue(), 0.0); } } } Instrument::~Instrument() noexcept { if (destroy_callback_) { destroy_callback_(&state_); } } const Parameter* Instrument::GetParameter(int index) const noexcept { assert(index >= 0); if (index < static_cast<int>(parameters_.size())) { return &parameters_[index]; } return nullptr; } bool Instrument::IsNoteOn(double pitch) const noexcept { return pitches_.contains(pitch); } // NOLINTNEXTLINE(bugprone-exception-escape) void Instrument::Process(double* output, int num_output_channels, int num_output_frames, double timestamp) noexcept { assert(output || num_output_channels == 0 || num_output_frames == 0); assert(num_output_channels >= 0); assert(num_output_frames >= 0); int frame = 0; // Process *all* events before the end timestamp. const double end_timestamp = timestamp + GetSeconds(num_output_frames); for (auto* event = event_queue_.GetNext(end_timestamp); event; event = event_queue_.GetNext(end_timestamp)) { const int message_frame = GetFrames(event->first - timestamp); if (frame < message_frame) { if (process_callback_) { process_callback_(&state_, &output[num_output_channels * frame], num_output_channels, message_frame - frame); } frame = message_frame; } std::visit( EventVisitor{[this](SetDataEvent& set_data_event) noexcept { if (set_data_callback_) { data_.swap(set_data_event.data); set_data_callback_(&state_, data_.data(), static_cast<int>(data_.size())); } }, [this](SetNoteOffEvent& set_note_off_event) noexcept { if (set_note_off_callback_) { set_note_off_callback_(&state_, set_note_off_event.pitch); } }, [this](SetNoteOnEvent& set_note_on_event) noexcept { if (set_note_on_callback_) { set_note_on_callback_(&state_, set_note_on_event.pitch, set_note_on_event.intensity); } }, [this](SetParameterEvent& set_parameter_event) noexcept { if (set_parameter_callback_) { set_parameter_callback_( &state_, set_parameter_event.index, set_parameter_event.value, GetSlopePerFrame(set_parameter_event.slope)); } }}, event->second); } // Process the rest of the buffer. if (frame < num_output_frames && process_callback_) { process_callback_(&state_, &output[num_output_channels * frame], num_output_channels, num_output_frames - frame); } } void Instrument::ResetAllParameters(double timestamp) noexcept { assert(timestamp >= 0.0); for (int index = 0; index < static_cast<int>(parameters_.size()); ++index) { if (parameters_[index].ResetValue()) { event_queue_.Add( timestamp, SetParameterEvent{index, parameters_[index].GetValue(), 0.0}); } } } bool Instrument::ResetParameter(int index, double timestamp) noexcept { assert(index >= 0); assert(timestamp >= 0.0); if (index < static_cast<int>(parameters_.size())) { if (parameters_[index].ResetValue()) { event_queue_.Add( timestamp, SetParameterEvent{index, parameters_[index].GetValue(), 0.0}); } return true; } return false; } void Instrument::SetData(std::vector<std::byte> data, double timestamp) noexcept { assert(timestamp >= 0.0); event_queue_.Add(timestamp, SetDataEvent{std::move(data)}); } void Instrument::SetNoteOffCallback(NoteOffCallback callback) noexcept { note_off_callback_ = std::move(callback); } void Instrument::SetNoteOnCallback(NoteOnCallback callback) noexcept { note_on_callback_ = std::move(callback); } bool Instrument::SetParameter(int index, double value, double slope, double timestamp) noexcept { assert(index >= 0); assert(timestamp >= 0.0); if (index < static_cast<int>(parameters_.size())) { if (parameters_[index].SetValue(value)) { event_queue_.Add( timestamp, SetParameterEvent{index, parameters_[index].GetValue(), slope}); } return true; } return false; } // NOLINTNEXTLINE(bugprone-exception-escape) void Instrument::StartNote(double pitch, double intensity, double timestamp) noexcept { assert(timestamp >= 0.0); if (pitches_.insert(pitch).second) { if (note_on_callback_) { note_on_callback_(pitch, intensity, timestamp); } event_queue_.Add(timestamp, SetNoteOnEvent{pitch, intensity}); } } void Instrument::StopAllNotes(double timestamp) noexcept { assert(timestamp >= 0.0); for (const double pitch : std::exchange(pitches_, {})) { if (note_off_callback_) { note_off_callback_(pitch, timestamp); } event_queue_.Add(timestamp, SetNoteOffEvent{pitch}); } } void Instrument::StopNote(double pitch, double timestamp) noexcept { assert(timestamp >= 0.0); if (pitches_.erase(pitch) > 0) { if (note_off_callback_) { note_off_callback_(pitch, timestamp); } event_queue_.Add(timestamp, SetNoteOffEvent{pitch}); } } int Instrument::GetFrames(double seconds) const noexcept { return frame_rate_ > 0 ? static_cast<int>(seconds * static_cast<double>(frame_rate_)) : 0; } double Instrument::GetSeconds(int frames) const noexcept { return frame_rate_ > 0 ? static_cast<double>(frames) / static_cast<double>(frame_rate_) : 0.0; } double Instrument::GetSlopePerFrame(double slope) const noexcept { return frame_rate_ > 0 ? slope / static_cast<double>(frame_rate_) : 0.0; } } // namespace barelyapi
34.723005
80
0.635749
[ "vector" ]
9497295365cb2da9a805d009ad73e937e52e66dd
3,897
hpp
C++
include/owlcpp/rdf/map_triple_crtpb.hpp
GreyMerlin/owl_cpp
ccc6128dbd08dcf7fcbe6679ec6acd714732bbb6
[ "BSL-1.0" ]
10
2017-12-21T05:20:40.000Z
2021-09-18T05:14:01.000Z
include/owlcpp/rdf/map_triple_crtpb.hpp
GreyMerlin/owl_cpp
ccc6128dbd08dcf7fcbe6679ec6acd714732bbb6
[ "BSL-1.0" ]
2
2017-12-21T07:31:54.000Z
2021-06-23T08:52:35.000Z
include/owlcpp/rdf/map_triple_crtpb.hpp
GreyMerlin/owl_cpp
ccc6128dbd08dcf7fcbe6679ec6acd714732bbb6
[ "BSL-1.0" ]
7
2016-02-17T13:20:31.000Z
2021-11-08T09:30:43.000Z
/** @file "/owlcpp/include/owlcpp/rdf/map_triple_crtpb.hpp" part of owlcpp project. @n @n Distributed under the Boost Software License, Version 1.0; see doc/license.txt. @n Copyright Mikhail K Levin 2012 *******************************************************************************/ #ifndef MAP_TRIPLE_CRTPB_HPP_ #define MAP_TRIPLE_CRTPB_HPP_ #include "boost/assert.hpp" #include "boost/concept/assert.hpp" #include "owlcpp/detail/map_traits.hpp" #include "owlcpp/rdf/triple.hpp" namespace owlcpp{ /**Enable operations on RDF triples. Base for CRTP (Curiously Recurring Template Pattern). *******************************************************************************/ template<class Super> class Map_triple_crtpb { typedef detail::Map_traits<Super> traits; typedef typename traits::map_triple_type map_triple_type; map_triple_type const& _map_triple() const { return static_cast<Super const&>(*this).map_triple_; } map_triple_type& _map_triple() { return static_cast<Super&>(*this).map_triple_; } public: template<class Subj, class Pred, class Obj, class Doc> struct query : public map_triple_type::template query<Subj,Pred,Obj,Doc>{}; template<bool Subj, bool Pred, bool Obj, bool Doc>struct query_b : public map_triple_type::template query_b<Subj,Pred,Obj,Doc>{}; /**@brief Search triples by subject, predicate, object, or document IDs. @details Polymorphically search stored triples to find ones that match specified node IDs for subject, predicate, or object nodes or document ID. An instance of \b any matches all values for the corresponding triple element. If none of the nodes are specified, i.e., <tt>find(any, any, any, any)</tt>, the search returns a range of all stored triples, [begin(), end()). @param subj predicate for first element of triple (subject node), e.g., \b Node_id, \b any @param pred predicate for second element of triple (predicate node), e.g., \b Node_id, \b any @param obj predicate for third element of triple (object node), e.g., \b Node_id, \b any @param doc predicate for fourth element of triple (document ID), e.g., \b Doc_id, \b any @return iterator range of triples matching the query. @details The type of the range can be obtained from @code template<class Subj, class Pred, class Obj, class Doc> class query; @endcode or from @code template<bool Subj, bool Pred, bool Obj, bool Doc> class query_b; @endcode For example, @code Triple_map<>::query_b<1,0,0,1>::range range = triple_map.find(subj, any, any, doc); @endcode */ template<class Subj, class Pred, class Obj, class Doc> typename query<Subj,Pred,Obj,Doc>::range find_triple(const Subj subj, const Pred pred, const Obj obj, const Doc doc) const { return _map_triple().find(subj, pred, obj, doc); } /**@brief Insert a new triple void insert( const Node_id subj, const Node_id pred, const Node_id obj, const Doc_id doc ) { insert(Triple::make(subj, pred, obj, doc)); } */ /**@brief Insert a new triple */ void insert(Triple const& t) { BOOST_CONCEPT_ASSERT((Node_store<Super>)); BOOST_ASSERT( static_cast<Super const&>(*this).find(t.subj_) && "invalid subject ID" ); BOOST_ASSERT( static_cast<Super const&>(*this).find(t.pred_) && "invalid predicate ID" ); BOOST_ASSERT( static_cast<Super const&>(*this).find(t.obj_) && "invalid object ID" ); BOOST_ASSERT( static_cast<Super const&>(*this).find(t.doc_) && "invalid document ID" ); _map_triple().insert(t); } void erase(Triple const& t) { _map_triple().erase(t); } }; }//namespace owlcpp #endif /* MAP_TRIPLE_CRTPB_HPP_ */
34.184211
86
0.639723
[ "object" ]
949bf632fd3f4545236c73397bf8436a6a614a88
9,078
hh
C++
RAVL2/Math/Geometry/Euclidean/3D/EulerAngle.hh
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
RAVL2/Math/Geometry/Euclidean/3D/EulerAngle.hh
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
RAVL2/Math/Geometry/Euclidean/3D/EulerAngle.hh
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
// This file is part of RAVL, Recognition And Vision Library // Copyright (C) 2002, University of Surrey // This code may be redistributed under the terms of the GNU Lesser // General Public License (LGPL). See the lgpl.licence file for details or // see http://www.gnu.org/copyleft/lesser.html // file-header-ends-here #ifndef RAVL_3D_EULER_ANGLE_HH #define RAVL_3D_EULER_ANGLE_HH 1 //! rcsid="$Id: EulerAngle.hh 5240 2005-12-06 17:16:50Z plugger $" //! lib=RavlMath //! date="7/12/2002" //! author="Joel Mitchelson" //! docentry="Ravl.API.Math.Geometry.3D" //! file="Ravl/Math/Geometry/Euclidean/3D/EulerAngle.hh" #include "Ravl/Vector3d.hh" #include "Ravl/Matrix3d.hh" namespace RavlN { //:-------------------------------------------------------- //! userlevel=Develop // C-style euler angle -> matrix conversions void EulerXYXToMatrix(const RealT* a, RealT* R); void EulerXYZToMatrix(const RealT* a, RealT* R); void EulerXZXToMatrix(const RealT* a, RealT* R); void EulerXZYToMatrix(const RealT* a, RealT* R); void EulerYXYToMatrix(const RealT* a, RealT* R); void EulerYXZToMatrix(const RealT* a, RealT* R); void EulerYZXToMatrix(const RealT* a, RealT* R); void EulerYZYToMatrix(const RealT* a, RealT* R); void EulerZXYToMatrix(const RealT* a, RealT* R); void EulerZXZToMatrix(const RealT* a, RealT* R); void EulerZYXToMatrix(const RealT* a, RealT* R); void EulerZYZToMatrix(const RealT* a, RealT* R); // C-style matrix -> euler angle conversions void MatrixToEulerXYX(const RealT* R, RealT* a, const RealT a0_default = 0.0); void MatrixToEulerXYZ(const RealT* R, RealT* a, const RealT a0_default = 0.0); void MatrixToEulerXZX(const RealT* R, RealT* a, const RealT a0_default = 0.0); void MatrixToEulerXZY(const RealT* R, RealT* a, const RealT a0_default = 0.0); void MatrixToEulerYXY(const RealT* R, RealT* a, const RealT a0_default = 0.0); void MatrixToEulerYXZ(const RealT* R, RealT* a, const RealT a0_default = 0.0); void MatrixToEulerYZX(const RealT* R, RealT* a, const RealT a0_default = 0.0); void MatrixToEulerYZY(const RealT* R, RealT* a, const RealT a0_default = 0.0); void MatrixToEulerZXY(const RealT* R, RealT* a, const RealT a0_default = 0.0); void MatrixToEulerZXZ(const RealT* R, RealT* a, const RealT a0_default = 0.0); void MatrixToEulerZYX(const RealT* R, RealT* a, const RealT a0_default = 0.0); void MatrixToEulerZYZ(const RealT* R, RealT* a, const RealT a0_default = 0.0); //:-------------------------------------------------------- //! userlevel=Advanced // Euler angle -> matrix conversions inline void EulerXYXToMatrix(const Vector3dC& a, Matrix3dC& R) { EulerXYXToMatrix(&a[0],&R[0][0]); } inline void EulerXYZToMatrix(const Vector3dC& a, Matrix3dC& R) { EulerXYZToMatrix(&a[0],&R[0][0]); } inline void EulerXZXToMatrix(const Vector3dC& a, Matrix3dC& R) { EulerXZXToMatrix(&a[0],&R[0][0]); } #if 0 void EulerXZYToMatrix(const Vector3dC& a, Matrix3dC& R) { EulerXZYToMatrix(&a[0],&R[0][0]); } void EulerYXYToMatrix(const Vector3dC& a, Matrix3dC& R) { EulerYXYToMatrix(&a[0],&R[0][0]); } void EulerYXZToMatrix(const Vector3dC& a, Matrix3dC& R) { EulerYXZToMatrix(&a[0],&R[0][0]); } void EulerYZXToMatrix(const Vector3dC& a, Matrix3dC& R) { EulerYZXToMatrix(&a[0],&R[0][0]); } void EulerYZYToMatrix(const Vector3dC& a, Matrix3dC& R) { EulerYZYToMatrix(&a[0],&R[0][0]); } void EulerZXYToMatrix(const Vector3dC& a, Matrix3dC& R) { EulerZXYToMatrix(&a[0],&R[0][0]); } void EulerZXZToMatrix(const Vector3dC& a, Matrix3dC& R) { EulerZXZToMatrix(&a[0],&R[0][0]); } void EulerZYXToMatrix(const Vector3dC& a, Matrix3dC& R) { EulerZYXToMatrix(&a[0],&R[0][0]); } void EulerZYZToMatrix(const Vector3dC& a, Matrix3dC& R) { EulerZYZToMatrix(&a[0],&R[0][0]); } #endif // Matrix -> euler angle conversions inline void MatrixToEulerXYX(const Matrix3dC& R, Vector3dC& a, const RealT a0_default = 0.0) { MatrixToEulerXYX(&R[0][0], &a[0], a0_default); } inline void MatrixToEulerXYZ(const Matrix3dC& R, Vector3dC& a, const RealT a0_default = 0.0) { MatrixToEulerXYZ(&R[0][0], &a[0], a0_default); } inline void MatrixToEulerXZX(const Matrix3dC& R, Vector3dC& a, const RealT a0_default = 0.0) { MatrixToEulerXZX(&R[0][0], &a[0], a0_default); } #if 0 void MatrixToEulerXZY(const Matrix3dC& R, Vector3dC& a, const RealT a0_default = 0.0) { MatrixToEulerXZY(&R[0][0], &a[0], a0_default);} void MatrixToEulerYXY(const Matrix3dC& R, Vector3dC& a, const RealT a0_default = 0.0) { MatrixToEulerYXY(&R[0][0], &a[0], a0_default); } void MatrixToEulerYXZ(const Matrix3dC& R, Vector3dC& a, const RealT a0_default = 0.0) { MatrixToEulerYXZ(&R[0][0], &a[0], a0_default); } void MatrixToEulerYZX(const Matrix3dC& R, Vector3dC& a, const RealT a0_default = 0.0) { MatrixToEulerYZX(&R[0][0], &a[0], a0_default); } void MatrixToEulerYZY(const Matrix3dC& R, Vector3dC& a, const RealT a0_default = 0.0) { MatrixToEulerYXY(&R[0][0], &a[0], a0_default); } void MatrixToEulerZXY(const Matrix3dC& R, Vector3dC& a, const RealT a0_default = 0.0) { MatrixToEulerZXY(&R[0][0], &a[0], a0_default); } void MatrixToEulerZXZ(const Matrix3dC& R, Vector3dC& a, const RealT a0_default = 0.0) { MatrixToEulerZXZ(&R[0][0], &a[0], a0_default); } void MatrixToEulerZYX(const Matrix3dC& R, Vector3dC& a, const RealT a0_default = 0.0) { MatrixToEulerZYX(&R[0][0], &a[0], a0_default); } void MatrixToEulerZYZ(const Matrix3dC& R, Vector3dC& a, const RealT a0_default = 0.0) { MatrixToEulerZYZ(&R[0][0], &a[0], a0_default); } #endif //:-------------------------------------------------------- //! userlevel=Normal // //: Euler angle sequence definition // // This class just holds an integer to specify the order of rotations // for a set of euler angles, // used by <a href="RavlN.EulerAngleC.html">EulerAngleC</a>. // //!classbugs: Doesn't yet support all sequences...will add more soon class EulerSequenceC { public: enum SequenceT { XYX, XYZ, XZX, NumSequences }; public: EulerSequenceC() { } //: Default constructor - construct invalid sequence. EulerSequenceC(int sequence) : s(sequence) { RavlAssert(s >= 0); RavlAssert(s < NumSequences); } //: Construct sequence from integer identifier EulerSequenceC(const char* str); //: Construct sequence from string, eg. "XYZ" public: operator int() const { return s; } protected: int s; }; //:-------------------------------------------------------- void EulerToMatrix(const Vector3dC& a, Matrix3dC& R, const EulerSequenceC sequence); //: Convert Euler angles to rotation matrix according to sequence // See <a href="RavlN.EulerAngleC.html">EulerAngleC</a> for a // description of the Euler angle representation. //!bug: Not all sequences yet supported. void MatrixToEuler(const Matrix3dC& R, Vector3dC& a, const EulerSequenceC sequence, const RealT a0_default = 0.0); //: Convert rotation matrix to Euler angles according to sequence // See <a href="RavlN.EulerAngleC.html">EulerAngleC</a> for a // description of the Euler angle representation. //!bug: Not all sequences yet supported. //:-------------------------------------------------------- //: Euler angle class // // Specifies a vector of 3 successive 3D rotations about // the 3 co-ordinate axes. // Such vectors are known as <i>Euler Angles</i>. // The sequence of axes about // which rotations are done is important, and must be specified // using an <a href="RavlN.EulerSequenceC.html">EulerSequenceC</a>. // //!classbugs: Not all euler sequences yet supported...will add more soon. class EulerAngleC : public Vector3dC { public: EulerAngleC() { } //: Default constructor (uninitialised angles and sequence). EulerAngleC(RealT a, RealT b, RealT c, EulerSequenceC sequence) : Vector3dC(a,b,c), s(sequence) { } //: Construct from angle parameters and sequence. EulerAngleC(const Vector3dC& a, EulerSequenceC sequence) : Vector3dC(a), s(sequence) { } //: Construct from angle vector and sequence. EulerAngleC(const Matrix3dC& R, EulerSequenceC sequence, RealT a0_default = 0.0) : s(sequence) { MatrixToEuler(R, *static_cast<Vector3dC*>(this), sequence, a0_default); } //: Construct from rotation matrix and sequence. public: const EulerSequenceC& Sequence() const { return s; }; //: Euler sequence (read-only) EulerSequenceC& Sequence() { return s; }; //: Euler sequence. public: void Matrix(Matrix3dC& R) const { EulerToMatrix(*static_cast<const Vector3dC*>(this), R, s); } //: Convert to rotation matrix. Matrix3dC Matrix() const { Matrix3dC R; Matrix(R); return R; } //: Convert to rotation matrix (as return value). protected: EulerSequenceC s; }; } #endif
35.186047
94
0.655981
[ "geometry", "vector", "3d" ]
94a9f9b3521b6727ab9c82d79e34ef563e57e463
958
cpp
C++
2019-feb-28/Problems/C- A Little Bit!/code/A_Little_Bit.cpp
acmiut/contests
757e198914697e81b9f3640ae315c3b539a49d17
[ "Apache-2.0" ]
null
null
null
2019-feb-28/Problems/C- A Little Bit!/code/A_Little_Bit.cpp
acmiut/contests
757e198914697e81b9f3640ae315c3b539a49d17
[ "Apache-2.0" ]
null
null
null
2019-feb-28/Problems/C- A Little Bit!/code/A_Little_Bit.cpp
acmiut/contests
757e198914697e81b9f3640ae315c3b539a49d17
[ "Apache-2.0" ]
3
2019-03-31T13:29:09.000Z
2021-12-20T02:03:06.000Z
#include <vector> #include <cstdio> #include <set> #include <map> #include <algorithm> #include <cstdlib> #include <sstream> #include <numeric> #include <queue> #include <iostream> #include <string> #include <cstring> #include <utility> #define sz(a) ((int)(a).size()) #define pb push_back #define mk make_pair #define fi first #define se second #define Rep(i,j,k) for (int i=(j); i<=(k); i++) #define Repd(i,j,k) for (int i=(j); i>=(k); i--) #define ALL(c) (c).begin(),(c).end() #define TR(c,i) for(typeof((c).begin()) i = (c).begin(); i != (c).end(); i++) #define SUM(a) accumulate(all(a),string()) #define online1 #define RAND ((rand()<<15)+rand()) using namespace std; typedef vector<int> VI; typedef vector<VI> VVI; typedef pair<int,int> II; typedef long long LL; string s; int main(){ cin>>s; Rep(i,0,sz(s)-1) if (s[i]=='0'){ s.erase(s.begin()+i); cout<<s<<endl; return 0; } s.erase(s.begin()); cout<<s<<endl; return 0; }
19.55102
77
0.622129
[ "vector" ]
94b1a39907e0786bef67fe5363f6e8f3fa50f67d
2,802
cpp
C++
UvA/U11110.cpp
fvannee/competitive-coding
92bc383c482b55f3e48a583cddc50d92474eb488
[ "MIT" ]
null
null
null
UvA/U11110.cpp
fvannee/competitive-coding
92bc383c482b55f3e48a583cddc50d92474eb488
[ "MIT" ]
null
null
null
UvA/U11110.cpp
fvannee/competitive-coding
92bc383c482b55f3e48a583cddc50d92474eb488
[ "MIT" ]
null
null
null
#include <vector> #include <list> #include <map> #include <set> #include <queue> #include <deque> #include <stack> #include <bitset> #include <algorithm> #include <functional> #include <numeric> #include <utility> #include <sstream> #include <iostream> #include <fstream> #include <iomanip> #include <cstdio> #include <cmath> #include <cstdlib> #include <ctime> #include <cstring> #include <assert.h> #define INF 1023123123 #define EPS 1e-11 #define LSOne(S) (S & (-S)) #define FORN(X,Y) for (int (X) = 0;(X) < (Y);++(X)) #define FORB(X,Y) for (int (X) = (Y);(X) >= 0;--(X)) #define REP(X,Y,Z) for (int (X) = (Y);(X) < (Z);++(X)) #define REPB(X,Y,Z) for (int (X) = (Y);(X) >= (Z);--(X)) #define SZ(Z) ((int)(Z).size()) #define ALL(W) (W).begin(), (W).end() #define PB push_back #define MP make_pair #define A first #define B second #define FORIT(X,Y) for(typeof((Y).begin()) X = (Y).begin();X!=(Y).end();X++) using namespace std; typedef long long ll; typedef double db; typedef vector<int> vi; typedef pair<int, int> ii; typedef vector<ii> vii; vector<vector<int> > graph; vector<bool> visited; int leftover; vi pset; vi cset; int ndisjoint; void initSet(int N) { cset = vi(N); pset.assign(N, 0); ndisjoint = N; for (int i = 0; i < N; i++) { pset[i] = i; cset[i] = 1; }} int findSet(int i) { return pset[i] == i ? i : pset[i] = (findSet(pset[i])); } bool isSameSet(int i, int j) { return findSet(i) == findSet(j); } void unionSet(int i, int j) { int pi = findSet(i); int pj = findSet(j); if (pi != pj) { pset[pi] = pj; ndisjoint--; cset[pj] += cset[pi]; }} int numDisjointSets() { return ndisjoint; } int sizeOfSet(int i) { return cset[findSet(i)]; } void dfs(vector<vi>& grid, int x, int y, int cur) { if (x < 0 || x >= grid.size() || y < 0 || y >= grid[x].size() || grid[x][y] != cur) return; grid[x][y] = -1; dfs(grid, x - 1, y, cur); dfs(grid, x + 1, y, cur); dfs(grid, x, y + 1, cur); dfs(grid, x, y - 1, cur); } int main() { while (true) { int n; cin >> n; cin.ignore(); if (n == 0) break; vector<vi> grid(n); vector<bool> had; had.assign(n, false); FORN(i, n) { grid[i].assign(n, n - 1); } FORN(i, n - 1) { string line; getline(cin, line); stringstream ss(line); int x, y; while (ss >> x >> y) { grid[x - 1][y - 1] = i; } } bool succ = true; FORN(x, n) FORN(y, n) { if (grid[x][y] != -1 && had[grid[x][y]]) succ = false; else if (grid[x][y] != -1) { int cur = grid[x][y]; dfs(grid, x, y, cur); had[cur] = true; } } cout << (succ ? "good" : "wrong") << endl; } }
23.35
140
0.524625
[ "vector" ]
94baa1a5454777bbed75909c1351c846c79bf55f
3,002
cpp
C++
librtt/Renderer/Rtt_GeometryPool.cpp
agramonte/corona
3a6892f14eea92fdab5fa6d41920aa1e97bc22b1
[ "MIT" ]
1,968
2018-12-30T21:14:22.000Z
2022-03-31T23:48:16.000Z
librtt/Renderer/Rtt_GeometryPool.cpp
agramonte/corona
3a6892f14eea92fdab5fa6d41920aa1e97bc22b1
[ "MIT" ]
303
2019-01-02T19:36:43.000Z
2022-03-31T23:52:45.000Z
librtt/Renderer/Rtt_GeometryPool.cpp
agramonte/corona
3a6892f14eea92fdab5fa6d41920aa1e97bc22b1
[ "MIT" ]
254
2019-01-02T19:05:52.000Z
2022-03-30T06:32:28.000Z
////////////////////////////////////////////////////////////////////////////// // // This file is part of the Corona game engine. // For overview and more information on licensing please refer to README.md // Home page: https://github.com/coronalabs/corona // Contact: support@coronalabs.com // ////////////////////////////////////////////////////////////////////////////// #include "Renderer/Rtt_GeometryPool.h" #include "Renderer/Rtt_Geometry_Renderer.h" #include "Core/Rtt_Allocator.h" // ---------------------------------------------------------------------------- namespace /*anonymous*/ { U32 LogBase2( U32 value ) { const U32 base = 2; return log( (double)value ) / log( (double)base ); } } // ---------------------------------------------------------------------------- namespace Rtt { // ---------------------------------------------------------------------------- GeometryPool::Bucket::Bucket( Rtt_Allocator* allocator, U32 vertexCount ) : fAllocator( allocator ), fGeometry( allocator ), fVertexCount( vertexCount ), fUsedCount( 0 ) {} Geometry* GeometryPool::Bucket::GetOrCreate() { if( fUsedCount == fGeometry.Length() ) { const U32 indexCount = 0; const bool storeOnGPU = false; fGeometry.Append( Rtt_NEW( fAllocator, Geometry( fAllocator, Geometry::kTriangleStrip, fVertexCount, indexCount, storeOnGPU ) ) ); } Geometry* result = fGeometry[fUsedCount++]; result->SetVerticesUsed( 0 ); return result; } GeometryPool::GeometryPool( Rtt_Allocator* allocator, U32 minimumVertexCount ) : fAllocator( allocator ), fFrontPool( Rtt_NEW( allocator, Array<Bucket*>( allocator ) ) ), fBackPool( Rtt_NEW( allocator, Array<Bucket*>( allocator) ) ), fMinimumVertexCount( minimumVertexCount ), fMinimumPower( LogBase2( fMinimumVertexCount ) ) {} GeometryPool::~GeometryPool() { fBackPool->Empty(); fFrontPool->Empty(); Rtt_DELETE( fBackPool ); Rtt_DELETE( fFrontPool ); } Geometry* GeometryPool::GetOrCreate( U32 requiredVertexCount ) { U32 finalCount = Max( fMinimumVertexCount, NextPowerOf2( requiredVertexCount ) ); U32 bucketIndex = LogBase2( finalCount ) - fMinimumPower; const S32 length = fBackPool->Length(); if( bucketIndex >= length ) { U32 vertexCount = fMinimumVertexCount; if ( length > 0 ) { // Double the count of the last bucket vertexCount = (*fBackPool)[length - 1]->fVertexCount * 2; } for( S32 i = length; i <= bucketIndex; ++i) { fBackPool->Append( Rtt_NEW( fAllocator, Bucket( fAllocator, vertexCount ) ) ); vertexCount *= 2; } } return (*fBackPool)[bucketIndex]->GetOrCreate(); } void GeometryPool::Swap() { Array<Bucket*>* temp = fFrontPool; fFrontPool = fBackPool; fBackPool = temp; const S32 length = fBackPool->Length(); for( S32 i = 0; i < length; ++i ) { (*fBackPool)[i]->fUsedCount = 0; } } // ---------------------------------------------------------------------------- } // namespace Rtt // ----------------------------------------------------------------------------
25.87931
88
0.571952
[ "geometry" ]
94c5b9b228869bf1a4da718ac762c0477c89b15f
2,092
cc
C++
examples/Geant4/CerenkovStandalone/RINDEXTest.cc
hanswenzel/opticks
b75b5929b6cf36a5eedeffb3031af2920f75f9f0
[ "Apache-2.0" ]
11
2020-07-05T02:39:32.000Z
2022-03-20T18:52:44.000Z
examples/Geant4/CerenkovStandalone/RINDEXTest.cc
hanswenzel/opticks
b75b5929b6cf36a5eedeffb3031af2920f75f9f0
[ "Apache-2.0" ]
null
null
null
examples/Geant4/CerenkovStandalone/RINDEXTest.cc
hanswenzel/opticks
b75b5929b6cf36a5eedeffb3031af2920f75f9f0
[ "Apache-2.0" ]
4
2020-09-03T20:36:32.000Z
2022-01-19T07:42:21.000Z
#include <cassert> #include <iostream> #include <iomanip> #include "G4SystemOfUnits.hh" #include "G4PhysicalConstants.hh" #include "OpticksDebug.hh" #include "NP.hh" struct RINDEXTest { static const char* FOLD ; NP* a ; G4MaterialPropertyVector* rindex ; RINDEXTest(const char* path) ; void g4_line_lookup(double nm0, double nm1, double nm_step); void save(const char* reldir=nullptr); std::vector<double> v ; }; const char* RINDEXTest::FOLD = "/tmp/RINDEXTest" ; RINDEXTest::RINDEXTest( const char* path ) : a(OpticksDebug::LoadArray(path)), rindex( a ? OpticksDebug::MakeProperty(a) : nullptr) { std::cout << "loaded from " << path << std::endl ; assert( a ); assert( rindex ); } void RINDEXTest::g4_line_lookup(double nm0, double nm1, double nm_step) { for(double wavelength=nm0 ; wavelength < nm1 ; wavelength += nm_step ) { double energy = h_Planck*c_light/(wavelength*nm) ; double value = rindex->Value(energy); std::cout << " wavelength " << std::setw(10) << std::fixed << std::setprecision(4) << wavelength << " energy/eV " << std::setw(10) << std::fixed << std::setprecision(4) << energy/eV << " value " << std::setw(10) << std::fixed << std::setprecision(4) << value << std::endl ; v.push_back(wavelength); v.push_back(value); } } void RINDEXTest::save(const char* reldir) { if( v.size() > 0 ) { // creates reldir if needed std::string path = OpticksDebug::prepare_path( FOLD, reldir, "photons.npy" ); std::cout << " saving to " << path << std::endl ; NP::Write( FOLD, reldir, "g4_line_lookup.npy", v.data(), v.size()/2, 2 ); } } int main(int argc, char** argv) { const char* path = "GScintillatorLib/LS_ori/RINDEX.npy" ; std::cout << " RINDEX path " << path << std::endl ; RINDEXTest t(path); t.g4_line_lookup(80., 800., 0.1); t.save(); return 0 ; }
24.045977
98
0.573614
[ "vector" ]
94cf8a27f091ecd853402cd1a79487ba32044654
3,833
cpp
C++
Example2D3DRegistration/Example2D3DRegistrationAlgorithm.cpp
ImFusionGmbH/public-demos
e2a5c5d5fcf21d7c2868e4182f9df77efb97f945
[ "BSD-3-Clause" ]
10
2019-09-26T20:04:22.000Z
2021-07-09T01:45:29.000Z
Example2D3DRegistration/Example2D3DRegistrationAlgorithm.cpp
ImFusionGmbH/public-demos
e2a5c5d5fcf21d7c2868e4182f9df77efb97f945
[ "BSD-3-Clause" ]
null
null
null
Example2D3DRegistration/Example2D3DRegistrationAlgorithm.cpp
ImFusionGmbH/public-demos
e2a5c5d5fcf21d7c2868e4182f9df77efb97f945
[ "BSD-3-Clause" ]
4
2020-01-19T08:46:17.000Z
2021-11-08T22:21:29.000Z
#include "Example2D3DRegistrationAlgorithm.h" #include <ImFusion/Base/DataList.h> #include <ImFusion/Base/ImageProcessing.h> #include <ImFusion/Base/Log.h> #include <ImFusion/Base/MemImage.h> #include <ImFusion/Base/Pose.h> #include <ImFusion/Base/SharedImage.h> #include <ImFusion/Base/SharedImageSet.h> #include <ImFusion/CT/ConeBeamData.h> #include <ImFusion/CT/ConeBeamSimulation.h> #include <ImFusion/CT/XRay2D3DRegistrationAlgorithm.h> // The following sets the log category for this file to "Example2D3DRegistration" #undef IMFUSION_LOG_DEFAULT_CATEGORY #define IMFUSION_LOG_DEFAULT_CATEGORY "Example2D3DRegistration" namespace ImFusion { Example2D3DRegistrationAlgorithm::Example2D3DRegistrationAlgorithm(SharedImageSet* volumeIn) : m_volumeIn(volumeIn) { // Convert the volume to use unsigned values internally. // ConeBeamSimulation currently uses the storage values of the volume, // so this is needed to avoid negative values. m_volumeIn->prepare(); } Example2D3DRegistrationAlgorithm::~Example2D3DRegistrationAlgorithm() { /// Since the registration algorithm uses the projections, make sure to delete registration algorithm first. m_regAlg = nullptr; m_projections = nullptr; } bool Example2D3DRegistrationAlgorithm::createCompatible(const DataList& data, Algorithm** a) { // check requirements to create the algorithm. In this case, we want to take in a single volume. if (data.size() != 1) return false; SharedImageSet* img = data.getImage(Data::VOLUME); if (img == nullptr) return false; // requirements are met, create the algorithm if asked if (a) { *a = new Example2D3DRegistrationAlgorithm(img); } return true; } // This function does all of the work of this class void Example2D3DRegistrationAlgorithm::compute() { // Basic consistency check. if (m_volumeIn == nullptr) { LOG_ERROR("Algorithm incorrectly initialized"); return; } // We create some simulated X-ray images. ConeBeamSimulation simulation(*m_volumeIn->get(0)); // This is the pose of the simulated X-ray images relative to the volume. mat4 groundTruthIso = Pose::eulerToMat(vec3(30.0,70.0,3.0), vec3(5.0,-5.0,2.0)); simulation.geometry().setIsoMatrix(groundTruthIso); auto& geom = simulation.geometry(); geom.sourceDetDistance = 1000.0; geom.sourcePatDistance = 500.0; geom.detSizeX = 200; geom.detSizeY = 200; geom.angleRange = 90; Properties p; simulation.configuration(&p); p.setParam("width", 384); p.setParam("height", 512); p.setParam("frames", 2); p.setParam("i0", 0.0); p.setParam("volPars/reconSize", 300); simulation.configure(&p); simulation.compute(); //<This runs the simulation // We save the result m_projections = simulation.takeOutput().extractFirst<ConeBeamData>(); // Reset the iso parameters to a different pose differing from the ground truth. m_projections->geometry().setIsoMatrix(Pose::eulerToMat(vec3(200,2.0,3.0),vec3(-10.0,0.0,0.0))); // Start an instance of XRay2D3DRegistrationAlgorithm with the volume and the projections. // We set a custom initialization mode with an instance of Custom2D3DRegistrationInitialization // that implements the initialization of the registration. m_regAlg = std::make_unique<XRay2D3DRegistrationAlgorithm>(*m_projections, *m_volumeIn); m_regAlg->p_initializationMode = XRay2D3DRegistrationAlgorithm::InitializationMode::Custom; auto customInit = std::make_unique<Custom2D3DRegistrationInitialization>(*m_regAlg, groundTruthIso); m_customInit = customInit.get(); m_regAlg->setCustomInitialization(std::move(customInit)); } OwningDataList Example2D3DRegistrationAlgorithm::takeOutput() { // if we have produced some output, add it to the list return OwningDataList(std::move(m_projections)); } }
33.622807
110
0.749804
[ "geometry" ]
94d6cfa260993d308ed46ae83fbfe35363e892c3
26,263
cpp
C++
src/VoxieBackend/Data/TomographyRawData2DAccessor.cpp
voxie-viewer/voxie
d2b5e6760519782e9ef2e51f5322a3baa0cb1198
[ "MIT" ]
4
2016-06-03T18:41:43.000Z
2020-04-17T20:28:58.000Z
src/VoxieBackend/Data/TomographyRawData2DAccessor.cpp
voxie-viewer/voxie
d2b5e6760519782e9ef2e51f5322a3baa0cb1198
[ "MIT" ]
null
null
null
src/VoxieBackend/Data/TomographyRawData2DAccessor.cpp
voxie-viewer/voxie
d2b5e6760519782e9ef2e51f5322a3baa0cb1198
[ "MIT" ]
null
null
null
/* * Copyright (c) 2014-2022 The Voxie Authors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "TomographyRawData2DAccessor.hpp" #include <QtCore/QCoreApplication> #include <QtCore/QThread> #include <VoxieBackend/DBus/ClientWrapper.hpp> #include <VoxieBackend/DBus/ObjectWrapper.hpp> #include <VoxieBackend/Data/ImageDataPixelInst.hpp> #include <VoxieBackend/Data/TomographyRawData2DRegular.hpp> #include <VoxieClient/DBusProxies.hpp> #include <VoxieClient/DBusUtil.hpp> #include <VoxieClient/JsonDBus.hpp> #include <VoxieClient/ObjectExport/BusManager.hpp> #include <VoxieClient/ObjectExport/DBusCallUtil.hpp> using namespace vx; GeometryEntry::GeometryEntry(GeometryEntry* parent, int pos, const QString& name, const QJsonObject& localGeometryData) : parent_(parent), pos_(pos), name_(name), localGeometryData_(localGeometryData) { if (!parent) { fullName_ = ""; nameComponents_ = {}; } else { if (parent->fullName() == "") fullName_ = ""; else fullName_ = parent->fullName() + " / "; nameComponents_ = parent->nameComponents(); if (dynamic_cast<GeometryEntryArray*>(parent)) { fullName_ += QString::number(pos); nameComponents_ << pos; } else { fullName_ += "'" + name + "'"; nameComponents_ << name; } } } GeometryEntry::~GeometryEntry() {} int GeometryEntry::pos() { if (!dynamic_cast<GeometryEntryArray*>(parent())) throw vx::Exception( "de.uni_stuttgart.Voxie.InternalError", "Attempting to call GeometryEntry::pos() on child of non-array"); return pos_; } QString GeometryEntry::name() { if (!dynamic_cast<GeometryEntryObject*>(parent())) throw vx::Exception( "de.uni_stuttgart.Voxie.InternalError", "Attempting to call GeometryEntry::pos() on child of non-object"); return name_; } QSharedPointer<GeometryEntry> GeometryEntry::parse(const QJsonValue& json, GeometryEntry* parent, int pos, const QString& name) { // qDebug() << "GeometryEntry::parse" << json.isArray() << json.isObject() // << parent << pos << name; if (json.isArray()) { return createQSharedPointer<GeometryEntryArray>(json.toArray(), parent, pos, name); } else if (json.isObject()) { auto obj = json.toObject(); if (obj.contains("ImageReference")) return createQSharedPointer<GeometryEntryImage>(obj, parent, pos, name); else return createQSharedPointer<GeometryEntryObject>(obj, parent, pos, name); } else { return QSharedPointer<GeometryEntry>(); } } GeometryEntryObject::GeometryEntryObject(const QJsonObject& json, GeometryEntry* parent, int pos, const QString& name) : GeometryEntry(parent, pos, name, json["ProjectionGeometry"].toObject()) { for (const auto& key : json.keys()) { if (key == "ImageReference") continue; auto entry = GeometryEntry::parse(json[key], this, -1, key); if (!entry) continue; children_[key] = entry; } } GeometryEntry* GeometryEntryObject::operator[](const QString& name) { if (!children_.contains(name)) throw vx::Exception("de.uni_stuttgart.Voxie.InternalError", "Could not find entry in GeometryEntryObject: " + name); return children_[name].data(); } void GeometryEntryObject::createImageLists( const QSharedPointer<GeometryEntry>& root, QList<QSharedPointer<GeometryImageList>>& outLists) { for (const auto& key : children_.keys()) { children_[key]->createImageLists(root, outLists); } } GeometryEntryArray::GeometryEntryArray(const QJsonArray& json, GeometryEntry* parent, int pos, const QString& name) : GeometryEntry(parent, pos, name, QJsonObject{}) { hasImageChildren_ = false; for (int i = 0; i < json.count(); i++) { auto entry = GeometryEntry::parse(json[i], this, i, ""); // Also add nullptr entries children_.append(entry); if (dynamic_cast<GeometryEntryImage*>(entry.data())) hasImageChildren_ = true; } } GeometryEntry* GeometryEntryArray::operator[](int pos) { if (pos < 0 || pos >= count()) throw vx::Exception( "de.uni_stuttgart.Voxie.InternalError", "Index out of range for GeometryEntryArray: " + QString::number(pos)); return children_[pos].data(); } void GeometryEntryArray::createImageLists( const QSharedPointer<GeometryEntry>& root, QList<QSharedPointer<GeometryImageList>>& outLists) { if (hasImageChildren()) outLists.append(createQSharedPointer<GeometryImageListArray>(root, this)); for (const auto& entry : children_) { if (entry) entry->createImageLists(root, outLists); } } GeometryEntryImage::GeometryEntryImage(const QJsonObject& json, GeometryEntry* parent, int pos, const QString& name) : GeometryEntryObject(json, parent, pos, name) { if (!json.contains("ImageReference")) throw vx::Exception( "de.uni_stuttgart.Voxie.InternalError", "GeometryEntryImage::GeometryEntryImage(): No ImageReference member"); auto ir = json["ImageReference"].toObject(); if (!ir.contains("Stream")) throw vx::Exception("de.uni_stuttgart.Voxie.Error", "GeometryEntryImage::GeometryEntryImage(): Got " "ImageReference without Stream member"); if (!ir.contains("ImageID")) throw vx::Exception("de.uni_stuttgart.Voxie.Error", "GeometryEntryImage::GeometryEntryImage(): Got " "ImageReference without ImageID member"); stream_ = ir["Stream"].toString(); id_ = ir["ImageID"].toInt(); } QJsonObject GeometryEntryImage::geometry() { QJsonObject result{}; for (GeometryEntry* obj = this; obj; obj = obj->parent()) { for (const auto& key : obj->localGeometryData().keys()) { if (result.contains(key)) continue; result[key] = obj->localGeometryData()[key]; } } return result; } void GeometryEntryImage::createImageLists( const QSharedPointer<GeometryEntry>& root, QList<QSharedPointer<GeometryImageList>>& outLists) { if (!dynamic_cast<GeometryEntryArray*>(parent())) { // Only add this if parent is not an array outLists.append(createQSharedPointer<GeometryImageListSingle>(root, this)); } GeometryEntryObject::createImageLists(root, outLists); } GeometryImageList::GeometryImageList(const QSharedPointer<GeometryEntry>& root, GeometryEntry* entry) : root(root), entry_(entry) {} GeometryImageList::~GeometryImageList() {} GeometryImageListSingle::GeometryImageListSingle( const QSharedPointer<GeometryEntry>& root, GeometryEntryImage* entry) : GeometryImageList(root, entry), image_(entry) {} int GeometryImageListSingle::count() { return 1; } GeometryEntryImage* GeometryImageListSingle::operator[](int pos) { if (pos != 0) throw vx::Exception("de.uni_stuttgart.Voxie.InternalError", "Index out of range for GeometryImageListSingle: " + QString::number(pos)); return image_; } GeometryImageListArray::GeometryImageListArray( const QSharedPointer<GeometryEntry>& root, GeometryEntryArray* array) : GeometryImageList(root, array), array_(array) {} int GeometryImageListArray::count() { return array_->count(); } GeometryEntryImage* GeometryImageListArray::operator[](int pos) { return dynamic_cast<GeometryEntryImage*>((*array_)[pos]); } class TomographyRawData2DAccessorOperationsImpl : public TomographyRawData2DAccessorOperationsAdaptor { TomographyRawData2DAccessor* object; public: TomographyRawData2DAccessorOperationsImpl(TomographyRawData2DAccessor* object) : TomographyRawData2DAccessorOperationsAdaptor(object), object(object) {} QStringList GetAvailableGeometryTypes( const QMap<QString, QDBusVariant>& options) override { try { ExportedObject::checkOptions(options); return vx::handleDBusCallOnBackgroundThreadOne<QStringList>( object, [self = object->thisShared()]() { return self->availableGeometryTypes(); }); } catch (Exception& e) { e.handle(object); return vx::dbusDefaultReturnValue(); } } QList<QMap<QString, QDBusVariant>> GetAvailableImageKinds( const QMap<QString, QDBusVariant>& options) override { try { ExportedObject::checkOptions(options); return vx::handleDBusCallOnBackgroundThreadOne< QList<QMap<QString, QDBusVariant>>>( object, [self = object->thisShared()]() { QList<QMap<QString, QDBusVariant>> result; for (const auto& kind : self->availableImageKinds()) result << vx::jsonToDBus(kind); return result; }); } catch (Exception& e) { e.handle(object); return vx::dbusDefaultReturnValue(); } } QStringList GetAvailableStreams( const QMap<QString, QDBusVariant>& options) override { try { ExportedObject::checkOptions(options); return vx::handleDBusCallOnBackgroundThreadOne<QStringList>( object, [self = object->thisShared()]() { return self->availableStreams(); }); } catch (Exception& e) { e.handle(object); return vx::dbusDefaultReturnValue(); } } QMap<QString, QDBusVariant> GetGeometryData( const QString& geometryType, const QMap<QString, QDBusVariant>& options) override { try { ExportedObject::checkOptions(options); return vx::handleDBusCallOnBackgroundThreadOne< QMap<QString, QDBusVariant>>( object, [self = object->thisShared(), geometryType]() { return vx::jsonToDBus(self->getGeometryData(geometryType)); }); } catch (Exception& e) { e.handle(object); return vx::dbusDefaultReturnValue(); } } std::tuple<quint64, quint64> GetImageShape( const QString& stream, qulonglong id, const QMap<QString, QDBusVariant>& options) override { try { ExportedObject::checkOptions(options); return vx::handleDBusCallOnBackgroundThreadOne< std::tuple<quint64, quint64>>( object, [self = object->thisShared(), stream, id]() { return self->imageSize(stream, id).toTupleVector(); }); } catch (Exception& e) { e.handle(object); return vx::dbusDefaultReturnValue(); } } QMap<QString, QDBusVariant> GetMetadata( const QMap<QString, QDBusVariant>& options) override { try { ExportedObject::checkOptions(options); return vx::handleDBusCallOnBackgroundThreadOne< QMap<QString, QDBusVariant>>(object, [self = object->thisShared()]() { return vx::jsonToDBus(self->metadata()); }); } catch (Exception& e) { e.handle(object); return vx::dbusDefaultReturnValue(); } } quint64 GetNumberOfImages( const QString& stream, const QMap<QString, QDBusVariant>& options) override { try { ExportedObject::checkOptions(options); return vx::handleDBusCallOnBackgroundThreadOne<quint64>( object, [self = object->thisShared(), stream]() { return self->numberOfImages(stream); }); } catch (Exception& e) { e.handle(object); return vx::dbusDefaultReturnValue(); } } QMap<QString, QDBusVariant> GetPerImageMetadata( const QString& stream, qulonglong id, const QMap<QString, QDBusVariant>& options) override { try { ExportedObject::checkOptions(options); return vx::handleDBusCallOnBackgroundThreadOne< QMap<QString, QDBusVariant>>( object, [self = object->thisShared(), stream, id]() { return vx::jsonToDBus(self->getPerImageMetadata(stream, id)); }); } catch (Exception& e) { e.handle(object); return vx::dbusDefaultReturnValue(); } } QString ReadImages(const QMap<QString, QDBusVariant>& imageKind, const QList<std::tuple<QString, quint64>>& images, const std::tuple<quint64, quint64>& inputRegionStart, const std::tuple<QString, QDBusObjectPath>& output, qulonglong firstOutputImageId, const std::tuple<quint64, quint64>& outputRegionStart, const std::tuple<quint64, quint64>& regionSize, const QMap<QString, QDBusVariant>& options) override { try { ExportedObject::checkOptions(options, "AllowIncompleteData"); auto allowIncompleteData = ExportedObject::getOptionValueOrDefault<bool>( options, "AllowIncompleteData", false); auto serviceVoxie = object->connection().baseService(); if (std::get<0>(output) != serviceVoxie) throw vx::Exception( "de.uni_stuttgart.Voxie.Error", "Got invalid image reference: Expected reference to service '" + serviceVoxie + "', got '" + std::get<0>(output) + "'"); auto outputObj = vx::TomographyRawData2DRegular::lookup(std::get<1>(output)); return vx::handleDBusCallOnBackgroundThreadOne<QString>( object, [self = object->thisShared(), imageKind, images, inputRegionStart, outputObj, firstOutputImageId, outputRegionStart, regionSize, allowIncompleteData]() { return self->readImages(vx::dbusToJson(imageKind), images, inputRegionStart, outputObj, firstOutputImageId, outputRegionStart, regionSize, allowIncompleteData); }); } catch (Exception& e) { e.handle(object); return vx::dbusDefaultReturnValue(); } } }; TomographyRawData2DAccessor::TomographyRawData2DAccessor() { new TomographyRawData2DAccessorOperationsImpl(this); } TomographyRawData2DAccessor::~TomographyRawData2DAccessor() {} QList<QString> TomographyRawData2DAccessor::supportedDBusInterfaces() { return { "de.uni_stuttgart.Voxie.TomographyRawData2DAccessor", "de.uni_stuttgart.Voxie.TomographyRawDataAccessor", "de.uni_stuttgart.Voxie.TomographyRawDataBase", }; } void TomographyRawData2DAccessor::readImage( const QString& stream, uint64_t id, const QSharedPointer<ImageDataPixel>& image, const QJsonObject& imageKind, const vx::VectorSizeT2& inputRegionStart, const vx::VectorSizeT2& outputRegionStart, const vx::VectorSizeT2& regionSize, bool allowIncompleteData) { this->readImages(imageKind, { std::make_tuple(stream, id), }, inputRegionStart.toTupleVector(), image->fakeTomographyRawData2DRegular(), 0, outputRegionStart.toTupleVector(), regionSize.toTupleVector(), allowIncompleteData); } QList<QSharedPointer<GeometryImageList>> TomographyRawData2DAccessor::getImageLists(const QString& geometryType) { { QMutexLocker locker(&mutex); if (imageListCache.contains(geometryType)) return imageListCache[geometryType]; } auto geometry = getGeometryData(geometryType); auto root = GeometryEntry::parse(geometry, nullptr, -1, ""); QList<QSharedPointer<GeometryImageList>> lists; if (root) root->createImageLists(root, lists); { QMutexLocker locker(&mutex); // Note: Another thread might have inserted a value if (imageListCache.contains(geometryType)) return imageListCache[geometryType]; imageListCache[geometryType] = lists; return imageListCache[geometryType]; } } QSharedPointer<GeometryImageList> TomographyRawData2DAccessor::getImageList( const QString& geometryType, const QJsonArray& path) { // TODO: Avoid loop here? for (const auto& list : getImageLists(geometryType)) { if (list->entry()->nameComponents() == path) return list; } return QSharedPointer<GeometryImageList>(); } QSharedPointer<QMap<std::tuple<QString, quint64>, QList<std::tuple<QString, GeometryEntryImage*>>>> TomographyRawData2DAccessor::getStreamToGeometryMap() { { QMutexLocker locker(&mutex); if (streamToGeometryCache) return streamToGeometryCache; } auto result = createQSharedPointer< QMap<std::tuple<QString, quint64>, QList<std::tuple<QString, GeometryEntryImage*>>>>(); for (const auto& geometryType : availableGeometryTypes()) { // TODO: Probably should not use lists here but GeometryEntrys directly auto lists = getImageLists(geometryType); for (const auto& list : lists) { for (int i = 0; i < list->count(); i++) { auto entry = (*list)[i]; if (!entry) continue; std::tuple<QString, quint64> key = std::make_tuple(entry->stream(), entry->id()); (*result)[key].append(std::make_tuple(geometryType, entry)); } } } { QMutexLocker locker(&mutex); // Note: Another thread might have inserted a value if (streamToGeometryCache) return streamToGeometryCache; streamToGeometryCache = result; return streamToGeometryCache; } } QList<std::tuple<QString, GeometryEntryImage*>> TomographyRawData2DAccessor::mapStreamImageToGeometryImage( const QString& stream, uint64_t id) { auto map = getStreamToGeometryMap(); std::tuple<QString, quint64> key = std::make_tuple(stream, id); if ((*map).contains(key)) return (*map)[key]; else return {}; } QList<std::tuple<QString, QJsonObject>> TomographyRawData2DAccessor::availableImageLists() { QList<std::tuple<QString, QJsonObject>> result; for (const auto& name : availableStreams()) { result << std::make_tuple( "de.uni_stuttgart.Voxie.TomographyRawDataImageListType.ImageStream", QJsonObject{ {"StreamName", name}, }); } for (const auto& geometryType : availableGeometryTypes()) { for (const auto& list : getImageLists(geometryType)) { result << std::make_tuple( "de.uni_stuttgart.Voxie.TomographyRawDataImageListType." "GeometryImageList", QJsonObject{ {"GeometryType", geometryType}, {"Path", list->entry()->nameComponents()}, }); } } return result; } TomographyRawData2DAccessorDBus::TomographyRawData2DAccessorDBus( const QSharedPointer<BusConnection>& connection, const std::tuple<QString, QDBusObjectPath>& provider) : connection_(connection), provider_(provider) { auto client = createQSharedPointer<ClientWrapper>(connection, std::get<0>(provider)); wrapper = createQSharedPointer<ObjectWrapper>(client, std::get<1>(provider), true); proxy = makeSharedQObject< de::uni_stuttgart::Voxie::TomographyRawData2DAccessorOperations>( std::get<0>(provider), std::get<1>(provider).path(), connection->connection()); // TODO: really do this here? metadata_ = vx::dbusToJson(HANDLEDBUSPENDINGREPLY( proxy->GetMetadata(QMap<QString, QDBusVariant>()))); for (const auto& kind : HANDLEDBUSPENDINGREPLY( proxy->GetAvailableImageKinds(QMap<QString, QDBusVariant>()))) availableImageKinds_ << vx::dbusToJson(kind); availableStreams_ = HANDLEDBUSPENDINGREPLY( proxy->GetAvailableStreams(QMap<QString, QDBusVariant>())); availableGeometryTypes_ = HANDLEDBUSPENDINGREPLY( proxy->GetAvailableGeometryTypes(QMap<QString, QDBusVariant>())); for (const auto& stream : availableStreams_) { numberOfImages_[stream] = HANDLEDBUSPENDINGREPLY( proxy->GetNumberOfImages(stream, QMap<QString, QDBusVariant>())); // qDebug() << "numberOfImages" << numberOfImages_; for (uint64_t i = 0; i < numberOfImages_[stream]; i++) { imageSizes_[std::make_tuple(stream, i)] = VectorSizeT2(HANDLEDBUSPENDINGREPLY( proxy->GetImageShape(stream, i, QMap<QString, QDBusVariant>()))); } QMap<uint64_t, QJsonObject> data; for (uint64_t i = 0; i < numberOfImages_[stream]; i++) { data[i] = vx::dbusToJson(HANDLEDBUSPENDINGREPLY(proxy->GetPerImageMetadata( stream, i, QMap<QString, QDBusVariant>()))); } perImageMetadata_[stream] = data; } // Populate cache to avoid HANDLEDBUSPENDINGREPLY() / nested main loops later // on for (const auto& type : availableGeometryTypes_) { getGeometryData(type); } } TomographyRawData2DAccessorDBus::~TomographyRawData2DAccessorDBus() {} uint64_t TomographyRawData2DAccessorDBus::numberOfImages( const QString& stream) { if (!numberOfImages_.contains(stream)) throw vx::Exception("de.uni_stuttgart.Voxie.Error", "Invalid stream"); return numberOfImages_[stream]; } QString TomographyRawData2DAccessorDBus::readImages( const QJsonObject& imageKind, const QList<std::tuple<QString, quint64>>& images, const std::tuple<quint64, quint64>& inputRegionStart, const QSharedPointer<TomographyRawData2DRegular>& output, qulonglong firstOutputImageId, const std::tuple<quint64, quint64>& outputRegionStart, const std::tuple<quint64, quint64>& regionSize, bool allowIncompleteData) { for (const auto& entry : images) { const auto& stream = std::get<0>(entry); const auto& id = std::get<1>(entry); if (!perImageMetadata().contains(stream)) { throw vx::Exception("de.uni_stuttgart.Voxie.Error", "Invalid stream '" + stream + "'"); } if (id >= (uint64_t)perImageMetadata()[stream].size()) { throw vx::Exception("de.uni_stuttgart.Voxie.Error", "Image ID " + QString::number(id) + " in stream '" + stream + "' is out of range"); } } QMap<QString, QDBusVariant> options; if (allowIncompleteData) { options["AllowIncompleteData"] = dbusMakeVariant<bool>(true); options["Optional"] = dbusMakeVariant<QList<QString>>({"AllowIncompleteData"}); } return HANDLEDBUSPENDINGREPLY(proxy->ReadImages( jsonToDBus(imageKind), images, inputRegionStart, std::tuple<QString, QDBusObjectPath>( connection_->connection().baseService(), output->getPath()), firstOutputImageId, outputRegionStart, regionSize, options)); } vx::VectorSizeT2 TomographyRawData2DAccessorDBus::imageSize( const QString& stream, uint64_t id) { auto pos = std::make_tuple(stream, id); if (!imageSizes().contains(pos)) throw vx::Exception("de.uni_stuttgart.Voxie.Error", "Image ID " + QString::number(id) + " is out of range for stream '" + stream + "'"); return imageSizes()[pos]; } QJsonObject TomographyRawData2DAccessorDBus::getPerImageMetadata( const QString& stream, uint64_t id) { if (!perImageMetadata_.contains(stream)) throw vx::Exception("de.uni_stuttgart.Voxie.Error", "Invalid stream"); const auto& data = perImageMetadata_[stream]; if (id >= (uint64_t)data.size()) { throw vx::Exception("de.uni_stuttgart.Voxie.Error", "Image ID " + QString::number(id) + " is out of range for stream '" + stream + "'"); } return data[id]; } QJsonObject TomographyRawData2DAccessorDBus::getGeometryData( const QString& geometryType) { { QMutexLocker locker(&mutex); if (geometryDataChache.contains(geometryType)) return geometryDataChache[geometryType]; } auto data = HANDLEDBUSPENDINGREPLY( proxy->GetGeometryData(geometryType, QMap<QString, QDBusVariant>())); auto dataJson = dbusToJson(data); { QMutexLocker locker(&mutex); // Note: Another thread might have inserted a value if (geometryDataChache.contains(geometryType)) return geometryDataChache[geometryType]; geometryDataChache[geometryType] = dataJson; return geometryDataChache[geometryType]; } } Q_NORETURN void TomographyRawData2DAccessor::throwMissingPerImageMetadata( const QString& stream, uint64_t id, const QString& name) { throw vx::Exception("de.uni_stuttgart.Voxie.Error", "No value given for per-image metadata '" + name + "' for image " + QString::number(id) + " in stream '" + stream + "'"); } Q_NORETURN void TomographyRawData2DAccessor::throwInvalidPerImageMetadata( const QString& stream, uint64_t id, const QString& name, const QString& expected, const QString& actual) { throw vx::Exception("de.uni_stuttgart.Voxie.Error", "Invalid type for per-image metadata '" + name + "' for image" + QString::number(id) + " in stream '" + stream + "': got " + actual + ", expected " + expected); } QList<QSharedPointer<SharedMemory>> TomographyRawData2DAccessorDBus::getSharedMemorySections() { return {}; }
37.626074
80
0.659254
[ "geometry", "object" ]
94de20f7532c00ff012c5aa75fde606b453e03f7
659
cpp
C++
src/texturemaker.cpp
therocode/painter
3b678552a53edc937c368b5212c49ca7d0aa1a3e
[ "MIT" ]
null
null
null
src/texturemaker.cpp
therocode/painter
3b678552a53edc937c368b5212c49ca7d0aa1a3e
[ "MIT" ]
null
null
null
src/texturemaker.cpp
therocode/painter
3b678552a53edc937c368b5212c49ca7d0aa1a3e
[ "MIT" ]
null
null
null
#include "texturemaker.hpp" fea::Texture makeTexture(std::string path) { fea::Texture texture; uint32_t width; uint32_t height; std::vector<unsigned char> image; //the raw pixels //decode unsigned error = lodepng::decode(image, width, height, path); //if there's an error, display it if(error) { std::cout << "decoder error " << error << ": " << lodepng_error_text(error) << std::endl; exit(4); } //the pixels are now in the vector "image", 4 bytes per pixel, ordered RGBARGBA..., use it as texture, draw it, ... texture.create(width, height, &image[0], false, true); return texture; }
26.36
119
0.62519
[ "vector" ]
94e3157d0336f88ca2c361ac395cdafd0e8712c2
4,055
cpp
C++
proxygen/lib/utils/test/TraceEventTest.cpp
BeeswaxIO/proxygen
ddd9ce537cb93ed39cc3aa8ca52f76966b559559
[ "BSD-3-Clause" ]
null
null
null
proxygen/lib/utils/test/TraceEventTest.cpp
BeeswaxIO/proxygen
ddd9ce537cb93ed39cc3aa8ca52f76966b559559
[ "BSD-3-Clause" ]
null
null
null
proxygen/lib/utils/test/TraceEventTest.cpp
BeeswaxIO/proxygen
ddd9ce537cb93ed39cc3aa8ca52f76966b559559
[ "BSD-3-Clause" ]
1
2021-01-09T09:01:41.000Z
2021-01-09T09:01:41.000Z
/* * Copyright (c) 2017, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include <proxygen/lib/utils/Exception.h> #include <proxygen/lib/utils/TraceEvent.h> #include <proxygen/lib/utils/TraceEventType.h> #include <proxygen/lib/utils/TraceFieldType.h> #include <folly/portability/GTest.h> #include <folly/portability/GMock.h> #include <string> #include <vector> using namespace proxygen; TEST(TraceEventTest, IntegralDataIntegralValue) { TraceEvent traceEvent( (TraceEventType::TotalRequest) ); int64_t data(13); traceEvent.addMeta(TraceFieldType::Protocol, data); ASSERT_EQ(data, traceEvent.getTraceFieldDataAs<int64_t>(TraceFieldType::Protocol)); } TEST(TraceEventTest, IntegralDataStringValue) { TraceEvent traceEvent( (TraceEventType::TotalRequest) ); int64_t intData(13); traceEvent.addMeta(TraceFieldType::Protocol, intData); std::string strData(std::to_string(intData)); ASSERT_EQ(strData, traceEvent.getTraceFieldDataAs<std::string>(TraceFieldType::Protocol)); } TEST(TraceEventTest, IntegralDataVectorValue) { TraceEvent traceEvent( (TraceEventType::TotalRequest) ); int64_t data(13); traceEvent.addMeta(TraceFieldType::Protocol, data); ASSERT_THROW( traceEvent.getTraceFieldDataAs<std::vector<std::string>>( TraceFieldType::Protocol), Exception); } TEST(TraceEventTest, StringDataIntegralValueConvertible) { TraceEvent traceEvent( (TraceEventType::TotalRequest) ); int64_t intData(13); std::string strData(std::to_string(intData)); traceEvent.addMeta(TraceFieldType::Protocol, strData); ASSERT_EQ(intData, traceEvent.getTraceFieldDataAs<int64_t>(TraceFieldType::Protocol)); } TEST(TraceEventTest, StringDataIntegralValueNonConvertible) { TraceEvent traceEvent( (TraceEventType::TotalRequest) ); std::string data("Abc"); traceEvent.addMeta(TraceFieldType::Protocol, data); ASSERT_ANY_THROW( traceEvent.getTraceFieldDataAs<int64_t>(TraceFieldType::Protocol)); } TEST(TraceEventTest, StringDataStringValue) { TraceEvent traceEvent( (TraceEventType::TotalRequest) ); std::string data("Abc"); traceEvent.addMeta(TraceFieldType::Protocol, data); ASSERT_EQ(data, traceEvent.getTraceFieldDataAs<std::string>(TraceFieldType::Protocol)); } TEST(TraceEventTest, StringDataVectorValue) { TraceEvent traceEvent( (TraceEventType::TotalRequest) ); std::string data("Abc"); traceEvent.addMeta(TraceFieldType::Protocol, data); ASSERT_THROW( traceEvent.getTraceFieldDataAs<std::vector<std::string>>( TraceFieldType::Protocol), Exception); } TEST(TraceEventTest, VectorDataIntegralValue) { TraceEvent traceEvent( (TraceEventType::TotalRequest) ); std::vector<std::string> data; data.push_back("Abc"); data.push_back("Hij"); data.push_back("Xyz"); traceEvent.addMeta(TraceFieldType::Protocol, data); ASSERT_THROW( traceEvent.getTraceFieldDataAs<int64_t>(TraceFieldType::Protocol), Exception); } TEST(TraceEventTest, VectorDataStringValue) { TraceEvent traceEvent( (TraceEventType::TotalRequest) ); std::vector<std::string> data; data.push_back("A"); data.push_back("B"); data.push_back("C"); traceEvent.addMeta(TraceFieldType::Protocol, data); ASSERT_THROW( traceEvent.getTraceFieldDataAs<std::string>(TraceFieldType::Protocol), Exception); } TEST(TraceEventTest, VectorDataVectorValue) { TraceEvent traceEvent( (TraceEventType::TotalRequest) ); std::vector<std::string> data; data.push_back("A"); data.push_back("B"); data.push_back("C"); traceEvent.addMeta(TraceFieldType::Protocol, data); std::vector<std::string> extractedData( traceEvent.getTraceFieldDataAs<std::vector<std::string>>( TraceFieldType::Protocol)); EXPECT_THAT(extractedData, testing::ContainerEq(data)); }
28.159722
79
0.745006
[ "vector" ]
94ec61b83b1d04999d23cfc1210ab51aa24f7068
4,258
cpp
C++
2M3/Source/Server/Network/ServerNetworkHandler.cpp
simatic/MultiplayerLab
f483a80882f32249923c4fbcc876cfdca2b7da10
[ "MIT" ]
null
null
null
2M3/Source/Server/Network/ServerNetworkHandler.cpp
simatic/MultiplayerLab
f483a80882f32249923c4fbcc876cfdca2b7da10
[ "MIT" ]
45
2020-10-08T13:32:36.000Z
2020-12-17T14:41:40.000Z
2M3/Source/Server/Network/ServerNetworkHandler.cpp
simatic/MultiplayerLab
f483a80882f32249923c4fbcc876cfdca2b7da10
[ "MIT" ]
3
2020-10-02T09:02:20.000Z
2020-11-07T00:14:13.000Z
// // Created by jglrxavpok on 15/10/2020. // #include <iostream> #include <thread> #include <Server/Network/ServerClock.h> #include "Server/Network/NetworkSettings.h" #include "Server/Network/ServerNetworkHandler.h" #include "Server/Network/DelayCreation.h" #include "Server/Interface.h" ServerNetworkHandler::ServerNetworkHandler(Buffer<Packet>& buffer, const std::string& ip, unsigned short port): ip(ip), port(port) { delayCreator = std::make_shared<DelayCreator>(*this, buffer); } void ServerNetworkHandler::killNetworkThread() { if(running) { delayCreator->join(); socket.unbind(); running = false; } } UdpClient& ServerNetworkHandler::getOrCreateClient(sf::IpAddress address, unsigned short port) { for (auto& client : clients) { if(client->address == address && client->port == port) { return *client; // found match } } std::cout << "New client at " << address << ":" << port << std::endl; clients.push_back(std::make_unique<UdpClient>(*this, currentClientID++, address, port, NetworkSettings())); auto& client = *clients.at(clients.size()-1); triggerEvent(client, NetworkEvent::Event{ServerClock::getInstance().get(), NetworkEvent::Type::Connected}); return client; } void ServerNetworkHandler::broadcast(std::unique_ptr<Packet> toBroadcast) { for(auto& client : clients) { client->send(std::move(toBroadcast)); } } void ServerNetworkHandler::updateNonConnectedClients() { while(running) { std::vector<ClientID> toDisconnect{}; for(auto& client : clients) { if(lastPacketTimes[client->id] + ServerNetworkHandler::DelayBeforeDeconnection < ServerClock::getInstance().asSeconds()) { toDisconnect.push_back(client->id); } } for(auto& id : toDisconnect) { clients.erase(std::find_if(clients.begin(), clients.end(), [&](const std::shared_ptr<UdpClient>& client) { return client->id == id; })); } sf::sleep(sf::seconds(1.0f)); } } void ServerNetworkHandler::updateLastPacketTime(const UdpClient &client) { lastPacketTimes[client.id] = ServerClock::getInstance().asSeconds(); } PacketSequenceIndex ServerNetworkHandler::generateNextIndex() { return ++sequenceIndex; } void ServerNetworkHandler::triggerEvent(const UdpClient& client, NetworkEvent::Event event) { for(auto& l : listeners) { l->onEvent(client, event); } } void ServerNetworkHandler::registerListener(IServerEventsListener *listener) { this->listeners.push_back(listener); } sf::UdpSocket& ServerNetworkHandler::getSocket() { return socket; } const std::string& ServerNetworkHandler::getIP() const { return ip; } const unsigned short ServerNetworkHandler::getPort() const { return port; } void ServerNetworkHandler::sendToClient(const UdpClient& client, std::unique_ptr<Packet>&& packet) { delayCreator->sendToClient(client, std::move(packet)); } DelayCreator& ServerNetworkHandler::getDelayCreator() { return *delayCreator; } bool ServerNetworkHandler::isRunning() { return running; } const char *NetworkEvent::name(NetworkEvent::Type t) { switch (t) { case Connected: return "Connexion"; case Disconnected: return "Déconnexion"; case PacketReceived: return "Packet envoyé par le client"; case PacketDelayed: return "Packet reçu par le serveur"; case SendingPacket: return "Packet envoyé par le serveur"; case SentPacket: return "Packet reçu par le client"; default: return "Unknown type"; } } UdpClient::UdpClient(ServerNetworkHandler& server, ClientID id, sf::IpAddress address, unsigned short port, NetworkSettings settings): server(server), id(id), address(address), port(port), settings(settings) {} void UdpClient::send(std::unique_ptr<Packet>&& packet) const { server.sendToClient(*this, std::move(packet)); } INetworkModule* ServerNetworkHandler::getNetworkModule() const { return networkModule; } void ServerNetworkHandler::setNetworkModule(INetworkModule* networkModule) { ServerNetworkHandler::networkModule = networkModule; }
31.308824
210
0.682715
[ "vector" ]
94ff1c8b69efba9e51cbed1f24f9965eae8c075b
1,548
hpp
C++
unittests/test-contracts/proxy/proxy.hpp
PicoFoundation/Pico2
8367d9edede9a9f7b1277d08333785d3bcf093b2
[ "MIT" ]
null
null
null
unittests/test-contracts/proxy/proxy.hpp
PicoFoundation/Pico2
8367d9edede9a9f7b1277d08333785d3bcf093b2
[ "MIT" ]
null
null
null
unittests/test-contracts/proxy/proxy.hpp
PicoFoundation/Pico2
8367d9edede9a9f7b1277d08333785d3bcf093b2
[ "MIT" ]
1
2021-01-28T06:01:01.000Z
2021-01-28T06:01:01.000Z
#pragma once #include <picoio/picoio.hpp> #include <picoio/singleton.hpp> #include <picoio/asset.hpp> // Extacted from picoio.token contract: namespace picoio { class [[picoio::contract("picoio.token")]] token : public picoio::contract { public: using picoio::contract::contract; [[picoio::action]] void transfer( picoio::name from, picoio::name to, picoio::asset quantity, const std::string& memo ); using transfer_action = picoio::action_wrapper<"transfer"_n, &token::transfer>; }; } // This contract: class [[picoio::contract]] proxy : public picoio::contract { public: proxy( picoio::name self, picoio::name first_receiver, picoio::datastream<const char*> ds ); [[picoio::action]] void setowner( picoio::name owner, uint32_t delay ); [[picoio::on_notify("picoio.token::transfer")]] void on_transfer( picoio::name from, picoio::name to, picoio::asset quantity, const std::string& memo ); [[picoio::on_notify("picoio::onerror")]] void on_error( uint128_t sender_id, picoio::ignore<std::vector<char>> sent_trx ); struct [[picoio::table]] config { picoio::name owner; uint32_t delay = 0; uint32_t next_id = 0; PICOLIB_SERIALIZE( config, (owner)(delay)(next_id) ) }; using config_singleton = picoio::singleton< "config"_n, config >; protected: config_singleton _config; };
29.769231
95
0.606589
[ "vector" ]
a200d31df3644c0e63607fce9e0c48cc387b25b5
2,425
cpp
C++
Source Code/Source/ReturnoftheGorm/FlameObstacle.cpp
creosB/Return-Of-the-Gorm
09f413cf30ae5bd74dd8f8afccf3a2824a82eeb3
[ "MIT" ]
null
null
null
Source Code/Source/ReturnoftheGorm/FlameObstacle.cpp
creosB/Return-Of-the-Gorm
09f413cf30ae5bd74dd8f8afccf3a2824a82eeb3
[ "MIT" ]
null
null
null
Source Code/Source/ReturnoftheGorm/FlameObstacle.cpp
creosB/Return-Of-the-Gorm
09f413cf30ae5bd74dd8f8afccf3a2824a82eeb3
[ "MIT" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. #include "FlameObstacle.h" #include "TimerManager.h" #include "DrawDebugHelpers.h" #include "Kismet/GameplayStatics.h" // Sets default values AFlameObstacle::AFlameObstacle() { // Set this pawn to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; FlameLauncherMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Flame Launcer Mesh")); RootComponent = FlameLauncherMesh; FlameEffect = CreateDefaultSubobject<UNiagaraComponent>(TEXT("Flame Effect")); FlameEffect->SetVisibility(false); FlameEffect->SetupAttachment(FlameLauncherMesh); EffectSpawnPoint = CreateDefaultSubobject<USceneComponent>(TEXT("Effect Spawn Point")); EffectSpawnPoint->SetupAttachment(FlameLauncherMesh); } // Called when the game starts or when spawned void AFlameObstacle::BeginPlay() { Super::BeginPlay(); // Effect location StartLocation = EffectSpawnPoint->GetComponentLocation(); EndLocation = StartLocation + FVector(900, 0, 0); // Cast to player Player = Cast<AContraCharacter>(UGameplayStatics::GetPlayerCharacter(this, 0)); // it's setting timer for effect on-off. GetWorldTimerManager().SetTimer(EffectTimer, this, &AFlameObstacle::EffectLogic, EffectDelay, true, EffectDelay); } // Called every frame void AFlameObstacle::Tick(float DeltaTime) { Super::Tick(DeltaTime); if (EffectSwitch) { EffectOn(); } else { EffectOff(); } } void AFlameObstacle::EffectLogic() { EffectSwitch = !EffectSwitch; } void AFlameObstacle::EffectOn() const { if (Trigger && Trigger->IsOverlappingActor(Player) && EffectSwitch && Player) { FlameEffect->SetVisibility(true); if(EffectHitStart()) { EffectHit(); } } } void AFlameObstacle::EffectOff() const { FlameEffect->SetVisibility(false); } bool AFlameObstacle::EffectHitStart() const { FHitResult Hit; FCollisionQueryParams TraceParams; // sending line trace between end-start GetWorld()->LineTraceSingleByObjectType( OUT Hit, StartLocation, EndLocation, ECC_Pawn, TraceParams ); AActor* ActorHit = Hit.GetActor(); // when hit the pawn and if pawn tag is player, returning true. if (ActorHit && ActorHit->ActorHasTag("Player")) { return true; } else { return false; } } void AFlameObstacle::EffectHit() const { if (Player) { Player->Health -= 0.1f; } }
22.045455
114
0.74433
[ "mesh" ]
a2164f6fe81250e6bc84c956ce7ae28df8e45968
2,979
cpp
C++
temp_save/C++code/Regulation.cpp
ustckun/USTC-Software2013
3b6b037dd96f20301595a153907b7aa635202546
[ "BSD-3-Clause" ]
2
2018-02-01T06:46:32.000Z
2018-02-01T06:46:36.000Z
temp_save/C++code/Regulation.cpp
ustckun/USTC-Software2013
3b6b037dd96f20301595a153907b7aa635202546
[ "BSD-3-Clause" ]
null
null
null
temp_save/C++code/Regulation.cpp
ustckun/USTC-Software2013
3b6b037dd96f20301595a153907b7aa635202546
[ "BSD-3-Clause" ]
2
2017-07-24T06:33:35.000Z
2020-02-10T11:57:01.000Z
// Regulation.cpp // Get regualtion matrix and 166 genes' names // // version 2.0 // change: // 1.add output to txt module // 2.add notation // //********************************************************************************** //this module read TF-TF regualtion from RegulonDB database //transform + - to +1 -1 and 0 if not relationships it will be 2 //filter the name to class TFIM::geneName //********************************************************************************** // //interface: //int getGeneAmount():all gene number //float originalMartix[200][200]:genes' regualtion //A to B 's regulation is originalMatrix[B][A] #include"TFIM.h" #include"Regulation.h" #include"EasytoDebug.h" //input:objexts of TFIM, read name and also get regulation, if file is not open int openFileError will be 1 void Regulation::readName(TFIM geneFirst[]) { ifstream data("TF-TF"); if(!data) { openFileError=1; } else openFileError=0; char ch; int i,num=0; int geneAM; char *Name; char STRING1[N][10]; float originalMA[N][N]; data.get(ch); for(i=0;i<N;) { int a,b; //data.get(ch); while(ch=='#')//filter RegulonDB line { string noUse; getline(data,noUse); data.get(ch); } while(ch!=' ') { STRING1[i][num]=ch; data.get(ch); num++; } STRING1[i][num]='\0'; Name=STRING1[i]; int j; for(j=0;j<i;j++) { strlwr(geneFirst[j].name); strlwr(Name); if(strcmp(geneFirst[j].name,Name)==0) { a=j; j=i+1; } } if(j==i) { geneFirst[i].name=Name; geneFirst[i].putName(); geneFirst[i].geneNumber=i; a=i; i++; } data.get(ch); num=0; while(ch!=' ') { STRING1[i][num]=ch; data.get(ch); num++; } STRING1[i][num]='\0'; Name=STRING1[i]; for(j=0;j<i;j++) { strlwr(geneFirst[j].name); strlwr(Name); if(strcmp(geneFirst[j].name,Name)==0) { b=j; j=i+1; } } if(j==i) { geneFirst[i].name=Name; geneFirst[i].putName(); geneFirst[i].geneNumber=i; b=i; i++; } //geneFirst[i].putName(); data.get(ch); if(ch=='-') { if(originalMA[b][a]==1||originalMA[b][a]==0) { originalMA[b][a]=0; } else originalMA[b][a]=-1; } else if(ch=='+') { data.get(ch); if(ch=='-') originalMA[b][a]=0; else originalMA[b][a]=1; } else originalMA[b][a]=2; string noUse; getline(data,noUse); num=0; if(!data.get(ch)) { geneAM=i; i=N; } } memcpy((char *)originalMatrix,(char *)originalMA,sizeof(float)*N*N); //originalMatrix=originalMA; geneAmount=geneAM; } //full fill the matrix with 2 void Regulation::fullFill() { float a; int n; // a=originalMatrix[0][0]; for(n=0;n<N;n++) { for(int m=0;m<N;m++) { a=originalMatrix[m][n]; if(a!=1.0&&a!=0.0&&a!=-1.0&&a!=2.0) { originalMatrix[m][n]=2; } } } } //get amount of genes int Regulation::getGeneAmount() { return geneAmount; } //know is file opened int Regulation::getOpenError() { return openFileError; }
17.219653
107
0.556227
[ "transform" ]
a218413d0b66813c6ad49144c889cac5eeb7e0d6
974
hpp
C++
include/preprocessing/import_charger_geojson.hpp
TheMarex/charge
85e35f7a6c8b8c161ecd851124d1363d5a450573
[ "BSD-2-Clause" ]
13
2018-03-09T14:37:31.000Z
2021-07-27T06:56:35.000Z
include/preprocessing/import_charger_geojson.hpp
AlexBlazee/charge
85e35f7a6c8b8c161ecd851124d1363d5a450573
[ "BSD-2-Clause" ]
null
null
null
include/preprocessing/import_charger_geojson.hpp
AlexBlazee/charge
85e35f7a6c8b8c161ecd851124d1363d5a450573
[ "BSD-2-Clause" ]
10
2018-04-14T02:27:32.000Z
2021-06-13T23:30:44.000Z
#ifndef CHARGE_PREPROCESSING_IMPORT_GEOJSON_HPP #define CHARGE_PREPROCESSING_IMPORT_GEOJSON_HPP #include "common/nearest_neighbour.hpp" #include <json.hpp> namespace charge::preprocessing { auto charger_from_geojson(const nlohmann::json &feature_collection, const std::vector<common::Coordinate> &coordinates) { std::vector<double> chargers(coordinates.size(), 0.0); common::NearestNeighbour<> nn(coordinates); for (const auto &f : feature_collection["features"]) { common::Coordinate c = common::Coordinate::from_floating(f["geometry"]["coordinates"][0], f["geometry"]["coordinates"][1]); auto min = nn.nearest(c); auto dist = common::haversine_distance(coordinates[min], c); if (dist < 500) { chargers[min] = f["properties"]["rate"]; } } return chargers; } } // namespace charge::preprocessing #endif
31.419355
98
0.629363
[ "geometry", "vector" ]
a21aaf8d4382a619094c87854084aebe9fa26b5c
9,142
cpp
C++
src/modules/statistics/statisticcontroller.cpp
565353780/railway-catenary-detect
edc32da2613a9f38febf2b6efa11fa64fdc31dac
[ "MIT" ]
null
null
null
src/modules/statistics/statisticcontroller.cpp
565353780/railway-catenary-detect
edc32da2613a9f38febf2b6efa11fa64fdc31dac
[ "MIT" ]
null
null
null
src/modules/statistics/statisticcontroller.cpp
565353780/railway-catenary-detect
edc32da2613a9f38febf2b6efa11fa64fdc31dac
[ "MIT" ]
null
null
null
#include "statisticcontroller.h" #include "services/SqlTable/SqlRecordCountTableModel.h" #include "modules/railwayCatenaryDataManager/railwaycatenarydatamanager.h" StatisticController::StatisticController(QObject *parent, RailwayCatenaryDataManager *database_manager) : QObject(parent), database_manager_(database_manager) { init(); } StatisticController::~StatisticController() {} void StatisticController::loadConfig(QJsonObject rootobj) { // do configuration // 属性过滤配置 if (rootobj.contains("StatisticsFilter")) { statistics_filter_field_ = rootobj.value("StatisticsFilter").toObject(); } // label表表头配置 if (rootobj.contains("Area")) { statistics_label_dict_ = rootobj.value("Area").toObject().value("labelDict").toObject(); initTableLabel(); updateTableLabelData(); } } void StatisticController::loadConfig(QString filename) { QFile loadFile(filename); if (!loadFile.open(QIODevice::ReadOnly)) { qDebug() << "could't open statistics_config.json"; return; } QByteArray allData = loadFile.readAll(); loadFile.close(); QJsonParseError json_error; QJsonDocument jsonDoc(QJsonDocument::fromJson(allData, &json_error)); if (json_error.error != QJsonParseError::NoError) { qDebug() << "statistic_config json error!" << json_error.error; return; } loadConfig(jsonDoc.object()); } void StatisticController::loadConfig(QString filename, QString tablename) { loadConfig(filename); } void StatisticController::set_standard_4c2c(QString name) { standard_4c2c_ = name; } void StatisticController::init() { database_ = database_manager_->database(); initTableLabel(); updateTableLabelData(); updatePieViewData(); updateAttributeFilterData(); } void StatisticController::initTableLabel() { SqlRecordCountTableModel *currentModel = new SqlRecordCountTableModel(this); table_label_header_title_.clear(); table_label_header_role_.clear(); QVariantList value; if (statistics_label_dict_.size() > 0) { QJsonArray labelArray = statistics_label_dict_[0].toObject().value("options").toArray(); for (int col_i = 0; col_i < labelArray.size(); col_i++) { QJsonArray label = labelArray[col_i].toArray(); currentModel->insertColumn(col_i); currentModel->setColumn(col_i, label[0].toString()); table_label_header_title_ << label[1].toString(); table_label_header_role_ << label[0].toString(); value << "0"; } } else { QSqlQueryModel model; QStringList result_columns; QString condition; QString tablename = "Standard"; table_label_header_title_.clear(); table_label_header_role_.clear(); // "select LabelNum, LabelTitle from Standard where name = '2C'" result_columns << "LabelNum" << "LabelTitle"; condition = "where name = '" + standard_4c2c_ + "'"; database_manager_->getQueryResult(model, result_columns, tablename, QJsonArray(), condition); int totalCounts = model.rowCount(); qDebug() << "totalCounts = " << totalCounts; if (totalCounts > 0) { QStringList titles = model.record(0).value(1).toString().split(";"); label_title_num_ = titles.size(); for (int col_i = 0; col_i < titles.size(); col_i++) { currentModel->insertColumn(col_i); currentModel->setColumn(col_i, QString::number(col_i)); table_label_header_title_ << titles[col_i]; table_label_header_role_ << QString::number(col_i); value << "0"; } } } currentModel->insertRow(0); currentModel->setRow(0, QString::number(0), value); table_model_label_ = currentModel; } void StatisticController::updateTableLabelData() { QVariantList value; for (int col_i = 0; col_i < label_title_num_; col_i++) { value << "0"; } // "select count(Predict_00) from Pic_2C where Predict_00 > 0" for (int col_i = 0; col_i < label_title_num_; col_i++) { QSqlQueryModel model; QString columname = "Predict_" + QString::number(col_i).rightJustified(2,'0'); QString condition = "where " + columname + " > 0"; QStringList result_columns; result_columns << "count(" + columname + ")"; database_manager_->getQueryResult(model, result_columns, "Pic_" + standard_4c2c_, user_filter_, condition); value[col_i] = model.record(0).value(0).toString(); } qDebug() << "model value = " << value; table_model_label_->setRow(0, QString::number(0), value); } void StatisticController::updatePieViewData() { QSqlQueryModel model_bad; QSqlQueryModel model_ok; QStringList result_columns; QString condition; QString tablename = "Pic_" + standard_4c2c_; // "select count(*) from Pic_2C where PredictResult = ReviewResult" result_columns << "count(*)"; condition = "where PredictResult = 1"; database_manager_->getQueryResult(model_ok, result_columns, tablename, user_filter_, condition); // "select count(*) from Pic_2C where PredictResult != ReviewResult" //condition = "where PredictResult != ReviewResult"; condition = "where PredictResult = 2"; database_manager_->getQueryResult(model_bad, result_columns, tablename, user_filter_, condition); pie_view_badnum_ = model_bad.record(0).value(0).toInt(); pie_view_oknum_ = model_ok.record(0).value(0).toInt(); } void StatisticController::updateData() { qDebug() << label_title_num_; if (label_title_num_ == 0) { initTableLabel(); } updateTableLabelData(); updatePieViewData(); updateAttributeFilterData(); } void StatisticController::updateUserFilter(QString attributeFilter, QString beginDate, QString endDate) { user_attribute_filter_ = attributeFilter; user_begin_date_ = beginDate; user_end_date_ = endDate; QJsonArray userFilter; if (beginDate.size() > 0 && endDate.size() > 0) { QJsonObject condition_beginDate; QJsonObject condition_endDate; condition_beginDate.insert("key", "Time"); condition_beginDate.insert("operator", ">="); condition_beginDate.insert("value", beginDate); condition_endDate.insert("key", "Time"); condition_endDate.insert("operator", "<="); condition_endDate.insert("value", endDate); userFilter.push_back(condition_beginDate); userFilter.push_back(condition_endDate); } if (user_attribute_filter_.size() > 0) { QList<QString> list = attributeFilter.split(","); foreach(QString value, list) { QList<QString> kv = value.split(":"); QJsonObject condition_attr; condition_attr.insert("key", kv[0]); condition_attr.insert("operator", "="); condition_attr.insert("value", kv[1]); userFilter.push_back(condition_attr); user_attribute_filter_obj_ = condition_attr; } } user_filter_ = userFilter; } QList<int>StatisticController::getPieViewInfo() { QList<int> info; info.push_back(pie_view_badnum_); info.push_back(pie_view_oknum_); return info; } SqlRecordCountTableModel * StatisticController::getTableLabelData() { return table_model_label_; } QVariantList StatisticController::getTableLabelHeaderTitle() { return table_label_header_title_; } QVariantList StatisticController::getTableLabelHeaderRole() { return table_label_header_role_; } void StatisticController::updateAttributeFilterData() { QSqlQuery query(*database_); QJsonObject result; foreach(QString field, statistics_filter_field_.keys()) { QJsonObject fieldObj; fieldObj.insert("role", field); fieldObj.insert("title", statistics_filter_field_.value(field)); QString command = QString("SELECT DISTINCT %1 FROM AOIPart WHERE( (Time >= '%2') and (Time <= '%3') )").arg(field).arg(user_begin_date_).arg(user_end_date_); query.exec(command); QSqlRecord record = query.record(); QJsonArray array; array.append(tr("ALL")); while (query.next()) { array.append(query.value(field).toJsonValue()); } fieldObj.insert("values", array); result.insert(field, fieldObj); } attribute_filter_jsonobj_ = result; } QJsonObject StatisticController::getAttributeFilterData() const { return attribute_filter_jsonobj_; }
30.575251
166
0.628746
[ "object", "model" ]
b8c79866017dc90d53615eea555af3b103b53b67
425
cpp
C++
sandbox/src/emptyscene.cpp
trbflxr/x808
d5ab9e96c5a6109283151a591c261e4183628075
[ "MIT" ]
null
null
null
sandbox/src/emptyscene.cpp
trbflxr/x808
d5ab9e96c5a6109283151a591c261e4183628075
[ "MIT" ]
null
null
null
sandbox/src/emptyscene.cpp
trbflxr/x808
d5ab9e96c5a6109283151a591c261e4183628075
[ "MIT" ]
null
null
null
// // Created by FLXR on 3/21/2019. // #include "emptyscene.hpp" using namespace xe; EmptyScene::EmptyScene() { } EmptyScene::~EmptyScene() { } void EmptyScene::render() { } void EmptyScene::renderImGui() { } void EmptyScene::update(float delta) { } void EmptyScene::fixedUpdate(float delta) { } void EmptyScene::input(Event &event) { if (event.key.code == Keyboard::Escape) { Application::exit(); } }
11.184211
43
0.658824
[ "render" ]
b8ccdb36edffd51d55a70e9fce5ee120d255f54b
4,558
hpp
C++
src/Omega_h_input.hpp
overfelt/omega_h
dfc19cc3ea0e183692ca6c548dda39f7892301b5
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
src/Omega_h_input.hpp
overfelt/omega_h
dfc19cc3ea0e183692ca6c548dda39f7892301b5
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
src/Omega_h_input.hpp
overfelt/omega_h
dfc19cc3ea0e183692ca6c548dda39f7892301b5
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
#ifndef OMEGA_H_INPUT_HPP #define OMEGA_H_INPUT_HPP #include <memory> #include <string> #include <vector> namespace Omega_h { struct Input { Input() : parent(nullptr), used(false) {} Input* parent; bool used; }; inline bool is_type<InputType>(Input& input) { auto ptr_in = &input; auto ptr_out = dynamic_cast<InputType*>(ptr_in); return ptr_out != nullptr; } inline InputType& as_type<InputType>(Input& input) { return dynamic_cast<InputType&>(input); } template <class ScalarType> struct ScalarInput : public Input { ScalarInput(ScalarType value_in) : value(value_in) {} ScalarType value; }; struct NamedInput : public Input { NamedInput(std::string const& name_in, Input* value_in) : name(name_in), value(value_in) {} std::string name; std::unique_ptr<Input> value; }; struct MapInput : public Input; struct ListInput : public Input; template <class InputType> InputType& get_input(Input& input) { auto out = as_type<InputType>(input); out.used = true; return out; } struct MapInput : public Input { std::vector<std::unique_ptr<NamedInput>> entries; std::rb_tree<std::string, NamedInput*, NameOfNamedInput> by_name; void add(NamedInput* named_input) { auto it = by_name.upper_bound(named_input->name); if (it != by_name.end() && (*it)->name == named_input->name) { fail( "Tried to add a mapped input value of name \"%s\" that already " "existed\n", named_input->name.c_str()); } std::unique_ptr<NamedInput> uptr(named_input); entries.push_back(std::move(uptr)); by_name.insert(it, named_input); } template <class InputType> bool is_input(std::string const& name) { auto it = by_name.find(name); if (it == by_name.end()) return false; auto& uptr = *it; return is_type(*uptr); } template <class ScalarType> bool is(std::string const& name) { return is_input<ScalarInput<ScalarType>>(name); } bool is_map(std::string const& name) { return is_input<MapInput>(name); } bool is_list(std::string const& name) { return is_input<ListInput>(name); } Input& get_named_input(std::string const& name) { auto it = by_name.find(name); if (it == by_name.end()) { auto s = get_full_name(*this) + name; fail("Tried to get named input \"%s\" that doesn't exist\n", s.c_str()); } auto& named_uptr = *it; auto& value_uptr = named_uptr->value; return *value_uptr; } template <class InputType> InputType& get_input(std::string const& name) { return Omega_h::get_input<InputType>(get_named_input(name)); } template <class ScalarType> ScalarType& get(std::string const& name) { return this->get_input<ScalarInput<ScalarType>>(name).value; } MapInput& get_map(std::string const& name) { return this->get_input<MapInput>(name).value; } ListInput& get_list(std::string const& name) { return this->get_input<ListInput>(name).value; } template <class ScalarType> ScalarType& get(std::string const& name, ScalarType const& default_value) { if (has_input<ScalarInput<ScalarType>>(name)) return this->get<ScalarType>(name); this->add(new NamedInput(name, new ScalarInput<ScalarType>(default_value))); } }; struct ListInput : public Input { std::vector<std::unique_ptr<Input>> entries; std::size_t position(Input& input) { auto it = std::find(entries.begin(), entries.end(), [&](std::unique_ptr<Input> const& uptr) { return uptr.get() == &input; }); OMEGA_H_CHECK(it != entries.end()); return it - entries.begin(); } LO size() { return LO(entries.size()); } template <class InputType> bool is_input(LO i) { return Omega_h::is_type<InputType>(*(entries[std::size_t(i)])); } template <class InputType> InputType& get_input(LO i) { return Omega_h::get_input<InputType>(*(entries[std::size_t(i)])); } template <class ScalarType> ScalarType& get_input(LO i) { return Omega_h::get_input<InputType>(*(entries[std::size_t(i)])); } }; std::string get_full_name(Input& input) { std::string full_name; if (input.parent != nullptr) { auto& parent = *(input.parent); full_name = get_full_name(parent); if (is_type<ListInput>(parent)) { auto i = as_type<ListInput>(parent).position(input); full_name += "["; full_name += std::to_string(i); full_name += "]"; } } if (is_type<NamedInput>(input)) { if (!full_name.empty()) full_name += "."; full_name += as_type<NamedInput>(input).name; } } }; // namespace Omega_h #endif
29.406452
80
0.665204
[ "vector" ]
b8d255895cef21170f57157bcbc19f33e345bba7
2,187
cpp
C++
src/rynx/editor/tools/instantiate_tool.cpp
Apodus/rynx
3e1babc2f2957702ba2b09d78be3a959f2f4ea18
[ "MIT" ]
11
2019-08-19T08:44:14.000Z
2020-09-22T20:04:46.000Z
src/rynx/editor/tools/instantiate_tool.cpp
Apodus/rynx
3e1babc2f2957702ba2b09d78be3a959f2f4ea18
[ "MIT" ]
null
null
null
src/rynx/editor/tools/instantiate_tool.cpp
Apodus/rynx
3e1babc2f2957702ba2b09d78be3a959f2f4ea18
[ "MIT" ]
null
null
null
#include <rynx/editor/tools/instantiate_tool.hpp> #include <rynx/menu/FileSelector.hpp> #include <rynx/math/geometry/ray.hpp> #include <rynx/math/geometry/plane.hpp> #include <rynx/tech/filesystem/filesystem.hpp> #include <rynx/tech/ecs.hpp> #include <rynx/graphics/texture/texturehandler.hpp> rynx::editor::tools::instantiation_tool::instantiation_tool(rynx::scheduler::context& ctx) { m_frame_tex_id = ctx.get_resource<rynx::graphics::GPUTextures>().findTextureByName("frame"); } void rynx::editor::tools::instantiation_tool::update(rynx::scheduler::context& ctx) { auto& input = ctx.get_resource<rynx::mapped_input>(); if (input.isKeyClicked(input.getMouseKeyPhysical(0))) { auto& gameCam = ctx.get_resource<rynx::camera>(); auto& ecs = ctx.get_resource<rynx::ecs>(); auto& reflections = ctx.get_resource<rynx::reflection::reflections>(); auto [point, hit] = input.mouseRay(gameCam).intersect(rynx::plane(0, 0, 1, 0)); // if mouse clicked the z-plane if (hit) { point.z = 0; // the floating point calculations are not 100% accurate, so fix the z value. rynx::serialization::vector_reader reader(rynx::filesystem::read_file(m_selectedScene)); auto ids = ecs.deserialize(reflections, reader); // translate to cursor for (auto id : ids) { auto* pos = ecs[id].try_get<rynx::components::position>(); if (pos) { pos->value += point; auto* boundary = ecs[id].try_get<rynx::components::boundary>(); if (boundary) { boundary->update_world_positions(pos->value, pos->angle); } } } } } } void rynx::editor::tools::instantiation_tool::on_tool_selected() { execute([this]() { auto fileselector = std::make_shared<rynx::menu::FileSelector>(m_frame_tex_id, rynx::vec3f(0.5f, 0.5f, 0.0f)); fileselector->file_type(".rynxscene"); fileselector->configure().m_allowNewFile = false; fileselector->configure().m_allowNewDir = false; m_editor_state->m_editor->push_popup(fileselector); fileselector->display( "../scenes/", [this](std::string filePath) { m_selectedScene = filePath; execute([this]() { m_editor_state->m_editor->pop_popup(); }); }, [](std::string dirPath) {} ); }); }
33.136364
112
0.698217
[ "geometry" ]
b8dd47e5b8a644e78a5f112d75daaab6c28afb1b
130,931
cpp
C++
blazetest/src/mathtest/dilatedsubmatrix/DenseTest1.cpp
igl42/blaze_tensor
f6a7ab2ae69ff52af32fdfabeaad53787d01bca0
[ "Unlicense" ]
30
2018-11-26T09:33:55.000Z
2021-12-21T21:19:58.000Z
blazetest/src/mathtest/dilatedsubmatrix/DenseTest1.cpp
igl42/blaze_tensor
f6a7ab2ae69ff52af32fdfabeaad53787d01bca0
[ "Unlicense" ]
31
2018-12-01T19:41:57.000Z
2020-08-06T12:03:38.000Z
blazetest/src/mathtest/dilatedsubmatrix/DenseTest1.cpp
igl42/blaze_tensor
f6a7ab2ae69ff52af32fdfabeaad53787d01bca0
[ "Unlicense" ]
6
2019-03-07T17:04:08.000Z
2021-06-28T22:15:19.000Z
//================================================================================================= /*! // \file src/mathtest/dilatedsubmatrix/DenseTest1.cpp // \brief Source file for the dilatedsubmatrix dense aligned test // // Copyright (C) 2012-2019 Klaus Iglberger - All Rights Reserved // Copyright (C) 2018-2019 Hartmut Kaiser - All Rights Reserved // Copyright (C) 2019 Bita Hasheminezhad - All Rights Reserved // // This file is part of the Blaze library. You can redistribute it and/or modify it under // the terms of the New (Revised) BSD License. Redistribution and use in source and binary // forms, with or without modification, are permitted provided that the following conditions // are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other materials // provided with the distribution. // 3. Neither the names of the Blaze development group nor the names of its contributors // may be used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT // SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED // TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR // BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. */ //================================================================================================= //************************************************************************************************* // Includes //************************************************************************************************* #include <cstdlib> #include <iostream> #include <memory> #include <blaze/math/CompressedMatrix.h> #include <blaze/math/CustomMatrix.h> #include <blaze/math/DynamicMatrix.h> #include <blaze/math/Views.h> #include <blaze/util/Memory.h> #include <blaze/util/policies/Deallocate.h> #include <blaze/util/typetraits/AlignmentOf.h> #include <blazetest/mathtest/RandomMaximum.h> #include <blazetest/mathtest/RandomMinimum.h> #include <blazetest/mathtest/dilatedsubmatrix/DenseTest.h> #ifdef BLAZE_USE_HPX_THREADS # include <hpx/hpx_main.hpp> #endif namespace blazetest { namespace mathtest { namespace dilatedsubmatrix { //================================================================================================= // // CONSTRUCTORS // //================================================================================================= //************************************************************************************************* /*!\brief Constructor for the dilatedsubmatrix dense aligned test. // // \exception std::runtime_error Operation error detected. */ DenseTest::DenseTest() : mat1_ ( 64UL, 64UL ) , mat2_ ( 64UL, 64UL ) , tmat1_( 64UL, 64UL ) , tmat2_( 64UL, 64UL ) { testConstructors(); testAssignment(); testAddAssign(); testSubAssign(); testSchurAssign(); testMultAssign(); } //************************************************************************************************* //================================================================================================= // // TEST FUNCTIONS // //================================================================================================= //************************************************************************************************* /*!\brief Test of the dilatedsubmatrix constructors. // // \return void // \exception std::runtime_error Error detected. // // This function performs a test of all constructors of the dilatedsubmatrix specialization. // In case an error is detected, a \a std::runtime_error exception is thrown. */ void DenseTest::testConstructors() { using blaze::dilatedsubmatrix; //===================================================================================== // Row-major dilatedsubmatrix tests //===================================================================================== { test_ = "Row-major dilatedsubmatrix constructor"; initialize(); const size_t alignment = blaze::AlignmentOf<int>::value; for( size_t row=0UL; row<mat1_.rows(); row+=alignment ) { for( size_t column=0UL; column<mat1_.columns(); column+=alignment ) { for( size_t maxm=0UL; ; maxm+=alignment ) { for( size_t maxn=0UL; ; maxn+=alignment ) { size_t m( blaze::min( maxm, mat1_.rows()-row ) ); size_t n( blaze::min( maxn, mat1_.columns()-column ) ); for (size_t rowdilation = 1UL; rowdilation < maxm; ++rowdilation) { for (size_t columndilation = 1UL; columndilation < maxn; ++columndilation) { while( row + (m - 1) * rowdilation >= mat1_.rows() ) --m; while( column + (n - 1) * columndilation >= mat1_.columns() ) --n; auto row_indices = generate_indices( row, m, rowdilation ); auto column_indices = generate_indices( column, n, columndilation ); const RCMT sm1 = blaze::rows( blaze::columns( mat1_, column_indices.data(), column_indices.size() ), row_indices.data(), row_indices.size() ); const DSMT sm2 = dilatedsubmatrix(mat2_, row, column, m, n, rowdilation, columndilation); if (sm1 != sm2) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Setup of dense dilatedsubmatrix failed\n" << " Details:\n" << " Index of first row = " << row << "\n" << " Index of first column = " << column << "\n" << " Number of rows = " << m << "\n" << " Number of columns = " << n << "\n" << " dilatedsubmatrix:\n" << sm1 << "\n" << " Reference:\n" << sm2 << "\n"; throw std::runtime_error(oss.str()); } } } if( column+maxn > mat1_.columns() ) break; } if( row+maxm > mat1_.rows() ) break; } } } } //===================================================================================== // Column-major dilatedsubmatrix tests //===================================================================================== { test_ = "Column-major dilatedsubmatrix constructor"; initialize(); const size_t alignment = blaze::AlignmentOf<int>::value; for( size_t column=0UL; column<mat1_.columns(); column+=alignment ) { for( size_t row=0UL; row<mat1_.rows(); row+=alignment ) { for( size_t maxn=0UL; ; maxn+=alignment ) { for( size_t maxm=0UL; ; maxm+=alignment ) { size_t n( blaze::min( maxn, mat1_.columns()-column ) ); size_t m( blaze::min( maxm, mat1_.rows()-row ) ); for (size_t columndilation = 1UL; columndilation < maxn; ++columndilation) { for (size_t rowdilation = 1UL; rowdilation < maxm; ++rowdilation) { while( column + (n - 1) * columndilation >= mat1_.columns() ) --n; while( row + (m - 1) * rowdilation >= mat1_.rows() ) --m; auto column_indices = generate_indices( column, n, columndilation ); auto row_indices = generate_indices( row, m, rowdilation ); const OCRMT sm1 = blaze::columns( blaze::rows( tmat1_, row_indices.data(), row_indices.size() ), column_indices.data(), column_indices.size() ); const ODSMT sm2 = dilatedsubmatrix(tmat2_, row, column, m, n, rowdilation, columndilation); if( sm1 != sm2 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Setup of dense dilatedsubmatrix failed\n" << " Details:\n" << " Index of first row = " << row << "\n" << " Index of first column = " << column << "\n" << " Number of rows = " << m << "\n" << " Number of columns = " << n << "\n" << " dilatedsubmatrix:\n" << sm1 << "\n" << " Reference:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } } if( row+maxm > mat1_.rows() ) break; } if( column+maxn > mat1_.columns() ) break; } } } } } ////************************************************************************************************* //************************************************************************************************* /*!\brief Test of the dilatedsubmatrix assignment operators. // // \return void // \exception std::runtime_error Error detected. // // This function performs a test of all assignment operators of the dilatedsubmatrix specialization. // In case an error is detected, a \a std::runtime_error exception is thrown. */ void DenseTest::testAssignment() { using blaze::dilatedsubmatrix; using blaze::padded; using blaze::unpadded; using blaze::rowMajor; using blaze::columnMajor; using blaze::initializer_list; //===================================================================================== // Row-major homogeneous assignment //===================================================================================== { test_ = "Row-major dilatedsubmatrix homogeneous assignment"; initialize(); // Assigning to a 8x4 dilatedsubmatrix with a 2x3 dilation { auto row_indices = generate_indices( 8UL, 8UL, 2UL ); auto column_indices = generate_indices( 16UL, 4UL, 3UL ); RCMT sm1 = blaze::rows( blaze::columns( mat1_, column_indices.data(), column_indices.size() ), row_indices.data(), row_indices.size() ); DSMT sm2 = dilatedsubmatrix( mat2_, 8UL, 16UL, 8UL, 4UL, 2UL, 3UL ); sm1 = 12; sm2 = 12; checkRows ( sm1, 8UL ); checkColumns( sm1, 4UL ); checkRows ( sm2, 8UL ); checkColumns( sm2, 4UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } // Assigning to a 16x8 dilatedsubmatrix { auto row_indices = generate_indices( 8UL, 16UL, 3UL ); auto column_indices = generate_indices( 16UL, 8UL, 2UL ); RCMT sm1 = blaze::rows( blaze::columns( mat1_, column_indices.data(), column_indices.size() ), row_indices.data(), row_indices.size() ); DSMT sm2 = dilatedsubmatrix ( mat2_, 8UL, 16UL, 16UL, 8UL, 3UL, 2UL ); sm1 = 15; sm2 = 15; checkRows ( sm1, 16UL ); checkColumns( sm1, 8UL ); checkRows ( sm2, 16UL ); checkColumns( sm2, 8UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } } //===================================================================================== // Row-major list assignment //===================================================================================== { test_ = "Row-major initializer list assignment (complete list)"; initialize(); auto row_indices = generate_indices( 8UL, 8UL, 3UL ); auto column_indices = generate_indices( 16UL, 16UL, 2UL ); RCMT sm1 = blaze::rows( blaze::columns( mat1_, column_indices.data(), column_indices.size() ), row_indices.data(), row_indices.size() ); DSMT sm2 = dilatedsubmatrix( mat2_, 8UL, 16UL, 8UL, 16UL, 3UL, 2UL ); initializer_list< initializer_list<int> > list = { { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }, { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32 }, { 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48 }, { 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 60, 64 }, { 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80 }, { 6, 12, 18, 24, 30, 36, 42, 48, 54, 60, 66, 72, 78, 86, 92, 98 }, { 7, 14, 21, 28, 35, 42, 49, 56, 63, 70, 77, 84, 91, 98, 105, 112 }, { 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 96, 104, 112, 120, 128 } }; sm1 = list; sm2 = list; checkRows ( sm1, 8UL ); checkColumns( sm1, 16UL ); checkRows ( sm2, 8UL ); checkColumns( sm2, 16UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } { test_ = "Row-major initializer list assignment (incomplete list)"; initialize(); auto row_indices = generate_indices( 8UL, 8UL, 3UL ); auto column_indices = generate_indices( 16UL, 16UL, 2UL ); RCMT sm1 = blaze::rows( blaze::columns( mat1_, column_indices.data(), column_indices.size() ), row_indices.data(), row_indices.size() ); DSMT sm2 = dilatedsubmatrix( mat2_, 8UL, 16UL, 8UL, 16UL, 3UL, 2UL ); initializer_list< initializer_list<int> > list = { { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }, { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28 }, { 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36 }, { 4, 8, 12, 16, 20, 24, 28, 32, 36, 40 }, { 5, 10, 15, 20, 25, 30, 35, 40 }, { 6, 12, 18, 24, 30, 36 }, { 7, 14, 21, 28 }, { 8, 16 } }; sm1 = list; sm2 = list; checkRows ( sm1, 8UL ); checkColumns( sm1, 16UL ); checkRows ( sm2, 8UL ); checkColumns( sm2, 16UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Row-major copy assignment //===================================================================================== { test_ = "Row-major dilatedsubmatrix copy assignment (no aliasing)"; initialize(); MT mat1( 64UL, 64UL ); MT mat2( 64UL, 64UL ); randomize( mat1, int(randmin), int(randmax) ); mat2 = mat1; auto row_indices = generate_indices( 8UL, 8UL, 3UL ); auto column_indices = generate_indices( 16UL, 16UL, 2UL ); RCMT sm1 = blaze::rows( blaze::columns( mat1_, column_indices.data(), column_indices.size() ), row_indices.data(), row_indices.size() ); DSMT sm2 = dilatedsubmatrix( mat2_, 8UL, 16UL, 8UL, 16UL, 3UL, 2UL ); sm1 = dilatedsubmatrix( mat1, 8UL, 16UL, 8UL, 16UL, 3UL, 2UL ); sm2 = dilatedsubmatrix( mat2, 8UL, 16UL, 8UL, 16UL, 3UL, 2UL ); checkRows ( sm1, 8UL ); checkColumns( sm1, 16UL ); checkRows ( sm2, 8UL ); checkColumns( sm2, 16UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } { test_ = "Row-major dilatedsubmatrix copy assignment (aliasing)"; initialize(); auto row_indices = generate_indices( 8UL, 8UL, 3UL ); auto column_indices = generate_indices( 16UL, 16UL, 2UL ); RCMT sm1 = blaze::rows( blaze::columns( mat1_, column_indices.data(), column_indices.size() ), row_indices.data(), row_indices.size() ); DSMT sm2 = dilatedsubmatrix( mat2_, 8UL, 16UL, 8UL, 16UL, 3UL, 2UL ); sm1 = dilatedsubmatrix( mat1_, 12UL, 16UL, 8UL, 16UL, 3UL, 2UL ); sm2 = dilatedsubmatrix( mat2_, 12UL, 16UL, 8UL, 16UL, 3UL, 2UL ); checkRows ( sm1, 8UL ); checkColumns( sm1, 16UL ); checkRows ( sm2, 8UL ); checkColumns( sm2, 16UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Row-major dense matrix assignment //===================================================================================== { test_ = "Row-major/row-major dense matrix assignment (mixed type)"; initialize(); auto row_indices = generate_indices( 8UL, 8UL, 3UL ); auto column_indices = generate_indices( 16UL, 16UL, 2UL ); RCMT sm1 = blaze::rows( blaze::columns( mat1_, column_indices.data(), column_indices.size() ), row_indices.data(), row_indices.size() ); DSMT sm2 = dilatedsubmatrix( mat2_, 8UL, 16UL, 8UL, 16UL, 3UL, 2UL ); blaze::DynamicMatrix<short,rowMajor> mat( 8UL, 16UL ); randomize( mat, short(randmin), short(randmax) ); sm1 = mat; sm2 = mat; checkRows ( sm1, 8UL ); checkColumns( sm1, 16UL ); checkRows ( sm2, 8UL ); checkColumns( sm2, 16UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } { test_ = "Row-major/row-major dense matrix assignment (aligned/padded)"; initialize(); auto row_indices = generate_indices( 8UL, 8UL, 3UL ); auto column_indices = generate_indices( 16UL, 16UL, 2UL ); RCMT sm1 = blaze::rows( blaze::columns( mat1_, column_indices.data(), column_indices.size() ), row_indices.data(), row_indices.size() ); DSMT sm2 = dilatedsubmatrix( mat2_, 8UL, 16UL, 8UL, 16UL, 3UL, 2UL ); using AlignedPadded = blaze::CustomMatrix<int,blaze::aligned,padded,rowMajor>; std::unique_ptr<int[],blaze::Deallocate> memory( blaze::allocate<int>( 128UL ) ); AlignedPadded mat( memory.get(), 8UL, 16UL, 16UL ); randomize( mat, int(randmin), int(randmax) ); sm1 = mat; sm2 = mat; checkRows ( sm1, 8UL ); checkColumns( sm1, 16UL ); checkRows ( sm2, 8UL ); checkColumns( sm2, 16UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } { test_ = "Row-major/row-major dense matrix assignment (unaligned/unpadded)"; initialize(); auto row_indices = generate_indices( 8UL, 8UL, 3UL ); auto column_indices = generate_indices( 16UL, 16UL, 2UL ); RCMT sm1 = blaze::rows( blaze::columns( mat1_, column_indices.data(), column_indices.size() ), row_indices.data(), row_indices.size() ); DSMT sm2 = dilatedsubmatrix( mat2_, 8UL, 16UL, 8UL, 16UL, 3UL, 2UL ); using UnalignedUnpadded = blaze::CustomMatrix<int,blaze::unaligned,unpadded,rowMajor>; std::unique_ptr<int[]> memory( new int[129UL] ); UnalignedUnpadded mat( memory.get()+1UL, 8UL, 16UL ); randomize( mat, int(randmin), int(randmax) ); sm1 = mat; sm2 = mat; checkRows ( sm1, 8UL ); checkColumns( sm1, 16UL ); checkRows ( sm2, 8UL ); checkColumns( sm2, 16UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } { test_ = "Row-major/column-major dense matrix assignment (mixed type)"; initialize(); auto row_indices = generate_indices( 8UL, 8UL, 3UL ); auto column_indices = generate_indices( 16UL, 16UL, 2UL ); RCMT sm1 = blaze::rows( blaze::columns( mat1_, column_indices.data(), column_indices.size() ), row_indices.data(), row_indices.size() ); DSMT sm2 = dilatedsubmatrix( mat2_, 8UL, 16UL, 8UL, 16UL, 3UL, 2UL ); blaze::DynamicMatrix<short,columnMajor> mat( 8UL, 16UL ); randomize( mat, short(randmin), short(randmax) ); sm1 = mat; sm2 = mat; checkRows ( sm1, 8UL ); checkColumns( sm1, 16UL ); checkRows ( sm2, 8UL ); checkColumns( sm2, 16UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } { test_ = "Row-major/column-major dense matrix assignment (aligned/padded)"; initialize(); auto row_indices = generate_indices( 8UL, 8UL, 3UL ); auto column_indices = generate_indices( 16UL, 16UL, 2UL ); RCMT sm1 = blaze::rows( blaze::columns( mat1_, column_indices.data(), column_indices.size() ), row_indices.data(), row_indices.size() ); DSMT sm2 = dilatedsubmatrix( mat2_, 8UL, 16UL, 8UL, 16UL, 3UL, 2UL ); using AlignedPadded = blaze::CustomMatrix<int,blaze::aligned,padded,columnMajor>; std::unique_ptr<int[],blaze::Deallocate> memory( blaze::allocate<int>( 256UL ) ); AlignedPadded mat( memory.get(), 8UL, 16UL, 16UL ); randomize( mat, int(randmin), int(randmax) ); sm1 = mat; sm2 = mat; checkRows ( sm1, 8UL ); checkColumns( sm1, 16UL ); checkRows ( sm2, 8UL ); checkColumns( sm2, 16UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } { test_ = "Row-major/column-major dense matrix assignment (unaligned/unpadded)"; initialize(); auto row_indices = generate_indices( 8UL, 8UL, 3UL ); auto column_indices = generate_indices( 16UL, 16UL, 2UL ); RCMT sm1 = blaze::rows( blaze::columns( mat1_, column_indices.data(), column_indices.size() ), row_indices.data(), row_indices.size() ); DSMT sm2 = dilatedsubmatrix( mat2_, 8UL, 16UL, 8UL, 16UL, 3UL, 2UL ); using UnalignedUnpadded = blaze::CustomMatrix<int,blaze::unaligned,unpadded,columnMajor>; std::unique_ptr<int[]> memory( new int[129UL] ); UnalignedUnpadded mat( memory.get()+1UL, 8UL, 16UL ); randomize( mat, int(randmin), int(randmax) ); sm1 = mat; sm2 = mat; checkRows ( sm1, 8UL ); checkColumns( sm1, 16UL ); checkRows ( sm2, 8UL ); checkColumns( sm2, 16UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Column-major homogeneous assignment //===================================================================================== { test_ = "Column-major dilatedsubmatrix homogeneous assignment"; initialize(); // Assigning to a 8x16 dilatedsubmatrix { auto row_indices = generate_indices( 8UL, 8UL, 2UL ); auto column_indices = generate_indices( 16UL, 4UL, 3UL ); OCRMT sm1 = blaze::columns( blaze::rows( tmat1_, row_indices.data(), row_indices.size() ), column_indices.data(), column_indices.size() ); ODSMT sm2 = dilatedsubmatrix( tmat2_, 8UL, 16UL, 8UL, 4UL, 2UL, 3UL ); sm1 = 12; sm2 = 12; checkRows ( sm1, 8UL ); checkColumns( sm1, 4UL ); checkRows ( sm2, 8UL ); checkColumns( sm2, 4UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } // Assigning to a 16x8 dilatedsubmatrix { auto row_indices = generate_indices( 8UL, 8UL, 2UL ); auto column_indices = generate_indices( 16UL, 4UL, 3UL ); OCRMT sm1 = blaze::columns( blaze::rows( tmat1_, row_indices.data(), row_indices.size() ), column_indices.data(), column_indices.size() ); ODSMT sm2 = dilatedsubmatrix( tmat2_, 8UL, 16UL, 8UL, 4UL, 2UL, 3UL ); sm1 = 15; sm2 = 15; checkRows ( sm1, 8UL ); checkColumns( sm1, 4UL ); checkRows ( sm2, 8UL ); checkColumns( sm2, 4UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } } //===================================================================================== // Column-major list assignment //===================================================================================== { test_ = "Column-major initializer list assignment (complete list)"; initialize(); auto row_indices = generate_indices( 16UL, 16UL, 2UL ); auto column_indices = generate_indices( 8UL, 8UL, 3UL ); OCRMT sm1 = blaze::columns( blaze::rows( tmat1_, row_indices.data(), row_indices.size() ), column_indices.data(), column_indices.size() ); ODSMT sm2 = dilatedsubmatrix( tmat2_, 16UL, 8UL, 16UL, 8UL, 2UL, 3UL ); initializer_list< initializer_list<int> > list = { { 1, 2, 3, 4, 5, 6, 7, 8 }, { 2, 4, 6, 8, 10, 12, 14, 16 }, { 3, 6, 9, 12, 15, 18, 21, 24 }, { 4, 8, 12, 16, 20, 24, 28, 32 }, { 5, 10, 15, 20, 25, 30, 35, 40 }, { 6, 12, 18, 24, 30, 36, 42, 48 }, { 7, 14, 21, 28, 35, 42, 49, 56 }, { 8, 16, 24, 32, 40, 48, 56, 64 }, { 9, 18, 27, 36, 45, 54, 63, 72 }, { 10, 20, 30, 40, 50, 60, 70, 80 }, { 11, 22, 33, 44, 55, 66, 77, 88 }, { 12, 24, 36, 48, 60, 72, 84, 96 }, { 13, 26, 39, 52, 65, 78, 91, 104 }, { 14, 28, 42, 56, 70, 84, 98, 112 }, { 15, 30, 45, 60, 75, 90, 105, 120 }, { 16, 32, 48, 64, 80, 96, 112, 128 } }; sm1 = list; sm2 = list; checkRows ( sm1, 16UL ); checkColumns( sm1, 8UL ); checkRows ( sm2, 16UL ); checkColumns( sm2, 8UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } { test_ = "Column-major initializer list assignment (incomplete list)"; initialize(); auto row_indices = generate_indices( 16UL, 16UL, 2UL ); auto column_indices = generate_indices( 8UL, 8UL, 3UL ); OCRMT sm1 = blaze::columns( blaze::rows( tmat1_, row_indices.data(), row_indices.size() ), column_indices.data(), column_indices.size() ); ODSMT sm2 = dilatedsubmatrix( tmat2_, 16UL, 8UL, 16UL, 8UL, 2UL, 3UL ); initializer_list< initializer_list<int> > list = { { 1, 2, 3, 4, 5, 6, 7, 8 }, { 2, 4, 6, 8, 10, 12, 14 }, { 3, 6, 9, 12, 15, 18 }, { 4, 8, 12, 16, 20 }, { 5, 10, 15, 20 }, { 6, 12, 18 }, { 7, 14 }, { 8 }, { 9, 18, 27, 36, 45, 54, 63, 72 }, { 10, 20, 30, 40, 50, 60, 70 }, { 11, 22, 33, 44, 55, 66 }, { 12, 24, 36, 48, 60 }, { 13, 26, 39, 52 }, { 14, 28, 42 }, { 15, 30 }, { 16 } }; sm1 = list; sm2 = list; checkRows ( sm1, 16UL ); checkColumns( sm1, 8UL ); checkRows ( sm2, 16UL ); checkColumns( sm2, 8UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Column-major copy assignment //===================================================================================== { test_ = "Column-major dilatedsubmatrix copy assignment (no aliasing)"; initialize(); OMT mat1( 64UL, 64UL ); OMT mat2( 64UL, 64UL ); randomize( mat1, int(randmin), int(randmax) ); mat2 = mat1; auto row_indices = generate_indices( 16UL, 16UL, 2UL ); auto column_indices = generate_indices( 8UL, 8UL, 3UL ); OCRMT sm1 = blaze::columns( blaze::rows( tmat1_, row_indices.data(), row_indices.size() ), column_indices.data(), column_indices.size() ); ODSMT sm2 = dilatedsubmatrix( tmat2_, 16UL, 8UL, 16UL, 8UL, 2UL, 3UL ); sm1 = dilatedsubmatrix( mat1, 16UL, 8UL, 16UL, 8UL, 2UL, 3UL ); sm2 = dilatedsubmatrix( mat2, 16UL, 8UL, 16UL, 8UL, 2UL, 3UL ); checkRows ( sm1, 16UL ); checkColumns( sm1, 8UL ); checkRows ( sm2, 16UL ); checkColumns( sm2, 8UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } { test_ = "Column-major dilatedsubmatrix copy assignment (aliasing)"; initialize(); auto row_indices = generate_indices( 16UL, 16UL, 2UL ); auto column_indices = generate_indices( 8UL, 8UL, 3UL ); OCRMT sm1 = blaze::columns( blaze::rows( tmat1_, row_indices.data(), row_indices.size() ), column_indices.data(), column_indices.size() ); ODSMT sm2 = dilatedsubmatrix( tmat2_, 16UL, 8UL, 16UL, 8UL, 2UL, 3UL ); sm1 = dilatedsubmatrix( tmat1_, 16UL, 12UL, 16UL, 8UL, 2UL, 3UL ); sm2 = dilatedsubmatrix( tmat2_, 16UL, 12UL, 16UL, 8UL, 2UL, 3UL ); checkRows ( sm1, 16UL ); checkColumns( sm1, 8UL ); checkRows ( sm2, 16UL ); checkColumns( sm2, 8UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Column-major dense matrix assignment //===================================================================================== { test_ = "Column-major/row-major dense matrix assignment (mixed type)"; initialize(); auto row_indices = generate_indices( 16UL, 16UL, 2UL ); auto column_indices = generate_indices( 8UL, 8UL, 3UL ); OCRMT sm1 = blaze::columns( blaze::rows( tmat1_, row_indices.data(), row_indices.size() ), column_indices.data(), column_indices.size() ); ODSMT sm2 = dilatedsubmatrix( tmat2_, 16UL, 8UL, 16UL, 8UL, 2UL, 3UL ); blaze::DynamicMatrix<short,rowMajor> mat( 16UL, 8UL ); randomize( mat, short(randmin), short(randmax) ); sm1 = mat; sm2 = mat; checkRows ( sm1, 16UL ); checkColumns( sm1, 8UL ); checkRows ( sm2, 16UL ); checkColumns( sm2, 8UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } { test_ = "Column-major/row-major dense matrix assignment (aligned/padded)"; initialize(); auto row_indices = generate_indices( 16UL, 16UL, 2UL ); auto column_indices = generate_indices( 8UL, 8UL, 3UL ); OCRMT sm1 = blaze::columns( blaze::rows( tmat1_, row_indices.data(), row_indices.size() ), column_indices.data(), column_indices.size() ); ODSMT sm2 = dilatedsubmatrix( tmat2_, 16UL, 8UL, 16UL, 8UL, 2UL, 3UL ); using AlignedPadded = blaze::CustomMatrix<int,blaze::aligned,padded,rowMajor>; std::unique_ptr<int[],blaze::Deallocate> memory( blaze::allocate<int>( 256UL ) ); AlignedPadded mat( memory.get(), 16UL, 8UL, 16UL ); randomize( mat, int(randmin), int(randmax) ); sm1 = mat; sm2 = mat; checkRows ( sm1, 16UL ); checkColumns( sm1, 8UL ); checkRows ( sm2, 16UL ); checkColumns( sm2, 8UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } { test_ = "Column-major/row-major dense matrix assignment (unaligned/unpadded)"; initialize(); auto row_indices = generate_indices( 16UL, 16UL, 2UL ); auto column_indices = generate_indices( 8UL, 8UL, 3UL ); OCRMT sm1 = blaze::columns( blaze::rows( tmat1_, row_indices.data(), row_indices.size() ), column_indices.data(), column_indices.size() ); ODSMT sm2 = dilatedsubmatrix( tmat2_, 16UL, 8UL, 16UL, 8UL, 2UL, 3UL ); using UnalignedUnpadded = blaze::CustomMatrix<int,blaze::unaligned,unpadded,rowMajor>; std::unique_ptr<int[]> memory( new int[129UL] ); UnalignedUnpadded mat( memory.get()+1UL, 16UL, 8UL ); randomize( mat, int(randmin), int(randmax) ); sm1 = mat; sm2 = mat; checkRows ( sm1, 16UL ); checkColumns( sm1, 8UL ); checkRows ( sm2, 16UL ); checkColumns( sm2, 8UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } { test_ = "Column-major/column-major dense matrix assignment (mixed type)"; initialize(); auto row_indices = generate_indices( 16UL, 16UL, 2UL ); auto column_indices = generate_indices( 8UL, 8UL, 3UL ); OCRMT sm1 = blaze::columns( blaze::rows( tmat1_, row_indices.data(), row_indices.size() ), column_indices.data(), column_indices.size() ); ODSMT sm2 = dilatedsubmatrix( tmat2_, 16UL, 8UL, 16UL, 8UL, 2UL, 3UL ); blaze::DynamicMatrix<short,columnMajor> mat( 16UL, 8UL ); randomize( mat, short(randmin), short(randmax) ); sm1 = mat; sm2 = mat; checkRows ( sm1, 16UL ); checkColumns( sm1, 8UL ); checkRows ( sm2, 16UL ); checkColumns( sm2, 8UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } { test_ = "Column-major/column-major dense matrix assignment (aligned/padded)"; initialize(); auto row_indices = generate_indices( 16UL, 16UL, 2UL ); auto column_indices = generate_indices( 8UL, 8UL, 3UL ); OCRMT sm1 = blaze::columns( blaze::rows( tmat1_, row_indices.data(), row_indices.size() ), column_indices.data(), column_indices.size() ); ODSMT sm2 = dilatedsubmatrix( tmat2_, 16UL, 8UL, 16UL, 8UL, 2UL, 3UL ); using AlignedPadded = blaze::CustomMatrix<int,blaze::aligned,padded,columnMajor>; std::unique_ptr<int[],blaze::Deallocate> memory( blaze::allocate<int>( 128UL ) ); AlignedPadded mat( memory.get(), 16UL, 8UL, 16UL ); randomize( mat, int(randmin), int(randmax) ); sm1 = mat; sm2 = mat; checkRows ( sm1, 16UL ); checkColumns( sm1, 8UL ); checkRows ( sm2, 16UL ); checkColumns( sm2, 8UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } { test_ = "Column-major/column-major dense matrix assignment (unaligned/unpadded)"; initialize(); auto row_indices = generate_indices( 16UL, 16UL, 2UL ); auto column_indices = generate_indices( 8UL, 8UL, 3UL ); OCRMT sm1 = blaze::columns( blaze::rows( tmat1_, row_indices.data(), row_indices.size() ), column_indices.data(), column_indices.size() ); ODSMT sm2 = dilatedsubmatrix( tmat2_, 16UL, 8UL, 16UL, 8UL, 2UL, 3UL ); using UnalignedUnpadded = blaze::CustomMatrix<int,blaze::unaligned,unpadded,columnMajor>; std::unique_ptr<int[]> memory( new int[129UL] ); UnalignedUnpadded mat( memory.get()+1UL, 16UL, 8UL ); randomize( mat, int(randmin), int(randmax) ); sm1 = mat; sm2 = mat; checkRows ( sm1, 16UL ); checkColumns( sm1, 8UL ); checkRows ( sm2, 16UL ); checkColumns( sm2, 8UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } } //************************************************************************************************* //************************************************************************************************* /*!\brief Test of the dilatedsubmatrix addition assignment operators. // // \return void // \exception std::runtime_error Error detected. // // This function performs a test of the addition assignment operators of the dilatedsubmatrix // specialization. In case an error is detected, a \a std::runtime_error exception is thrown. */ void DenseTest::testAddAssign() { using blaze::dilatedsubmatrix; using blaze::padded; using blaze::unpadded; using blaze::rowMajor; using blaze::columnMajor; //===================================================================================== // Row-major dilatedsubmatrix addition assignment //===================================================================================== { test_ = "Row-major dilatedsubmatrix addition assignment (no aliasing)"; initialize(); MT mat1( 64UL, 64UL ); MT mat2( 64UL, 64UL ); randomize( mat1, int(randmin), int(randmax) ); mat2 = mat1; auto row_indices = generate_indices( 8UL, 8UL, 2UL ); auto column_indices = generate_indices( 16UL, 4UL, 3UL ); RCMT sm1 = blaze::rows( blaze::columns( mat1_, column_indices.data(), column_indices.size() ), row_indices.data(), row_indices.size() ); DSMT sm2 = dilatedsubmatrix( mat2_, 8UL, 16UL, 8UL, 4UL, 2UL, 3UL ); sm1 += dilatedsubmatrix( mat1, 8UL, 16UL, 8UL, 4UL, 2UL, 3UL ); sm2 += dilatedsubmatrix( mat2, 8UL, 16UL, 8UL, 4UL, 2UL, 3UL ); checkRows ( sm1, 8UL ); checkColumns( sm1, 4UL ); checkRows ( sm2, 8UL ); checkColumns( sm2, 4UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } { test_ = "Row-major dilatedsubmatrix addition assignment (aliasing)"; initialize(); auto row_indices = generate_indices( 8UL, 8UL, 2UL ); auto column_indices = generate_indices( 16UL, 4UL, 3UL ); RCMT sm1 = blaze::rows( blaze::columns( mat1_, column_indices.data(), column_indices.size() ), row_indices.data(), row_indices.size() ); DSMT sm2 = dilatedsubmatrix( mat2_, 8UL, 16UL, 8UL, 4UL, 2UL, 3UL ); sm1 += dilatedsubmatrix( mat1_, 12UL, 16UL, 8UL, 4UL, 2UL, 3UL ); sm2 += dilatedsubmatrix( mat2_, 12UL, 16UL, 8UL, 4UL, 2UL, 3UL ); checkRows ( sm1, 8UL ); checkColumns( sm1, 4UL ); checkRows ( sm2, 8UL ); checkColumns( sm2, 4UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Row-major dense matrix addition assignment //===================================================================================== { test_ = "Row-major/row-major dense matrix addition assignment (mixed type)"; initialize(); auto row_indices = generate_indices( 8UL, 16UL, 2UL ); auto column_indices = generate_indices( 16UL, 4UL, 3UL ); RCMT sm1 = blaze::rows( blaze::columns( mat1_, column_indices.data(), column_indices.size() ), row_indices.data(), row_indices.size() ); DSMT sm2 = dilatedsubmatrix( mat2_, 8UL, 16UL, 16UL, 4UL, 2UL, 3UL ); blaze::DynamicMatrix<short,rowMajor> mat( 16UL, 4UL ); randomize( mat, short(randmin), short(randmax) ); sm1 += mat; sm2 += mat; checkRows ( sm1, 16UL ); checkColumns( sm1, 4UL ); checkRows ( sm2, 16UL ); checkColumns( sm2, 4UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } { test_ = "Row-major/row-major dense matrix addition assignment (aligned/padded)"; initialize(); auto row_indices = generate_indices( 8UL, 16UL, 3UL ); auto column_indices = generate_indices( 8UL, 16UL, 2UL ); RCMT sm1 = blaze::rows( blaze::columns( mat1_, column_indices.data(), column_indices.size() ), row_indices.data(), row_indices.size() ); DSMT sm2 = dilatedsubmatrix( mat2_, 8UL, 8UL, 16UL, 16UL, 3UL, 2UL ); using AlignedPadded = blaze::CustomMatrix<int,blaze::aligned,padded,rowMajor>; std::unique_ptr<int[],blaze::Deallocate> memory( blaze::allocate<int>( 256UL ) ); AlignedPadded mat( memory.get(), 16UL, 16UL, 16UL ); randomize( mat, int(randmin), int(randmax) ); sm1 += mat; sm2 += mat; checkRows ( sm1, 16UL ); checkColumns( sm1, 16UL ); checkRows ( sm2, 16UL ); checkColumns( sm2, 16UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } { test_ = "Row-major/row-major dense matrix addition assignment (unaligned/unpadded)"; initialize(); auto row_indices = generate_indices( 8UL, 16UL, 3UL ); auto column_indices = generate_indices( 8UL, 16UL, 2UL ); RCMT sm1 = blaze::rows( blaze::columns( mat1_, column_indices.data(), column_indices.size() ), row_indices.data(), row_indices.size() ); DSMT sm2 = dilatedsubmatrix( mat2_, 8UL, 8UL, 16UL, 16UL, 3UL, 2UL ); using UnalignedUnpadded = blaze::CustomMatrix<int,blaze::unaligned,unpadded,rowMajor>; std::unique_ptr<int[]> memory( new int[257UL] ); UnalignedUnpadded mat( memory.get()+1UL, 16UL, 16UL ); randomize( mat, int(randmin), int(randmax) ); sm1 += mat; sm2 += mat; checkRows ( sm1, 16UL ); checkColumns( sm1, 16UL ); checkRows ( sm2, 16UL ); checkColumns( sm2, 16UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } { test_ = "Row-major/column-major dense matrix addition assignment (mixed type)"; initialize(); auto row_indices = generate_indices( 8UL, 8UL, 3UL ); auto column_indices = generate_indices( 16UL, 16UL, 2UL ); RCMT sm1 = blaze::rows( blaze::columns( mat1_, column_indices.data(), column_indices.size() ), row_indices.data(), row_indices.size() ); DSMT sm2 = dilatedsubmatrix( mat2_, 8UL, 16UL, 8UL, 16UL, 3UL, 2UL ); blaze::DynamicMatrix<short,columnMajor> mat( 8UL, 16UL ); randomize( mat, short(randmin), short(randmax) ); sm1 += mat; sm2 += mat; checkRows ( sm1, 8UL ); checkColumns( sm1, 16UL ); checkRows ( sm2, 8UL ); checkColumns( sm2, 16UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } { test_ = "Row-major/column-major dense matrix addition assignment (aligned/padded)"; initialize(); auto row_indices = generate_indices( 8UL, 8UL, 3UL ); auto column_indices = generate_indices( 16UL, 16UL, 2UL ); RCMT sm1 = blaze::rows( blaze::columns( mat1_, column_indices.data(), column_indices.size() ), row_indices.data(), row_indices.size() ); DSMT sm2 = dilatedsubmatrix( mat2_, 8UL, 16UL, 8UL, 16UL, 3UL, 2UL ); using AlignedPadded = blaze::CustomMatrix<int,blaze::aligned,padded,columnMajor>; std::unique_ptr<int[],blaze::Deallocate> memory( blaze::allocate<int>( 256UL ) ); AlignedPadded mat( memory.get(), 8UL, 16UL, 16UL ); randomize( mat, int(randmin), int(randmax) ); sm1 += mat; sm2 += mat; checkRows ( sm1, 8UL ); checkColumns( sm1, 16UL ); checkRows ( sm2, 8UL ); checkColumns( sm2, 16UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } { test_ = "Row-major/column-major dense matrix addition assignment (unaligned/unpadded)"; initialize(); auto row_indices = generate_indices( 8UL, 8UL, 3UL ); auto column_indices = generate_indices( 16UL, 16UL, 2UL ); RCMT sm1 = blaze::rows( blaze::columns( mat1_, column_indices.data(), column_indices.size() ), row_indices.data(), row_indices.size() ); DSMT sm2 = dilatedsubmatrix( mat2_, 8UL, 16UL, 8UL, 16UL, 3UL, 2UL ); using UnalignedUnpadded = blaze::CustomMatrix<int,blaze::unaligned,unpadded,columnMajor>; std::unique_ptr<int[]> memory( new int[129UL] ); UnalignedUnpadded mat( memory.get()+1UL, 8UL, 16UL ); randomize( mat, int(randmin), int(randmax) ); sm1 += mat; sm2 += mat; checkRows ( sm1, 8UL ); checkColumns( sm1, 16UL ); checkRows ( sm2, 8UL ); checkColumns( sm2, 16UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Column-major dilatedsubmatrix addition assignment //===================================================================================== { test_ = "Column-major dilatedsubmatrix addition assignment (no aliasing)"; initialize(); OMT mat1( 64UL, 64UL ); OMT mat2( 64UL, 64UL ); randomize( mat1, int(randmin), int(randmax) ); mat2 = mat1; auto row_indices = generate_indices( 16UL, 16UL, 2UL ); auto column_indices = generate_indices( 8UL, 8UL, 3UL ); OCRMT sm1 = blaze::columns( blaze::rows( tmat1_, row_indices.data(), row_indices.size() ), column_indices.data(), column_indices.size() ); ODSMT sm2 = dilatedsubmatrix( tmat2_, 16UL, 8UL, 16UL, 8UL, 2UL, 3UL ); sm1 += dilatedsubmatrix( mat1, 16UL, 8UL, 16UL, 8UL, 2UL, 3UL ); sm2 += dilatedsubmatrix( mat2, 16UL, 8UL, 16UL, 8UL, 2UL, 3UL ); checkRows ( sm1, 16UL ); checkColumns( sm1, 8UL ); checkRows ( sm2, 16UL ); checkColumns( sm2, 8UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } { test_ = "Column-major dilatedsubmatrix addition assignment (aliasing)"; initialize(); auto row_indices = generate_indices( 16UL, 16UL, 2UL ); auto column_indices = generate_indices( 8UL, 8UL, 3UL ); OCRMT sm1 = blaze::columns( blaze::rows( tmat1_, row_indices.data(), row_indices.size() ), column_indices.data(), column_indices.size() ); ODSMT sm2 = dilatedsubmatrix( tmat2_, 16UL, 8UL, 16UL, 8UL, 2UL, 3UL ); sm1 += dilatedsubmatrix( tmat1_, 16UL, 12UL, 16UL, 8UL, 2UL, 3UL ); sm2 += dilatedsubmatrix( tmat2_, 16UL, 12UL, 16UL, 8UL, 2UL, 3UL ); checkRows ( sm1, 16UL ); checkColumns( sm1, 8UL ); checkRows ( sm2, 16UL ); checkColumns( sm2, 8UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Column-major dense matrix addition assignment //===================================================================================== { test_ = "Column-major/row-major dense matrix addition assignment (mixed type)"; initialize(); auto row_indices = generate_indices( 16UL, 16UL, 2UL ); auto column_indices = generate_indices( 8UL, 8UL, 3UL ); OCRMT sm1 = blaze::columns( blaze::rows( tmat1_, row_indices.data(), row_indices.size() ), column_indices.data(), column_indices.size() ); ODSMT sm2 = dilatedsubmatrix( tmat2_, 16UL, 8UL, 16UL, 8UL, 2UL, 3UL ); blaze::DynamicMatrix<short,rowMajor> mat( 16UL, 8UL ); randomize( mat, short(randmin), short(randmax) ); sm1 += mat; sm2 += mat; checkRows ( sm1, 16UL ); checkColumns( sm1, 8UL ); checkRows ( sm2, 16UL ); checkColumns( sm2, 8UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } { test_ = "Column-major/row-major dense matrix addition assignment (aligned/padded)"; initialize(); auto row_indices = generate_indices( 16UL, 16UL, 2UL ); auto column_indices = generate_indices( 8UL, 8UL, 3UL ); OCRMT sm1 = blaze::columns( blaze::rows( tmat1_, row_indices.data(), row_indices.size() ), column_indices.data(), column_indices.size() ); ODSMT sm2 = dilatedsubmatrix( tmat2_, 16UL, 8UL, 16UL, 8UL, 2UL, 3UL ); using AlignedPadded = blaze::CustomMatrix<int,blaze::aligned,padded,rowMajor>; std::unique_ptr<int[],blaze::Deallocate> memory( blaze::allocate<int>( 256UL ) ); AlignedPadded mat( memory.get(), 16UL, 8UL, 16UL ); randomize( mat, int(randmin), int(randmax) ); sm1 += mat; sm2 += mat; checkRows ( sm1, 16UL ); checkColumns( sm1, 8UL ); checkRows ( sm2, 16UL ); checkColumns( sm2, 8UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } { test_ = "Column-major/row-major dense matrix addition assignment (unaligned/unpadded)"; initialize(); auto row_indices = generate_indices( 16UL, 16UL, 2UL ); auto column_indices = generate_indices( 8UL, 8UL, 3UL ); OCRMT sm1 = blaze::columns( blaze::rows( tmat1_, row_indices.data(), row_indices.size() ), column_indices.data(), column_indices.size() ); ODSMT sm2 = dilatedsubmatrix( tmat2_, 16UL, 8UL, 16UL, 8UL, 2UL, 3UL ); using UnalignedUnpadded = blaze::CustomMatrix<int,blaze::unaligned,unpadded,rowMajor>; std::unique_ptr<int[]> memory( new int[129UL] ); UnalignedUnpadded mat( memory.get()+1UL, 16UL, 8UL ); randomize( mat, int(randmin), int(randmax) ); sm1 += mat; sm2 += mat; checkRows ( sm1, 16UL ); checkColumns( sm1, 8UL ); checkRows ( sm2, 16UL ); checkColumns( sm2, 8UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } { test_ = "Column-major/column-major dense matrix addition assignment (mixed type)"; initialize(); auto row_indices = generate_indices( 16UL, 16UL, 2UL ); auto column_indices = generate_indices( 8UL, 8UL, 3UL ); OCRMT sm1 = blaze::columns( blaze::rows( tmat1_, row_indices.data(), row_indices.size() ), column_indices.data(), column_indices.size() ); ODSMT sm2 = dilatedsubmatrix( tmat2_, 16UL, 8UL, 16UL, 8UL, 2UL, 3UL ); blaze::DynamicMatrix<short,columnMajor> mat( 16UL, 8UL ); randomize( mat, short(randmin), short(randmax) ); sm1 += mat; sm2 += mat; checkRows ( sm1, 16UL ); checkColumns( sm1, 8UL ); checkRows ( sm2, 16UL ); checkColumns( sm2, 8UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } { test_ = "Column-major/column-major dense matrix addition assignment (aligned/padded)"; initialize(); auto row_indices = generate_indices( 16UL, 16UL, 2UL ); auto column_indices = generate_indices( 8UL, 8UL, 3UL ); OCRMT sm1 = blaze::columns( blaze::rows( tmat1_, row_indices.data(), row_indices.size() ), column_indices.data(), column_indices.size() ); ODSMT sm2 = dilatedsubmatrix( tmat2_, 16UL, 8UL, 16UL, 8UL, 2UL, 3UL ); using AlignedPadded = blaze::CustomMatrix<int,blaze::aligned,padded,columnMajor>; std::unique_ptr<int[],blaze::Deallocate> memory( blaze::allocate<int>( 128UL ) ); AlignedPadded mat( memory.get(), 16UL, 8UL, 16UL ); randomize( mat, int(randmin), int(randmax) ); sm1 += mat; sm2 += mat; checkRows ( sm1, 16UL ); checkColumns( sm1, 8UL ); checkRows ( sm2, 16UL ); checkColumns( sm2, 8UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } { test_ = "Column-major/column-major dense matrix addition assignment (unaligned/unpadded)"; initialize(); auto row_indices = generate_indices( 16UL, 16UL, 2UL ); auto column_indices = generate_indices( 8UL, 8UL, 3UL ); OCRMT sm1 = blaze::columns( blaze::rows( tmat1_, row_indices.data(), row_indices.size() ), column_indices.data(), column_indices.size() ); ODSMT sm2 = dilatedsubmatrix( tmat2_, 16UL, 8UL, 16UL, 8UL, 2UL, 3UL ); using UnalignedUnpadded = blaze::CustomMatrix<int,blaze::unaligned,unpadded,columnMajor>; std::unique_ptr<int[]> memory( new int[129UL] ); UnalignedUnpadded mat( memory.get()+1UL, 16UL, 8UL ); randomize( mat, int(randmin), int(randmax) ); sm1 += mat; sm2 += mat; checkRows ( sm1, 16UL ); checkColumns( sm1, 8UL ); checkRows ( sm2, 16UL ); checkColumns( sm2, 8UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } } //************************************************************************************************* //************************************************************************************************* /*!\brief Test of the dilatedsubmatrix subtraction assignment operators. // // \return void // \exception std::runtime_error Error detected. // // This function performs a test of the subtraction assignment operators of the dilatedsubmatrix // specialization. In case an error is detected, a \a std::runtime_error exception is thrown. */ void DenseTest::testSubAssign() { using blaze::dilatedsubmatrix; using blaze::padded; using blaze::unpadded; using blaze::rowMajor; using blaze::columnMajor; //===================================================================================== // Row-major dilatedsubmatrix subtraction assignment //===================================================================================== { test_ = "Row-major dilatedsubmatrix subtraction assignment (no aliasing)"; initialize(); MT mat1( 64UL, 64UL ); MT mat2( 64UL, 64UL ); randomize( mat1, int(randmin), int(randmax) ); mat2 = mat1; auto row_indices = generate_indices( 8UL, 8UL, 2UL ); auto column_indices = generate_indices( 16UL, 4UL, 3UL ); RCMT sm1 = blaze::rows( blaze::columns( mat1_, column_indices.data(), column_indices.size() ), row_indices.data(), row_indices.size() ); DSMT sm2 = dilatedsubmatrix( mat2_, 8UL, 16UL, 8UL, 4UL, 2UL, 3UL ); sm1 -= dilatedsubmatrix( mat1, 8UL, 16UL, 8UL, 4UL, 2UL, 3UL ); sm2 -= dilatedsubmatrix( mat2, 8UL, 16UL, 8UL, 4UL, 2UL, 3UL ); checkRows ( sm1, 8UL ); checkColumns( sm1, 4UL ); checkRows ( sm2, 8UL ); checkColumns( sm2, 4UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } { test_ = "Row-major dilatedsubmatrix subtraction assignment (aliasing)"; initialize(); auto row_indices = generate_indices( 8UL, 8UL, 2UL ); auto column_indices = generate_indices( 16UL, 4UL, 3UL ); RCMT sm1 = blaze::rows( blaze::columns( mat1_, column_indices.data(), column_indices.size() ), row_indices.data(), row_indices.size() ); DSMT sm2 = dilatedsubmatrix( mat2_, 8UL, 16UL, 8UL, 4UL, 2UL, 3UL ); sm1 -= dilatedsubmatrix( mat1_, 12UL, 16UL, 8UL, 4UL, 2UL, 3UL ); sm2 -= dilatedsubmatrix( mat2_, 12UL, 16UL, 8UL, 4UL, 2UL, 3UL ); checkRows ( sm1, 8UL ); checkColumns( sm1, 4UL ); checkRows ( sm2, 8UL ); checkColumns( sm2, 4UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Row-major dense matrix subtraction assignment //===================================================================================== { test_ = "Row-major/row-major dense matrix subtraction assignment (mixed type)"; initialize(); auto row_indices = generate_indices( 8UL, 16UL, 2UL ); auto column_indices = generate_indices( 16UL, 4UL, 3UL ); RCMT sm1 = blaze::rows( blaze::columns( mat1_, column_indices.data(), column_indices.size() ), row_indices.data(), row_indices.size() ); DSMT sm2 = dilatedsubmatrix( mat2_, 8UL, 16UL, 16UL, 4UL, 2UL, 3UL ); blaze::DynamicMatrix<short,rowMajor> mat( 16UL, 4UL ); randomize( mat, short(randmin), short(randmax) ); sm1 -= mat; sm2 -= mat; checkRows ( sm1, 16UL ); checkColumns( sm1, 4UL ); checkRows ( sm2, 16UL ); checkColumns( sm2, 4UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } { test_ = "Row-major/row-major dense matrix subtraction assignment (aligned/padded)"; initialize(); auto row_indices = generate_indices( 8UL, 16UL, 3UL ); auto column_indices = generate_indices( 8UL, 16UL, 2UL ); RCMT sm1 = blaze::rows( blaze::columns( mat1_, column_indices.data(), column_indices.size() ), row_indices.data(), row_indices.size() ); DSMT sm2 = dilatedsubmatrix( mat2_, 8UL, 8UL, 16UL, 16UL, 3UL, 2UL ); using AlignedPadded = blaze::CustomMatrix<int,blaze::aligned,padded,rowMajor>; std::unique_ptr<int[],blaze::Deallocate> memory( blaze::allocate<int>( 256UL ) ); AlignedPadded mat( memory.get(), 16UL, 16UL, 16UL ); randomize( mat, int(randmin), int(randmax) ); sm1 -= mat; sm2 -= mat; checkRows ( sm1, 16UL ); checkColumns( sm1, 16UL ); checkRows ( sm2, 16UL ); checkColumns( sm2, 16UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } { test_ = "Row-major/row-major dense matrix subtraction assignment (unaligned/unpadded)"; initialize(); auto row_indices = generate_indices( 8UL, 16UL, 3UL ); auto column_indices = generate_indices( 8UL, 16UL, 2UL ); RCMT sm1 = blaze::rows( blaze::columns( mat1_, column_indices.data(), column_indices.size() ), row_indices.data(), row_indices.size() ); DSMT sm2 = dilatedsubmatrix( mat2_, 8UL, 8UL, 16UL, 16UL, 3UL, 2UL ); using UnalignedUnpadded = blaze::CustomMatrix<int,blaze::unaligned,unpadded,rowMajor>; std::unique_ptr<int[]> memory( new int[257UL] ); UnalignedUnpadded mat( memory.get()+1UL, 16UL, 16UL ); randomize( mat, int(randmin), int(randmax) ); sm1 -= mat; sm2 -= mat; checkRows ( sm1, 16UL ); checkColumns( sm1, 16UL ); checkRows ( sm2, 16UL ); checkColumns( sm2, 16UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } { test_ = "Row-major/column-major dense matrix subtraction assignment (mixed type)"; initialize(); auto row_indices = generate_indices( 8UL, 8UL, 3UL ); auto column_indices = generate_indices( 16UL, 16UL, 2UL ); RCMT sm1 = blaze::rows( blaze::columns( mat1_, column_indices.data(), column_indices.size() ), row_indices.data(), row_indices.size() ); DSMT sm2 = dilatedsubmatrix( mat2_, 8UL, 16UL, 8UL, 16UL, 3UL, 2UL ); blaze::DynamicMatrix<short,columnMajor> mat( 8UL, 16UL ); randomize( mat, short(randmin), short(randmax) ); sm1 -= mat; sm2 -= mat; checkRows ( sm1, 8UL ); checkColumns( sm1, 16UL ); checkRows ( sm2, 8UL ); checkColumns( sm2, 16UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } { test_ = "Row-major/column-major dense matrix subtraction assignment (aligned/padded)"; initialize(); auto row_indices = generate_indices( 8UL, 8UL, 3UL ); auto column_indices = generate_indices( 16UL, 16UL, 2UL ); RCMT sm1 = blaze::rows( blaze::columns( mat1_, column_indices.data(), column_indices.size() ), row_indices.data(), row_indices.size() ); DSMT sm2 = dilatedsubmatrix( mat2_, 8UL, 16UL, 8UL, 16UL, 3UL, 2UL ); using AlignedPadded = blaze::CustomMatrix<int,blaze::aligned,padded,columnMajor>; std::unique_ptr<int[],blaze::Deallocate> memory( blaze::allocate<int>( 256UL ) ); AlignedPadded mat( memory.get(), 8UL, 16UL, 16UL ); randomize( mat, int(randmin), int(randmax) ); sm1 -= mat; sm2 -= mat; checkRows ( sm1, 8UL ); checkColumns( sm1, 16UL ); checkRows ( sm2, 8UL ); checkColumns( sm2, 16UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } { test_ = "Row-major/column-major dense matrix subtraction assignment (unaligned/unpadded)"; initialize(); auto row_indices = generate_indices( 8UL, 8UL, 3UL ); auto column_indices = generate_indices( 16UL, 16UL, 2UL ); RCMT sm1 = blaze::rows( blaze::columns( mat1_, column_indices.data(), column_indices.size() ), row_indices.data(), row_indices.size() ); DSMT sm2 = dilatedsubmatrix( mat2_, 8UL, 16UL, 8UL, 16UL, 3UL, 2UL ); using UnalignedUnpadded = blaze::CustomMatrix<int,blaze::unaligned,unpadded,columnMajor>; std::unique_ptr<int[]> memory( new int[129UL] ); UnalignedUnpadded mat( memory.get()+1UL, 8UL, 16UL ); randomize( mat, int(randmin), int(randmax) ); sm1 -= mat; sm2 -= mat; checkRows ( sm1, 8UL ); checkColumns( sm1, 16UL ); checkRows ( sm2, 8UL ); checkColumns( sm2, 16UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Column-major dilatedsubmatrix subtraction assignment //===================================================================================== { test_ = "Column-major dilatedsubmatrix subtraction assignment (no aliasing)"; initialize(); OMT mat1( 64UL, 64UL ); OMT mat2( 64UL, 64UL ); randomize( mat1, int(randmin), int(randmax) ); mat2 = mat1; auto row_indices = generate_indices( 16UL, 16UL, 2UL ); auto column_indices = generate_indices( 8UL, 8UL, 3UL ); OCRMT sm1 = blaze::columns( blaze::rows( tmat1_, row_indices.data(), row_indices.size() ), column_indices.data(), column_indices.size() ); ODSMT sm2 = dilatedsubmatrix( tmat2_, 16UL, 8UL, 16UL, 8UL, 2UL, 3UL ); sm1 -= dilatedsubmatrix( mat1, 16UL, 8UL, 16UL, 8UL, 2UL, 3UL ); sm2 -= dilatedsubmatrix( mat2, 16UL, 8UL, 16UL, 8UL, 2UL, 3UL ); checkRows ( sm1, 16UL ); checkColumns( sm1, 8UL ); checkRows ( sm2, 16UL ); checkColumns( sm2, 8UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } { test_ = "Column-major dilatedsubmatrix subtraction assignment (aliasing)"; initialize(); auto row_indices = generate_indices( 16UL, 16UL, 2UL ); auto column_indices = generate_indices( 8UL, 8UL, 3UL ); OCRMT sm1 = blaze::columns( blaze::rows( tmat1_, row_indices.data(), row_indices.size() ), column_indices.data(), column_indices.size() ); ODSMT sm2 = dilatedsubmatrix( tmat2_, 16UL, 8UL, 16UL, 8UL, 2UL, 3UL ); sm1 -= dilatedsubmatrix( tmat1_, 16UL, 12UL, 16UL, 8UL, 2UL, 3UL ); sm2 -= dilatedsubmatrix( tmat2_, 16UL, 12UL, 16UL, 8UL, 2UL, 3UL ); checkRows ( sm1, 16UL ); checkColumns( sm1, 8UL ); checkRows ( sm2, 16UL ); checkColumns( sm2, 8UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Column-major dense matrix subtraction assignment //===================================================================================== { test_ = "Column-major/row-major dense matrix subtraction assignment (mixed type)"; initialize(); auto row_indices = generate_indices( 16UL, 16UL, 2UL ); auto column_indices = generate_indices( 8UL, 8UL, 3UL ); OCRMT sm1 = blaze::columns( blaze::rows( tmat1_, row_indices.data(), row_indices.size() ), column_indices.data(), column_indices.size() ); ODSMT sm2 = dilatedsubmatrix( tmat2_, 16UL, 8UL, 16UL, 8UL, 2UL, 3UL ); blaze::DynamicMatrix<short,rowMajor> mat( 16UL, 8UL ); randomize( mat, short(randmin), short(randmax) ); sm1 -= mat; sm2 -= mat; checkRows ( sm1, 16UL ); checkColumns( sm1, 8UL ); checkRows ( sm2, 16UL ); checkColumns( sm2, 8UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } { test_ = "Column-major/row-major dense matrix subtraction assignment (aligned/padded)"; initialize(); auto row_indices = generate_indices( 16UL, 16UL, 2UL ); auto column_indices = generate_indices( 8UL, 8UL, 3UL ); OCRMT sm1 = blaze::columns( blaze::rows( tmat1_, row_indices.data(), row_indices.size() ), column_indices.data(), column_indices.size() ); ODSMT sm2 = dilatedsubmatrix( tmat2_, 16UL, 8UL, 16UL, 8UL, 2UL, 3UL ); using AlignedPadded = blaze::CustomMatrix<int,blaze::aligned,padded,rowMajor>; std::unique_ptr<int[],blaze::Deallocate> memory( blaze::allocate<int>( 256UL ) ); AlignedPadded mat( memory.get(), 16UL, 8UL, 16UL ); randomize( mat, int(randmin), int(randmax) ); sm1 -= mat; sm2 -= mat; checkRows ( sm1, 16UL ); checkColumns( sm1, 8UL ); checkRows ( sm2, 16UL ); checkColumns( sm2, 8UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } { test_ = "Column-major/row-major dense matrix subtraction assignment (unaligned/unpadded)"; initialize(); auto row_indices = generate_indices( 16UL, 16UL, 2UL ); auto column_indices = generate_indices( 8UL, 8UL, 3UL ); OCRMT sm1 = blaze::columns( blaze::rows( tmat1_, row_indices.data(), row_indices.size() ), column_indices.data(), column_indices.size() ); ODSMT sm2 = dilatedsubmatrix( tmat2_, 16UL, 8UL, 16UL, 8UL, 2UL, 3UL ); using UnalignedUnpadded = blaze::CustomMatrix<int,blaze::unaligned,unpadded,rowMajor>; std::unique_ptr<int[]> memory( new int[129UL] ); UnalignedUnpadded mat( memory.get()+1UL, 16UL, 8UL ); randomize( mat, int(randmin), int(randmax) ); sm1 -= mat; sm2 -= mat; checkRows ( sm1, 16UL ); checkColumns( sm1, 8UL ); checkRows ( sm2, 16UL ); checkColumns( sm2, 8UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } { test_ = "Column-major/column-major dense matrix subtraction assignment (mixed type)"; initialize(); auto row_indices = generate_indices( 16UL, 16UL, 2UL ); auto column_indices = generate_indices( 8UL, 8UL, 3UL ); OCRMT sm1 = blaze::columns( blaze::rows( tmat1_, row_indices.data(), row_indices.size() ), column_indices.data(), column_indices.size() ); ODSMT sm2 = dilatedsubmatrix( tmat2_, 16UL, 8UL, 16UL, 8UL, 2UL, 3UL ); blaze::DynamicMatrix<short,columnMajor> mat( 16UL, 8UL ); randomize( mat, short(randmin), short(randmax) ); sm1 -= mat; sm2 -= mat; checkRows ( sm1, 16UL ); checkColumns( sm1, 8UL ); checkRows ( sm2, 16UL ); checkColumns( sm2, 8UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } { test_ = "Column-major/column-major dense matrix subtraction assignment (aligned/padded)"; initialize(); auto row_indices = generate_indices( 16UL, 16UL, 2UL ); auto column_indices = generate_indices( 8UL, 8UL, 3UL ); OCRMT sm1 = blaze::columns( blaze::rows( tmat1_, row_indices.data(), row_indices.size() ), column_indices.data(), column_indices.size() ); ODSMT sm2 = dilatedsubmatrix( tmat2_, 16UL, 8UL, 16UL, 8UL, 2UL, 3UL ); using AlignedPadded = blaze::CustomMatrix<int,blaze::aligned,padded,columnMajor>; std::unique_ptr<int[],blaze::Deallocate> memory( blaze::allocate<int>( 128UL ) ); AlignedPadded mat( memory.get(), 16UL, 8UL, 16UL ); randomize( mat, int(randmin), int(randmax) ); sm1 -= mat; sm2 -= mat; checkRows ( sm1, 16UL ); checkColumns( sm1, 8UL ); checkRows ( sm2, 16UL ); checkColumns( sm2, 8UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } { test_ = "Column-major/column-major dense matrix subtraction assignment (unaligned/unpadded)"; initialize(); auto row_indices = generate_indices( 16UL, 16UL, 2UL ); auto column_indices = generate_indices( 8UL, 8UL, 3UL ); OCRMT sm1 = blaze::columns( blaze::rows( tmat1_, row_indices.data(), row_indices.size() ), column_indices.data(), column_indices.size() ); ODSMT sm2 = dilatedsubmatrix( tmat2_, 16UL, 8UL, 16UL, 8UL, 2UL, 3UL ); using UnalignedUnpadded = blaze::CustomMatrix<int,blaze::unaligned,unpadded,columnMajor>; std::unique_ptr<int[]> memory( new int[129UL] ); UnalignedUnpadded mat( memory.get()+1UL, 16UL, 8UL ); randomize( mat, int(randmin), int(randmax) ); sm1 -= mat; sm2 -= mat; checkRows ( sm1, 16UL ); checkColumns( sm1, 8UL ); checkRows ( sm2, 16UL ); checkColumns( sm2, 8UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } } //************************************************************************************************* //************************************************************************************************* /*!\brief Test of the dilatedsubmatrix Schur product assignment operators. // // \return void // \exception std::runtime_error Error detected. // // This function performs a test of the Schur product assignment operators of the dilatedsubmatrix // specialization. In case an error is detected, a \a std::runtime_error exception is thrown. */ void DenseTest::testSchurAssign() { using blaze::dilatedsubmatrix; using blaze::aligned; using blaze::unaligned; using blaze::padded; using blaze::unpadded; using blaze::rowMajor; using blaze::columnMajor; //===================================================================================== // Row-major dilatedsubmatrix Schur product assignment //===================================================================================== { test_ = "Row-major dilatedsubmatrix Schur product assignment (no aliasing)"; initialize(); MT mat1( 64UL, 64UL ); MT mat2( 64UL, 64UL ); randomize( mat1, int(randmin), int(randmax) ); mat2 = mat1; auto row_indices = generate_indices( 8UL, 8UL, 2UL ); auto column_indices = generate_indices( 16UL, 4UL, 3UL ); RCMT sm1 = blaze::rows( blaze::columns( mat1_, column_indices.data(), column_indices.size() ), row_indices.data(), row_indices.size() ); DSMT sm2 = dilatedsubmatrix( mat2_, 8UL, 16UL, 8UL, 4UL, 2UL, 3UL ); sm1 %= dilatedsubmatrix( mat1, 8UL, 16UL, 8UL, 4UL, 2UL, 3UL ); sm2 %= dilatedsubmatrix( mat2, 8UL, 16UL, 8UL, 4UL, 2UL, 3UL ); checkRows ( sm1, 8UL ); checkColumns( sm1, 4UL ); checkRows ( sm2, 8UL ); checkColumns( sm2, 4UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Schur product assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } { test_ = "Row-major dilatedsubmatrix Schur product assignment (aliasing)"; initialize(); auto row_indices = generate_indices( 8UL, 8UL, 2UL ); auto column_indices = generate_indices( 16UL, 4UL, 3UL ); RCMT sm1 = blaze::rows( blaze::columns( mat1_, column_indices.data(), column_indices.size() ), row_indices.data(), row_indices.size() ); DSMT sm2 = dilatedsubmatrix( mat2_, 8UL, 16UL, 8UL, 4UL, 2UL, 3UL ); sm1 %= dilatedsubmatrix( mat1_, 12UL, 16UL, 8UL, 4UL, 2UL, 3UL ); sm2 %= dilatedsubmatrix( mat2_, 12UL, 16UL, 8UL, 4UL, 2UL, 3UL ); checkRows ( sm1, 8UL ); checkColumns( sm1, 4UL ); checkRows ( sm2, 8UL ); checkColumns( sm2, 4UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Schur product assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Row-major dense matrix Schur product assignment //===================================================================================== { test_ = "Row-major/row-major dense matrix Schur product assignment (mixed type)"; initialize(); auto row_indices = generate_indices( 8UL, 16UL, 2UL ); auto column_indices = generate_indices( 16UL, 4UL, 3UL ); RCMT sm1 = blaze::rows( blaze::columns( mat1_, column_indices.data(), column_indices.size() ), row_indices.data(), row_indices.size() ); DSMT sm2 = dilatedsubmatrix( mat2_, 8UL, 16UL, 16UL, 4UL, 2UL, 3UL ); blaze::DynamicMatrix<short,rowMajor> mat( 16UL, 4UL ); randomize( mat, short(randmin), short(randmax) ); sm1 %= mat; sm2 %= mat; checkRows ( sm1, 16UL ); checkColumns( sm1, 4UL ); checkRows ( sm2, 16UL ); checkColumns( sm2, 4UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Schur product assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } { test_ = "Row-major/row-major dense matrix Schur product assignment (aligned/padded)"; initialize(); auto row_indices = generate_indices( 8UL, 16UL, 3UL ); auto column_indices = generate_indices( 8UL, 16UL, 2UL ); RCMT sm1 = blaze::rows( blaze::columns( mat1_, column_indices.data(), column_indices.size() ), row_indices.data(), row_indices.size() ); DSMT sm2 = dilatedsubmatrix( mat2_, 8UL, 8UL, 16UL, 16UL, 3UL, 2UL ); using AlignedPadded = blaze::CustomMatrix<int,aligned,padded,rowMajor>; std::unique_ptr<int[],blaze::Deallocate> memory( blaze::allocate<int>( 256UL ) ); AlignedPadded mat( memory.get(), 16UL, 16UL, 16UL ); randomize( mat, int(randmin), int(randmax) ); sm1 %= mat; sm2 %= mat; checkRows ( sm1, 16UL ); checkColumns( sm1, 16UL ); checkRows ( sm2, 16UL ); checkColumns( sm2, 16UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Schur product assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } { test_ = "Row-major/row-major dense matrix Schur product assignment (unaligned/unpadded)"; initialize(); auto row_indices = generate_indices( 8UL, 16UL, 3UL ); auto column_indices = generate_indices( 8UL, 16UL, 2UL ); RCMT sm1 = blaze::rows( blaze::columns( mat1_, column_indices.data(), column_indices.size() ), row_indices.data(), row_indices.size() ); DSMT sm2 = dilatedsubmatrix( mat2_, 8UL, 8UL, 16UL, 16UL, 3UL, 2UL ); using UnalignedUnpadded = blaze::CustomMatrix<int,unaligned,unpadded,rowMajor>; std::unique_ptr<int[]> memory( new int[257UL] ); UnalignedUnpadded mat( memory.get()+1UL, 16UL, 16UL ); randomize( mat, int(randmin), int(randmax) ); sm1 %= mat; sm2 %= mat; checkRows ( sm1, 16UL ); checkColumns( sm1, 16UL ); checkRows ( sm2, 16UL ); checkColumns( sm2, 16UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Schur product assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } { test_ = "Row-major/column-major dense matrix Schur product assignment (mixed type)"; initialize(); auto row_indices = generate_indices( 8UL, 8UL, 3UL ); auto column_indices = generate_indices( 16UL, 16UL, 2UL ); RCMT sm1 = blaze::rows( blaze::columns( mat1_, column_indices.data(), column_indices.size() ), row_indices.data(), row_indices.size() ); DSMT sm2 = dilatedsubmatrix( mat2_, 8UL, 16UL, 8UL, 16UL, 3UL, 2UL ); blaze::DynamicMatrix<short,columnMajor> mat( 8UL, 16UL ); randomize( mat, short(randmin), short(randmax) ); sm1 %= mat; sm2 %= mat; checkRows ( sm1, 8UL ); checkColumns( sm1, 16UL ); checkRows ( sm2, 8UL ); checkColumns( sm2, 16UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Schur product assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } { test_ = "Row-major/column-major dense matrix Schur product assignment (aligned/padded)"; initialize(); auto row_indices = generate_indices( 8UL, 8UL, 3UL ); auto column_indices = generate_indices( 16UL, 16UL, 2UL ); RCMT sm1 = blaze::rows( blaze::columns( mat1_, column_indices.data(), column_indices.size() ), row_indices.data(), row_indices.size() ); DSMT sm2 = dilatedsubmatrix( mat2_, 8UL, 16UL, 8UL, 16UL, 3UL, 2UL ); using AlignedPadded = blaze::CustomMatrix<int,aligned,padded,columnMajor>; std::unique_ptr<int[],blaze::Deallocate> memory( blaze::allocate<int>( 256UL ) ); AlignedPadded mat( memory.get(), 8UL, 16UL, 16UL ); randomize( mat, int(randmin), int(randmax) ); sm1 %= mat; sm2 %= mat; checkRows ( sm1, 8UL ); checkColumns( sm1, 16UL ); checkRows ( sm2, 8UL ); checkColumns( sm2, 16UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Schur product assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } { test_ = "Row-major/column-major dense matrix Schur product assignment (unaligned/unpadded)"; initialize(); auto row_indices = generate_indices( 8UL, 8UL, 3UL ); auto column_indices = generate_indices( 16UL, 16UL, 2UL ); RCMT sm1 = blaze::rows( blaze::columns( mat1_, column_indices.data(), column_indices.size() ), row_indices.data(), row_indices.size() ); DSMT sm2 = dilatedsubmatrix( mat2_, 8UL, 16UL, 8UL, 16UL, 3UL, 2UL ); using UnalignedUnpadded = blaze::CustomMatrix<int,unaligned,unpadded,columnMajor>; std::unique_ptr<int[]> memory( new int[129UL] ); UnalignedUnpadded mat( memory.get()+1UL, 8UL, 16UL ); randomize( mat, int(randmin), int(randmax) ); sm1 %= mat; sm2 %= mat; checkRows ( sm1, 8UL ); checkColumns( sm1, 16UL ); checkRows ( sm2, 8UL ); checkColumns( sm2, 16UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Schur product assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Column-major dilatedsubmatrix Schur product assignment //===================================================================================== { test_ = "Column-major dilatedsubmatrix Schur product assignment (no aliasing)"; initialize(); OMT mat1( 64UL, 64UL ); OMT mat2( 64UL, 64UL ); randomize( mat1, int(randmin), int(randmax) ); mat2 = mat1; auto row_indices = generate_indices( 16UL, 16UL, 2UL ); auto column_indices = generate_indices( 8UL, 8UL, 3UL ); OCRMT sm1 = blaze::columns( blaze::rows( tmat1_, row_indices.data(), row_indices.size() ), column_indices.data(), column_indices.size() ); ODSMT sm2 = dilatedsubmatrix( tmat2_, 16UL, 8UL, 16UL, 8UL, 2UL, 3UL ); sm1 %= dilatedsubmatrix( mat1, 16UL, 8UL, 16UL, 8UL, 2UL, 3UL ); sm2 %= dilatedsubmatrix( mat2, 16UL, 8UL, 16UL, 8UL, 2UL, 3UL ); checkRows ( sm1, 16UL ); checkColumns( sm1, 8UL ); checkRows ( sm2, 16UL ); checkColumns( sm2, 8UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Schur product assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } { test_ = "Column-major dilatedsubmatrix Schur product assignment (aliasing)"; initialize(); auto row_indices = generate_indices( 16UL, 16UL, 2UL ); auto column_indices = generate_indices( 8UL, 8UL, 3UL ); OCRMT sm1 = blaze::columns( blaze::rows( tmat1_, row_indices.data(), row_indices.size() ), column_indices.data(), column_indices.size() ); ODSMT sm2 = dilatedsubmatrix( tmat2_, 16UL, 8UL, 16UL, 8UL, 2UL, 3UL ); sm1 %= dilatedsubmatrix( tmat1_, 16UL, 12UL, 16UL, 8UL, 2UL, 3UL ); sm2 %= dilatedsubmatrix( tmat2_, 16UL, 12UL, 16UL, 8UL, 2UL, 3UL ); checkRows ( sm1, 16UL ); checkColumns( sm1, 8UL ); checkRows ( sm2, 16UL ); checkColumns( sm2, 8UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Schur product assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Column-major dense matrix Schur product assignment //===================================================================================== { test_ = "Column-major/row-major dense matrix Schur product assignment (mixed type)"; initialize(); auto row_indices = generate_indices( 16UL, 16UL, 2UL ); auto column_indices = generate_indices( 8UL, 8UL, 3UL ); OCRMT sm1 = blaze::columns( blaze::rows( tmat1_, row_indices.data(), row_indices.size() ), column_indices.data(), column_indices.size() ); ODSMT sm2 = dilatedsubmatrix( tmat2_, 16UL, 8UL, 16UL, 8UL, 2UL, 3UL ); blaze::DynamicMatrix<short,rowMajor> mat( 16UL, 8UL ); randomize( mat, short(randmin), short(randmax) ); sm1 %= mat; sm2 %= mat; checkRows ( sm1, 16UL ); checkColumns( sm1, 8UL ); checkRows ( sm2, 16UL ); checkColumns( sm2, 8UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Schur product assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } { test_ = "Column-major/row-major dense matrix Schur product assignment (aligned/padded)"; initialize(); auto row_indices = generate_indices( 16UL, 16UL, 2UL ); auto column_indices = generate_indices( 8UL, 8UL, 3UL ); OCRMT sm1 = blaze::columns( blaze::rows( tmat1_, row_indices.data(), row_indices.size() ), column_indices.data(), column_indices.size() ); ODSMT sm2 = dilatedsubmatrix( tmat2_, 16UL, 8UL, 16UL, 8UL, 2UL, 3UL ); using AlignedPadded = blaze::CustomMatrix<int,aligned,padded,rowMajor>; std::unique_ptr<int[],blaze::Deallocate> memory( blaze::allocate<int>( 256UL ) ); AlignedPadded mat( memory.get(), 16UL, 8UL, 16UL ); randomize( mat, int(randmin), int(randmax) ); sm1 %= mat; sm2 %= mat; checkRows ( sm1, 16UL ); checkColumns( sm1, 8UL ); checkRows ( sm2, 16UL ); checkColumns( sm2, 8UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Schur product assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } { test_ = "Column-major/row-major dense matrix Schur product assignment (unaligned/unpadded)"; initialize(); auto row_indices = generate_indices( 16UL, 16UL, 2UL ); auto column_indices = generate_indices( 8UL, 8UL, 3UL ); OCRMT sm1 = blaze::columns( blaze::rows( tmat1_, row_indices.data(), row_indices.size() ), column_indices.data(), column_indices.size() ); ODSMT sm2 = dilatedsubmatrix( tmat2_, 16UL, 8UL, 16UL, 8UL, 2UL, 3UL ); using UnalignedUnpadded = blaze::CustomMatrix<int,unaligned,unpadded,rowMajor>; std::unique_ptr<int[]> memory( new int[129UL] ); UnalignedUnpadded mat( memory.get()+1UL, 16UL, 8UL ); randomize( mat, int(randmin), int(randmax) ); sm1 %= mat; sm2 %= mat; checkRows ( sm1, 16UL ); checkColumns( sm1, 8UL ); checkRows ( sm2, 16UL ); checkColumns( sm2, 8UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Schur product assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } { test_ = "Column-major/column-major dense matrix Schur product assignment (mixed type)"; initialize(); auto row_indices = generate_indices( 16UL, 16UL, 2UL ); auto column_indices = generate_indices( 8UL, 8UL, 3UL ); OCRMT sm1 = blaze::columns( blaze::rows( tmat1_, row_indices.data(), row_indices.size() ), column_indices.data(), column_indices.size() ); ODSMT sm2 = dilatedsubmatrix( tmat2_, 16UL, 8UL, 16UL, 8UL, 2UL, 3UL ); blaze::DynamicMatrix<short,columnMajor> mat( 16UL, 8UL ); randomize( mat, short(randmin), short(randmax) ); sm1 %= mat; sm2 %= mat; checkRows ( sm1, 16UL ); checkColumns( sm1, 8UL ); checkRows ( sm2, 16UL ); checkColumns( sm2, 8UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Schur product assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } { test_ = "Column-major/column-major dense matrix Schur product assignment (aligned/padded)"; initialize(); auto row_indices = generate_indices( 16UL, 16UL, 2UL ); auto column_indices = generate_indices( 8UL, 8UL, 3UL ); OCRMT sm1 = blaze::columns( blaze::rows( tmat1_, row_indices.data(), row_indices.size() ), column_indices.data(), column_indices.size() ); ODSMT sm2 = dilatedsubmatrix( tmat2_, 16UL, 8UL, 16UL, 8UL, 2UL, 3UL ); using AlignedPadded = blaze::CustomMatrix<int,aligned,padded,columnMajor>; std::unique_ptr<int[],blaze::Deallocate> memory( blaze::allocate<int>( 128UL ) ); AlignedPadded mat( memory.get(), 16UL, 8UL, 16UL ); randomize( mat, int(randmin), int(randmax) ); sm1 %= mat; sm2 %= mat; checkRows ( sm1, 16UL ); checkColumns( sm1, 8UL ); checkRows ( sm2, 16UL ); checkColumns( sm2, 8UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Schur product assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } { test_ = "Column-major/column-major dense matrix Schur product assignment (unaligned/unpadded)"; initialize(); auto row_indices = generate_indices( 16UL, 16UL, 2UL ); auto column_indices = generate_indices( 8UL, 8UL, 3UL ); OCRMT sm1 = blaze::columns( blaze::rows( tmat1_, row_indices.data(), row_indices.size() ), column_indices.data(), column_indices.size() ); ODSMT sm2 = dilatedsubmatrix( tmat2_, 16UL, 8UL, 16UL, 8UL, 2UL, 3UL ); using UnalignedUnpadded = blaze::CustomMatrix<int,unaligned,unpadded,columnMajor>; std::unique_ptr<int[]> memory( new int[129UL] ); UnalignedUnpadded mat( memory.get()+1UL, 16UL, 8UL ); randomize( mat, int(randmin), int(randmax) ); sm1 %= mat; sm2 %= mat; checkRows ( sm1, 16UL ); checkColumns( sm1, 8UL ); checkRows ( sm2, 16UL ); checkColumns( sm2, 8UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Schur product assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } } //************************************************************************************************* //************************************************************************************************* /*!\brief Test of the dilatedsubmatrix multiplication assignment operators. // // \return void // \exception std::runtime_error Error detected. // // This function performs a test of the multiplication assignment operators of the dilatedsubmatrix // specialization. In case an error is detected, a \a std::runtime_error exception is thrown. */ void DenseTest::testMultAssign() { using blaze::dilatedsubmatrix; using blaze::aligned; using blaze::unaligned; using blaze::padded; using blaze::unpadded; using blaze::rowMajor; using blaze::columnMajor; //===================================================================================== // Row-major dilatedsubmatrix multiplication assignment //===================================================================================== { test_ = "Row-major dilatedsubmatrix multiplication assignment (no aliasing)"; initialize(); MT mat1( 64UL, 64UL ); MT mat2( 64UL, 64UL ); randomize( mat1, int(randmin), int(randmax) ); mat2 = mat1; auto row_indices = generate_indices( 16UL, 8UL, 2UL ); auto column_indices = generate_indices( 16UL, 8UL, 3UL ); RCMT sm1 = blaze::rows( blaze::columns( mat1_, column_indices.data(), column_indices.size() ), row_indices.data(), row_indices.size() ); DSMT sm2 = dilatedsubmatrix( mat2_, 16UL, 16UL, 8UL, 8UL, 2UL, 3UL ); sm1 *= dilatedsubmatrix( mat1, 16UL, 16UL, 8UL, 8UL, 2UL, 3UL ); sm2 *= dilatedsubmatrix( mat2, 16UL, 16UL, 8UL, 8UL, 2UL, 3UL ); checkRows ( sm1, 8UL ); checkColumns( sm1, 8UL ); checkRows ( sm2, 8UL ); checkColumns( sm2, 8UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } { test_ = "Row-major dilatedsubmatrix multiplication assignment (aliasing)"; initialize(); auto row_indices = generate_indices( 16UL, 8UL, 2UL ); auto column_indices = generate_indices( 16UL, 8UL, 3UL ); RCMT sm1 = blaze::rows( blaze::columns( mat1_, column_indices.data(), column_indices.size() ), row_indices.data(), row_indices.size() ); DSMT sm2 = dilatedsubmatrix( mat2_, 16UL, 16UL, 8UL, 8UL, 2UL, 3UL ); sm1 *= dilatedsubmatrix( mat1_, 24UL, 16UL, 8UL, 8UL, 2UL, 3UL ); sm2 *= dilatedsubmatrix( mat2_, 24UL, 16UL, 8UL, 8UL, 2UL, 3UL ); checkRows ( sm1, 8UL ); checkColumns( sm1, 8UL ); checkRows ( sm2, 8UL ); checkColumns( sm2, 8UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Row-major dense matrix multiplication assignment //===================================================================================== { test_ = "Row-major/row-major dense matrix multiplication assignment (mixed type)"; initialize(); auto row_indices = generate_indices( 16UL, 8UL, 2UL ); auto column_indices = generate_indices( 16UL, 8UL, 3UL ); RCMT sm1 = blaze::rows( blaze::columns( mat1_, column_indices.data(), column_indices.size() ), row_indices.data(), row_indices.size() ); DSMT sm2 = dilatedsubmatrix( mat2_, 16UL, 16UL, 8UL, 8UL, 2UL, 3UL ); blaze::DynamicMatrix<short,rowMajor> mat( 8UL, 8UL ); randomize( mat, short(randmin), short(randmax) ); sm1 *= mat; sm2 *= mat; checkRows ( sm1, 8UL ); checkColumns( sm1, 8UL ); checkRows ( sm2, 8UL ); checkColumns( sm2, 8UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } { test_ = "Row-major/row-major dense matrix multiplication assignment (aligned/padded)"; initialize(); auto row_indices = generate_indices( 16UL, 8UL, 2UL ); auto column_indices = generate_indices( 16UL, 8UL, 3UL ); RCMT sm1 = blaze::rows( blaze::columns( mat1_, column_indices.data(), column_indices.size() ), row_indices.data(), row_indices.size() ); DSMT sm2 = dilatedsubmatrix( mat2_, 16UL, 16UL, 8UL, 8UL, 2UL, 3UL ); using AlignedPadded = blaze::CustomMatrix<int,aligned,padded,rowMajor>; std::unique_ptr<int[],blaze::Deallocate> memory( blaze::allocate<int>( 128UL ) ); AlignedPadded mat( memory.get(), 8UL, 8UL, 16UL ); randomize( mat, int(randmin), int(randmax) ); sm1 *= mat; sm2 *= mat; checkRows ( sm1, 8UL ); checkColumns( sm1, 8UL ); checkRows ( sm2, 8UL ); checkColumns( sm2, 8UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } { test_ = "Row-major/row-major dense matrix multiplication assignment (unaligned/unpadded)"; initialize(); auto row_indices = generate_indices( 16UL, 8UL, 2UL ); auto column_indices = generate_indices( 16UL, 8UL, 3UL ); RCMT sm1 = blaze::rows( blaze::columns( mat1_, column_indices.data(), column_indices.size() ), row_indices.data(), row_indices.size() ); DSMT sm2 = dilatedsubmatrix( mat2_, 16UL, 16UL, 8UL, 8UL, 2UL, 3UL ); using UnalignedUnpadded = blaze::CustomMatrix<int,unaligned,unpadded,rowMajor>; std::unique_ptr<int[]> memory( new int[65UL] ); UnalignedUnpadded mat( memory.get()+1UL, 8UL, 8UL ); randomize( mat, int(randmin), int(randmax) ); sm1 *= mat; sm2 *= mat; checkRows ( sm1, 8UL ); checkColumns( sm1, 8UL ); checkRows ( sm2, 8UL ); checkColumns( sm2, 8UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } { test_ = "Row-major/column-major dense matrix multiplication assignment (mixed type)"; initialize(); auto row_indices = generate_indices( 16UL, 8UL, 2UL ); auto column_indices = generate_indices( 16UL, 8UL, 3UL ); RCMT sm1 = blaze::rows( blaze::columns( mat1_, column_indices.data(), column_indices.size() ), row_indices.data(), row_indices.size() ); DSMT sm2 = dilatedsubmatrix( mat2_, 16UL, 16UL, 8UL, 8UL, 2UL, 3UL ); blaze::DynamicMatrix<short,columnMajor> mat( 8UL, 8UL ); randomize( mat, short(randmin), short(randmax) ); sm1 *= mat; sm2 *= mat; checkRows ( sm1, 8UL ); checkColumns( sm1, 8UL ); checkRows ( sm2, 8UL ); checkColumns( sm2, 8UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } { test_ = "Row-major/column-major dense matrix multiplication assignment (aligned/padded)"; initialize(); auto row_indices = generate_indices( 16UL, 8UL, 2UL ); auto column_indices = generate_indices( 16UL, 8UL, 3UL ); RCMT sm1 = blaze::rows( blaze::columns( mat1_, column_indices.data(), column_indices.size() ), row_indices.data(), row_indices.size() ); DSMT sm2 = dilatedsubmatrix( mat2_, 16UL, 16UL, 8UL, 8UL, 2UL, 3UL ); using AlignedPadded = blaze::CustomMatrix<int,aligned,padded,columnMajor>; std::unique_ptr<int[],blaze::Deallocate> memory( blaze::allocate<int>( 128UL ) ); AlignedPadded mat( memory.get(), 8UL, 8UL, 16UL ); randomize( mat, int(randmin), int(randmax) ); sm1 *= mat; sm2 *= mat; checkRows ( sm1, 8UL ); checkColumns( sm1, 8UL ); checkRows ( sm2, 8UL ); checkColumns( sm2, 8UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } { test_ = "Row-major/column-major dense matrix multiplication assignment (unaligned/unpadded)"; initialize(); auto row_indices = generate_indices( 16UL, 8UL, 2UL ); auto column_indices = generate_indices( 16UL, 8UL, 3UL ); RCMT sm1 = blaze::rows( blaze::columns( mat1_, column_indices.data(), column_indices.size() ), row_indices.data(), row_indices.size() ); DSMT sm2 = dilatedsubmatrix( mat2_, 16UL, 16UL, 8UL, 8UL, 2UL, 3UL ); using UnalignedUnpadded = blaze::CustomMatrix<int,unaligned,unpadded,columnMajor>; std::unique_ptr<int[]> memory( new int[65UL] ); UnalignedUnpadded mat( memory.get()+1UL, 8UL, 8UL ); randomize( mat, int(randmin), int(randmax) ); sm1 *= mat; sm2 *= mat; checkRows ( sm1, 8UL ); checkColumns( sm1, 8UL ); checkRows ( sm2, 8UL ); checkColumns( sm2, 8UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Column-major dilatedsubmatrix multiplication assignment //===================================================================================== { test_ = "Column-major dilatedsubmatrix multiplication assignment (no aliasing)"; initialize(); OMT mat1( 64UL, 64UL ); OMT mat2( 64UL, 64UL ); randomize( mat1, int(randmin), int(randmax) ); mat2 = mat1; auto row_indices = generate_indices( 16UL, 8UL, 2UL ); auto column_indices = generate_indices( 8UL, 8UL, 3UL ); OCRMT sm1 = blaze::columns( blaze::rows( tmat1_, row_indices.data(), row_indices.size() ), column_indices.data(), column_indices.size() ); ODSMT sm2 = dilatedsubmatrix( tmat2_, 16UL, 8UL, 8UL, 8UL, 2UL, 3UL ); sm1 *= dilatedsubmatrix( mat1, 16UL, 16UL, 8UL, 8UL, 2UL, 3UL ); sm2 *= dilatedsubmatrix( mat2, 16UL, 16UL, 8UL, 8UL, 2UL, 3UL ); checkRows ( sm1, 8UL ); checkColumns( sm1, 8UL ); checkRows ( sm2, 8UL ); checkColumns( sm2, 8UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } { test_ = "Column-major dilatedsubmatrix multiplication assignment (aliasing)"; initialize(); auto row_indices = generate_indices( 16UL, 8UL, 2UL ); auto column_indices = generate_indices( 8UL, 8UL, 3UL ); OCRMT sm1 = blaze::columns( blaze::rows( tmat1_, row_indices.data(), row_indices.size() ), column_indices.data(), column_indices.size() ); ODSMT sm2 = dilatedsubmatrix( tmat2_, 16UL, 8UL, 8UL, 8UL, 2UL, 3UL ); sm1 *= dilatedsubmatrix( tmat1_, 16UL, 24UL, 8UL, 8UL, 1UL, 1UL ); sm2 *= dilatedsubmatrix( tmat2_, 16UL, 24UL, 8UL, 8UL, 1UL, 1UL ); checkRows ( sm1, 8UL ); checkColumns( sm1, 8UL ); checkRows ( sm2, 8UL ); checkColumns( sm2, 8UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Column-major dense matrix multiplication assignment //===================================================================================== { test_ = "Column-major/row-major dense matrix multiplication assignment (mixed type)"; initialize(); auto row_indices = generate_indices( 16UL, 8UL, 2UL ); auto column_indices = generate_indices( 8UL, 8UL, 3UL ); OCRMT sm1 = blaze::columns( blaze::rows( tmat1_, row_indices.data(), row_indices.size() ), column_indices.data(), column_indices.size() ); ODSMT sm2 = dilatedsubmatrix( tmat2_, 16UL, 8UL, 8UL, 8UL, 2UL, 3UL ); blaze::DynamicMatrix<short,rowMajor> mat( 8UL, 8UL ); randomize( mat, int(randmin), int(randmax) ); sm1 *= mat; sm2 *= mat; checkRows ( sm1, 8UL ); checkColumns( sm1, 8UL ); checkRows ( sm2, 8UL ); checkColumns( sm2, 8UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } { test_ = "Column-major/row-major dense matrix multiplication assignment (aligned/padded)"; initialize(); auto row_indices = generate_indices( 16UL, 8UL, 2UL ); auto column_indices = generate_indices( 8UL, 8UL, 3UL ); OCRMT sm1 = blaze::columns( blaze::rows( tmat1_, row_indices.data(), row_indices.size() ), column_indices.data(), column_indices.size() ); ODSMT sm2 = dilatedsubmatrix( tmat2_, 16UL, 8UL, 8UL, 8UL, 2UL, 3UL ); using AlignedPadded = blaze::CustomMatrix<int,aligned,padded,rowMajor>; std::unique_ptr<int[],blaze::Deallocate> memory( blaze::allocate<int>( 128UL ) ); AlignedPadded mat( memory.get(), 8UL, 8UL, 16UL ); randomize( mat, int(randmin), int(randmax) ); sm1 *= mat; sm2 *= mat; checkRows ( sm1, 8UL ); checkColumns( sm1, 8UL ); checkRows ( sm2, 8UL ); checkColumns( sm2, 8UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } { test_ = "Column-major/row-major dense matrix multiplication assignment (unaligned/unpadded)"; initialize(); auto row_indices = generate_indices( 16UL, 8UL, 2UL ); auto column_indices = generate_indices( 8UL, 8UL, 3UL ); OCRMT sm1 = blaze::columns( blaze::rows( tmat1_, row_indices.data(), row_indices.size() ), column_indices.data(), column_indices.size() ); ODSMT sm2 = dilatedsubmatrix( tmat2_, 16UL, 8UL, 8UL, 8UL, 2UL, 3UL ); using UnalignedUnpadded = blaze::CustomMatrix<int,unaligned,unpadded,rowMajor>; std::unique_ptr<int[]> memory( new int[65UL] ); UnalignedUnpadded mat( memory.get()+1UL, 8UL, 8UL ); randomize( mat, int(randmin), int(randmax) ); sm1 *= mat; sm2 *= mat; checkRows ( sm1, 8UL ); checkColumns( sm1, 8UL ); checkRows ( sm2, 8UL ); checkColumns( sm2, 8UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } { test_ = "Column-major/column-major dense matrix multiplication assignment (mixed type)"; initialize(); auto row_indices = generate_indices( 16UL, 8UL, 2UL ); auto column_indices = generate_indices( 8UL, 8UL, 3UL ); OCRMT sm1 = blaze::columns( blaze::rows( tmat1_, row_indices.data(), row_indices.size() ), column_indices.data(), column_indices.size() ); ODSMT sm2 = dilatedsubmatrix( tmat2_, 16UL, 8UL, 8UL, 8UL, 2UL, 3UL ); blaze::DynamicMatrix<short,columnMajor> mat( 8UL, 8UL ); randomize( mat, int(randmin), int(randmax) ); sm1 *= mat; sm2 *= mat; checkRows ( sm1, 8UL ); checkColumns( sm1, 8UL ); checkRows ( sm2, 8UL ); checkColumns( sm2, 8UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } { test_ = "Column-major/column-major dense matrix multiplication assignment (aligned/padded)"; initialize(); auto row_indices = generate_indices( 16UL, 8UL, 2UL ); auto column_indices = generate_indices( 8UL, 8UL, 3UL ); OCRMT sm1 = blaze::columns( blaze::rows( tmat1_, row_indices.data(), row_indices.size() ), column_indices.data(), column_indices.size() ); ODSMT sm2 = dilatedsubmatrix( tmat2_, 16UL, 8UL, 8UL, 8UL, 2UL, 3UL ); using AlignedPadded = blaze::CustomMatrix<int,aligned,padded,columnMajor>; std::unique_ptr<int[],blaze::Deallocate> memory( blaze::allocate<int>( 128UL ) ); AlignedPadded mat( memory.get(), 8UL, 8UL, 16UL ); randomize( mat, int(randmin), int(randmax) ); sm1 *= mat; sm2 *= mat; checkRows ( sm1, 8UL ); checkColumns( sm1, 8UL ); checkRows ( sm2, 8UL ); checkColumns( sm2, 8UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } { test_ = "Column-major/column-major dense matrix multiplication assignment (unaligned/unpadded)"; initialize(); auto row_indices = generate_indices( 16UL, 8UL, 2UL ); auto column_indices = generate_indices( 8UL, 8UL, 3UL ); OCRMT sm1 = blaze::columns( blaze::rows( tmat1_, row_indices.data(), row_indices.size() ), column_indices.data(), column_indices.size() ); ODSMT sm2 = dilatedsubmatrix( tmat2_, 16UL, 8UL, 8UL, 8UL, 2UL, 3UL ); using UnalignedUnpadded = blaze::CustomMatrix<int,unaligned,unpadded,columnMajor>; std::unique_ptr<int[]> memory( new int[65UL] ); UnalignedUnpadded mat( memory.get()+1UL, 8UL, 8UL ); randomize( mat, int(randmin), int(randmax) ); sm1 *= mat; sm2 *= mat; checkRows ( sm1, 8UL ); checkColumns( sm1, 8UL ); checkRows ( sm2, 8UL ); checkColumns( sm2, 8UL ); if( sm1 != sm2 || mat1_ != mat2_ ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment failed\n" << " Details:\n" << " Result:\n" << sm1 << "\n" << " Expected result:\n" << sm2 << "\n"; throw std::runtime_error( oss.str() ); } } } //************************************************************************************************* //================================================================================================= // // UTILITY FUNCTIONS // //================================================================================================= //************************************************************************************************* /*!\brief Initialization of all member matrices. // // \return void // \exception std::runtime_error Error detected. // // This function initializes all member matrices to specific predetermined values. */ void DenseTest::initialize() { // Initializing the row-major dynamic matrices randomize( mat1_, int(randmin), int(randmax) ); mat2_ = mat1_; // Initializing the column-major dynamic matrices randomize( tmat1_, int(randmin), int(randmax) ); tmat2_ = tmat1_; } //************************************************************************************************* //************************************************************************************************* /*!\brief Create dilated sequence of elements. // // \return elements // // This function returns a sequence of element indices. */ std::vector<size_t> DenseTest::generate_indices(size_t offset, size_t n, size_t dilation) { std::vector<size_t> indices; for( size_t i = 0; i != n; ++i ) { indices.push_back( offset + i * dilation ); } return indices; } //************************************************************************************************* } // namespace dilatedsubmatrix } // namespace mathtest } // namespace blazetest //================================================================================================= // // MAIN FUNCTION // //================================================================================================= //************************************************************************************************* int main() { std::cout << " Running dilatedsubmatrix dense test ..." << std::endl; try { RUN_DILATEDSUBMATRIX_DENSE_TEST; } catch( std::exception& ex ) { std::cerr << "\n\n ERROR DETECTED during dilatedsubmatrix dense test (part 1):\n" << ex.what() << "\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; } //*************************************************************************************************
35.281865
115
0.514462
[ "vector" ]
b8e123ae953fc489fca5ffc173f6012157488257
24,193
hpp
C++
visa/iga/IGALibrary/Backend/Native/InstEncoder.hpp
dkurt/intel-graphics-compiler
247cfb9ca64bc187ee9cf3b437ad184fb2d5c471
[ "MIT" ]
null
null
null
visa/iga/IGALibrary/Backend/Native/InstEncoder.hpp
dkurt/intel-graphics-compiler
247cfb9ca64bc187ee9cf3b437ad184fb2d5c471
[ "MIT" ]
null
null
null
visa/iga/IGALibrary/Backend/Native/InstEncoder.hpp
dkurt/intel-graphics-compiler
247cfb9ca64bc187ee9cf3b437ad184fb2d5c471
[ "MIT" ]
null
null
null
/*===================== begin_copyright_notice ================================== Copyright (c) 2017 Intel Corporation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ======================= end_copyright_notice ==================================*/ #ifndef IGA_BACKEND_NATIVE_INSTENCODER_HPP #define IGA_BACKEND_NATIVE_INSTENCODER_HPP #include "MInst.hpp" #include "Field.hpp" #include "../BitProcessor.hpp" #include "../EncoderOpts.hpp" #include "../../IR/Kernel.hpp" #include "../../asserts.hpp" #include "../../bits.hpp" // #include <cstdint> #include <functional> #include <sstream> #include <string> #include <vector> // #ifdef _DEBUG // IGA_VALIDATE_BITS adds extra structures and code to ensure that each bit // the instruction encoded gets written at most once. This can catch // accidental field overlaps quite effectively. // // The neceessary assumption follows that encoders must not get lazy or sloppy // and just clobber bits. Set it once only. #define IGA_VALIDATE_BITS #endif namespace iga { // immLo <= offset < immHi static inline bool rangeContains(int immLo, int immHi, int offset) { return immLo <= offset && offset < immHi; } struct InstEncoderState { int instIndex = 0; const Instruction* inst = nullptr; #ifdef IGA_VALIDATE_BITS // All the bit fields set by some field during this instruction encoding // e.g. if a field with bits [127:96] is set to 00000000....0001b // this bit mask will contain 1111....111b's for that field // This allows us to detect writing to two overlapped fields, which // indicates an internal logical error in the encoder. MInst dirty; // This contains a list of all the fields we set during an instruction // encoding so we can run through the list and determine which fields // overlapped. std::vector<const Field *> fieldsSet; #endif InstEncoderState( int _instIndex , const Instruction *_inst #ifdef IGA_VALIDATE_BITS , const MInst &_dirty , const std::vector<const Field*> &_fieldsSet #endif ) : instIndex(_instIndex) , inst(_inst) #ifdef IGA_VALIDATE_BITS , dirty(_dirty) , fieldsSet(_fieldsSet) #endif { } InstEncoderState() { } }; struct Backpatch { InstEncoderState state; const Block *target; const Field &field; enum Type {REL, ABS} type; Backpatch( InstEncoderState &_state, const Block *_target, const Field &_field, Type _type = REL) : state(_state) , target(_target) , field(_field) , type(_type) { } // TODO: determine where copy construction used to eliminate // Backpatch(const Backpatch&) = delete; }; typedef std::vector<Backpatch> BackpatchList; // can be passed into the encoding if we want to know the result struct CompactionDebugInfo { std::vector<Op> fieldOps; // the op we were trying to compact std::vector<const CompactedField *> fieldMisses; // which indices missed std::vector<uint64_t> fieldMapping; // what we tried to match (parallel) }; enum CompactionResult { CR_SUCCESS, CR_NO_COMPACT, // {NoCompact} (or -Xnoautocompact and {} CR_NO_FORMAT, // e.g. send or jump CR_NO_AUTOCOMPACT, // no annotation and {Compacted} not set CR_MISS // fragment misses }; ////////////////////////////////////////////////////////// // generic encoder for all platforms // subclasses specialize the necessary functions class InstEncoder : public BitProcessor { // the encoder options (e.g. for auto-compaction) EncoderOpts opts; // The target bits to encode to MInst *bits = nullptr; // A backpatch list that we can add to. A parent encoder is permitted // to copy or shadow this list. Hence, this class may not assume the // state is preserved between the calls of encodeInstruction and // resolveBackpatch. BackpatchList backpatches; // state used by the encoder (can be saved for backpatches) InstEncoderState state; public: InstEncoder( const EncoderOpts &_opts, BitProcessor &_parent) : BitProcessor(_parent) , opts(_opts) { } InstEncoder(const InstEncoder&) = delete; BackpatchList &getBackpatches() {return backpatches;} const OpSpec &getOpSpec() const {return state.inst->getOpSpec();} // void setBits(MInst mi) {*bits = mi;} // MInst getBits() const {return *bits;} //////////////////////////////////////////////////////////////////////// // external interface (called by parent encoder; e.g. SerialEncoder) // //////////////////////////////////////////////////////////////////////// // Called externally by our parent encoder algorithm to start the encoding // of an instruction. The instruction size is determined by the compaction // bit in the target instruction. template <Platform P> void encodeInstruction( int ix, const Instruction &i, MInst *_bits) { setCurrInst(&i); state.instIndex = ix; state.inst = &i; #ifdef VALIDATE_BITS state.dirty.qw0 = 0; state.dirty.qw1 = 0; state.fieldsSet.clear(); #endif memset(_bits, 0, sizeof(*_bits)); bits = _bits; encodeForPlatform(P,i); } void resolveBackpatch(Backpatch &bp, MInst *_bits) { bits = _bits; state = bp.state; setCurrInst(bp.state.inst); if (bp.type == Backpatch::ABS) { encode(bp.field, bp.target->getPC()); } else { encode(bp.field, bp.target->getPC() - bp.state.inst->getPC()); } } ////////////////////////////////////////////////////// // internal (to the encoder package, not private) instances of // encodeForPlatform<P> and their subtrees will call these methods. ////////////////////////////////////////////////////// void registerBackpatch( const Field &f, const Block *b, Backpatch::Type t = Backpatch::Type::REL) { backpatches.emplace_back(state, b, f, t); } void encode(const Field &f, int32_t val) { encodeFieldBits(f, (uint32_t)val); } void encode(const Field &f, int64_t val) { encodeFieldBits(f, (uint64_t)val); } void encode(const Field &f, uint32_t val) { encodeFieldBits(f, (uint64_t)val); } void encode(const Field &f, uint64_t val) { encodeFieldBits(f, val); } void encode(const Field &f, bool val) { encodeFieldBits(f, val ? 1 : 0); } void encode(const Field &f, const Model &model, const OpSpec &os); void encode(const Field &f, ExecSize es); void encode(const Field &f, MathMacroExt acc); void encode(const Field &f, Region::Vert vt); void encode(const Field &f, Region::Width wi); void encode(const Field &f, Region::Horz hz); void encode(const Field &f, SrcModifier mods); template <OpIx IX> void encodeSubreg( const Field &f, RegName reg, RegRef rr, Type ty); void encodeReg( const Field &fREGFILE, const Field &fREG, RegName reg, int regNum); ////////////////////////////////////////////////////// // Helper Functions ////////////////////////////////////////////////////// void encodeFieldBits(const Field &f, uint64_t val) { checkFieldOverlaps(f); #ifndef _DEBUG // short circuit since we start with zeros // debug build can do the additional mask sanity check below if (val == 0) { return; } #endif uint64_t shiftedVal = val << f.offset % 64; // shift into position uint64_t mask = getFieldMask(f); if (shiftedVal & ~mask) { // either val has bits greater than what this field represents // or below the shift (e.g. smaller value than we accept) // e.g. Dst.Subreg[4:3] just has the high two bits of // the subregister and can't represent small values. // // Generally, this indicates an internal IGA problem: // e.g. something we need to catch during parse, IR check, or // some other higher level (i.e. we're looking at bad IR) error("0x%x: value too large or too small for %s", val, f.name); return; } bits->qws[f.offset / 64] |= shiftedVal; } uint64_t getFieldMask(const Field &f) const { return iga::getFieldMask<uint64_t>(f.offset, f.length); } uint64_t getFieldMaskUnshifted(const Field &f) const { return iga::getFieldMaskUnshifted<uint64_t>(f.length); } void encodingError(const std::string &msg) { encodingError("", msg); } void encodingError(const Field *f, const std::string &msg) { encodingError(f ? f->name : "", msg); } void encodingError(const Field &f, const std::string &msg) { encodingError(f.name, msg); } void encodingError(OpIx ix, const std::string &msg) { encodingError(ToStringOpIx(ix), msg); } void encodingError(const std::string &ctx, const std::string &msg) { if (ctx.empty()) { error(msg.c_str()); } else { std::stringstream ss; ss << ctx << ": " << msg; error(ss.str().c_str()); } } void internalErrorBadIR(const char *what) { error("INTERNAL ERROR: malformed IR: %s", what); } void internalErrorBadIR(const Field &f) { internalErrorBadIR(f.name); } template <typename T> void encodeEnum(const Field &f, T lo, T hi, T x) { if (x < lo || x > hi) { encodingError(f, "invalid value"); } encodeFieldBits(f, static_cast<uint64_t>(x)); } private: #ifdef VALIDATE_BITS void checkFieldOverlaps(const Field &f); // real work #else void checkFieldOverlaps(const Field &) { } // nop #endif private: void encodeForPlatform(Platform p, const Instruction &i); }; // end class InstEncoder /////////////////////////////////////////////////////////////////////////// // longer method implementations inline void InstEncoder::encode( const Field &f, const Model &model, const OpSpec &os) { if (!os.isValid()) { encodingError(f, "invalid opcode"); } encodeFieldBits(f, os.code); if (os.isSubop()) { int fcValue = os.functionControlValue; const OpSpec *parOp = model.lookupSubOpParent(os); IGA_ASSERT(parOp != nullptr, "cannot find SubOpParent"); IGA_ASSERT(parOp->functionControlFields[0].length >= 0, "cannot find subop fields"); for (int i = 0; i < sizeof(parOp->functionControlFields)/sizeof(parOp->functionControlFields[0]); i++) { if (parOp->functionControlFields[i].length == 0) { break; // previous fragment was last } uint64_t fragMask = getFieldMaskUnshifted(parOp->functionControlFields[i]); encode(parOp->functionControlFields[i], fcValue & fragMask); fcValue >>= parOp->functionControlFields[i].length; } } } #define ENCODING_CASE(X, V) case X: val = (V); break inline void InstEncoder::encode(const Field &f, ExecSize es) { uint64_t val = 0; switch (es) { ENCODING_CASE(ExecSize::SIMD1, 0); ENCODING_CASE(ExecSize::SIMD2, 1); ENCODING_CASE(ExecSize::SIMD4, 2); ENCODING_CASE(ExecSize::SIMD8, 3); ENCODING_CASE(ExecSize::SIMD16, 4); ENCODING_CASE(ExecSize::SIMD32, 5); default: internalErrorBadIR(f); } encodeFieldBits(f, val); } // encodes this as an math macro operand reference (e.g. r12.mme2) // *not* as an explicit operand (for context save and restore) inline void InstEncoder::encode(const Field &f, MathMacroExt mme) { uint64_t val = 0; switch (mme) { ENCODING_CASE(MathMacroExt::MME0, 0x0); ENCODING_CASE(MathMacroExt::MME1, 0x1); ENCODING_CASE(MathMacroExt::MME2, 0x2); ENCODING_CASE(MathMacroExt::MME3, 0x3); ENCODING_CASE(MathMacroExt::MME4, 0x4); ENCODING_CASE(MathMacroExt::MME5, 0x5); ENCODING_CASE(MathMacroExt::MME6, 0x6); ENCODING_CASE(MathMacroExt::MME7, 0x7); ENCODING_CASE(MathMacroExt::NOMME, 0x8); default: internalErrorBadIR(f); } encodeFieldBits(f, val); } inline void InstEncoder::encode(const Field &f, Region::Vert vt) { uint64_t val = 0; switch (vt) { ENCODING_CASE(Region::Vert::VT_0, 0); ENCODING_CASE(Region::Vert::VT_1, 1); ENCODING_CASE(Region::Vert::VT_2, 2); ENCODING_CASE(Region::Vert::VT_4, 3); ENCODING_CASE(Region::Vert::VT_8, 4); ENCODING_CASE(Region::Vert::VT_16, 5); ENCODING_CASE(Region::Vert::VT_32, 6); ENCODING_CASE(Region::Vert::VT_VxH, 0xF); default: internalErrorBadIR(f); } encodeFieldBits(f, val); } inline void InstEncoder::encode(const Field &f, Region::Width wi) { uint64_t val = 0; switch (wi) { ENCODING_CASE(Region::Width::WI_1, 0); ENCODING_CASE(Region::Width::WI_2, 1); ENCODING_CASE(Region::Width::WI_4, 2); ENCODING_CASE(Region::Width::WI_8, 3); ENCODING_CASE(Region::Width::WI_16, 4); default: internalErrorBadIR(f); } encodeFieldBits(f, val); } inline void InstEncoder::encode(const Field &f, Region::Horz hz) { uint64_t val = 0; switch (hz) { ENCODING_CASE(Region::Horz::HZ_0, 0); ENCODING_CASE(Region::Horz::HZ_1, 1); ENCODING_CASE(Region::Horz::HZ_2, 2); ENCODING_CASE(Region::Horz::HZ_4, 3); default: internalErrorBadIR(f); } encodeFieldBits(f, val); } inline void InstEncoder::encode(const Field &f, SrcModifier mods) { uint64_t val = 0; switch (mods) { ENCODING_CASE(SrcModifier::NONE, 0); ENCODING_CASE(SrcModifier::ABS, 1); ENCODING_CASE(SrcModifier::NEG, 2); ENCODING_CASE(SrcModifier::NEG_ABS, 3); default: internalErrorBadIR(f); } encodeFieldBits(f, val); } inline void InstEncoder::encodeReg( const Field &fREGFILE, const Field &fREG, RegName reg, int regNum) { uint64_t regFileVal = 0, val = 0; // regVal (ENCODING_CASE assumes "val") switch (reg) { ENCODING_CASE(RegName::ARF_NULL, 0); ENCODING_CASE(RegName::ARF_A, 1); ENCODING_CASE(RegName::ARF_ACC, 2); ENCODING_CASE(RegName::ARF_MME, 2); ENCODING_CASE(RegName::ARF_F, 3); ENCODING_CASE(RegName::ARF_CE, 4); ENCODING_CASE(RegName::ARF_MSG, 5); ENCODING_CASE(RegName::ARF_SP, 6); ENCODING_CASE(RegName::ARF_SR, 7); ENCODING_CASE(RegName::ARF_CR, 8); ENCODING_CASE(RegName::ARF_N, 9); ENCODING_CASE(RegName::ARF_IP, 10); ENCODING_CASE(RegName::ARF_TDR, 11); ENCODING_CASE(RegName::ARF_TM, 12); ENCODING_CASE(RegName::ARF_FC, 13); ENCODING_CASE(RegName::ARF_DBG, 15); case RegName::GRF_R: val = regNum; regFileVal = 1; break; default: internalErrorBadIR(fREG); } if (reg != RegName::GRF_R) { val = val << 4; val |= (regNum & 0xF); } encodeFieldBits(fREGFILE, regFileVal); encodeFieldBits(fREG, val); } #undef ENCODING_CASE template <OpIx IX> inline void InstEncoder::encodeSubreg( const Field &f, RegName reg, RegRef rr, Type ty) { uint64_t val = (uint64_t)rr.subRegNum; // branches have implicit :d val = ty == Type::INVALID ? 4*val : SubRegToBytesOffset((int)val, reg, ty); if (IX == OpIx::TER_DST) { if (val & 0x7) { // Dst.SubReg[4:3] encodingError(f, "field lacks the bits to encode this " "subregister (low bits are implicitly 0)"); } val >>= 3; // unscale } encodeFieldBits(f, val); } class InstCompactor : public BitProcessor { const OpSpec *os = nullptr; MInst compactedBits; MInst uncompactedBits; CompactionDebugInfo *compactionDebugInfo = nullptr; bool compactionMissed = false; // the compaction result (if compaction enabled) CompactionResult compactionResult = CompactionResult::CR_NO_COMPACT; // various platforms define this CompactionResult tryToCompactImpl(Platform p); public: InstCompactor(BitProcessor &_parent) : BitProcessor(_parent) { } template <Platform P> CompactionResult tryToCompact( const OpSpec *_os, MInst _uncompactedBits, // copy-in MInst *compactedBitsOutput, // output CompactionDebugInfo *cdbi) { os = _os; uncompactedBits = _uncompactedBits; compactedBits.qw0 = compactedBits.qw1 = 0; compactionDebugInfo = cdbi; auto cr = tryToCompactImpl(P); if (cr == CompactionResult::CR_SUCCESS) { // only clobber their memory if we succeed *compactedBitsOutput = compactedBits; } return cr; } /////////////////////////////////////////////////////////////////////// // used by child implementations const OpSpec &getOpSpec() const {return *os;} uint64_t getUncompactedField(const Field &f) const {return uncompactedBits.getField(f);} void setCompactedField(const Field &f, uint64_t val) { compactedBits.setField(f, val); } bool getCompactionMissed() const {return compactionMissed;} void setCompactionResult(CompactionResult cr) {compactionResult = cr;} void transferField(const Field &compactedField, const Field &nativeField) { IGA_ASSERT(compactedField.length == nativeField.length, "native and compaction field length mismatch"); compactedBits.setField(compactedField, uncompactedBits.getField(nativeField)); } // returns false upon failure (so we can exit compaction early) // // the immLo and immHi values tells us the range of bits that hold // immediate value bits; the bounds are [lo,hi): inclusive/exclusive bool compactIndex(const CompactedField &ci, int immLo, int immHi) { // fragments are ordered from high bit down to 0 // hence, we have to walk them in reverse order to build the // word in reverse order // // we build up the don't-care mask as we assemble the // desired mapping uint64_t relevantBits = 0xFFFFFFFFFFFFFFFFull; int indexOffset = 0; // offset into the compaction index value uint64_t mappedValue = 0; for (int i = (int)ci.numMappings - 1; i >= 0; i--) { const Field *mappedField = ci.mappings[i]; if (rangeContains(immLo, immHi, mappedField->offset) || rangeContains(immLo, immHi, mappedField->offset + mappedField->length - 1)) { // this is a don't-care field since the imm value expands // into this field; strip those bits out relevantBits &= ~getFieldMask<uint64_t>(indexOffset,mappedField->length); } else { // we omit the random bits in don't care fields to give us // a normalized lookup value (for debugging) // technically we can match any table entry for don't-care // bits uint64_t uncompactedValue = uncompactedBits.getField(*mappedField); setBits(&mappedValue, indexOffset, mappedField->length, uncompactedValue); } indexOffset += mappedField->length; } // TODO: make lookup constant (could use a prefix tree or just a simple hash) for (size_t i = 0; i < ci.numValues; i++) { if ((ci.values[i] & relevantBits) == mappedValue) { if (!compactedBits.setField(ci.index, (uint64_t)i)) { IGA_ASSERT_FALSE("compaction index overruns field"); } return true; // hit } } // compaction miss fail(ci, mappedValue); return compactionDebugInfo != nullptr; } bool compactIndex(const CompactedField &ci) { return compactIndex(ci, 0, 0); } void fail(const CompactedField &ci, uint64_t mappedValue) { if (compactionDebugInfo) { compactionDebugInfo->fieldOps.push_back(os->op); compactionDebugInfo->fieldMisses.push_back(&ci); compactionDebugInfo->fieldMapping.push_back(mappedValue); } compactionMissed = true; } }; // InstCompactor inline void InstEncoder::encodeForPlatform( Platform p, const Instruction &i) { switch (p) { case Platform::GENNEXT: default: encodingError("unsupported platform for native encoder"); } } inline CompactionResult InstCompactor::tryToCompactImpl(Platform p) { switch (p) { case Platform::GENNEXT: default: compactionMissed = true; IGA_ASSERT_FALSE("compaction not supported on this platform"); return CompactionResult::CR_NO_COMPACT; } } } // end iga::* #endif /* IGA_BACKEND_NATIVE_INSTENCODER_HPP */
38.462639
97
0.564791
[ "vector", "model" ]
b8e1dbf551d343270cdbcce834816346a2334ad9
11,596
cpp
C++
libraries/pico-vm/tests/spec/call_tests.cpp
PicoFoundation/Pico2
8367d9edede9a9f7b1277d08333785d3bcf093b2
[ "MIT" ]
null
null
null
libraries/pico-vm/tests/spec/call_tests.cpp
PicoFoundation/Pico2
8367d9edede9a9f7b1277d08333785d3bcf093b2
[ "MIT" ]
null
null
null
libraries/pico-vm/tests/spec/call_tests.cpp
PicoFoundation/Pico2
8367d9edede9a9f7b1277d08333785d3bcf093b2
[ "MIT" ]
1
2021-01-28T06:01:01.000Z
2021-01-28T06:01:01.000Z
#include <algorithm> #include <vector> #include <iostream> #include <iterator> #include <cmath> #include <cstdlib> #include <catch2/catch.hpp> #include <utils.hpp> #include <wasm_config.hpp> #include <picoio/vm/backend.hpp> using namespace picoio; using namespace picoio::vm; extern wasm_allocator wa; BACKEND_TEST_CASE( "Testing wasm <call_0_wasm>", "[call_0_wasm_tests]" ) { using backend_t = backend<std::nullptr_t, TestType>; auto code = backend_t::read_wasm( std::string(wasm_directory) + "call.0.wasm"); backend_t bkend( code ); bkend.set_wasm_allocator( &wa ); bkend.initialize(nullptr); CHECK(bkend.call_with_return(nullptr, "env", "type-i32")->to_ui32() == UINT32_C(306)); CHECK(bkend.call_with_return(nullptr, "env", "type-i64")->to_ui64() == UINT32_C(356)); CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "type-f32")->to_f32()) == UINT32_C(1165172736)); CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "type-f64")->to_f64()) == UINT64_C(4660882566700597248)); CHECK(bkend.call_with_return(nullptr, "env", "type-first-i32")->to_ui32() == UINT32_C(32)); CHECK(bkend.call_with_return(nullptr, "env", "type-first-i64")->to_ui64() == UINT32_C(64)); CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "type-first-f32")->to_f32()) == UINT32_C(1068037571)); CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "type-first-f64")->to_f64()) == UINT64_C(4610064722561534525)); CHECK(bkend.call_with_return(nullptr, "env", "type-second-i32")->to_ui32() == UINT32_C(32)); CHECK(bkend.call_with_return(nullptr, "env", "type-second-i64")->to_ui64() == UINT32_C(64)); CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "type-second-f32")->to_f32()) == UINT32_C(1107296256)); CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "type-second-f64")->to_f64()) == UINT64_C(4634211053438658150)); CHECK(bkend.call_with_return(nullptr, "env", "fac", UINT64_C(0))->to_ui64() == UINT32_C(1)); CHECK(bkend.call_with_return(nullptr, "env", "fac", UINT64_C(1))->to_ui64() == UINT32_C(1)); CHECK(bkend.call_with_return(nullptr, "env", "fac", UINT64_C(5))->to_ui64() == UINT32_C(120)); CHECK(bkend.call_with_return(nullptr, "env", "fac", UINT64_C(25))->to_ui64() == UINT32_C(7034535277573963776)); CHECK(bkend.call_with_return(nullptr, "env", "fac-acc", UINT64_C(0), UINT64_C(1))->to_ui64() == UINT32_C(1)); CHECK(bkend.call_with_return(nullptr, "env", "fac-acc", UINT64_C(1), UINT64_C(1))->to_ui64() == UINT32_C(1)); CHECK(bkend.call_with_return(nullptr, "env", "fac-acc", UINT64_C(5), UINT64_C(1))->to_ui64() == UINT32_C(120)); CHECK(bkend.call_with_return(nullptr, "env", "fac-acc", UINT64_C(25), UINT64_C(1))->to_ui64() == UINT32_C(7034535277573963776)); CHECK(bkend.call_with_return(nullptr, "env", "fib", UINT64_C(0))->to_ui64() == UINT32_C(1)); CHECK(bkend.call_with_return(nullptr, "env", "fib", UINT64_C(1))->to_ui64() == UINT32_C(1)); CHECK(bkend.call_with_return(nullptr, "env", "fib", UINT64_C(2))->to_ui64() == UINT32_C(2)); CHECK(bkend.call_with_return(nullptr, "env", "fib", UINT64_C(5))->to_ui64() == UINT32_C(8)); CHECK(bkend.call_with_return(nullptr, "env", "fib", UINT64_C(20))->to_ui64() == UINT32_C(10946)); CHECK(bkend.call_with_return(nullptr, "env", "even", UINT64_C(0))->to_ui32() == UINT32_C(44)); CHECK(bkend.call_with_return(nullptr, "env", "even", UINT64_C(1))->to_ui32() == UINT32_C(99)); CHECK(bkend.call_with_return(nullptr, "env", "even", UINT64_C(100))->to_ui32() == UINT32_C(44)); CHECK(bkend.call_with_return(nullptr, "env", "even", UINT64_C(77))->to_ui32() == UINT32_C(99)); CHECK(bkend.call_with_return(nullptr, "env", "odd", UINT64_C(0))->to_ui32() == UINT32_C(99)); CHECK(bkend.call_with_return(nullptr, "env", "odd", UINT64_C(1))->to_ui32() == UINT32_C(44)); CHECK(bkend.call_with_return(nullptr, "env", "odd", UINT64_C(200))->to_ui32() == UINT32_C(99)); CHECK(bkend.call_with_return(nullptr, "env", "odd", UINT64_C(77))->to_ui32() == UINT32_C(44)); CHECK(bkend.call_with_return(nullptr, "env", "as-select-first")->to_ui32() == UINT32_C(306)); CHECK(bkend.call_with_return(nullptr, "env", "as-select-mid")->to_ui32() == UINT32_C(2)); CHECK(bkend.call_with_return(nullptr, "env", "as-select-last")->to_ui32() == UINT32_C(2)); CHECK(bkend.call_with_return(nullptr, "env", "as-if-condition")->to_ui32() == UINT32_C(1)); CHECK(bkend.call_with_return(nullptr, "env", "as-br_if-first")->to_ui32() == UINT32_C(306)); CHECK(bkend.call_with_return(nullptr, "env", "as-br_if-last")->to_ui32() == UINT32_C(2)); CHECK(bkend.call_with_return(nullptr, "env", "as-br_table-first")->to_ui32() == UINT32_C(306)); CHECK(bkend.call_with_return(nullptr, "env", "as-br_table-last")->to_ui32() == UINT32_C(2)); CHECK(bkend.call_with_return(nullptr, "env", "as-call_indirect-first")->to_ui32() == UINT32_C(306)); CHECK(bkend.call_with_return(nullptr, "env", "as-call_indirect-mid")->to_ui32() == UINT32_C(2)); CHECK_THROWS_AS(bkend(nullptr, "env", "as-call_indirect-last"), std::exception); CHECK(!bkend.call_with_return(nullptr, "env", "as-store-first")); CHECK(!bkend.call_with_return(nullptr, "env", "as-store-last")); CHECK(bkend.call_with_return(nullptr, "env", "as-memory.grow-value")->to_ui32() == UINT32_C(1)); CHECK(bkend.call_with_return(nullptr, "env", "as-return-value")->to_ui32() == UINT32_C(306)); CHECK(!bkend.call_with_return(nullptr, "env", "as-drop-operand")); CHECK(bkend.call_with_return(nullptr, "env", "as-br-value")->to_ui32() == UINT32_C(306)); CHECK(bkend.call_with_return(nullptr, "env", "as-local.set-value")->to_ui32() == UINT32_C(306)); CHECK(bkend.call_with_return(nullptr, "env", "as-local.tee-value")->to_ui32() == UINT32_C(306)); CHECK(bkend.call_with_return(nullptr, "env", "as-global.set-value")->to_ui32() == UINT32_C(306)); CHECK(bkend.call_with_return(nullptr, "env", "as-load-operand")->to_ui32() == UINT32_C(1)); CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "as-unary-operand")->to_f32()) == UINT32_C(0)); CHECK(bkend.call_with_return(nullptr, "env", "as-binary-left")->to_ui32() == UINT32_C(11)); CHECK(bkend.call_with_return(nullptr, "env", "as-binary-right")->to_ui32() == UINT32_C(9)); CHECK(bkend.call_with_return(nullptr, "env", "as-test-operand")->to_ui32() == UINT32_C(0)); CHECK(bkend.call_with_return(nullptr, "env", "as-compare-left")->to_ui32() == UINT32_C(1)); CHECK(bkend.call_with_return(nullptr, "env", "as-compare-right")->to_ui32() == UINT32_C(1)); CHECK(bkend.call_with_return(nullptr, "env", "as-convert-operand")->to_ui64() == UINT32_C(1)); } BACKEND_TEST_CASE( "Testing wasm <call_1_wasm>", "[call_1_wasm_tests]" ) { using backend_t = backend<std::nullptr_t, TestType>; auto code = backend_t::read_wasm( std::string(wasm_directory) + "call.1.wasm"); CHECK_THROWS_AS(backend_t(code), std::exception); } BACKEND_TEST_CASE( "Testing wasm <call_10_wasm>", "[call_10_wasm_tests]" ) { using backend_t = backend<std::nullptr_t, TestType>; auto code = backend_t::read_wasm( std::string(wasm_directory) + "call.10.wasm"); CHECK_THROWS_AS(backend_t(code), std::exception); } BACKEND_TEST_CASE( "Testing wasm <call_11_wasm>", "[call_11_wasm_tests]" ) { using backend_t = backend<std::nullptr_t, TestType>; auto code = backend_t::read_wasm( std::string(wasm_directory) + "call.11.wasm"); CHECK_THROWS_AS(backend_t(code), std::exception); } BACKEND_TEST_CASE( "Testing wasm <call_12_wasm>", "[call_12_wasm_tests]" ) { using backend_t = backend<std::nullptr_t, TestType>; auto code = backend_t::read_wasm( std::string(wasm_directory) + "call.12.wasm"); CHECK_THROWS_AS(backend_t(code), std::exception); } BACKEND_TEST_CASE( "Testing wasm <call_13_wasm>", "[call_13_wasm_tests]" ) { using backend_t = backend<std::nullptr_t, TestType>; auto code = backend_t::read_wasm( std::string(wasm_directory) + "call.13.wasm"); CHECK_THROWS_AS(backend_t(code), std::exception); } BACKEND_TEST_CASE( "Testing wasm <call_14_wasm>", "[call_14_wasm_tests]" ) { using backend_t = backend<std::nullptr_t, TestType>; auto code = backend_t::read_wasm( std::string(wasm_directory) + "call.14.wasm"); CHECK_THROWS_AS(backend_t(code), std::exception); } BACKEND_TEST_CASE( "Testing wasm <call_15_wasm>", "[call_15_wasm_tests]" ) { using backend_t = backend<std::nullptr_t, TestType>; auto code = backend_t::read_wasm( std::string(wasm_directory) + "call.15.wasm"); CHECK_THROWS_AS(backend_t(code), std::exception); } BACKEND_TEST_CASE( "Testing wasm <call_16_wasm>", "[call_16_wasm_tests]" ) { using backend_t = backend<std::nullptr_t, TestType>; auto code = backend_t::read_wasm( std::string(wasm_directory) + "call.16.wasm"); CHECK_THROWS_AS(backend_t(code), std::exception); } BACKEND_TEST_CASE( "Testing wasm <call_17_wasm>", "[call_17_wasm_tests]" ) { using backend_t = backend<std::nullptr_t, TestType>; auto code = backend_t::read_wasm( std::string(wasm_directory) + "call.17.wasm"); CHECK_THROWS_AS(backend_t(code), std::exception); } BACKEND_TEST_CASE( "Testing wasm <call_18_wasm>", "[call_18_wasm_tests]" ) { using backend_t = backend<std::nullptr_t, TestType>; auto code = backend_t::read_wasm( std::string(wasm_directory) + "call.18.wasm"); CHECK_THROWS_AS(backend_t(code), std::exception); } BACKEND_TEST_CASE( "Testing wasm <call_2_wasm>", "[call_2_wasm_tests]" ) { using backend_t = backend<std::nullptr_t, TestType>; auto code = backend_t::read_wasm( std::string(wasm_directory) + "call.2.wasm"); CHECK_THROWS_AS(backend_t(code), std::exception); } BACKEND_TEST_CASE( "Testing wasm <call_3_wasm>", "[call_3_wasm_tests]" ) { using backend_t = backend<std::nullptr_t, TestType>; auto code = backend_t::read_wasm( std::string(wasm_directory) + "call.3.wasm"); CHECK_THROWS_AS(backend_t(code), std::exception); } BACKEND_TEST_CASE( "Testing wasm <call_4_wasm>", "[call_4_wasm_tests]" ) { using backend_t = backend<std::nullptr_t, TestType>; auto code = backend_t::read_wasm( std::string(wasm_directory) + "call.4.wasm"); CHECK_THROWS_AS(backend_t(code), std::exception); } BACKEND_TEST_CASE( "Testing wasm <call_5_wasm>", "[call_5_wasm_tests]" ) { using backend_t = backend<std::nullptr_t, TestType>; auto code = backend_t::read_wasm( std::string(wasm_directory) + "call.5.wasm"); CHECK_THROWS_AS(backend_t(code), std::exception); } BACKEND_TEST_CASE( "Testing wasm <call_6_wasm>", "[call_6_wasm_tests]" ) { using backend_t = backend<std::nullptr_t, TestType>; auto code = backend_t::read_wasm( std::string(wasm_directory) + "call.6.wasm"); CHECK_THROWS_AS(backend_t(code), std::exception); } BACKEND_TEST_CASE( "Testing wasm <call_7_wasm>", "[call_7_wasm_tests]" ) { using backend_t = backend<std::nullptr_t, TestType>; auto code = backend_t::read_wasm( std::string(wasm_directory) + "call.7.wasm"); CHECK_THROWS_AS(backend_t(code), std::exception); } BACKEND_TEST_CASE( "Testing wasm <call_8_wasm>", "[call_8_wasm_tests]" ) { using backend_t = backend<std::nullptr_t, TestType>; auto code = backend_t::read_wasm( std::string(wasm_directory) + "call.8.wasm"); CHECK_THROWS_AS(backend_t(code), std::exception); } BACKEND_TEST_CASE( "Testing wasm <call_9_wasm>", "[call_9_wasm_tests]" ) { using backend_t = backend<std::nullptr_t, TestType>; auto code = backend_t::read_wasm( std::string(wasm_directory) + "call.9.wasm"); CHECK_THROWS_AS(backend_t(code), std::exception); }
59.773196
131
0.706709
[ "vector" ]
b8f773c1fc81ff1af65088ac57d20e039f05279d
34,912
cc
C++
src/evaluators/bayesian_strategy_evaluator.cc
brettdh/instruments
7e07c1a9f63c9747360b543d140cff0603aa6f1c
[ "BSD-2-Clause" ]
1
2015-08-28T09:42:01.000Z
2015-08-28T09:42:01.000Z
src/evaluators/bayesian_strategy_evaluator.cc
brettdh/instruments
7e07c1a9f63c9747360b543d140cff0603aa6f1c
[ "BSD-2-Clause" ]
null
null
null
src/evaluators/bayesian_strategy_evaluator.cc
brettdh/instruments
7e07c1a9f63c9747360b543d140cff0603aa6f1c
[ "BSD-2-Clause" ]
null
null
null
#include "bayesian_strategy_evaluator.h" #include "estimator.h" #include "stats_distribution_binned.h" #include "debug.h" #include "timeops.h" #include "stopwatch.h" #include "error_weight_params.h" namespace inst = instruments; using inst::INFO; using inst::DEBUG; using inst::MAX_SAMPLES; #include <vector> #include <map> #include <functional> #include <algorithm> #include <stdexcept> #include <fstream> #include <sstream> #include <iomanip> #include <memory> using std::vector; using std::map; using std::make_pair; using std::runtime_error; using std::ostringstream; using std::istringstream; using std::ostream; using std::string; using std::setprecision; using std::setw; using std::ifstream; using std::ofstream; using std::endl; using std::pair; using std::any_of; using std::shared_ptr; #include <stdlib.h> #include <assert.h> #include <math.h> #include <float.h> static inline double my_fabs(double x) { // trick GDB into not being stupid. return ((double (*)(double)) fabs)(x); } typedef double (*combiner_fn_t)(double, double); template <typename T> class VectorLess { constexpr static double THRESHOLD = 0.0001; public: // return true iff first < second bool operator()(const vector<T>& first, const vector<T>& second) const { ASSERT(first.size() == second.size()); for (size_t i = 0; i < first.size(); ++i) { T diff = first[i] - second[i]; if (fabs(diff) > THRESHOLD) { return diff < 0.0; } } return false; } }; template <typename T> class VectorsEqual { VectorLess<T> less; public: bool operator()(const vector<T>& first, const vector<T>& second) const { return !(less(first, second) || less(second, first)); } }; class DistributionKey { public: DistributionKey(BayesianStrategyEvaluator *evaluator); ~DistributionKey(); void addEstimatorValue(Estimator *estimator, double value); void forEachEstimator(std::function<bool(Estimator *, double)> fn) const; bool operator<(const DistributionKey& other) const; bool operator==(const DistributionKey& other) const; ostream& print(ostream& os) const; size_t getPrintSize() const; private: static size_t VALUE_PRINT_WIDTH; typedef map<Estimator *, size_t> EstimatorIndicesMap; typedef shared_ptr<EstimatorIndicesMap> EstimatorIndicesMapPtr; typedef map<BayesianStrategyEvaluator *, EstimatorIndicesMapPtr> EstimatorIndicesByEvaluatorMap; static EstimatorIndicesByEvaluatorMap estimator_indices_maps; BayesianStrategyEvaluator *evaluator; shared_ptr<EstimatorIndicesMap> estimator_indices; vector<int> key; // list of indices into binned distribution VectorLess<int> less; VectorsEqual<int> equal; }; DistributionKey::EstimatorIndicesByEvaluatorMap DistributionKey::estimator_indices_maps; DistributionKey::DistributionKey(BayesianStrategyEvaluator *evaluator_) : evaluator(evaluator_) { if (estimator_indices_maps.count(evaluator) == 0) { estimator_indices_maps[evaluator].reset(new EstimatorIndicesMap); } estimator_indices = estimator_indices_maps[evaluator]; } DistributionKey::~DistributionKey() { if (estimator_indices.use_count() == 2) { // I'm the last DistributionKey from this evaluator to go away, // so only me and the global map hold references to this map estimator_indices_maps.erase(evaluator); } // managed map will get cleaned up by my shared_ptr's destructor } void DistributionKey::addEstimatorValue(Estimator *estimator, double value) { ASSERT(estimator_indices != nullptr); if (estimator_indices->count(estimator) == 0) { estimator_indices->insert(make_pair(estimator, estimator_indices->size())); } size_t index = estimator_indices->at(estimator); if (key.size() <= index) { key.resize(index + 1); } ASSERT(evaluator->estimatorSamples.count(estimator) > 0); size_t bin_index = evaluator->estimatorSamples[estimator]->getIndex(value); key[index] = bin_index; } void DistributionKey::forEachEstimator(std::function<bool(Estimator *, double)> fn) const { ASSERT(estimator_indices != nullptr); ASSERT(estimator_indices->size() == key.size()); for (auto& p : *estimator_indices) { Estimator *estimator = p.first; size_t index = p.second; ASSERT(index < key.size()); // unnecessary most of the time, except when the tail values can change. double value = evaluator->estimatorSamples[estimator]->getValueAtIndex(key[index]); if (fn(estimator, value) == false) { break; } } } bool DistributionKey::operator<(const DistributionKey& other) const { return less(key, other.key); } bool DistributionKey::operator==(const DistributionKey& other) const { return equal(key, other.key); } ostream& DistributionKey::print(ostream& os) const { os << "[ "; forEachEstimator([&](Estimator *estimator, double value) { os << setw(VALUE_PRINT_WIDTH) << value << " "; return true; }); os << "]"; return os; } ostream& operator<<(ostream& os, const DistributionKey& key) { return key.print(os); } size_t DistributionKey::VALUE_PRINT_WIDTH = 10; size_t DistributionKey::getPrintSize() const { const size_t extra_chars = 3; // "[ ... ]" return extra_chars + (VALUE_PRINT_WIDTH + 1) * estimator_indices->size(); } class BayesianStrategyEvaluator::SimpleEvaluator : public StrategyEvaluator { public: SimpleEvaluator(const string& name, const instruments_strategy_t *new_strategies, size_t num_strategies); ~SimpleEvaluator(); Strategy *chooseStrategy(void *chooser_arg); virtual double expectedValue(Strategy *strategy, typesafe_eval_fn_t fn, void *strategy_arg, void *chooser_arg, ComparisonType comparison_type); virtual double getAdjustedEstimatorValue(Estimator *estimator); // nothing to save/restore. virtual void saveToFile(const char *filename) {} virtual void restoreFromFileImpl(const char *filename) {} void setEstimatorValue(Estimator *estimator, double value); void setEstimatorValues(const vector<pair<Estimator *, double> >& new_estimator_values); vector<pair<Estimator *, double> > getEstimatorValues(); void clear(); private: map<Estimator *, double> estimator_values; }; class BayesianStrategyEvaluator::Likelihood { public: Likelihood(BayesianStrategyEvaluator *evaluator_); void addObservation(Estimator *estimator, double observation); void addDecision(const vector<pair<Estimator *,double> >& estimator_values); double getWeightedSum(SimpleEvaluator *tmp_simple_valuator, Strategy *strategy, typesafe_eval_fn_t fn, void *strategy_arg, void *chooser_arg); double getCurrentEstimatorSample(Estimator *estimator); void clear(); private: BayesianStrategyEvaluator *evaluator; map<Estimator *, double> last_observation; // for use during iterated weighted sum. map<Estimator *, double> currentEstimatorSamples; // Each value_type is a map of likelihood-value-tuples to // their likeihood decision histograms. // I keep these separately for each strategy for easy lookup // and iteration over only those estimators that matter // for the current strategy. typedef map<DistributionKey, DecisionsHistogram *> LikelihoodMap; LikelihoodMap likelihood_distribution; DistributionKey getCurrentEstimatorKey(const vector<pair<Estimator *, double> >& estimator_values); DistributionKey makeEstimatorKey(const vector<pair<Estimator *, double> >& estimator_values); void setEstimatorSamples(DistributionKey& key); double jointPriorProbability(DistributionKey& key); }; class BayesianStrategyEvaluator::DecisionsHistogram { public: DecisionsHistogram(BayesianStrategyEvaluator *evaluator_); void addDecision(const vector<pair<Estimator *,double> >& estimator_values); double getWinnerProbability(SimpleEvaluator *tmp_simple_evaluator, void *chooser_strategy, bool ensure_nonzero); void clear(); private: BayesianStrategyEvaluator *evaluator; vector<vector<pair<Estimator *, double> > > decisions; void *last_chooser_arg; map<Strategy *, double> last_winner_probability; }; BayesianStrategyEvaluator::BayesianStrategyEvaluator(bool weighted_) : simple_evaluator(NULL), weighted(weighted_) { likelihood = new Likelihood(this); normalizer = new DecisionsHistogram(this); } BayesianStrategyEvaluator::~BayesianStrategyEvaluator() { clearDistributions(); delete likelihood; delete normalizer; } void BayesianStrategyEvaluator::clearDistributions() { for (auto& p : estimatorSamples) { StatsDistributionBinned *distribution = p.second; delete distribution; } estimatorSamples.clear(); last_estimator_values.clear(); ordered_observations.clear(); num_historical_observations = 0; likelihood->clear(); normalizer->clear(); } string BayesianStrategyEvaluator::makeSimpleEvaluatorName() { ostringstream oss; oss << getName() << "-simple"; return oss.str(); } void BayesianStrategyEvaluator::setStrategies(const instruments_strategy_t *new_strategies, size_t num_strategies) { StrategyEvaluator::setStrategies(new_strategies, num_strategies); if (!simple_evaluator) { simple_evaluator = new SimpleEvaluator(makeSimpleEvaluatorName(), new_strategies, num_strategies); simple_evaluator->setSilent(true); } for (Estimator *estimator : getAllEstimators()) { estimators_by_name[estimator->getName()] = estimator; } } bool BayesianStrategyEvaluator::uninitializedStrategiesExist() { auto is_uninitialized = [&](Estimator *estimator) { return estimatorSamples.count(estimator) == 0; }; auto has_uninitialized_estimators = [&](Strategy *strategy) { if (strategy->isRedundant()) { // ignore; captured by child strategies' estimators return false; }; auto estimators = strategy->getEstimators(); return any_of(estimators.begin(), estimators.end(), is_uninitialized); }; return any_of(strategies.begin(), strategies.end(), has_uninitialized_estimators); } Strategy * BayesianStrategyEvaluator::getBestSingularStrategy(void *chooser_arg) { ASSERT(!uninitializedStrategiesExist()); return (Strategy *) simple_evaluator->chooseStrategy(chooser_arg); } double BayesianStrategyEvaluator::getAdjustedEstimatorValue(Estimator *estimator) { // it's bandwidth or latency stored in the distribution, rather // than an error value, so just return the value. // XXX-BAYESIAN: yes, this may over-emphasize history. known (potential) issue. return likelihood->getCurrentEstimatorSample(estimator); } void BayesianStrategyEvaluator::processObservation(Estimator *estimator, double observation, double old_estimate, double new_estimate) { inst::dbgprintf(INFO, "[bayesian] %s evaluator: Adding observation %f to estimator %s\n", getName(), observation, estimator->getName().c_str()); bool add_decision = !uninitializedStrategiesExist(); const string& name = estimator->getName(); if (estimators_by_name.count(name) == 0) { estimators_by_name[name] = estimator; } if (estimatorSamples.count(estimator) == 0) { estimatorSamples[estimator] = createStatsDistribution(estimator); } estimatorSamples[estimator]->addValue(observation); likelihood->addObservation(estimator, observation); if (add_decision) { auto estimator_values = simple_evaluator->getEstimatorValues(); likelihood->addDecision(estimator_values); normalizer->addDecision(estimator_values); } ordered_observations.push_back({estimator->getName(), observation, old_estimate, new_estimate}); simple_evaluator->setEstimatorValue(estimator, new_estimate); } void BayesianStrategyEvaluator::processEstimatorReset(Estimator *estimator, const char *filename) { decltype(ordered_observations) replay_observations; if (filename) { // get all observations since the last restore replay_observations.assign(ordered_observations.begin() + num_historical_observations, ordered_observations.end()); restoreFromFileImpl(filename); } else { replay_observations = ordered_observations; clearDistributions(); } string estimator_name = estimator->getName(); // make sure there's at least one observation for this estimator // (the first one among the ones we're choosing not to replay) bool no_observations = (!filename); // replay the observations for all other estimators for (auto& obs : replay_observations) { if (obs.estimator_name != estimator_name || no_observations) { Estimator *other_estimator = getEstimator(obs.estimator_name); processObservation(other_estimator, obs.observation, obs.old_estimate, obs.new_estimate); if (no_observations && obs.estimator_name == estimator_name) { no_observations = false; } } } } StatsDistributionBinned * BayesianStrategyEvaluator::createStatsDistribution(Estimator *estimator) { return StatsDistributionBinned::create(estimator, weighted); } #include <functional> static inline double min(double a, double b) { return (a < b) ? a : b; } static inline double sum(double a, double b) { return a + b; } combiner_fn_t get_combiner_fn(typesafe_eval_fn_t fn) { if (fn == redundant_strategy_minimum_time) { return min; } else if (fn == redundant_strategy_total_energy_cost || fn == redundant_strategy_total_data_cost) { return sum; } else { return NULL; } } double BayesianStrategyEvaluator::expectedValue(Strategy *strategy, typesafe_eval_fn_t fn, void *strategy_arg, void *chooser_arg, ComparisonType comparison_type) { instruments_strategy_t *strategies_array = new instruments_strategy_t[strategies.size()]; for (size_t i = 0; i < strategies.size(); ++i) { strategies_array[i] = strategies[i]; } // temporary, so don't store updates to me SimpleEvaluator tmp_simple_evaluator(makeSimpleEvaluatorName(), strategies_array, strategies.size()); delete [] strategies_array; tmp_simple_evaluator.setSilent(true); return likelihood->getWeightedSum(&tmp_simple_evaluator, strategy, fn, strategy_arg, chooser_arg); } BayesianStrategyEvaluator::Likelihood::Likelihood(BayesianStrategyEvaluator *evaluator_) : evaluator(evaluator_) { } void BayesianStrategyEvaluator::Likelihood::addObservation(Estimator *estimator, double observation) { last_observation[estimator] = observation; } void BayesianStrategyEvaluator::Likelihood::addDecision(const vector<pair<Estimator *,double> >& estimator_values) { // get the current key over all estimators (vector of bins, based on estimator values) // look up the histogram in the likelihood map // add an entry to the decisions pseudo-histogram DistributionKey key = getCurrentEstimatorKey(estimator_values); if (likelihood_distribution.count(key) == 0) { // make sure that all vectors used as keys for the map have the same length ASSERT(likelihood_distribution.empty() || (likelihood_distribution.begin()->first == key || !(likelihood_distribution.begin()->first == key))); likelihood_distribution[key] = new DecisionsHistogram(evaluator); } DecisionsHistogram *histogram = likelihood_distribution[key]; ASSERT(histogram); histogram->addDecision(estimator_values); } void BayesianStrategyEvaluator::Likelihood::setEstimatorSamples(DistributionKey& key) { key.forEachEstimator([&](Estimator *estimator, double sample) { currentEstimatorSamples[estimator] = sample; return true; }); } DistributionKey BayesianStrategyEvaluator::Likelihood::getCurrentEstimatorKey(const vector<pair<Estimator *, double> >& estimator_values) { DistributionKey key(evaluator); for (auto& p : estimator_values) { Estimator *estimator = p.first; ASSERT(last_observation.count(estimator) > 0); double obs = last_observation[estimator]; key.addEstimatorValue(estimator, obs); } return key; } DistributionKey BayesianStrategyEvaluator::Likelihood::makeEstimatorKey(const vector<pair<Estimator *, double> >& estimator_values) { DistributionKey key(evaluator); for (auto& p : estimator_values) { Estimator *estimator = p.first; double obs = p.second; key.addEstimatorValue(estimator, obs); } return key; } double BayesianStrategyEvaluator::Likelihood::getCurrentEstimatorSample(Estimator *estimator) { ASSERT(currentEstimatorSamples.count(estimator) > 0); return currentEstimatorSamples[estimator]; } double BayesianStrategyEvaluator::Likelihood::jointPriorProbability(DistributionKey& key) { double probability = 1.0; static ostringstream oss; if (inst::is_debugging_on(DEBUG)) { oss.str(""); } key.forEachEstimator([&](Estimator *estimator, double sample) { ASSERT(evaluator->estimatorSamples.count(estimator) > 0); if (!estimator->valueMeetsConditions(sample)) { // we're doing a conditional probability summation, so // prune this sample from the joint prior distribution probability = 0.0; return false; // break the foreach iteration } double single_prob = evaluator->estimatorSamples[estimator]->getProbability(sample); probability *= single_prob; if (inst::is_debugging_on(DEBUG)) { oss << single_prob << " "; } return true; }); /* if (inst::is_debugging_on(DEBUG)) { string s = oss.str(); dbgprintf(DEBUG, "Probabilities: %s joint: %f\n", s.c_str(), probability); } */ return probability; } #ifdef NDEBUG #define assert_valid_probability(value) #else #define assert_valid_probability(value) \ do { \ const double threshold = 0.00001; \ if (value < -threshold || value - 1.0 > threshold) { \ fprintf(stderr, "%s (%f) is invalid probability at %s:%d\n", \ #value, value, __FILE__, __LINE__); \ ASSERT(false); \ } \ } while (0) #endif double BayesianStrategyEvaluator::Likelihood::getWeightedSum(SimpleEvaluator *tmp_simple_evaluator, Strategy *strategy, typesafe_eval_fn_t fn, void *strategy_arg, void *chooser_arg) { double weightedSum = 0.0; #ifndef NDEBUG double prior_sum = 0.0; #endif double posterior_sum = 0.0; const auto& estimator_values = evaluator->simple_evaluator->getEstimatorValues(); DistributionKey cur_key = getCurrentEstimatorKey(estimator_values); string value_name = get_value_name(strategy, fn); bool debugging = inst::is_debugging_on(DEBUG); if (likelihood_distribution.empty()) { inst::dbgprintf(DEBUG, "[bayesian] (no entries in likelihood distribution)\n"); } else { size_t print_size = likelihood_distribution.begin()->first.getPrintSize(); inst::dbgprintf(DEBUG, "[bayesian] %*s %13s %10s %10s %10s\n", print_size - 2, "key", "prior", "likelihood", "posterior", value_name.c_str()); } // Store joint_prior along with decisions histogram // in order to set the single joint probability // in the extreme corner case map<DistributionKey, pair<double, DecisionsHistogram *> > pruned_likelihood_distribution; for (const LikelihoodMap::reference map_pair : likelihood_distribution) { DistributionKey key = map_pair.first; DecisionsHistogram *histogram = map_pair.second; double joint_prior = jointPriorProbability(key); if (joint_prior > 0.0) { pruned_likelihood_distribution[key] = make_pair(joint_prior, histogram); } } DecisionsHistogram *dummy_decision = nullptr; if (pruned_likelihood_distribution.empty()) { // I have no history that helps me decide what to do; // all my history is ruled out by the conditional bounds. // Therefore, I just return the function call value with the // last estimator values, conditional bounds considered // (which is essentially what the other methods are doing in this case too). auto dummy_estimator_values = evaluator->simple_evaluator->getEstimatorValues(); for (auto& p : dummy_estimator_values) { Estimator *estimator = p.first; double& value = p.second; // there may be multiple estimators out of bounds; // make sure we get them all if (!estimator->valueMeetsConditions(value)) { value = estimator->getConditionalBound(); } } tmp_simple_evaluator->setEstimatorValues(dummy_estimator_values); if (inst::is_debugging_on(inst::DEBUG)) { ostringstream s; for (auto& p : dummy_estimator_values) { s << p.second << " "; } inst::dbgprintf(inst::DEBUG, "History all pruned by conditional bounds; Just using estimator values: %s\n", s.str().c_str()); } return tmp_simple_evaluator->expectedValue(strategy, fn, strategy_arg, chooser_arg, COMPARISON_TYPE_IRRELEVANT); } Stopwatch stopwatch; stopwatch.setEnabled(debugging); for (auto& map_pair : pruned_likelihood_distribution) { DistributionKey key = map_pair.first; auto& value_pair = map_pair.second; double joint_prior = value_pair.first; DecisionsHistogram *histogram = value_pair.second; stopwatch.start("setEstimatorSamples"); setEstimatorSamples(key); stopwatch.start("eval_fn"); double value = fn(evaluator, strategy_arg, chooser_arg); stopwatch.stop(); double prior = joint_prior; assert_valid_probability(prior); #ifndef NDEBUG prior_sum += prior; assert_valid_probability(prior_sum); #endif bool ensure_nonzero = (cur_key == key); stopwatch.start("likelihood"); double likelihood_coeff = histogram->getWinnerProbability(tmp_simple_evaluator, chooser_arg, ensure_nonzero); stopwatch.stop(); if (likelihood_coeff == 0.0) { stopwatch.start("posterior"); stopwatch.start("printing"); stopwatch.start("remaining summation"); stopwatch.stop(); stopwatch.freezeLabels(); continue; } stopwatch.start("posterior"); double posterior = prior * likelihood_coeff; stopwatch.stop(); assert_valid_probability(likelihood_coeff); assert_valid_probability(posterior); stopwatch.start("printing"); if (debugging) { ostringstream s; s << "[bayesian] " << key << " " << setw(13) << prior << " " << setw(10) << likelihood_coeff << " " << setw(10) << posterior << " " << setw(10) << value; inst::dbgprintf(DEBUG, "%s\n", s.str().c_str()); } stopwatch.start("remaining summation"); posterior_sum += posterior; assert_valid_probability(posterior_sum); weightedSum += value * posterior; stopwatch.stop(); stopwatch.freezeLabels(); } if (debugging) { inst::dbgprintf(DEBUG, "[bayesian] calc times: [ %s ]\n", stopwatch.toString().c_str()); } delete dummy_decision; inst::dbgprintf(INFO, "[bayesian] calculated posterior from %zu samples\n", pruned_likelihood_distribution.size()); #ifndef NDEBUG inst::dbgprintf(INFO, "[bayesian] prior sum: %f\n", prior_sum); #endif inst::dbgprintf(INFO, "[bayesian] posterior sum: %f\n", posterior_sum); // here's the normalization. summing the posterior values ensures that // I'm using the correct value. ASSERT(posterior_sum > 0.0); return weightedSum / posterior_sum; } void BayesianStrategyEvaluator::Likelihood::clear() { last_observation.clear(); currentEstimatorSamples.clear(); for (auto& q : likelihood_distribution) { DecisionsHistogram *histogram = q.second; delete histogram; } likelihood_distribution.clear(); } BayesianStrategyEvaluator::DecisionsHistogram:: DecisionsHistogram(BayesianStrategyEvaluator *evaluator_) : evaluator(evaluator_), last_chooser_arg(NULL) { } void BayesianStrategyEvaluator::DecisionsHistogram::clear() { decisions.clear(); } void BayesianStrategyEvaluator::DecisionsHistogram:: addDecision(const vector<pair<Estimator *, double> >& estimator_values) { decisions.push_back(estimator_values); last_winner_probability.clear(); // needs to be recalculated // TODO: can do better. calculate this value every time a decision is added. // TODO: calculating it is very cheap, too (don't need to recompute everything // TODO: until the chooser_arg changes) } double BayesianStrategyEvaluator::DecisionsHistogram::getWinnerProbability(SimpleEvaluator *tmp_simple_evaluator, void *chooser_arg, bool ensure_nonzero) { bool debugging = inst::is_debugging_on(DEBUG); Stopwatch stopwatch; stopwatch.setEnabled(debugging); Strategy *winner = evaluator->getBestSingularStrategy(chooser_arg); ASSERT(winner); if (chooser_arg == last_chooser_arg) { if (last_winner_probability.count(winner) > 0) { return last_winner_probability[winner]; } } else { last_winner_probability.clear(); } size_t cur_wins = 0; size_t cur_decisions = decisions.size(); for (auto decision : decisions) { stopwatch.start("setEstimatorValues"); tmp_simple_evaluator->setEstimatorValues(decision); stopwatch.start("chooseStrategy"); Strategy *cur_winner = (Strategy *) tmp_simple_evaluator->chooseStrategy(chooser_arg); stopwatch.start("summation"); if (cur_winner == winner) { cur_wins++; } stopwatch.stop(); stopwatch.freezeLabels(); } if (debugging) { inst::dbgprintf(DEBUG, "[bayesian] winner calc times: [ %s ]\n", stopwatch.toString().c_str()); } if (cur_wins == 0 && ensure_nonzero) { ++cur_wins; ++cur_decisions; } double prob = cur_wins / ((double) cur_decisions); last_chooser_arg = chooser_arg; last_winner_probability[winner] = prob; return prob; } static int PRECISION = 20; static void write_estimate(ostream& out, double estimate) { if (estimate_is_valid(estimate)) { out << estimate << " "; } else { out << "(invalid) "; } } static std::istream& read_estimate(std::istream& in, double& estimate) { string estimate_str; if (in >> estimate_str) { istringstream s(estimate_str); if (!(s >> estimate)) { estimate = invalid_estimate(); } } return in; } void BayesianStrategyEvaluator::saveToFile(const char *filename) { ostringstream err("Failed to open "); err << filename; ofstream out(filename); check(out, err.str()); out << estimators_by_name.size() << " estimators" << endl; out << "name hint_min hint_max hint_num_bins" << endl; for (auto& p : estimators_by_name) { const string& name = p.first; Estimator *estimator = p.second; out << name << " "; if (estimator->hasRangeHints()) { EstimatorRangeHints hints = estimator->getRangeHints(); out << hints.min << " " << hints.max << " " << hints.num_bins; } else { out << "none none none"; } out << endl; } out << endl; out << ordered_observations.size() << " observations" << endl; out << "name observation old_estimate new_estimate" << endl; for (const stored_observation& obs : ordered_observations) { out << obs.estimator_name << " " << setprecision(PRECISION) << obs.observation << " "; write_estimate(out, obs.old_estimate); write_estimate(out, obs.new_estimate); out << endl; check(out, "Failed to save bayesian evaluator to file"); } out.close(); } void BayesianStrategyEvaluator::restoreFromFileImpl(const char *filename) { inst::dbgprintf(INFO, "Restoring Bayesian distribution from %s\n", filename); clearDistributions(); ostringstream err("Failed to open "); err << filename; ifstream in(filename); check(in, err.str()); size_t i = 0; size_t num_observations; string name; double old_estimate; double new_estimate; double observation; string header; size_t num_estimators; check(in >> num_estimators >> header, "Failed to read num_estimators"); check(getline(in, header), "Unexpected EOF"); // consume newline check(getline(in, header), "Failed to read estimators-header"); for (i = 0; i < num_estimators; ++i) { string line; check(getline(in, line), "Failed to get an estimator's hints or lack thereof"); istringstream iss(line); check(iss >> name, "Failed to get estimator name"); EstimatorRangeHints hints; Estimator *estimator = getEstimator(name); if (iss >> hints.min >> hints.max >> hints.num_bins) { estimator->setRangeHints(hints.min, hints.max, hints.num_bins); } // else: no hints, ignore line } check(getline(in, header), "Missing blank line"); // ignore blank line check(in >> num_observations >> header, "Failed to read num_observations"); check(getline(in, header), "Unexpected EOF"); // consume newline check(getline(in, header), "Failed to read header"); // ignore header i = 0; while ((in >> name >> observation) && read_estimate(in, old_estimate) && read_estimate(in, new_estimate)) { Estimator *estimator = getEstimator(name); processObservation(estimator, observation, old_estimate, new_estimate); ++i; } in.close(); check(num_observations == i, "Got wrong number of observations"); num_historical_observations = ordered_observations.size(); } Estimator * BayesianStrategyEvaluator::getEstimator(const string& name) { ASSERT(estimators_by_name.count(name) > 0); return estimators_by_name[name]; } BayesianStrategyEvaluator::SimpleEvaluator::SimpleEvaluator(const string& name, const instruments_strategy_t *new_strategies, size_t num_strategies) : StrategyEvaluator(true) // these don't need updates from estimators { setName(name.c_str()); instruments_strategy_t *singular_strategies = new instruments_strategy_t[num_strategies]; size_t count = 0; for (size_t i = 0; i < num_strategies; ++i) { Strategy *strategy = (Strategy*) new_strategies[i]; if (!strategy->isRedundant()) { singular_strategies[count++] = new_strategies[i]; } } StrategyEvaluator::setStrategies(singular_strategies, count); delete [] singular_strategies; inst::dbgprintf(INFO, "[bayesian] %s evaluator: Creating simple evaluator %p\n", getName(), this); } BayesianStrategyEvaluator::SimpleEvaluator::~SimpleEvaluator() { inst::dbgprintf(INFO, "[bayesian] %s evaluator: Destroying simple evaluator %p\n", getName(), this); } Strategy * BayesianStrategyEvaluator::SimpleEvaluator::chooseStrategy(void *chooser_arg) { double min_time = DBL_MAX; Strategy *winner = NULL; for (Strategy *strategy : strategies) { double time = strategy->calculateTime(this, chooser_arg, COMPARISON_TYPE_IRRELEVANT); if (!winner || time < min_time) { winner = strategy; min_time = time; } } return winner; } double BayesianStrategyEvaluator::SimpleEvaluator::expectedValue(Strategy *strategy, typesafe_eval_fn_t fn, void *strategy_arg, void *chooser_arg, ComparisonType comparison_type) { return fn(this, strategy_arg, chooser_arg); } double BayesianStrategyEvaluator::SimpleEvaluator::getAdjustedEstimatorValue(Estimator *estimator) { if (estimator_values.count(estimator) > 0) { return estimator_values[estimator]; } else { // this should only happen once, when I have no history on this estimator. return estimator->getEstimate(); } } void BayesianStrategyEvaluator::SimpleEvaluator::setEstimatorValue(Estimator *estimator, double value) { estimator_values[estimator] = value; } void BayesianStrategyEvaluator::SimpleEvaluator::setEstimatorValues(const vector<pair<Estimator *, double> >& new_estimator_values) { for (auto p : new_estimator_values) { Estimator *estimator = p.first; double value = p.second; setEstimatorValue(estimator, value); } } vector<pair<Estimator *, double> > BayesianStrategyEvaluator::SimpleEvaluator::getEstimatorValues() { vector<pair<Estimator *, double> > estimator_value_pairs; for (auto p : estimator_values) { Estimator *estimator = p.first; double value = p.second; estimator_value_pairs.push_back(make_pair(estimator, value)); } return estimator_value_pairs; }
33.569231
126
0.656422
[ "vector" ]
b8f93a3f0682a62391ebe5e53acf8327f416ca7e
2,604
cpp
C++
SOURCE/Dictionary.cpp
dousu/MSILM
470d3af9b28c1fa88a7daa5f7c9ba562f2b61c48
[ "MIT" ]
null
null
null
SOURCE/Dictionary.cpp
dousu/MSILM
470d3af9b28c1fa88a7daa5f7c9ba562f2b61c48
[ "MIT" ]
8
2018-06-13T07:14:38.000Z
2018-07-01T14:19:04.000Z
SOURCE/Dictionary.cpp
dousu/MSILM
470d3af9b28c1fa88a7daa5f7c9ba562f2b61c48
[ "MIT" ]
null
null
null
/* * Dictionary.cpp * * Created on: 2012/11/23 * Author: Hiroki Sudo */ #include "Dictionary.h" std::map<int, std::string> Dictionary::individual; std::map<int, std::string> Dictionary::symbol; std::map<std::string, int> Dictionary::conv_individual; std::map<std::string, int> Dictionary::conv_symbol; void Dictionary::load(std::string file_path) { std::string line; std::ifstream source(file_path.c_str()); //read test if (!source.good()) { std::cerr << "not found dictionary file" << std::endl; exit(1); } //read items std::vector<std::string> individual_buffer; std::vector<std::string> symbol_buffer; while (std::getline(source, line)) { const std::regex line_code("[(\r\n)\n]"); auto del_line_code = std::sregex_token_iterator(std::begin(line), std::end(line), line_code, -1); //getlineで1行だということが保証されていると仮定 std::string str = *del_line_code; const std::regex re("[,=]"); std::sregex_token_iterator it(std::begin(str), std::end(str), re, -1), it_end; if (*it == "IND") { it++; std::copy(it, it_end, std::back_inserter(individual_buffer)); } else if (*it == "SYM") { it++; std::copy(it, it_end, std::back_inserter(symbol_buffer)); } else { std::cerr << "undefined key\"" << (*it) << "\"" << std::endl; exit(1); } } if (symbol_buffer.size() == 0 || individual_buffer.size() == 0) { std::cerr << "no dictionary data" << std::endl; exit(1); } //store items int index; std::vector<std::string>::iterator it; it = individual_buffer.begin(); index = 0; while (it != individual_buffer.end()) { if (individual.find(index) == individual.end() && conv_individual.find(*it) == conv_individual.end()) { individual.insert(std::map<int, std::string>::value_type(index, *it)); conv_individual.insert( std::map<std::string, int>::value_type(*it, index)); } if (index + 1 <= index) { std::cerr << "range over" << std::endl; exit(1); } index++; it++; } it = symbol_buffer.begin(); index = 0; while (it != symbol_buffer.end()) { if (symbol.find(index) == symbol.end() && conv_symbol.find(*it) == conv_symbol.end()) { symbol.insert(std::map<int, std::string>::value_type(index, *it)); conv_symbol.insert(std::map<std::string, int>::value_type(*it, index)); } if (index + 1 <= index) { std::cerr << "range over" << std::endl; exit(1); } index++; it++; } } Dictionary Dictionary::copy(void) { return Dictionary(); }
24.566038
131
0.589478
[ "vector" ]
b8fe0c6436a57b2bede16ddfed33fa16cdbfed4c
645
cpp
C++
src/main.cpp
kanishkarj/3d-map-simulator
a14121bbb861e371ba9121aead9f11e9f84a7f3d
[ "MIT" ]
1
2020-02-02T15:31:00.000Z
2020-02-02T15:31:00.000Z
src/main.cpp
kanishkarj/3d-map-simulator
a14121bbb861e371ba9121aead9f11e9f84a7f3d
[ "MIT" ]
null
null
null
src/main.cpp
kanishkarj/3d-map-simulator
a14121bbb861e371ba9121aead9f11e9f84a7f3d
[ "MIT" ]
1
2021-02-06T17:39:59.000Z
2021-02-06T17:39:59.000Z
#include<bits/stdc++.h> #include <GL/glut.h> #include "../include/vec3f.h" #include "../include/terrain.h" #include "../include/imageloader.h" #include "../include/renderer.h" Terrain* _terrain = new Terrain("./resources/heightmap.bmp", 50); int main(int argc, char** argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(800, 600); glutCreateWindow("3D Map simulator"); initRendering(); glutDisplayFunc(drawScene); glutKeyboardFunc(keyboard); glutSetCursor(GLUT_CURSOR_NONE); glutPassiveMotionFunc(mouse); glutReshapeFunc(handleResize); glutMainLoop(); return 0; }
24.807692
65
0.730233
[ "3d" ]
770592f1adc005185ce79bdc3cc13e01e1d8e638
3,272
cpp
C++
code/juryjeopardy.cpp
matthewReff/Kattis-Problems
848628af630c990fb91bde6256a77afad6a3f5f6
[ "MIT" ]
8
2020-02-21T22:21:01.000Z
2022-02-16T05:30:54.000Z
code/juryjeopardy.cpp
matthewReff/Kattis-Problems
848628af630c990fb91bde6256a77afad6a3f5f6
[ "MIT" ]
null
null
null
code/juryjeopardy.cpp
matthewReff/Kattis-Problems
848628af630c990fb91bde6256a77afad6a3f5f6
[ "MIT" ]
3
2020-08-05T05:42:35.000Z
2021-08-30T05:39:51.000Z
#define _USE_MATH_DEFINES #include <iostream> #include <stdio.h> #include <cmath> #include <iomanip> #include <vector> #include <string> #include <algorithm> #include <unordered_set> #include <unordered_map> #include <ctype.h> #include <queue> #include <map> #include <set> typedef long long ll; typedef unsigned long long ull; using namespace std; int main() { ll i, j, k; ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); ll cases; string path; cin >> cases; map<char, int> directionMapping; directionMapping['F'] = 0; directionMapping['R'] = 1; directionMapping['B'] = 2; directionMapping['L'] = 3; map<pair<ll, ll>, int> reverseDirectionMapping; reverseDirectionMapping[make_pair(-1, 0)] = 0; reverseDirectionMapping[make_pair(0, 1)] = 1; reverseDirectionMapping[make_pair(1, 0)] = 2; reverseDirectionMapping[make_pair(0, -1)] = 3; // clockwise from 'up' is 0-4, first entry being current direction and second being new vector<vector<pair<ll, ll>>> newDirections(4); newDirections[0].push_back(make_pair(-1, 0)); newDirections[0].push_back(make_pair(0, 1)); newDirections[0].push_back(make_pair(1, 0)); newDirections[0].push_back(make_pair(0, -1)); newDirections[1].push_back(make_pair(0, 1)); newDirections[1].push_back(make_pair(1, 0)); newDirections[1].push_back(make_pair(0, -1)); newDirections[1].push_back(make_pair(-1, 0)); newDirections[2].push_back(make_pair(1, 0)); newDirections[2].push_back(make_pair(0, -1)); newDirections[2].push_back(make_pair(-1, 0)); newDirections[2].push_back(make_pair(0, 1)); newDirections[3].push_back(make_pair(0, -1)); newDirections[3].push_back(make_pair(-1, 0)); newDirections[3].push_back(make_pair(0, 1)); newDirections[3].push_back(make_pair(1, 0)); cout << cases << "\n"; for(i = 0; i < cases; i++) { cin >> path; ll lastDirection = 1; vector<pair<ll, ll>> reached; reached.push_back(make_pair(0, 0)); pair<ll, ll> currentLoc = make_pair(0, 0); for(auto step : path) { pair<ll, ll> nextMove = newDirections[lastDirection][directionMapping[step]]; currentLoc.first += nextMove.first; currentLoc.second += nextMove.second; reached.push_back(currentLoc); lastDirection = reverseDirectionMapping[nextMove]; } ll furthestUp = 999999; ll furthestdown = -999999; ll furthestright = -999999; for(auto locPair : reached) { furthestUp = min(furthestUp, locPair.first); furthestdown = max(furthestdown, locPair.first); furthestright = max(furthestright, locPair.second); } for(j = 0; j < (int)reached.size(); j++) { reached[j].first += -furthestUp; } ll rowResult = -furthestUp + furthestdown + 3; ll colResult = furthestright + 2; vector<string> outArr(rowResult); for(j = 0; j < rowResult; j++) { outArr[j].resize(colResult, '#'); } for(auto locPair : reached) { outArr[locPair.first+1][locPair.second] = '.'; } cout << rowResult << " " << colResult << "\n"; for(auto rowString : outArr) { cout << rowString << "\n"; } } return 0; }
27.041322
91
0.632335
[ "vector" ]
7707951def20b22206e60446772be97e17fccae9
714
cpp
C++
leetcode.com/0477 Total Hamming Distance/main.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
1
2020-08-20T11:02:49.000Z
2020-08-20T11:02:49.000Z
leetcode.com/0477 Total Hamming Distance/main.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
null
null
null
leetcode.com/0477 Total Hamming Distance/main.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
1
2022-01-01T23:23:13.000Z
2022-01-01T23:23:13.000Z
#include <iostream> #include <vector> using namespace std; class Solution { public: int totalHammingDistance(vector<int>& nums) { int res = 0, ones, sz = nums.size(); for (int i = 0; i <= 30; ++i) { ones = 0; for (int num : nums) { ones += (num >> i) & 1; } res += (sz - ones) * ones; } return res; } }; class Solution2 { public: int totalHammingDistance(vector<int>& nums) { int res = 0; for (int i = 0; i <= 30; i += 2) { int cnt[4]{}; for (int num : nums) { cnt[(num >> i) & 3]++; } res += (cnt[1] + cnt[2]) * (cnt[0] + cnt[3]) + 2 * (cnt[1] * cnt[2] + cnt[0] * cnt[3]); } return res; } };
20.4
53
0.463585
[ "vector" ]
771876a397d255a0bd78d4277e937cfabaf489b1
3,466
cpp
C++
src/actor.cpp
Axram/Roguelike
d6b557968f7b29c255e79cf8c668b63716f6daf1
[ "MIT" ]
null
null
null
src/actor.cpp
Axram/Roguelike
d6b557968f7b29c255e79cf8c668b63716f6daf1
[ "MIT" ]
null
null
null
src/actor.cpp
Axram/Roguelike
d6b557968f7b29c255e79cf8c668b63716f6daf1
[ "MIT" ]
null
null
null
#include "actor.hpp" #include <cassert> Actor::Actor(){} void Actor::move(int dx, int dy){ //Player uses its own move with added prints _px += dx; _py += dy; std::string out_str = _name + " moves to " + std::to_string(_px) +";" +std::to_string(_py)+ "."; scroll(_textbox); mvwprintw(_textbox,1,1, "%s", out_str.c_str()); wrefresh(_textbox); } Actor::Actor(int hp, int attack, int defense, int experience, int exp_worth, int speed, int speed_c ){ _hp = hp; _attack = attack; _defense = defense; _experience = experience; _experience_worth = exp_worth; _speed = speed; _speed_counter = speed_c; //std::cout << _hp << std::endl; //std::cout << _attack << std::endl; //std::cout << _defense << std::endl; //assert(false); } /* void Actor::set_vars(int hp, int attack, int defense, int experience, int exp_worth, int speed, int speed_c){ _hp = hp; _attack = attack; _defense = defense; _experience = experience; _experience_worth = exp_worth; _speed = speed; _speed_counter = speed_c; } */ bool Actor::may_act(){ ++_speed_counter; if(_speed_counter > _speed){ _speed_counter = 0; return true; } return false; } bool Actor::damage(int amount){ int resulting_damage = amount - _defense; if(resulting_damage < 0) resulting_damage = 0; _hp -= resulting_damage; std::string out_str = _name + " is dealt " + std::to_string(resulting_damage) + " damage!"; scroll(_textbox); mvwprintw(_textbox,1,1, "%s", out_str.c_str()); wrefresh(_textbox); if(_hp <= 0){ std::string out_str = _name + " dies!"; scroll(_textbox); mvwprintw(_textbox,1,1, "%s", out_str.c_str()); wrefresh(_textbox); _to_be_removed = true; return true; } return false; } void Actor::heal(int amount){ } void Actor::attack(Actor & target){ std::string out_str = _name + " attacks " + target.get_name() + "."; scroll(_textbox); mvwprintw(_textbox,1,1, "%s", out_str.c_str()); wrefresh(_textbox); target.damage(_attack); } std::vector<Item*>* Actor::get_inventory(){ return & _inventory; } void Actor::add_item(Item * newitem){ _inventory.push_back(newitem); } void Actor::interact(Structure * target){ std::string out_str = _name + " interacts with " + target->get_name() + "."; scroll(_textbox); mvwprintw(_textbox,1,1, "%s", out_str.c_str()); wrefresh(_textbox); target->interact(&_inventory); } std::string Actor::get_data(){ std::string return_data; return_data += _name+'\n'; return_data += std::to_string(_px)+'\n'; return_data += std::to_string(_py)+'\n'; return_data += std::to_string(_hp)+'\n'; return_data += std::to_string(_experience)+'\n'; for(auto i = _inventory.begin(); i != _inventory.end(); ++i){ return_data += (**i).get_name() + '\n'; } return_data += "$\n"; return return_data; } std::string Actor::get_data_new(){ std::string s = ""; s += Gameobject::get_data_new(); s += std::to_string(_hp) + '\n'; s += std::to_string(_attack) + '\n'; s += std::to_string(_defense) + '\n'; s += std::to_string(_experience) + '\n'; s += std::to_string(_experience_worth) + '\n'; s += std::to_string(_speed) + '\n'; s += std::to_string(_speed_counter) + '\n'; for(auto i = _inventory.begin(); i != _inventory.end(); ++i){ s += (**i).get_name() + '\n'; } s += "$\n"; return s; } void Actor::remove_items(){ for(auto i = _inventory.begin(); i != _inventory.end(); ++i){ delete *i; } }
26.06015
109
0.630987
[ "vector" ]
771dab7dee1dcf3ad94cfa774a2f803a1de6bf8d
904
cpp
C++
Problem Solving Paradigm/Greedy/Involving Sorting (Or The Input Is Already Sorted)/12210.cpp
joe-stifler/uHunt
02465ea9868403691e4f0aaa6ddde730afa11f47
[ "MIT" ]
3
2019-05-22T00:36:23.000Z
2021-03-22T12:23:18.000Z
Problem Solving Paradigm/Greedy/Involving Sorting (Or The Input Is Already Sorted)/12210.cpp
joe-stifler/uHunt
02465ea9868403691e4f0aaa6ddde730afa11f47
[ "MIT" ]
null
null
null
Problem Solving Paradigm/Greedy/Involving Sorting (Or The Input Is Already Sorted)/12210.cpp
joe-stifler/uHunt
02465ea9868403691e4f0aaa6ddde730afa11f47
[ "MIT" ]
null
null
null
/*------------------------------------------------*/ // Uva Problem No: 12210 // Problem Name: A Match Making Problem // Type: Involving Sorting (Greedy) // Autor: Joe Stifler // Data: 2018-06-17 03:33:20 // Runtime: 0.010s // Universidade: Unicamp /*------------------------------------------------*/ #include <bits/stdc++.h> using namespace std; int main() { int test = 1; while (true) { int b, s; scanf("%d %d", &b, &s); if (b == 0 || s == 0) break; int menor = 1000; vector<int> m(b), f(s); for (int i = 0; i < b; i++) { scanf("%d", &m[i]); menor = min(menor, m[i]); } for (int i = 0; i < s; i++) scanf("%d", &f[i]); int total = max(0, b - s); printf("Case %d: %d", test, total); if (b > s) printf(" %d", menor); printf("\n"); test++; } return 0; }
22.6
55
0.404867
[ "vector" ]
771f360b9cd086cc4966cb0f11b5961074decb57
9,922
cpp
C++
component/oai-amf/src/sbi/amf_server/model/N1N2MessageTransferReqData.cpp
kukkalli/oai-cn5g-fed
15634fac935ac8671b61654bdf75bf8af07d3c3a
[ "Apache-2.0" ]
null
null
null
component/oai-amf/src/sbi/amf_server/model/N1N2MessageTransferReqData.cpp
kukkalli/oai-cn5g-fed
15634fac935ac8671b61654bdf75bf8af07d3c3a
[ "Apache-2.0" ]
null
null
null
component/oai-amf/src/sbi/amf_server/model/N1N2MessageTransferReqData.cpp
kukkalli/oai-cn5g-fed
15634fac935ac8671b61654bdf75bf8af07d3c3a
[ "Apache-2.0" ]
null
null
null
/** * Namf_Communication * AMF Communication Service © 2019, 3GPP Organizational Partners (ARIB, ATIS, * CCSA, ETSI, TSDSI, TTA, TTC). All rights reserved. * * The version of the OpenAPI document: 1.1.0.alpha-1 * * * NOTE: This class is auto generated by OpenAPI Generator * (https://openapi-generator.tech). https://openapi-generator.tech Do not edit * the class manually. */ #include "N1N2MessageTransferReqData.h" namespace oai { namespace amf { namespace model { N1N2MessageTransferReqData::N1N2MessageTransferReqData() { m_N1MessageContainerIsSet = false; m_N2InfoContainerIsSet = false; m_SkipInd = false; m_SkipIndIsSet = false; m_LastMsgIndication = false; m_LastMsgIndicationIsSet = false; m_PduSessionId = 0; m_PduSessionIdIsSet = false; m_LcsCorrelationId = ""; m_LcsCorrelationIdIsSet = false; m_Ppi = 0; m_PpiIsSet = false; m_ArpIsSet = false; m__5qi = 0; m__5qiIsSet = false; m_N1n2FailureTxfNotifURI = ""; m_N1n2FailureTxfNotifURIIsSet = false; m_SmfReallocationInd = false; m_SmfReallocationIndIsSet = false; m_AreaOfValidityIsSet = false; m_SupportedFeatures = ""; m_SupportedFeaturesIsSet = false; } N1N2MessageTransferReqData::~N1N2MessageTransferReqData() {} void N1N2MessageTransferReqData::validate() { // TODO: implement validation } void to_json(nlohmann::json& j, const N1N2MessageTransferReqData& o) { j = nlohmann::json(); if (o.n1MessageContainerIsSet()) j["n1MessageContainer"] = o.m_N1MessageContainer; if (o.n2InfoContainerIsSet()) j["n2InfoContainer"] = o.m_N2InfoContainer; if (o.skipIndIsSet()) j["skipInd"] = o.m_SkipInd; if (o.lastMsgIndicationIsSet()) j["lastMsgIndication"] = o.m_LastMsgIndication; if (o.pduSessionIdIsSet()) j["pduSessionId"] = o.m_PduSessionId; if (o.lcsCorrelationIdIsSet()) j["lcsCorrelationId"] = o.m_LcsCorrelationId; if (o.ppiIsSet()) j["ppi"] = o.m_Ppi; if (o.arpIsSet()) j["arp"] = o.m_Arp; if (o._5qiIsSet()) j["5qi"] = o.m__5qi; if (o.n1n2FailureTxfNotifURIIsSet()) j["n1n2FailureTxfNotifURI"] = o.m_N1n2FailureTxfNotifURI; if (o.smfReallocationIndIsSet()) j["smfReallocationInd"] = o.m_SmfReallocationInd; if (o.areaOfValidityIsSet()) j["areaOfValidity"] = o.m_AreaOfValidity; if (o.supportedFeaturesIsSet()) j["supportedFeatures"] = o.m_SupportedFeatures; } void from_json(const nlohmann::json& j, N1N2MessageTransferReqData& o) { if (j.find("n1MessageContainer") != j.end()) { // j.at("n1MessageContainer").get_to(o.m_N1MessageContainer); // o.m_N1MessageContainerIsSet = true; } if (j.find("n2InfoContainer") != j.end()) { // j.at("n2InfoContainer").get_to(o.m_N2InfoContainer); // o.m_N2InfoContainerIsSet = true; } if (j.find("skipInd") != j.end()) { j.at("skipInd").get_to(o.m_SkipInd); o.m_SkipIndIsSet = true; } if (j.find("lastMsgIndication") != j.end()) { j.at("lastMsgIndication").get_to(o.m_LastMsgIndication); o.m_LastMsgIndicationIsSet = true; } if (j.find("pduSessionId") != j.end()) { j.at("pduSessionId").get_to(o.m_PduSessionId); o.m_PduSessionIdIsSet = true; } if (j.find("lcsCorrelationId") != j.end()) { j.at("lcsCorrelationId").get_to(o.m_LcsCorrelationId); o.m_LcsCorrelationIdIsSet = true; } if (j.find("ppi") != j.end()) { j.at("ppi").get_to(o.m_Ppi); o.m_PpiIsSet = true; } if (j.find("arp") != j.end()) { j.at("arp").get_to(o.m_Arp); o.m_ArpIsSet = true; } if (j.find("5qi") != j.end()) { j.at("5qi").get_to(o.m__5qi); o.m__5qiIsSet = true; } if (j.find("n1n2FailureTxfNotifURI") != j.end()) { j.at("n1n2FailureTxfNotifURI").get_to(o.m_N1n2FailureTxfNotifURI); o.m_N1n2FailureTxfNotifURIIsSet = true; } if (j.find("smfReallocationInd") != j.end()) { j.at("smfReallocationInd").get_to(o.m_SmfReallocationInd); o.m_SmfReallocationIndIsSet = true; } if (j.find("areaOfValidity") != j.end()) { j.at("areaOfValidity").get_to(o.m_AreaOfValidity); o.m_AreaOfValidityIsSet = true; } if (j.find("supportedFeatures") != j.end()) { j.at("supportedFeatures").get_to(o.m_SupportedFeatures); o.m_SupportedFeaturesIsSet = true; } } N1MessageContainer N1N2MessageTransferReqData::getN1MessageContainer() const { return m_N1MessageContainer; } void N1N2MessageTransferReqData::setN1MessageContainer( N1MessageContainer const& value) { m_N1MessageContainer = value; m_N1MessageContainerIsSet = true; } bool N1N2MessageTransferReqData::n1MessageContainerIsSet() const { return m_N1MessageContainerIsSet; } void N1N2MessageTransferReqData::unsetN1MessageContainer() { m_N1MessageContainerIsSet = false; } N2InfoContainer N1N2MessageTransferReqData::getN2InfoContainer() const { return m_N2InfoContainer; } void N1N2MessageTransferReqData::setN2InfoContainer( N2InfoContainer const& value) { m_N2InfoContainer = value; m_N2InfoContainerIsSet = true; } bool N1N2MessageTransferReqData::n2InfoContainerIsSet() const { return m_N2InfoContainerIsSet; } void N1N2MessageTransferReqData::unsetN2InfoContainer() { m_N2InfoContainerIsSet = false; } bool N1N2MessageTransferReqData::isSkipInd() const { return m_SkipInd; } void N1N2MessageTransferReqData::setSkipInd(bool const value) { m_SkipInd = value; m_SkipIndIsSet = true; } bool N1N2MessageTransferReqData::skipIndIsSet() const { return m_SkipIndIsSet; } void N1N2MessageTransferReqData::unsetSkipInd() { m_SkipIndIsSet = false; } bool N1N2MessageTransferReqData::isLastMsgIndication() const { return m_LastMsgIndication; } void N1N2MessageTransferReqData::setLastMsgIndication(bool const value) { m_LastMsgIndication = value; m_LastMsgIndicationIsSet = true; } bool N1N2MessageTransferReqData::lastMsgIndicationIsSet() const { return m_LastMsgIndicationIsSet; } void N1N2MessageTransferReqData::unsetLastMsgIndication() { m_LastMsgIndicationIsSet = false; } int32_t N1N2MessageTransferReqData::getPduSessionId() const { return m_PduSessionId; } void N1N2MessageTransferReqData::setPduSessionId(int32_t const value) { m_PduSessionId = value; m_PduSessionIdIsSet = true; } bool N1N2MessageTransferReqData::pduSessionIdIsSet() const { return m_PduSessionIdIsSet; } void N1N2MessageTransferReqData::unsetPduSessionId() { m_PduSessionIdIsSet = false; } std::string N1N2MessageTransferReqData::getLcsCorrelationId() const { return m_LcsCorrelationId; } void N1N2MessageTransferReqData::setLcsCorrelationId(std::string const& value) { m_LcsCorrelationId = value; m_LcsCorrelationIdIsSet = true; } bool N1N2MessageTransferReqData::lcsCorrelationIdIsSet() const { return m_LcsCorrelationIdIsSet; } void N1N2MessageTransferReqData::unsetLcsCorrelationId() { m_LcsCorrelationIdIsSet = false; } int32_t N1N2MessageTransferReqData::getPpi() const { return m_Ppi; } void N1N2MessageTransferReqData::setPpi(int32_t const value) { m_Ppi = value; m_PpiIsSet = true; } bool N1N2MessageTransferReqData::ppiIsSet() const { return m_PpiIsSet; } void N1N2MessageTransferReqData::unsetPpi() { m_PpiIsSet = false; } Arp N1N2MessageTransferReqData::getArp() const { return m_Arp; } void N1N2MessageTransferReqData::setArp(Arp const& value) { m_Arp = value; m_ArpIsSet = true; } bool N1N2MessageTransferReqData::arpIsSet() const { return m_ArpIsSet; } void N1N2MessageTransferReqData::unsetArp() { m_ArpIsSet = false; } int32_t N1N2MessageTransferReqData::get5qi() const { return m__5qi; } void N1N2MessageTransferReqData::set5qi(int32_t const value) { m__5qi = value; m__5qiIsSet = true; } bool N1N2MessageTransferReqData::_5qiIsSet() const { return m__5qiIsSet; } void N1N2MessageTransferReqData::unset_5qi() { m__5qiIsSet = false; } std::string N1N2MessageTransferReqData::getN1n2FailureTxfNotifURI() const { return m_N1n2FailureTxfNotifURI; } void N1N2MessageTransferReqData::setN1n2FailureTxfNotifURI( std::string const& value) { m_N1n2FailureTxfNotifURI = value; m_N1n2FailureTxfNotifURIIsSet = true; } bool N1N2MessageTransferReqData::n1n2FailureTxfNotifURIIsSet() const { return m_N1n2FailureTxfNotifURIIsSet; } void N1N2MessageTransferReqData::unsetN1n2FailureTxfNotifURI() { m_N1n2FailureTxfNotifURIIsSet = false; } bool N1N2MessageTransferReqData::isSmfReallocationInd() const { return m_SmfReallocationInd; } void N1N2MessageTransferReqData::setSmfReallocationInd(bool const value) { m_SmfReallocationInd = value; m_SmfReallocationIndIsSet = true; } bool N1N2MessageTransferReqData::smfReallocationIndIsSet() const { return m_SmfReallocationIndIsSet; } void N1N2MessageTransferReqData::unsetSmfReallocationInd() { m_SmfReallocationIndIsSet = false; } AreaOfValidity N1N2MessageTransferReqData::getAreaOfValidity() const { return m_AreaOfValidity; } void N1N2MessageTransferReqData::setAreaOfValidity( AreaOfValidity const& value) { m_AreaOfValidity = value; m_AreaOfValidityIsSet = true; } bool N1N2MessageTransferReqData::areaOfValidityIsSet() const { return m_AreaOfValidityIsSet; } void N1N2MessageTransferReqData::unsetAreaOfValidity() { m_AreaOfValidityIsSet = false; } std::string N1N2MessageTransferReqData::getSupportedFeatures() const { return m_SupportedFeatures; } void N1N2MessageTransferReqData::setSupportedFeatures( std::string const& value) { m_SupportedFeatures = value; m_SupportedFeaturesIsSet = true; } bool N1N2MessageTransferReqData::supportedFeaturesIsSet() const { return m_SupportedFeaturesIsSet; } void N1N2MessageTransferReqData::unsetSupportedFeatures() { m_SupportedFeaturesIsSet = false; } } // namespace model } // namespace amf } // namespace oai
32.424837
80
0.732614
[ "model" ]
77214db517410845b3325f355d1018397dc74267
572
cpp
C++
main.cpp
PatrikValkovic/Sudoku
5640ae845f11d532e70468b0ee74d9b60fed8e02
[ "MIT" ]
1
2021-02-04T12:42:59.000Z
2021-02-04T12:42:59.000Z
main.cpp
PatrikValkovic/Sudoku
5640ae845f11d532e70468b0ee74d9b60fed8e02
[ "MIT" ]
null
null
null
main.cpp
PatrikValkovic/Sudoku
5640ae845f11d532e70468b0ee74d9b60fed8e02
[ "MIT" ]
1
2021-02-04T12:43:00.000Z
2021-02-04T12:43:00.000Z
#include <iostream> #include "Group.h" #include "Functions.h" using namespace std; int main() { Manager* man = new Manager; vector<vector<Options*>> opts = CreateContainer(man); vector<Group*> groups = createGroups(opts); int endResult = 0; try { Parse(opts); if(!SolveMoreResults(opts,groups,man)) throw new exception(); WriteFinal(opts); } catch (std::exception* e) { cout << "Nema reseni"; endResult = 1; } ClearValues(opts,man,groups); return endResult; }
15.052632
57
0.578671
[ "vector" ]
7723cf4e13612ac46cc393366ce6d845dd3bfe5b
12,323
cpp
C++
Game/OGRE/OgreMain/src/OgreTexture.cpp
hackerlank/SourceCode
b702c9e0a9ca5d86933f3c827abb02a18ffc9a59
[ "MIT" ]
4
2021-07-31T13:56:01.000Z
2021-11-13T02:55:10.000Z
Game/OGRE/OgreMain/src/OgreTexture.cpp
shacojx/SourceCodeGameTLBB
e3cea615b06761c2098a05427a5f41c236b71bf7
[ "MIT" ]
null
null
null
Game/OGRE/OgreMain/src/OgreTexture.cpp
shacojx/SourceCodeGameTLBB
e3cea615b06761c2098a05427a5f41c236b71bf7
[ "MIT" ]
7
2021-08-31T14:34:23.000Z
2022-01-19T08:25:58.000Z
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2005 The OGRE Team Also see acknowledgements in Readme.html This program 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 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA, or go to http://www.gnu.org/copyleft/lesser.txt. ----------------------------------------------------------------------------- */ #include "OgreStableHeaders.h" #include "OgreLogManager.h" #include "OgreHardwarePixelBuffer.h" #include "OgreImage.h" #include "OgreTexture.h" #include "OgreException.h" #include "OgreResourceManager.h" #include "OgreTextureManager.h" namespace Ogre { //-------------------------------------------------------------------------- Texture::Texture(ResourceManager* creator, const String& name, ResourceHandle handle, const String& group, bool isManual, ManualResourceLoader* loader) : Resource(creator, name, handle, group, isManual, loader), // init defaults; can be overridden before load() mHeight(512), mWidth(512), mDepth(1), mNumRequestedMipmaps(0), mNumMipmaps(0), mMipmapsHardwareGenerated(false), mGamma(1.0f), mTextureType(TEX_TYPE_2D), mFormat(PF_UNKNOWN), mUsage(TU_DEFAULT), mSrcFormat(PF_UNKNOWN), mSrcWidth(0), mSrcHeight(0), mSrcDepth(0), mDesiredFormat(PF_UNKNOWN), mDesiredIntegerBitDepth(0), mDesiredFloatBitDepth(0), mTreatLuminanceAsAlpha(false), mInternalResourcesCreated(false) { if (createParamDictionary("Texture")) { // Define the parameters that have to be present to load // from a generic source; actually there are none, since when // predeclaring, you use a texture file which includes all the // information required. } // Set some defaults for default load path if (TextureManager::getSingletonPtr()) { TextureManager& tmgr = TextureManager::getSingleton(); setNumMipmaps(tmgr.getDefaultNumMipmaps()); setDesiredBitDepths(tmgr.getPreferredIntegerBitDepth(), tmgr.getPreferredFloatBitDepth()); } } //-------------------------------------------------------------------------- void Texture::loadRawData( DataStreamPtr& stream, ushort uWidth, ushort uHeight, PixelFormat eFormat) { Image img; img.loadRawData(stream, uWidth, uHeight, eFormat); loadImage(img); } //-------------------------------------------------------------------------- void Texture::setFormat(PixelFormat pf) { mFormat = pf; mDesiredFormat = pf; mSrcFormat = pf; } //-------------------------------------------------------------------------- bool Texture::hasAlpha(void) const { return PixelUtil::hasAlpha(mFormat); } //-------------------------------------------------------------------------- void Texture::setDesiredIntegerBitDepth(ushort bits) { mDesiredIntegerBitDepth = bits; } //-------------------------------------------------------------------------- ushort Texture::getDesiredIntegerBitDepth(void) const { return mDesiredIntegerBitDepth; } //-------------------------------------------------------------------------- void Texture::setDesiredFloatBitDepth(ushort bits) { mDesiredFloatBitDepth = bits; } //-------------------------------------------------------------------------- ushort Texture::getDesiredFloatBitDepth(void) const { return mDesiredFloatBitDepth; } //-------------------------------------------------------------------------- void Texture::setDesiredBitDepths(ushort integerBits, ushort floatBits) { mDesiredIntegerBitDepth = integerBits; mDesiredFloatBitDepth = floatBits; } //-------------------------------------------------------------------------- void Texture::setTreatLuminanceAsAlpha(bool asAlpha) { mTreatLuminanceAsAlpha = asAlpha; } //-------------------------------------------------------------------------- bool Texture::getTreatLuminanceAsAlpha(void) const { return mTreatLuminanceAsAlpha; } //-------------------------------------------------------------------------- size_t Texture::calculateSize(void) const { return getNumFaces() * PixelUtil::getMemorySize(mWidth, mHeight, mDepth, mFormat); } //-------------------------------------------------------------------------- size_t Texture::getNumFaces(void) const { return getTextureType() == TEX_TYPE_CUBE_MAP ? 6 : 1; } //-------------------------------------------------------------------------- void Texture::_loadImages( const std::vector<const Image*>& images ) { if(images.size() < 1) OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Cannot load empty vector of images", "Texture::loadImages"); if( mIsLoaded ) { LogManager::getSingleton().logMessage( LML_NORMAL, "Texture: "+mName+": Unloading Image"); unload(); } // Set desired texture size and properties from images[0] mSrcWidth = mWidth = images[0]->getWidth(); mSrcHeight = mHeight = images[0]->getHeight(); mSrcDepth = mDepth = images[0]->getDepth(); // Get source image format and adjust if required mSrcFormat = images[0]->getFormat(); if (mTreatLuminanceAsAlpha && mSrcFormat == PF_L8) { mSrcFormat = PF_A8; } if (mDesiredFormat != PF_UNKNOWN) { // If have desired format, use it mFormat = mDesiredFormat; } else { // Get the format according with desired bit depth mFormat = PixelUtil::getFormatForBitDepths(mSrcFormat, mDesiredIntegerBitDepth, mDesiredFloatBitDepth); } // The custom mipmaps in the image have priority over everything size_t imageMips = images[0]->getNumMipmaps(); if(imageMips > 0) { mNumMipmaps = images[0]->getNumMipmaps(); // Disable flag for auto mip generation mUsage &= ~TU_AUTOMIPMAP; } // Create the texture createInternalResources(); // Check if we're loading one image with multiple faces // or a vector of images representing the faces size_t faces; bool multiImage; // Load from multiple images? if(images.size() > 1) { faces = images.size(); multiImage = true; } else { faces = images[0]->getNumFaces(); multiImage = false; } // Check wether number of faces in images exceeds number of faces // in this texture. If so, clamp it. if(faces > getNumFaces()) faces = getNumFaces(); // Say what we're doing StringUtil::StrStreamType str; str << "Texture: " << mName << ": Loading " << faces << " faces" << "(" << PixelUtil::getFormatName(images[0]->getFormat()) << "," << images[0]->getWidth() << "x" << images[0]->getHeight() << "x" << images[0]->getDepth() << ") with "; if (!(mMipmapsHardwareGenerated && mNumMipmaps == 0)) str << mNumMipmaps; if(mUsage & TU_AUTOMIPMAP) { if (mMipmapsHardwareGenerated) str << " hardware"; str << " generated mipmaps"; } else { str << " custom mipmaps"; } if(multiImage) str << " from multiple Images."; else str << " from Image."; // Scoped { // Print data about first destination surface HardwarePixelBufferSharedPtr buf = getBuffer(0, 0); str << " Internal format is " << PixelUtil::getFormatName(buf->getFormat()) << "," << buf->getWidth() << "x" << buf->getHeight() << "x" << buf->getDepth() << "."; } LogManager::getSingleton().logMessage( LML_NORMAL, str.str()); // Main loading loop // imageMips == 0 if the image has no custom mipmaps, otherwise contains the number of custom mips for(size_t mip = 0; mip<=imageMips; ++mip) { for(size_t i = 0; i < faces; ++i) { PixelBox src; if(multiImage) { // Load from multiple images src = images[i]->getPixelBox(0, mip); } else { // Load from faces of images[0] src = images[0]->getPixelBox(i, mip); } // Sets to treated format in case is difference src.format = mSrcFormat; if(mGamma != 1.0f) { // Apply gamma correction // Do not overwrite original image but do gamma correction in temporary buffer MemoryDataStreamPtr buf; // for scoped deletion of conversion buffer buf.bind(new MemoryDataStream( PixelUtil::getMemorySize( src.getWidth(), src.getHeight(), src.getDepth(), src.format))); PixelBox corrected = PixelBox(src.getWidth(), src.getHeight(), src.getDepth(), src.format, buf->getPtr()); PixelUtil::bulkPixelConversion(src, corrected); Image::applyGamma(static_cast<uint8*>(corrected.data), mGamma, corrected.getConsecutiveSize(), PixelUtil::getNumElemBits(src.format)); // Destination: entire texture. blitFromMemory does the scaling to // a power of two for us when needed getBuffer(i, mip)->blitFromMemory(corrected); } else { // Destination: entire texture. blitFromMemory does the scaling to // a power of two for us when needed getBuffer(i, mip)->blitFromMemory(src); } } } // Update size (the final size, not including temp space) mSize = getNumFaces() * PixelUtil::getMemorySize(mWidth, mHeight, mDepth, mFormat); mIsLoaded = true; } //----------------------------------------------------------------------------- void Texture::createInternalResources(void) { if (!mInternalResourcesCreated) { createInternalResourcesImpl(); mInternalResourcesCreated = true; } } //----------------------------------------------------------------------------- void Texture::freeInternalResources(void) { if (mInternalResourcesCreated) { freeInternalResourcesImpl(); mInternalResourcesCreated = false; } } //----------------------------------------------------------------------------- void Texture::unloadImpl(void) { freeInternalResources(); } //----------------------------------------------------------------------------- void Texture::copyToTexture( TexturePtr& target ) { if(target->getNumFaces() != getNumFaces()) { OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Texture types must match", "Texture::copyToTexture"); } size_t numMips = std::min(getNumMipmaps(), target->getNumMipmaps()); if((mUsage & TU_AUTOMIPMAP) || (target->getUsage()&TU_AUTOMIPMAP)) numMips = 0; for(unsigned int face=0; face<getNumFaces(); face++) { for(unsigned int mip=0; mip<=numMips; mip++) { target->getBuffer(face, mip)->blit(getBuffer(face, mip)); } } } }
35.718841
126
0.529011
[ "object", "vector" ]
772795bb9ce71fd1454afeae2851e124d02a94f3
9,980
hpp
C++
include/kitty/threshold_identification.hpp
SeriemSid/kitty
9b7bebd0a3f5c47492b8506e049ec6f04705bb8c
[ "MIT" ]
null
null
null
include/kitty/threshold_identification.hpp
SeriemSid/kitty
9b7bebd0a3f5c47492b8506e049ec6f04705bb8c
[ "MIT" ]
null
null
null
include/kitty/threshold_identification.hpp
SeriemSid/kitty
9b7bebd0a3f5c47492b8506e049ec6f04705bb8c
[ "MIT" ]
null
null
null
/* kitty: C++ truth table library * Copyright (C) 2017-2020 EPFL * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ /*! \file threshold_identification.hpp \brief Threshold logic function identification \author CS-472 2020 Fall students */ // Seriem Sid-Ahmed ALGORITHM #pragma once #include <vector> #include <iostream> #include <lpsolve/lp_lib.h> /* uncomment this line to include lp_solve */ #include "traits.hpp" #include "operators.hpp" #include "operations.hpp" #include "properties.hpp" #include "implicant.hpp" #include "constructors.hpp" #include "bit_operations.hpp" #include "isop.hpp" using namespace std; namespace kitty { /*! \brief Threshold logic function identification Given a truth table, this function determines whether it is a threshold logic function (TF) and finds a linear form if it is. A Boolean function is a TF if it can be expressed as f(x_1, ..., x_n) = \sum_{i=1}^n w_i x_i >= T where w_i are the weight values and T is the threshold value. The linear form of a TF is the vector [w_1, ..., w_n; T]. \param tt The truth table \param plf Pointer to a vector that will hold a linear form of `tt` if it is a TF. The linear form has `tt.num_vars()` weight values and the threshold value in the end. \return `true` if `tt` is a TF; `false` if `tt` is a non-TF. */ int powerof2(int n){ int sortie = 1; for ( auto i = 1; i <= n; ++i ){ sortie = 2*sortie; } return sortie;} template<typename TT, typename = std::enable_if_t<is_complete_truth_table<TT>::value>> bool is_threshold( const TT& tt, std::vector<int64_t>* plf = nullptr ) { TT tt2 = tt ; // We can't flip a const so we need to use a second truth table to flip it std::vector<int64_t> linear_form; std::vector<int8_t> positivevect ; // Store the positives variables std::vector<int8_t> negativevect ; // Store the negatives variables. // Boolean that we help us to know if we find a positive and a negative bit to return false if it's the case // Check if a truth table is positive or negative or binate and return false if it is binate for (unsigned int i = 0 ; i < tt.num_vars() ; i++){ bool neg = false; bool pos = false; auto const cof0 = cofactor0(tt,i); auto const cof1 = cofactor1(tt,i); for (auto k = 0 ; k < (powerof2((tt.num_vars()-1))); k ++ ){ if(get_bit(cof0,k)< get_bit(cof1,k)){ pos = true ; } else if (get_bit(cof0,k)> get_bit(cof1,k)) { neg = true ; } } if (pos && neg){ // The case where a variable has positive and negative bits return false; } else{ } if (neg == true){ negativevect.push_back(i); // Store the negatives variables to use them for linear_form tt2=flip(tt2, i); // Flip the negatives variables in order to work with a positive truth table } else{ positivevect.push_back(i); // Not very useful we don't use the positives variables } } // Cube that will be used to get the onset and offset minterms for the constraints const auto onset_cube = isop(tt2); const auto offset_cube = isop(unary_not(tt2)); lprec *lp; int Ncol, *colno = NULL, ret = 0; REAL *row = NULL; /* We will build the model row by row*/ Ncol = tt.num_vars() + 1; // Num_vars weights and the treshold value lp = make_lp(0, Ncol); if (lp == NULL) { ret = 1 ; /* couldn't construct a new model... */ return false; } /* let us name our variables. Not required, but can be useful for debugging */ for(unsigned int i = 1 ; i != tt.num_vars()-1; i++){ set_col_name(lp, i, "x"); } /* create space large enough for one row */ colno = (int*) malloc(Ncol * sizeof(*colno)); row = (REAL*) malloc(Ncol * sizeof(*row)); if ((colno == NULL) || (row == NULL)) { ret = 2 ; return false; } set_add_rowmode(lp, TRUE);/* makes building the model faster if it is done rows by row */ if (ret == 0) { // We just check that all the weights wi and the treshold value are positives for(unsigned int j = 0; j <= tt.num_vars(); j++){ colno[0] = j+1; row[j] = 1; add_constraintex(lp, 1, row, colno, GE, 0); // w1 + w2 ... + T > 0 } } if (ret == 0) { // We compute the onset minterms inequalities for (long unsigned int k = 0; k <= onset_cube.size()-1; k++) { // We compute for all the minterms for (unsigned int i = 0; i < tt.num_vars(); i++) { if (onset_cube.at(k).get_mask(i) && onset_cube.at(k).get_bit(i)) {// We look if the variable is in the cube and if the bit is 1 colno[i] =i+1; row[i] = 1; } else { colno[i] =i+1; row[i] = 0; } } colno[tt.num_vars()]=tt.num_vars()+1; // We compute separately the treshold value row[tt.num_vars()] = -1; // We move the treshold on the left of the inequalities // w1*x1 + .... wnum_vars*xnum_vars -T >= 0 with xi the onset minterms add_constraintex(lp, Ncol, row, colno, GE, 0); } } if (ret == 0) { //We compute the offset minterms inequalities for (long unsigned int k = 0; k <= offset_cube.size()-1; k++) { // We compute for all the minterms for (unsigned int i = 0; i < tt.num_vars(); i++) { if (offset_cube.at(k).get_mask(i)==false || (offset_cube.at(k).get_mask(i))&&(offset_cube.at(k).get_bit(i))) // We look if the variable is not the cube or if the bit is 1 { colno[i] =i+1; row[i] = 1; } else { colno[i] =i+1; row[i] = 0; } } colno[tt.num_vars()] = tt.num_vars()+1; // We compute separately the treshold value row[tt.num_vars()] = -1; // We move the treshold to the left of the inequalities // w1*x1 + .... wnum_vars*xnum_vars -T <= 0 with xi the offset minterms add_constraintex(lp, Ncol, row, colno, LE, -1); } } if (ret == 0) { set_add_rowmode(lp, FALSE); /* rowmode should be turned off again when done building the model */ // We check that the sum of the weights values and treshold values are minimize ( min(w1+...w_num_vars + T )) for (int j = 0; j < Ncol; j++) { colno[j] = j + 1; row[j] = 1; } set_obj_fnex(lp, Ncol, row, colno); // This is the objective function that we minimize after (w1+....w_num_vars+T) } /* set the object direction to minimize */ set_minim(lp); /* just out of curioucity, now show the model in lp format on screen */ /* this only works if this is a console application. If not, use write_lp and a filename */ // write_LP(lp, stdout); //write_lp(lp, "model.lp"); /* I only want to see important messages on screen while solving */ set_verbose(lp, IMPORTANT); /* Now let lpsolve calculate a solution */ ret = solve(lp); if (ret == 0){ get_variables(lp, row); for (unsigned int j = 0; j <= tt.num_vars(); j++) { linear_form.push_back(row[j]); // We put all the results in linear form vector } // All the variables that were negative and were changed into positives are again set negatives for (auto k : negativevect) { linear_form.at(k) = -linear_form.at(k); linear_form.at(Ncol-1) = linear_form.at(Ncol-1) + linear_form.at(k); } if ( plf ) { *plf = linear_form; } /* free allocated memory to avoid issues with malloc in order to not break your computer */ if ( colno != NULL ) free( colno ); if ( row != NULL ) free( row ); if ( lp != NULL ) /* clean up such that all used memory by lpsolve is freed */ delete_lp( lp ); return true; } return false; } }
39.44664
192
0.552204
[ "object", "vector", "model" ]
7728776dd707adb2022f7301dd4ae9fed9c3e651
11,049
cpp
C++
deform_control/external_libs/OpenSceneGraph-2.8.5/examples/osganimationnode/osganimationnode.cpp
UM-ARM-Lab/mab_ms
f199f05b88060182cfbb47706bd1ff3479032c43
[ "BSD-2-Clause" ]
3
2018-08-20T12:12:43.000Z
2021-06-06T09:43:27.000Z
deform_control/external_libs/OpenSceneGraph-2.8.5/examples/osganimationnode/osganimationnode.cpp
UM-ARM-Lab/mab_ms
f199f05b88060182cfbb47706bd1ff3479032c43
[ "BSD-2-Clause" ]
null
null
null
deform_control/external_libs/OpenSceneGraph-2.8.5/examples/osganimationnode/osganimationnode.cpp
UM-ARM-Lab/mab_ms
f199f05b88060182cfbb47706bd1ff3479032c43
[ "BSD-2-Clause" ]
1
2022-03-31T03:12:23.000Z
2022-03-31T03:12:23.000Z
/* -*-c++-*- * Copyright (C) 2008 Cedric Pinson <mornifle@plopbyte.net> * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * 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 * OpenSceneGraph Public License for more details. */ #include <iostream> #include <osg/Geometry> #include <osg/Shape> #include <osg/ShapeDrawable> #include <osgViewer/Viewer> #include <osgGA/TrackballManipulator> #include <osg/MatrixTransform> #include <osg/Material> #include <osgAnimation/Sampler> class AnimtkUpdateCallback : public osg::NodeCallback { public: META_Object(osgAnimation, AnimtkUpdateCallback); AnimtkUpdateCallback() { _sampler = new osgAnimation::Vec3CubicBezierSampler; _playing = false; _lastUpdate = 0; } AnimtkUpdateCallback(const AnimtkUpdateCallback& val, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY): osg::Object(val, copyop), osg::NodeCallback(val, copyop), _sampler(val._sampler), _startTime(val._startTime), _currentTime(val._currentTime), _playing(val._playing), _lastUpdate(val._lastUpdate) { } /** Callback method called by the NodeVisitor when visiting a node.*/ virtual void operator()(osg::Node* node, osg::NodeVisitor* nv) { if (nv->getVisitorType() == osg::NodeVisitor::UPDATE_VISITOR && nv->getFrameStamp() && nv->getFrameStamp()->getFrameNumber() != _lastUpdate) { _lastUpdate = nv->getFrameStamp()->getFrameNumber(); _currentTime = osg::Timer::instance()->tick(); if (_playing && _sampler.get() && _sampler->getKeyframeContainer()) { osg::MatrixTransform* transform = dynamic_cast<osg::MatrixTransform*>(node); if (transform) { osg::Vec3 result; float t = osg::Timer::instance()->delta_s(_startTime, _currentTime); float duration = _sampler->getEndTime() - _sampler->getStartTime(); t = fmod(t, duration); t += _sampler->getStartTime(); _sampler->getValueAt(t, result); transform->setMatrix(osg::Matrix::translate(result)); } } } // note, callback is responsible for scenegraph traversal so // they must call traverse(node,nv) to ensure that the // scene graph subtree (and associated callbacks) are traversed. traverse(node,nv); } void start() { _startTime = osg::Timer::instance()->tick(); _currentTime = _startTime; _playing = true;} void stop() { _currentTime = _startTime; _playing = false;} osg::ref_ptr<osgAnimation::Vec3CubicBezierSampler> _sampler; osg::Timer_t _startTime; osg::Timer_t _currentTime; bool _playing; int _lastUpdate; }; class AnimtkStateSetUpdateCallback : public osg::StateSet::Callback { public: META_Object(osgAnimation, AnimtkStateSetUpdateCallback); AnimtkStateSetUpdateCallback() { _sampler = new osgAnimation::Vec4LinearSampler; _playing = false; _lastUpdate = 0; } AnimtkStateSetUpdateCallback(const AnimtkStateSetUpdateCallback& val, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY): osg::Object(val, copyop), osg::StateSet::Callback(val, copyop), _sampler(val._sampler), _startTime(val._startTime), _currentTime(val._currentTime), _playing(val._playing), _lastUpdate(val._lastUpdate) { } /** Callback method called by the NodeVisitor when visiting a node.*/ virtual void operator()(osg::StateSet* state, osg::NodeVisitor* nv) { if (state && nv->getVisitorType() == osg::NodeVisitor::UPDATE_VISITOR && nv->getFrameStamp() && nv->getFrameStamp()->getFrameNumber() != _lastUpdate) { _lastUpdate = nv->getFrameStamp()->getFrameNumber(); _currentTime = osg::Timer::instance()->tick(); if (_playing && _sampler.get() && _sampler->getKeyframeContainer()) { osg::Material* material = dynamic_cast<osg::Material*>(state->getAttribute(osg::StateAttribute::MATERIAL)); if (material) { osg::Vec4 result; float t = osg::Timer::instance()->delta_s(_startTime, _currentTime); float duration = _sampler->getEndTime() - _sampler->getStartTime(); t = fmod(t, duration); t += _sampler->getStartTime(); _sampler->getValueAt(t, result); material->setDiffuse(osg::Material::FRONT_AND_BACK, result); } } } } void start() { _startTime = osg::Timer::instance()->tick(); _currentTime = _startTime; _playing = true;} void stop() { _currentTime = _startTime; _playing = false;} osg::ref_ptr<osgAnimation::Vec4LinearSampler> _sampler; osg::Timer_t _startTime; osg::Timer_t _currentTime; bool _playing; int _lastUpdate; }; osg::Geode* createAxis() { osg::Geode* geode = new osg::Geode; osg::ref_ptr<osg::Geometry> geometry (new osg::Geometry()); osg::ref_ptr<osg::Vec3Array> vertices (new osg::Vec3Array()); vertices->push_back (osg::Vec3 ( 0.0, 0.0, 0.0)); vertices->push_back (osg::Vec3 ( 10.0, 0.0, 0.0)); vertices->push_back (osg::Vec3 ( 0.0, 0.0, 0.0)); vertices->push_back (osg::Vec3 ( 0.0, 10.0, 0.0)); vertices->push_back (osg::Vec3 ( 0.0, 0.0, 0.0)); vertices->push_back (osg::Vec3 ( 0.0, 0.0, 10.0)); geometry->setVertexArray (vertices.get()); osg::ref_ptr<osg::Vec4Array> colors (new osg::Vec4Array()); colors->push_back (osg::Vec4 (1.0f, 0.0f, 0.0f, 1.0f)); colors->push_back (osg::Vec4 (1.0f, 0.0f, 0.0f, 1.0f)); colors->push_back (osg::Vec4 (0.0f, 1.0f, 0.0f, 1.0f)); colors->push_back (osg::Vec4 (0.0f, 1.0f, 0.0f, 1.0f)); colors->push_back (osg::Vec4 (0.0f, 0.0f, 1.0f, 1.0f)); colors->push_back (osg::Vec4 (0.0f, 0.0f, 1.0f, 1.0f)); geometry->setColorArray (colors.get()); geometry->setColorBinding (osg::Geometry::BIND_PER_VERTEX); geometry->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::LINES,0,6)); geode->addDrawable( geometry.get() ); geode->getOrCreateStateSet()->setMode(GL_LIGHTING, false); return geode; } osg::StateSet* setupStateSet() { osg::StateSet* st = new osg::StateSet; st->setAttributeAndModes(new osg::Material, true); st->setMode(GL_BLEND, true); AnimtkStateSetUpdateCallback* callback = new AnimtkStateSetUpdateCallback; osgAnimation::Vec4KeyframeContainer* keys = callback->_sampler->getOrCreateKeyframeContainer(); keys->push_back(osgAnimation::Vec4Keyframe(0, osg::Vec4(0,0,0,0))); keys->push_back(osgAnimation::Vec4Keyframe(2, osg::Vec4(0.5,0,0,0.5))); keys->push_back(osgAnimation::Vec4Keyframe(4, osg::Vec4(0,0.5,0,1))); keys->push_back(osgAnimation::Vec4Keyframe(6, osg::Vec4(0,0,0.5,1))); keys->push_back(osgAnimation::Vec4Keyframe(8, osg::Vec4(1,1,1,0.5))); keys->push_back(osgAnimation::Vec4Keyframe(10, osg::Vec4(0,0,0,0))); callback->start(); st->setUpdateCallback(callback); return st; } osg::Node* setupCube() { osg::Geode* geode = new osg::Geode; geode->addDrawable(new osg::ShapeDrawable(new osg::Box(osg::Vec3(0.0f,0.0f,0.0f),2))); geode->setStateSet(setupStateSet()); return geode; } osg::MatrixTransform* setupAnimtkNode() { osg::Vec3 v[5]; v[0] = osg::Vec3(0,0,0); v[1] = osg::Vec3(10,-50,0); v[2] = osg::Vec3(30,-10,20); v[3] = osg::Vec3(-10,20,-20); v[4] = osg::Vec3(0,0,0); osg::MatrixTransform* node = new osg::MatrixTransform; AnimtkUpdateCallback* callback = new AnimtkUpdateCallback; osgAnimation::Vec3CubicBezierKeyframeContainer* keys = callback->_sampler->getOrCreateKeyframeContainer(); keys->push_back(osgAnimation::Vec3CubicBezierKeyframe(0, osgAnimation::Vec3CubicBezier( v[0], // pos v[0] + (v[0] - v[3]), // p1 v[1] - (v[1] - v[0]) // p2 ))); keys->push_back(osgAnimation::Vec3CubicBezierKeyframe(2, osgAnimation::Vec3CubicBezier( v[1], // pos v[1] + (v[1] - v[0]), v[2] - (v[2] - v[1]) ))); keys->push_back(osgAnimation::Vec3CubicBezierKeyframe(4, osgAnimation::Vec3CubicBezier( v[2], // pos v[2] + (v[2] - v[1]), v[3] - (v[3] - v[2]) ))); keys->push_back(osgAnimation::Vec3CubicBezierKeyframe(6, osgAnimation::Vec3CubicBezier( v[3], // pos v[3] + (v[3] - v[2]), v[4] - (v[4] - v[3]) ))); keys->push_back(osgAnimation::Vec3CubicBezierKeyframe(8, osgAnimation::Vec3CubicBezier( v[4], // pos v[4] + (v[4] - v[3]), v[0] - (v[0] - v[4]) ))); callback->start(); node->setUpdateCallback(callback); node->addChild(setupCube()); return node; } int main (int argc, char* argv[]) { osg::ArgumentParser arguments(&argc, argv); osgViewer::Viewer viewer(arguments); osgGA::TrackballManipulator* manipulator = new osgGA::TrackballManipulator(); viewer.setCameraManipulator(manipulator); osg::Group* root = new osg::Group; root->setInitialBound(osg::BoundingSphere(osg::Vec3(10,0,10), 30)); root->addChild(createAxis()); osg::MatrixTransform* node = setupAnimtkNode(); node->addChild(createAxis()); root->addChild(node); viewer.setSceneData( root ); viewer.realize(); while (!viewer.done()) { viewer.frame(); } }
40.178182
129
0.567834
[ "geometry", "object", "shape", "transform" ]
772dbc0ce535bc9c5f7ceff6b28d11088e18c684
2,650
cpp
C++
Engine_Source/Source/Insight/Rendering/Renderer.cpp
GCourtney27/DirectX11RenderingEngine
ebbe470b697c6e5ab98502c0be4163500d91641a
[ "Apache-2.0" ]
2
2021-01-29T08:03:01.000Z
2021-04-10T19:18:54.000Z
Engine_Source/Source/Insight/Rendering/Renderer.cpp
GCourtney27/DirectX11RenderingEngine
ebbe470b697c6e5ab98502c0be4163500d91641a
[ "Apache-2.0" ]
3
2020-06-04T23:37:07.000Z
2020-06-04T23:39:04.000Z
Engine_Source/Source/Insight/Rendering/Renderer.cpp
GCourtney27/DirectX11RenderingEngine
ebbe470b697c6e5ab98502c0be4163500d91641a
[ "Apache-2.0" ]
1
2021-04-10T13:36:23.000Z
2021-04-10T13:36:23.000Z
#include <Engine_pch.h> #include "Renderer.h" #include "Insight/Core/Application.h" #include "Platform/DirectX_11/Direct3D11_Context.h" #include "Platform/DirectX_12/Direct3D12_Context.h" namespace Insight { Renderer* Renderer::s_Instance = nullptr; Renderer::Renderer() { } void Renderer::HandleEvents() { while(s_Instance->m_WindowResizeEventQueue.size() != 0) { s_Instance->OnWindowResize(s_Instance->m_WindowResizeEventQueue.front()); s_Instance->m_WindowResizeEventQueue.pop(); } while (s_Instance->m_ShaderReloadEventQueue.size() != 0) { s_Instance->OnShaderReload(s_Instance->m_ShaderReloadEventQueue.front()); s_Instance->m_ShaderReloadEventQueue.pop(); } while (s_Instance->m_WindowFullScreenEventQueue.size() != 0) { s_Instance->OnWindowFullScreen(s_Instance->m_WindowFullScreenEventQueue.front()); s_Instance->m_WindowFullScreenEventQueue.pop(); } } Renderer::~Renderer() { } bool Renderer::SetSettingsAndCreateContext(GraphicsSettings GraphicsSettings, std::shared_ptr<Window> pWindow) { IE_ASSERT(!s_Instance, "Rendering Context already exists! Cannot have more that one context created at a time."); IE_ASSERT(pWindow, "Cannot initialize renderer with NULL window context."); switch (GraphicsSettings.TargetRenderAPI) { #if defined (IE_PLATFORM_WINDOWS) case TargetRenderAPI::Direct3D_11: { s_Instance = new Direct3D11Context(); break; } case TargetRenderAPI::Direct3D_12: { s_Instance = new Direct3D12Context(); break; } #endif // IE_PLATFORM_WINDOWS default: { IE_DEBUG_LOG(LogSeverity::Error, "Failed to create render with given context type: {0}", GraphicsSettings.TargetRenderAPI); break; } } s_Instance->m_pWindowRef = pWindow; s_Instance->SetGraphicsSettings(GraphicsSettings); s_Instance->Init(); return s_Instance != nullptr; } CB_PS_DirectionalLight Renderer::GetDirectionalLightCB() const { return s_Instance->m_pWorldDirectionalLight->GetConstantBuffer(); } void Renderer::UnRegisterWorldDirectionalLight() { s_Instance->m_pWorldDirectionalLight = nullptr; } void Renderer::UnRegisterPointLight(APointLight* pPointLight) { auto iter = std::find(s_Instance->m_PointLights.begin(), s_Instance->m_PointLights.end(), pPointLight); if (iter != s_Instance->m_PointLights.end()) { s_Instance->m_PointLights.erase(iter); } } void Renderer::UnRegisterSpotLight(ASpotLight* pSpotLight) { auto iter = std::find(s_Instance->m_SpotLights.begin(), s_Instance->m_SpotLights.end(), pSpotLight); if (iter != s_Instance->m_SpotLights.end()) { s_Instance->m_SpotLights.erase(iter); } } }
25.980392
126
0.74717
[ "render" ]
7737f3a74315a91cbfdd29fe774c14fd6e9d481e
1,580
cpp
C++
map_usage_sort.cpp
yangyueren/PAT
950d820ec9174c5e2d74adafeb2abde4acdc635f
[ "MIT" ]
1
2020-02-01T08:20:26.000Z
2020-02-01T08:20:26.000Z
map_usage_sort.cpp
yangyueren/PAT
950d820ec9174c5e2d74adafeb2abde4acdc635f
[ "MIT" ]
null
null
null
map_usage_sort.cpp
yangyueren/PAT
950d820ec9174c5e2d74adafeb2abde4acdc635f
[ "MIT" ]
null
null
null
//功能:输入单词,统计单词出现次数并按照单词出现次数从多到少排序 #include <iostream> #include <cstdlib> #include <map> #include <vector> #include <string> #include <algorithm> using namespace std; int cmp(const pair<string, int>& x, const pair<string, int>& y) { return x.second > y.second; } void sortMapByValue(map<string, int>& tMap,vector<pair<string, int> >& tVector) { for (map<string, int>::iterator curr = tMap.begin(); curr != tMap.end(); curr++) tVector.push_back(make_pair(curr->first, curr->second)); sort(tVector.begin(), tVector.end()-1, cmp); } struct cmpByKey //自定义比较规则 { bool operator () (const string& str1, const string& str2) const { return str1.length() < str2.length(); } }; void sortMapByKey(){ map<string, int, cmpByKey > scoreMap; //这边调用cmp map<string, int, cmpByKey >::iterator iter; scoreMap["LiMin"] = 90; scoreMap["ZZihsf"] = 95; scoreMap["Kim"] = 100; scoreMap.insert(map<string, int>::value_type("Jack", 88)); for(iter=scoreMap.begin(); iter!=scoreMap.end(); iter++) cout<<iter->first<<' '<<iter->second<<endl; } int main() { sortMapByKey(); map<string, int> tMap; string word; int re = 3; while (re-- > 0) { cin >> word; pair<map<string,int>::iterator,bool> ret = tMap.insert(make_pair(word, 1)); if (!ret.second) ++ret.first->second; } vector<pair<string,int>> tVector; sortMapByValue(tMap,tVector); for(int i=0;i<tVector.size();i++) cout<<tVector[i].first<<": "<<tVector[i].second<<endl; return 0; }
23.939394
84
0.611392
[ "vector" ]
77430289dada64714bbe7b68c8d43857eb1f9fc6
584
cpp
C++
Plugins/video/camera_motion_tracking.cpp
zhangyldanny/EagleEye
5b04ab52cdb03f710eff836e84f695446282848d
[ "BSD-3-Clause" ]
14
2015-10-07T13:08:30.000Z
2021-03-04T08:05:24.000Z
Plugins/video/camera_motion_tracking.cpp
zhangyldanny/EagleEye
5b04ab52cdb03f710eff836e84f695446282848d
[ "BSD-3-Clause" ]
29
2015-03-01T20:29:59.000Z
2017-09-05T06:58:04.000Z
Plugins/video/camera_motion_tracking.cpp
zhangyldanny/EagleEye
5b04ab52cdb03f710eff836e84f695446282848d
[ "BSD-3-Clause" ]
8
2016-11-16T19:59:59.000Z
2018-07-02T11:20:31.000Z
#include "camera_motion_tracking.hpp" #include <Aquila/nodes/NodeInfo.hpp> using namespace aq; using namespace aq::nodes; std::vector<std::vector<std::string>> track_camera_motion::GetParentalDependencies() { std::vector<std::vector<std::string>> output; output.push_back(std::vector<std::string>({ "GoodFeaturesToTrack", "FastFeatureDetector", "ORBFeatureDetector" })); output.push_back(std::vector<std::string>({ "SparsePyrLKOpticalFlow" })); return output; } bool track_camera_motion::processImpl() { return false; } MO_REGISTER_CLASS(track_camera_motion);
27.809524
119
0.748288
[ "vector" ]
77479330cf22c575f06b8476312d58b233c51082
46,535
cpp
C++
cpp/open3d/t/io/file_format/FilePCD.cpp
SenseOfSpace/Open3D
6dea870f1c12c80b0fda0ee4bc439bf30b434a7f
[ "MIT" ]
null
null
null
cpp/open3d/t/io/file_format/FilePCD.cpp
SenseOfSpace/Open3D
6dea870f1c12c80b0fda0ee4bc439bf30b434a7f
[ "MIT" ]
null
null
null
cpp/open3d/t/io/file_format/FilePCD.cpp
SenseOfSpace/Open3D
6dea870f1c12c80b0fda0ee4bc439bf30b434a7f
[ "MIT" ]
null
null
null
// ---------------------------------------------------------------------------- // - Open3D: www.open3d.org - // ---------------------------------------------------------------------------- // The MIT License (MIT) // // Copyright (c) 2018-2021 www.open3d.org // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // ---------------------------------------------------------------------------- #include <liblzf/lzf.h> #include <cinttypes> #include <cstdint> #include <cstdio> #include <sstream> #include "open3d/core/Dtype.h" #include "open3d/core/ParallelFor.h" #include "open3d/core/Tensor.h" #include "open3d/io/FileFormatIO.h" #include "open3d/t/io/PointCloudIO.h" #include "open3d/utility/FileSystem.h" #include "open3d/utility/Helper.h" #include "open3d/utility/Logging.h" #include "open3d/utility/ProgressReporters.h" // References for PCD file IO // http://pointclouds.org/documentation/tutorials/pcd_file_format.html // https://github.com/PointCloudLibrary/pcl/blob/master/io/src/pcd_io.cpp // https://www.mathworks.com/matlabcentral/fileexchange/40382-matlab-to-point-cloud-library namespace open3d { namespace t { namespace io { enum class PCDDataType { ASCII = 0, BINARY = 1, BINARY_COMPRESSED = 2 }; struct PCLPointField { public: std::string name; int size; char type; int count; // helper variable int count_offset = 0; int offset = 0; }; struct PCDHeader { public: std::string version; std::vector<PCLPointField> fields; int width; int height; int points; PCDDataType datatype; std::string viewpoint; // helper variables int elementnum; int pointsize; std::unordered_map<std::string, bool> has_attr; std::unordered_map<std::string, core::Dtype> attr_dtype; }; struct ReadAttributePtr { ReadAttributePtr(void *data_ptr = nullptr, const int row_idx = 0, const int row_length = 0, const int size = 0) : data_ptr_(data_ptr), row_idx_(row_idx), row_length_(row_length), size_(size) {} void *data_ptr_; const int row_idx_; const int row_length_; const int size_; }; struct WriteAttributePtr { WriteAttributePtr(const core::Dtype &dtype, const void *data_ptr, const int group_size) : dtype_(dtype), data_ptr_(data_ptr), group_size_(group_size) {} const core::Dtype dtype_; const void *data_ptr_; const int group_size_; }; static core::Dtype GetDtypeFromPCDHeaderField(char type, int size) { if (type == 'I') { if (size == 1) return core::Dtype::Int8; if (size == 2) return core::Dtype::Int16; if (size == 4) return core::Dtype::Int32; if (size == 8) return core::Dtype::Int64; else utility::LogError("Unsupported data type."); } else if (type == 'U') { if (size == 1) return core::Dtype::UInt8; if (size == 2) return core::Dtype::UInt16; if (size == 4) return core::Dtype::UInt32; if (size == 8) return core::Dtype::UInt64; else utility::LogError("Unsupported data type."); } else if (type == 'F') { if (size == 4) return core::Dtype::Float32; if (size == 8) return core::Dtype::Float64; else utility::LogError("Unsupported data type."); } else { utility::LogError("Unsupported data type."); } } static bool InitializeHeader(PCDHeader &header) { if (header.points <= 0 || header.pointsize <= 0) { utility::LogWarning("[Write PCD] PCD has no data."); return false; } if (header.fields.size() == 0 || header.pointsize <= 0) { utility::LogWarning("[Write PCD] PCD has no fields."); return false; } header.has_attr["positions"] = false; header.has_attr["normals"] = false; header.has_attr["colors"] = false; std::unordered_set<std::string> known_field; std::unordered_map<std::string, core::Dtype> field_dtype; for (const auto &field : header.fields) { if (field.name == "x" || field.name == "y" || field.name == "z" || field.name == "normal_x" || field.name == "normal_y" || field.name == "normal_z" || field.name == "rgb" || field.name == "rgba") { known_field.insert(field.name); field_dtype[field.name] = GetDtypeFromPCDHeaderField(field.type, field.size); } else { header.has_attr[field.name] = true; header.attr_dtype[field.name] = GetDtypeFromPCDHeaderField(field.type, field.size); } } if (known_field.count("x") && known_field.count("y") && known_field.count("z")) { if ((field_dtype["x"] == field_dtype["y"]) && (field_dtype["x"] == field_dtype["z"])) { header.has_attr["positions"] = true; header.attr_dtype["positions"] = field_dtype["x"]; } else { utility::LogWarning( "[Write PCD] Dtype for positions data are not " "same."); return false; } } else { utility::LogWarning( "[Write PCD] Fields for positions data are not " "complete."); return false; } if (known_field.count("normal_x") && known_field.count("normal_y") && known_field.count("normal_z")) { if ((field_dtype["normal_x"] == field_dtype["normal_y"]) && (field_dtype["normal_x"] == field_dtype["normal_z"])) { header.has_attr["normals"] = true; header.attr_dtype["normals"] = field_dtype["x"]; } else { utility::LogWarning( "[InitializeHeader] Dtype for normals data are not same."); return false; } } if (known_field.count("rgb")) { header.has_attr["colors"] = true; header.attr_dtype["colors"] = field_dtype["rgb"]; } else if (known_field.count("rgba")) { header.has_attr["colors"] = true; header.attr_dtype["colors"] = field_dtype["rgba"]; } return true; } static bool ReadPCDHeader(FILE *file, PCDHeader &header) { char line_buffer[DEFAULT_IO_BUFFER_SIZE]; size_t specified_channel_count = 0; while (fgets(line_buffer, DEFAULT_IO_BUFFER_SIZE, file)) { std::string line(line_buffer); if (line == "") { continue; } std::vector<std::string> st = utility::SplitString(line, "\t\r\n "); std::stringstream sstream(line); sstream.imbue(std::locale::classic()); std::string line_type; sstream >> line_type; if (line_type.substr(0, 1) == "#") { } else if (line_type.substr(0, 7) == "VERSION") { if (st.size() >= 2) { header.version = st[1]; } } else if (line_type.substr(0, 6) == "FIELDS" || line_type.substr(0, 7) == "COLUMNS") { specified_channel_count = st.size() - 1; if (specified_channel_count == 0) { utility::LogWarning("[ReadPCDHeader] Bad PCD file format."); return false; } header.fields.resize(specified_channel_count); int count_offset = 0, offset = 0; for (size_t i = 0; i < specified_channel_count; ++i, count_offset += 1, offset += 4) { header.fields[i].name = st[i + 1]; header.fields[i].size = 4; header.fields[i].type = 'F'; header.fields[i].count = 1; header.fields[i].count_offset = count_offset; header.fields[i].offset = offset; } header.elementnum = count_offset; header.pointsize = offset; } else if (line_type.substr(0, 4) == "SIZE") { if (specified_channel_count != st.size() - 1) { utility::LogWarning("[ReadPCDHeader] Bad PCD file format."); return false; } int offset = 0, col_type = 0; for (size_t i = 0; i < specified_channel_count; ++i, offset += col_type) { sstream >> col_type; header.fields[i].size = col_type; header.fields[i].offset = offset; } header.pointsize = offset; } else if (line_type.substr(0, 4) == "TYPE") { if (specified_channel_count != st.size() - 1) { utility::LogWarning("[ReadPCDHeader] Bad PCD file format."); return false; } for (size_t i = 0; i < specified_channel_count; ++i) { header.fields[i].type = st[i + 1].c_str()[0]; } } else if (line_type.substr(0, 5) == "COUNT") { if (specified_channel_count != st.size() - 1) { utility::LogWarning("[ReadPCDHeader] Bad PCD file format."); return false; } int count_offset = 0, offset = 0, col_count = 0; for (size_t i = 0; i < specified_channel_count; ++i) { sstream >> col_count; header.fields[i].count = col_count; header.fields[i].count_offset = count_offset; header.fields[i].offset = offset; count_offset += col_count; offset += col_count * header.fields[i].size; } header.elementnum = count_offset; header.pointsize = offset; } else if (line_type.substr(0, 5) == "WIDTH") { sstream >> header.width; } else if (line_type.substr(0, 6) == "HEIGHT") { sstream >> header.height; header.points = header.width * header.height; } else if (line_type.substr(0, 9) == "VIEWPOINT") { if (st.size() >= 2) { header.viewpoint = st[1]; } } else if (line_type.substr(0, 6) == "POINTS") { sstream >> header.points; } else if (line_type.substr(0, 4) == "DATA") { header.datatype = PCDDataType::ASCII; if (st.size() >= 2) { if (st[1].substr(0, 17) == "binary_compressed") { header.datatype = PCDDataType::BINARY_COMPRESSED; } else if (st[1].substr(0, 6) == "binary") { header.datatype = PCDDataType::BINARY; } } break; } } if (!InitializeHeader(header)) { return false; } return true; } static void ReadASCIIPCDColorsFromField(ReadAttributePtr &attr, const PCLPointField &field, const char *data_ptr, const int index) { std::uint8_t *attr_data_ptr = static_cast<std::uint8_t *>(attr.data_ptr_) + index * attr.row_length_; if (field.size == 4) { std::uint8_t data[4] = {0}; char *end; if (field.type == 'I') { std::int32_t value = std::strtol(data_ptr, &end, 0); std::memcpy(data, &value, sizeof(std::int32_t)); } else if (field.type == 'U') { std::uint32_t value = std::strtoul(data_ptr, &end, 0); std::memcpy(data, &value, sizeof(std::uint32_t)); } else if (field.type == 'F') { float value = std::strtof(data_ptr, &end); std::memcpy(data, &value, sizeof(float)); } // color data is packed in BGR order. attr_data_ptr[0] = data[2]; attr_data_ptr[1] = data[1]; attr_data_ptr[2] = data[0]; } else { attr_data_ptr[0] = 0; attr_data_ptr[1] = 0; attr_data_ptr[2] = 0; } } template <typename scalar_t> static void UnpackASCIIPCDElement(scalar_t &data, const char *data_ptr) = delete; template <> void UnpackASCIIPCDElement<float>(float &data, const char *data_ptr) { char *end; data = std::strtof(data_ptr, &end); } template <> void UnpackASCIIPCDElement<double>(double &data, const char *data_ptr) { char *end; data = std::strtod(data_ptr, &end); } template <> void UnpackASCIIPCDElement<std::int8_t>(std::int8_t &data, const char *data_ptr) { char *end; data = static_cast<std::int8_t>(std::strtol(data_ptr, &end, 0)); } template <> void UnpackASCIIPCDElement<std::int16_t>(std::int16_t &data, const char *data_ptr) { char *end; data = static_cast<std::int16_t>(std::strtol(data_ptr, &end, 0)); } template <> void UnpackASCIIPCDElement<std::int32_t>(std::int32_t &data, const char *data_ptr) { char *end; data = static_cast<std::int32_t>(std::strtol(data_ptr, &end, 0)); } template <> void UnpackASCIIPCDElement<std::int64_t>(std::int64_t &data, const char *data_ptr) { char *end; data = std::strtol(data_ptr, &end, 0); } template <> void UnpackASCIIPCDElement<std::uint8_t>(std::uint8_t &data, const char *data_ptr) { char *end; data = static_cast<std::uint8_t>(std::strtoul(data_ptr, &end, 0)); } template <> void UnpackASCIIPCDElement<std::uint16_t>(std::uint16_t &data, const char *data_ptr) { char *end; data = static_cast<std::uint16_t>(std::strtoul(data_ptr, &end, 0)); } template <> void UnpackASCIIPCDElement<std::uint32_t>(std::uint32_t &data, const char *data_ptr) { char *end; data = static_cast<std::uint32_t>(std::strtoul(data_ptr, &end, 0)); } template <> void UnpackASCIIPCDElement<std::uint64_t>(std::uint64_t &data, const char *data_ptr) { char *end; data = std::strtoul(data_ptr, &end, 0); } static void ReadASCIIPCDElementsFromField(ReadAttributePtr &attr, const PCLPointField &field, const char *data_ptr, const int index) { DISPATCH_DTYPE_TO_TEMPLATE( GetDtypeFromPCDHeaderField(field.type, field.size), [&] { scalar_t *attr_data_ptr = static_cast<scalar_t *>(attr.data_ptr_) + index * attr.row_length_ + attr.row_idx_; UnpackASCIIPCDElement<scalar_t>(attr_data_ptr[0], data_ptr); }); } static void ReadBinaryPCDColorsFromField(ReadAttributePtr &attr, const PCLPointField &field, const void *data_ptr, const int index) { std::uint8_t *attr_data_ptr = static_cast<std::uint8_t *>(attr.data_ptr_) + index * attr.row_length_; if (field.size == 4) { std::uint8_t data[4] = {0}; std::memcpy(data, data_ptr, 4 * sizeof(std::uint8_t)); // color data is packed in BGR order. attr_data_ptr[0] = data[2]; attr_data_ptr[1] = data[1]; attr_data_ptr[2] = data[0]; } else { attr_data_ptr[0] = 0; attr_data_ptr[1] = 0; attr_data_ptr[2] = 0; } } static void ReadBinaryPCDElementsFromField(ReadAttributePtr &attr, const PCLPointField &field, const void *data_ptr, const int index) { DISPATCH_DTYPE_TO_TEMPLATE( GetDtypeFromPCDHeaderField(field.type, field.size), [&] { scalar_t *attr_data_ptr = static_cast<scalar_t *>(attr.data_ptr_) + index * attr.row_length_ + attr.row_idx_; std::memcpy(attr_data_ptr, data_ptr, sizeof(scalar_t)); }); } static bool ReadPCDData(FILE *file, PCDHeader &header, t::geometry::PointCloud &pointcloud, const ReadPointCloudOption &params) { // The header should have been checked pointcloud.Clear(); std::unordered_map<std::string, ReadAttributePtr> map_field_to_attr_ptr; if (header.has_attr["positions"]) { pointcloud.SetPointPositions(core::Tensor::Empty( {header.points, 3}, header.attr_dtype["positions"])); void *data_ptr = pointcloud.GetPointPositions().GetDataPtr(); ReadAttributePtr position_x(data_ptr, 0, 3, header.points); ReadAttributePtr position_y(data_ptr, 1, 3, header.points); ReadAttributePtr position_z(data_ptr, 2, 3, header.points); map_field_to_attr_ptr.emplace(std::string("x"), position_x); map_field_to_attr_ptr.emplace(std::string("y"), position_y); map_field_to_attr_ptr.emplace(std::string("z"), position_z); } else { utility::LogWarning( "[ReadPCDData] Fields for point data are not complete."); return false; } if (header.has_attr["normals"]) { pointcloud.SetPointNormals(core::Tensor::Empty( {header.points, 3}, header.attr_dtype["normals"])); void *data_ptr = pointcloud.GetPointNormals().GetDataPtr(); ReadAttributePtr normal_x(data_ptr, 0, 3, header.points); ReadAttributePtr normal_y(data_ptr, 1, 3, header.points); ReadAttributePtr normal_z(data_ptr, 2, 3, header.points); map_field_to_attr_ptr.emplace(std::string("normal_x"), normal_x); map_field_to_attr_ptr.emplace(std::string("normal_y"), normal_y); map_field_to_attr_ptr.emplace(std::string("normal_z"), normal_z); } if (header.has_attr["colors"]) { // Colors stored in a PCD file is ALWAYS in UInt8 format. // However it is stored as a single packed floating value. pointcloud.SetPointColors( core::Tensor::Empty({header.points, 3}, core::UInt8)); void *data_ptr = pointcloud.GetPointColors().GetDataPtr(); ReadAttributePtr colors(data_ptr, 0, 3, header.points); map_field_to_attr_ptr.emplace(std::string("colors"), colors); } // PCLPointField for (const auto &field : header.fields) { if (header.has_attr[field.name] && field.name != "x" && field.name != "y" && field.name != "z" && field.name != "normal_x" && field.name != "normal_y" && field.name != "normal_z" && field.name != "rgb" && field.name != "rgba") { pointcloud.SetPointAttr( field.name, core::Tensor::Empty({header.points, 1}, header.attr_dtype[field.name])); void *data_ptr = pointcloud.GetPointAttr(field.name).GetDataPtr(); ReadAttributePtr attr(data_ptr, 0, 1, header.points); map_field_to_attr_ptr.emplace(field.name, attr); } } utility::CountingProgressReporter reporter(params.update_progress); reporter.SetTotal(header.points); if (header.datatype == PCDDataType::ASCII) { char line_buffer[DEFAULT_IO_BUFFER_SIZE]; int idx = 0; while (fgets(line_buffer, DEFAULT_IO_BUFFER_SIZE, file) && idx < header.points) { std::string line(line_buffer); std::vector<std::string> strs = utility::SplitString(line, "\t\r\n "); if ((int)strs.size() < header.elementnum) { continue; } for (size_t i = 0; i < header.fields.size(); ++i) { const auto &field = header.fields[i]; if (field.name == "rgb" || field.name == "rgba") { ReadASCIIPCDColorsFromField( map_field_to_attr_ptr["colors"], field, strs[field.count_offset].c_str(), idx); } else { ReadASCIIPCDElementsFromField( map_field_to_attr_ptr[field.name], field, strs[field.count_offset].c_str(), idx); } } ++idx; if (idx % 1000 == 0) { reporter.Update(idx); } } } else if (header.datatype == PCDDataType::BINARY) { std::unique_ptr<char[]> buffer(new char[header.pointsize]); for (int i = 0; i < header.points; ++i) { if (fread(buffer.get(), header.pointsize, 1, file) != 1) { utility::LogWarning( "[ReadPCDData] Failed to read data record."); pointcloud.Clear(); return false; } for (const auto &field : header.fields) { if (field.name == "rgb" || field.name == "rgba") { ReadBinaryPCDColorsFromField( map_field_to_attr_ptr["colors"], field, buffer.get() + field.offset, i); } else { ReadBinaryPCDElementsFromField( map_field_to_attr_ptr[field.name], field, buffer.get() + field.offset, i); } } if (i % 1000 == 0) { reporter.Update(i); } } } else if (header.datatype == PCDDataType::BINARY_COMPRESSED) { double reporter_total = 100.0; reporter.SetTotal(int(reporter_total)); reporter.Update(int(reporter_total * 0.01)); std::uint32_t compressed_size; std::uint32_t uncompressed_size; if (fread(&compressed_size, sizeof(compressed_size), 1, file) != 1) { utility::LogWarning("[ReadPCDData] Failed to read data record."); pointcloud.Clear(); return false; } if (fread(&uncompressed_size, sizeof(uncompressed_size), 1, file) != 1) { utility::LogWarning("[ReadPCDData] Failed to read data record."); pointcloud.Clear(); return false; } utility::LogDebug( "PCD data with {:d} compressed size, and {:d} uncompressed " "size.", compressed_size, uncompressed_size); std::unique_ptr<char[]> buffer_compressed(new char[compressed_size]); reporter.Update(int(reporter_total * .1)); if (fread(buffer_compressed.get(), 1, compressed_size, file) != compressed_size) { utility::LogWarning("[ReadPCDData] Failed to read data record."); pointcloud.Clear(); return false; } std::unique_ptr<char[]> buffer(new char[uncompressed_size]); reporter.Update(int(reporter_total * .2)); if (lzf_decompress(buffer_compressed.get(), (unsigned int)compressed_size, buffer.get(), (unsigned int)uncompressed_size) != uncompressed_size) { utility::LogWarning("[ReadPCDData] Uncompression failed."); pointcloud.Clear(); return false; } for (const auto &field : header.fields) { const char *base_ptr = buffer.get() + field.offset * header.points; double progress = double(base_ptr - buffer.get()) / uncompressed_size; reporter.Update(int(reporter_total * (progress + .2))); if (field.name == "rgb" || field.name == "rgba") { for (int i = 0; i < header.points; ++i) { ReadBinaryPCDColorsFromField( map_field_to_attr_ptr["colors"], field, base_ptr + i * field.size * field.count, i); } } else { for (int i = 0; i < header.points; ++i) { ReadBinaryPCDElementsFromField( map_field_to_attr_ptr[field.name], field, base_ptr + i * field.size * field.count, i); } } } } reporter.Finish(); return true; } // Write functions. static void SetPCDHeaderFieldTypeAndSizeFromDtype(const core::Dtype &dtype, PCLPointField &field) { if (dtype == core::Int8) { field.type = 'I'; field.size = 1; } else if (dtype == core::Int16) { field.type = 'I'; field.size = 2; } else if (dtype == core::Int32) { field.type = 'I'; field.size = 4; } else if (dtype == core::Int64) { field.type = 'I'; field.size = 8; } else if (dtype == core::UInt8) { field.type = 'U'; field.size = 1; } else if (dtype == core::UInt16) { field.type = 'U'; field.size = 2; } else if (dtype == core::UInt32) { field.type = 'U'; field.size = 4; } else if (dtype == core::UInt64) { field.type = 'U'; field.size = 8; } else if (dtype == core::Float32) { field.type = 'F'; field.size = 4; } else if (dtype == core::Float64) { field.type = 'F'; field.size = 8; } else { utility::LogError("Unsupported data type."); } } static bool GenerateHeader(const t::geometry::PointCloud &pointcloud, const bool write_ascii, const bool compressed, PCDHeader &header) { if (!pointcloud.HasPointPositions()) { return false; } header.version = "0.7"; header.width = static_cast<int>(pointcloud.GetPointPositions().GetLength()); header.height = 1; header.points = header.width; header.fields.clear(); PCLPointField field_x, field_y, field_z; field_x.name = "x"; field_x.count = 1; SetPCDHeaderFieldTypeAndSizeFromDtype( pointcloud.GetPointPositions().GetDtype(), field_x); header.fields.push_back(field_x); field_y = field_x; field_y.name = "y"; header.fields.push_back(field_y); field_z = field_x; field_z.name = "z"; header.fields.push_back(field_z); header.elementnum = 3 * field_x.count; header.pointsize = 3 * field_x.size; if (pointcloud.HasPointNormals()) { PCLPointField field_normal_x, field_normal_y, field_normal_z; field_normal_x.name = "normal_x"; field_normal_x.count = 1; SetPCDHeaderFieldTypeAndSizeFromDtype( pointcloud.GetPointPositions().GetDtype(), field_normal_x); header.fields.push_back(field_normal_x); field_normal_y = field_normal_x; field_normal_y.name = "normal_y"; header.fields.push_back(field_normal_y); field_normal_z = field_normal_x; field_normal_z.name = "normal_z"; header.fields.push_back(field_normal_z); header.elementnum += 3 * field_normal_x.count; header.pointsize += 3 * field_normal_x.size; } if (pointcloud.HasPointColors()) { PCLPointField field_colors; field_colors.name = "rgb"; field_colors.count = 1; field_colors.type = 'F'; field_colors.size = 4; header.fields.push_back(field_colors); header.elementnum++; header.pointsize += 4; } // Custom attribute support of shape {num_points, 1}. for (auto &kv : pointcloud.GetPointAttr()) { if (kv.first != "positions" && kv.first != "normals" && kv.first != "colors") { if (kv.second.GetShape() == core::SizeVector( {pointcloud.GetPointPositions().GetLength(), 1})) { PCLPointField field_custom_attr; field_custom_attr.name = kv.first; field_custom_attr.count = 1; SetPCDHeaderFieldTypeAndSizeFromDtype(kv.second.GetDtype(), field_custom_attr); header.fields.push_back(field_custom_attr); header.elementnum++; header.pointsize += field_custom_attr.size; } else { utility::LogWarning( "Write PCD : Skipping {} attribute. PointCloud " "contains {} attribute which is not supported by PCD " "IO. Only points, normals, colors and attributes with " "shape (num_points, 1) are supported. Expected shape: " "{} but got {}.", kv.first, kv.first, core::SizeVector( {pointcloud.GetPointPositions().GetLength(), 1}) .ToString(), kv.second.GetShape().ToString()); } } } if (write_ascii) { header.datatype = PCDDataType::ASCII; } else { if (compressed) { header.datatype = PCDDataType::BINARY_COMPRESSED; } else { header.datatype = PCDDataType::BINARY; } } return true; } static bool WritePCDHeader(FILE *file, const PCDHeader &header) { fprintf(file, "# .PCD v%s - Point Cloud Data file format\n", header.version.c_str()); fprintf(file, "VERSION %s\n", header.version.c_str()); fprintf(file, "FIELDS"); for (const auto &field : header.fields) { fprintf(file, " %s", field.name.c_str()); } fprintf(file, "\n"); fprintf(file, "SIZE"); for (const auto &field : header.fields) { fprintf(file, " %d", field.size); } fprintf(file, "\n"); fprintf(file, "TYPE"); for (const auto &field : header.fields) { fprintf(file, " %c", field.type); } fprintf(file, "\n"); fprintf(file, "COUNT"); for (const auto &field : header.fields) { fprintf(file, " %d", field.count); } fprintf(file, "\n"); fprintf(file, "WIDTH %d\n", header.width); fprintf(file, "HEIGHT %d\n", header.height); fprintf(file, "VIEWPOINT 0 0 0 1 0 0 0\n"); fprintf(file, "POINTS %d\n", header.points); switch (header.datatype) { case PCDDataType::BINARY: fprintf(file, "DATA binary\n"); break; case PCDDataType::BINARY_COMPRESSED: fprintf(file, "DATA binary_compressed\n"); break; case PCDDataType::ASCII: default: fprintf(file, "DATA ascii\n"); break; } return true; } template <typename scalar_t> static void ColorToUint8(const scalar_t *input_color, std::uint8_t *output_color) { utility::LogError( "Color format not supported. Supported color format includes " "Float32, Float64, UInt8, UInt16, UInt32."); } template <> void ColorToUint8<float>(const float *input_color, std::uint8_t *output_color) { const float normalisation_factor = static_cast<float>(std::numeric_limits<std::uint8_t>::max()); for (int i = 0; i < 3; ++i) { output_color[i] = static_cast<std::uint8_t>( std::round(std::min(1.f, std::max(0.f, input_color[2 - i])) * normalisation_factor)); } output_color[3] = 0; } template <> void ColorToUint8<double>(const double *input_color, std::uint8_t *output_color) { const double normalisation_factor = static_cast<double>(std::numeric_limits<std::uint8_t>::max()); for (int i = 0; i < 3; ++i) { output_color[i] = static_cast<std::uint8_t>( std::round(std::min(1., std::max(0., input_color[2 - i])) * normalisation_factor)); } output_color[3] = 0; } template <> void ColorToUint8<std::uint8_t>(const std::uint8_t *input_color, std::uint8_t *output_color) { for (int i = 0; i < 3; ++i) { output_color[i] = input_color[2 - i]; } output_color[3] = 0; } template <> void ColorToUint8<std::uint16_t>(const std::uint16_t *input_color, std::uint8_t *output_color) { const float normalisation_factor = static_cast<float>(std::numeric_limits<std::uint8_t>::max()) / static_cast<float>(std::numeric_limits<std::uint16_t>::max()); for (int i = 0; i < 3; ++i) { output_color[i] = static_cast<std::uint16_t>(input_color[2 - i] * normalisation_factor); } output_color[3] = 0; } template <> void ColorToUint8<std::uint32_t>(const std::uint32_t *input_color, std::uint8_t *output_color) { const float normalisation_factor = static_cast<float>(std::numeric_limits<std::uint8_t>::max()) / static_cast<float>(std::numeric_limits<std::uint32_t>::max()); for (int i = 0; i < 3; ++i) { output_color[i] = static_cast<std::uint32_t>(input_color[2 - i] * normalisation_factor); } output_color[3] = 0; } static core::Tensor PackColorsToFloat(const core::Tensor &colors_contiguous) { core::Tensor packed_color = core::Tensor::Empty({colors_contiguous.GetLength(), 1}, core::Float32, core::Device("CPU:0")); auto packed_color_ptr = packed_color.GetDataPtr<float>(); DISPATCH_DTYPE_TO_TEMPLATE(colors_contiguous.GetDtype(), [&]() { auto colors_ptr = colors_contiguous.GetDataPtr<scalar_t>(); core::ParallelFor(core::Device("CPU:0"), colors_contiguous.GetLength(), [&](std::int64_t workload_idx) { std::uint8_t rgba[4] = {0}; ColorToUint8<scalar_t>( colors_ptr + 3 * workload_idx, rgba); float val = 0; std::memcpy(&val, rgba, 4 * sizeof(std::uint8_t)); packed_color_ptr[workload_idx] = val; }); }); return packed_color; } template <typename scalar_t> static int WriteElementDataToFileASCII(const scalar_t &data, FILE *file) = delete; template <> int WriteElementDataToFileASCII<float>(const float &data, FILE *file) { return fprintf(file, "%.10g ", data); } template <> int WriteElementDataToFileASCII<double>(const double &data, FILE *file) { return fprintf(file, "%.10g ", data); } template <> int WriteElementDataToFileASCII<std::int8_t>(const std::int8_t &data, FILE *file) { return fprintf(file, "%" PRId8 " ", data); } template <> int WriteElementDataToFileASCII<std::int16_t>(const std::int16_t &data, FILE *file) { return fprintf(file, "%" PRId16 " ", data); } template <> int WriteElementDataToFileASCII<std::int32_t>(const std::int32_t &data, FILE *file) { return fprintf(file, "%" PRId32 " ", data); } template <> int WriteElementDataToFileASCII<std::int64_t>(const std::int64_t &data, FILE *file) { return fprintf(file, "%" PRId64 " ", data); } template <> int WriteElementDataToFileASCII<std::uint8_t>(const std::uint8_t &data, FILE *file) { return fprintf(file, "%" PRIu8 " ", data); } template <> int WriteElementDataToFileASCII<std::uint16_t>(const std::uint16_t &data, FILE *file) { return fprintf(file, "%" PRIu16 " ", data); } template <> int WriteElementDataToFileASCII<std::uint32_t>(const std::uint32_t &data, FILE *file) { return fprintf(file, "%" PRIu32 " ", data); } template <> int WriteElementDataToFileASCII<std::uint64_t>(const std::uint64_t &data, FILE *file) { return fprintf(file, "%" PRIu64 " ", data); } static bool WritePCDData(FILE *file, const PCDHeader &header, const geometry::PointCloud &pointcloud, const WritePointCloudOption &params) { if (pointcloud.IsEmpty()) { utility::LogWarning("Write PLY failed: point cloud has 0 points."); return false; } // TODO: Add device transfer in tensor map and use it here. geometry::TensorMap t_map(pointcloud.GetPointAttr().Contiguous()); const std::int64_t num_points = static_cast<std::int64_t>( pointcloud.GetPointPositions().GetLength()); std::vector<WriteAttributePtr> attribute_ptrs; attribute_ptrs.emplace_back(t_map["positions"].GetDtype(), t_map["positions"].GetDataPtr(), 3); if (pointcloud.HasPointNormals()) { attribute_ptrs.emplace_back(t_map["normals"].GetDtype(), t_map["normals"].GetDataPtr(), 3); } if (pointcloud.HasPointColors()) { t_map["colors"] = PackColorsToFloat(t_map["colors"]); attribute_ptrs.emplace_back(core::Float32, t_map["colors"].GetDataPtr(), 1); } // Sanity check for the attributes is done before adding it to the // `header.fields`. for (auto &field : header.fields) { if (field.name != "x" && field.name != "y" && field.name != "z" && field.name != "normal_x" && field.name != "normal_y" && field.name != "normal_z" && field.name != "rgb" && field.name != "rgba" && field.count == 1) { attribute_ptrs.emplace_back(t_map[field.name].GetDtype(), t_map[field.name].GetDataPtr(), 1); } } utility::CountingProgressReporter reporter(params.update_progress); reporter.SetTotal(num_points); if (header.datatype == PCDDataType::ASCII) { for (std::int64_t i = 0; i < num_points; ++i) { for (auto &it : attribute_ptrs) { DISPATCH_DTYPE_TO_TEMPLATE(it.dtype_, [&]() { const scalar_t *data_ptr = static_cast<const scalar_t *>(it.data_ptr_); for (int idx_offset = it.group_size_ * i; idx_offset < it.group_size_ * (i + 1); ++idx_offset) { WriteElementDataToFileASCII<scalar_t>( data_ptr[idx_offset], file); } }); } fprintf(file, "\n"); if (i % 1000 == 0) { reporter.Update(i); } } } else if (header.datatype == PCDDataType::BINARY) { std::vector<char> buffer((header.pointsize * header.points)); std::uint32_t buffer_index = 0; for (std::int64_t i = 0; i < num_points; ++i) { for (auto &it : attribute_ptrs) { DISPATCH_DTYPE_TO_TEMPLATE(it.dtype_, [&]() { const scalar_t *data_ptr = static_cast<const scalar_t *>(it.data_ptr_); for (int idx_offset = it.group_size_ * i; idx_offset < it.group_size_ * (i + 1); ++idx_offset) { std::memcpy(buffer.data() + buffer_index, reinterpret_cast<const char *>( &data_ptr[idx_offset]), sizeof(scalar_t)); buffer_index += sizeof(scalar_t); } }); } if (i % 1000 == 0) { reporter.Update(i); } } fwrite(buffer.data(), sizeof(char), buffer.size(), file); } else if (header.datatype == PCDDataType::BINARY_COMPRESSED) { // BINARY_COMPRESSED data contains attributes in column layout // for better compression. // For example instead of X Y Z NX NY NZ X Y Z NX NY NZ, the data is // stored as X X Y Y Z Z NX NX NY NY NZ NZ. const std::int64_t report_total = attribute_ptrs.size() * 2; // 0%-50% packing into buffer // 50%-75% compressing buffer // 75%-100% writing compressed buffer reporter.SetTotal(report_total); const std::uint32_t buffer_size_in_bytes = header.pointsize * header.points; std::vector<char> buffer(buffer_size_in_bytes); std::vector<char> buffer_compressed(2 * buffer_size_in_bytes); std::uint32_t buffer_index = 0; std::int64_t count = 0; for (auto &it : attribute_ptrs) { DISPATCH_DTYPE_TO_TEMPLATE(it.dtype_, [&]() { const scalar_t *data_ptr = static_cast<const scalar_t *>(it.data_ptr_); for (int idx_offset = 0; idx_offset < it.group_size_; ++idx_offset) { for (std::int64_t i = 0; i < num_points; ++i) { std::memcpy(buffer.data() + buffer_index, reinterpret_cast<const char *>( &data_ptr[i * it.group_size_ + idx_offset]), sizeof(scalar_t)); buffer_index += sizeof(scalar_t); } } }); reporter.Update(count++); } std::uint32_t size_compressed = lzf_compress( buffer.data(), buffer_size_in_bytes, buffer_compressed.data(), buffer_size_in_bytes * 2); if (size_compressed == 0) { utility::LogWarning("[WritePCDData] Failed to compress data."); return false; } utility::LogDebug( "[WritePCDData] {:d} bytes data compressed into {:d} bytes.", buffer_size_in_bytes, size_compressed); reporter.Update(static_cast<std::int64_t>(report_total * 0.75)); fwrite(&size_compressed, sizeof(size_compressed), 1, file); fwrite(&buffer_size_in_bytes, sizeof(buffer_size_in_bytes), 1, file); fwrite(buffer_compressed.data(), 1, size_compressed, file); } reporter.Finish(); return true; } bool ReadPointCloudFromPCD(const std::string &filename, t::geometry::PointCloud &pointcloud, const ReadPointCloudOption &params) { PCDHeader header; FILE *file = utility::filesystem::FOpen(filename.c_str(), "rb"); if (file == NULL) { utility::LogWarning("Read PCD failed: unable to open file: {}", filename); return false; } if (!ReadPCDHeader(file, header)) { utility::LogWarning("Read PCD failed: unable to parse header."); fclose(file); return false; } utility::LogDebug( "PCD header indicates {:d} fields, {:d} bytes per point, and {:d} " "points in total.", (int)header.fields.size(), header.pointsize, header.points); for (const auto &field : header.fields) { utility::LogDebug("{}, {}, {:d}, {:d}, {:d}", field.name.c_str(), field.type, field.size, field.count, field.offset); } utility::LogDebug("Compression method is {:d}.", (int)header.datatype); utility::LogDebug("Points: {}; normals: {}; colors: {}", header.has_attr["positions"] ? "yes" : "no", header.has_attr["normals"] ? "yes" : "no", header.has_attr["colors"] ? "yes" : "no"); if (!ReadPCDData(file, header, pointcloud, params)) { utility::LogWarning("Read PCD failed: unable to read data."); fclose(file); return false; } fclose(file); return true; } bool WritePointCloudToPCD(const std::string &filename, const geometry::PointCloud &pointcloud, const WritePointCloudOption &params) { pointcloud.GetPointPositions().AssertDevice( core::Device("CPU:0"), "Write PCD failed: expects point cloud to be on CPU device."); PCDHeader header; if (!GenerateHeader(pointcloud, bool(params.write_ascii), bool(params.compressed), header)) { utility::LogWarning("Write PCD failed: unable to generate header."); return false; } FILE *file = utility::filesystem::FOpen(filename.c_str(), "wb"); if (file == NULL) { utility::LogWarning("Write PCD failed: unable to open file."); return false; } if (!WritePCDHeader(file, header)) { utility::LogWarning("Write PCD failed: unable to write header."); fclose(file); return false; } if (!WritePCDData(file, header, pointcloud, params)) { utility::LogWarning("Write PCD failed: unable to write data."); fclose(file); return false; } fclose(file); return true; } } // namespace io } // namespace t } // namespace open3d
37.925835
91
0.542022
[ "geometry", "shape", "vector" ]
7754228cab4ce50194988b3e3f7d24e15ca92501
48,096
cpp
C++
Code/trunk/cpp/RandomLib/Random.cpp
jlconlin/PhDThesis
8e704613721a800ce1c59576e94f40fa6f7cd986
[ "MIT" ]
null
null
null
Code/trunk/cpp/RandomLib/Random.cpp
jlconlin/PhDThesis
8e704613721a800ce1c59576e94f40fa6f7cd986
[ "MIT" ]
null
null
null
Code/trunk/cpp/RandomLib/Random.cpp
jlconlin/PhDThesis
8e704613721a800ce1c59576e94f40fa6f7cd986
[ "MIT" ]
null
null
null
/** * \file Random.cpp * \brief Code for RandomSeed, MT19937, SFMT19937, RandomCanonical, and Power2 * * RandomSeed provides support for seed management, MT19937 implements the * Mersenne-Twister random number generator, SFMT19937 implements the * SIMD-oriented Fast Mersenne-Twister random number generator, RandomCanonical * supplies uniform distributions of integers and reals, and Power2 multiplies * reals by powers of two. * * The Mersenne Twister random number generator, * <a href="http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html"> * mt19937</a> , is described in \n Makoto Matsumoto and Takuji Nishimura,\n * Mersenne Twister: A 623-Dimensionally Equidistributed Uniform Pseudo-Random * Number Generator,\n ACM TOMACS 8, 3-30 (1998) * * The code for NextBatch is adapted from the code for genrand_int32 by Makoto * Matsumoto and Takuji Nishimura in * http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/CODES/mt19937ar.c * * PreviousBatch is adapted from revand by Katsumi Hagita. See * http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/VERSIONS/FORTRAN/REVmt19937b.f * The code for SeedToState is adapted from init_genrand{,64} and * init_by_array{,64} by Makoto Matsumoto and Takuji Nishimura in * http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/CODES/mt19937ar.c and * http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/VERSIONS/C-LANG/mt19937-64.c * following the seed_seq class given in * http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n2079.pdf * * The * <a href="http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/SFMT/index.html"> * SFMT</a> algorithm is described in\n * Mutsuo Saito,\n An Application of Finite Field: Design and Implementation of * 128-bit Instruction-Based Fast Pseudorandom Number Generator,\n Master's * Thesis, Dept. of Math. Hiroshima University (Feb. 2007),\n * http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/SFMT/M062821.pdf\n * Mutsuo Saito and Makoto Matsumoto,\n * SIMD-oriented Fast Mersenne Twister: a 128-bit Pseudorandom Number * Generator,\n accepted in the proceedings of MCQMC2006\n * http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/ARTICLES/sfmt.pdf * * The adaption to the C++ and the rest of the code was written by * <a href="http://charles.karney.info/"> Charles Karney</a> * <charles@karney.com> and licensed under the LGPL. For more information, see * http://charles.karney.info/random/ **********************************************************************/ #include "RandomLib/Random.hpp" #include <limits> #include <fstream> // For SeedWord reading /dev/urandom #include <ctime> // For SeedWord calling time() #if !WINDOWS #include <sys/time.h> // For SeedWord calling gettimeofday #include <unistd.h> // For SeedWord calling getpid(), gethostid() #include <netinet/in.h> // For Save/Load #else #include <windows.h> // For SeedWord calling high prec timer #include <winbase.h> #include <process.h> // For SeedWord calling getpid() #define getpid _getpid #endif namespace { char rcsid[] = "$Id: Random.cpp 173 2007-11-09 20:30:45Z jlconlin $"; char* h_rcsid[] = { RCSID_RANDOM_H, RCSID_RANDOMCANONICAL_H, RCSID_POWER2_H, RCSID_MT19937_H, RCSID_SFMT19937_H, RCSID_RANDOMSEED_H, }; } /** * \brief Namespace for random number library ***********************************************************************/ namespace RandomLib { // RandomSeed implementation RandomSeed::seed_type RandomSeed::SeedWord() { // Check that the assumptions made about the capabilities of the number // system are valid. STATIC_ASSERT(std::numeric_limits<seed_type>::radix == 2 && std::numeric_limits<u32>::radix == 2 && std::numeric_limits<u64>::radix == 2 && !std::numeric_limits<seed_type>::is_signed && !std::numeric_limits<u32>::is_signed && !std::numeric_limits<u64>::is_signed); STATIC_ASSERT(std::numeric_limits<seed_type>::digits >= 32 && std::numeric_limits<u32>::digits >= 32 && std::numeric_limits<u64>::digits >= 64); seed_type t = 0; // Linux has /dev/urandom to initialize the seed randomly. (Use // /dev/urandom instead of /dev/random because it does not block.) { std::ifstream f("/dev/urandom", std::ios::binary | std::ios::in); if (f.good()) { u32 x; // Only need 32 bits from /dev/urandom f.read(reinterpret_cast<char *>(&x), sizeof(x)); t = seed_type(x); } } // XOR with PID to prevent correlations between jobs started close together // on the same node. Multiply by a different prime from that used for the // time of day to avoid correlations with the time (e.g., if jobs are // started at regular intervals so that both the PID and the time are // arithmetic progressions). t ^= static_cast<seed_type>(getpid()) * seed_type(10000019UL); #if !WINDOWS timeval tv; if (gettimeofday(&tv, 0) == 0) // XOR with microsec time. Multiply secs by a prime, in case // gettimeofday lamely returns zero for the usecs. t ^= static_cast<seed_type>(tv.tv_sec) * seed_type(1000003UL) + static_cast<seed_type>(tv.tv_usec); #else LARGE_INTEGER taux; if (QueryPerformanceCounter((LARGE_INTEGER *)&taux)) t ^= static_cast<seed_type>(taux.HighPart) * seed_type(1000003UL) + static_cast<seed_type>(taux.LowPart); #endif else // XOR with plain time as a fall back t ^= static_cast<seed_type>(std::time(0)); return SeedMask(t); } std::vector<RandomSeed::seed_type> RandomSeed::SeedVector() { std::vector<seed_type> v; { // fine-grained timer #if !WINDOWS timeval tv; if (gettimeofday(&tv, 0) == 0) v.push_back(static_cast<seed_type>(tv.tv_usec)); #else LARGE_INTEGER taux; if (QueryPerformanceCounter((LARGE_INTEGER *)&taux)) { v.push_back(static_cast<seed_type>(taux.LowPart)); v.push_back(static_cast<seed_type>(taux.HighPart)); } #endif } // seconds const time_t tim = std::time(0); v.push_back(static_cast<seed_type>(std::time(0))); // PID v.push_back(static_cast<seed_type>(getpid())); #if !WINDOWS // host ID v.push_back(static_cast<seed_type>(gethostid())); #endif { // year const tm* gt = std::gmtime(&tim); v.push_back((seed_type(1900) + static_cast<seed_type>(gt->tm_year))); } std::transform(v.begin(), v.end(), v.begin(), SeedMask); return v; } std::vector<RandomSeed::seed_type> RandomSeed::StringToVector(const std::string& s) throw(std::bad_alloc) { std::vector<seed_type> v(0); const char* c = s.c_str(); char* q; std::string::size_type p = 0; while (true) { p = s.find_first_of("0123456789", p); if (p == std::string::npos) break; v.push_back(SeedMask(std::strtoul(c + p, &q, 0))); p = q - c; } return v; } // Save and restore. template<> void RandomSeed::Write32<RandomSeed::u32, 32u>(std::ostream& os, bool bin, int& cnt, u32 x) throw(std::ios::failure) { if (bin) { unsigned char buf[4]; // Use network order -- most significant byte first buf[3] = static_cast<unsigned char>(x); buf[2] = static_cast<unsigned char>(x >>= 8); buf[1] = static_cast<unsigned char>(x >>= 8); buf[0] = static_cast<unsigned char>(x >>= 8); os.write(reinterpret_cast<const char *>(buf), 4); } else { const int longsperline = 72/11; // No spacing before or after if (cnt > 0) // Newline every longsperline longs os << (cnt % longsperline ? " " : "\n"); os << x; ++cnt; } } template<> void RandomSeed::Read32<RandomSeed::u32, 32u>(std::istream& is, bool bin, u32& x) throw(std::ios::failure) { if (bin) { unsigned char buf[4]; is.read(reinterpret_cast<char *>(buf), 4); // Use network order -- most significant byte first x = u32(buf[0]) << 24 | u32(buf[1]) << 16 | u32(buf[2]) << 8 | u32(buf[3]); } else { u32 n; is >> std::ws >> n; x = n; } // x &= U32_MASK; } template<> void RandomSeed::Write32<RandomSeed::u64, 64u>(std::ostream& os, bool bin, int& cnt, u64 x) throw(std::ios::failure) { Write32<u32, 32u>(os, bin, cnt, static_cast<u32>(x >> 32) & U32_MASK); Write32<u32, 32u>(os, bin, cnt, static_cast<u32>(x ) & U32_MASK); } template<> void RandomSeed::Read32<RandomSeed::u64, 64u>(std::istream& is, bool bin, u64& x) throw(std::ios::failure) { u32 t; Read32<u32, 32u>(is, bin, t); x = static_cast<u64>(t) << 32; Read32<u32, 32u>(is, bin, t); x |= static_cast<u64>(t); } template<> void RandomSeed::SeedToState<RandomSeed::u32, 32u>(u32 state[], unsigned n) const throw() { // This is the algorithm given in the seed_seq class described in // http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n2079.pdf It is // adapted from // http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/CODES/mt19937ar.c const unsigned s = static_cast<unsigned>(_seed.size()); const unsigned w = 32u; u32 r = (u32(5489UL) + s) & U32_MASK; state[0] = r; for (unsigned k = 1; k < n; ++k) { r = u32(1812433253UL) * (r ^ r >> w - 2) + k; r &= U32_MASK; state[k] = r; } if (s > 0) { unsigned i1 = 0; for (unsigned k = (n > s ? n : s), j = 0; k; --k, i1 = i1 == n - 1 ? 0 : i1 + 1, // i1 = i1 + 1 mod n j = j == s - 1 ? 0 : j + 1 ) { // j = j+1 mod s r = state[i1] ^ u32(1664525UL) * (r ^ r >> w - 2); r += static_cast<u32>(_seed[j]) + j; r &= U32_MASK; state[i1] = r; } for (unsigned k = n; k; --k, i1 = i1 == n - 1 ? 0 : i1 + 1) { // i1 = i1 + 1 mod n r = state[i1] ^ u32(1566083941UL) * (r ^ r >> w - 2); r -= i1; r &= U32_MASK; state[i1] = r; } } } template<> void RandomSeed::SeedToState<RandomSeed::u64, 64u>(u64 state[], unsigned n) const throw() { // This is adapted from // http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/VERSIONS/C-LANG/mt19937-64.c // with some changes to bring it into line with the seed_seq class given in // http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n2079.pdf The // differences from the 32-bit version are: different (bigger) // multiplicative constants; packing the seed array into 64-bit chunks. const unsigned s = static_cast<unsigned>(_seed.size()); const unsigned w = 64u; u64 r = (u64(5489ULL) + s) & U64_MASK; state[0] = r; for (unsigned k = 1; k < n; ++k) { r = u64(6364136223846793005ULL) * (r ^ r >> w - 2) + k; r &= U64_MASK; state[k] = r; } if (s > 0) { const unsigned key2 = (s + 1)/2; unsigned i1 = 0; for (unsigned k = (n > key2 ? n : key2), j = 0; k; --k, i1 = i1 == n - 1 ? 0 : i1 + 1, // i1 = i1 + 1 mod n j = j == key2 - 1 ? 0 : j + 1 ) { // j = j + 1 mod key2 r = state[i1] ^ u64(3935559000370003845ULL) * (r ^ r >> w - 2); r += j + static_cast<u64>(_seed[2 * j]) + (2 * j + 1 == s ? u64(0) : static_cast<u64>(_seed[2 * j + 1]) << 32); r &= U64_MASK; state[i1] = r; } for (unsigned k = n; k; --k, i1 = i1 == n - 1 ? 0 : i1 + 1) { // i1 = i1 + 1 mod n r = state[i1] ^ u64(2862933555777941757ULL) * (r ^ r >> w - 2); r -= i1; r &= U64_MASK; state[i1] = r; } } } // Note that BitWidth = 128u is a bogus setting. This is really a 32-bit // SeedToState algorithm. 128u is used since the algorithm was introduced // with the 128-bit SFMT19937 and to distinguish it from the 32-bit algorithm // used by MT19937 template<> void RandomSeed::SeedToState<RandomSeed::u32, 128u>(u32 state[], unsigned n) const throw() { // This is adapted from the routine init_by_array by Mutsuo Saito given in // http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/SFMT/SFMT-src-1.2.tar.gz if (n == 0) return; // Nothing to do const unsigned s = static_cast<unsigned>(_seed.size()), // Add treatment of small n with lag = (n - 1)/2 for n <= 7. In // particular, the first operation (xor or plus) in each for loop // involves three distinct indices for n > 2. lag = n >= 623 ? 11 : (n >= 68 ? 7 : (n >= 39 ? 5 : (n >= 7 ? 3 : (n - 1)/2))), // count = max( s + 1, n ) count = s + 1 > n ? s + 1 : n; std::fill(state, state + n, u32(0x8b8b8b8bUL)); const unsigned w = 32u; unsigned i = 0, k = (n - lag) / 2, l = k + lag; u32 r = state[n - 1]; for (unsigned j = 0; j < count; ++j, i = i == n - 1 ? 0 : i + 1, k = k == n - 1 ? 0 : k + 1, l = l == n - 1 ? 0 : l + 1) { // Here r = state[(j - 1) mod n] // i = j mod n // k = (j + (n - lag)/2) mod n // l = (j + (n - lag)/2 + lag) mod n r ^= state[i] ^ state[k]; r &= U32_MASK; r = u32(1664525UL) * (r ^ r >> w - 5); state[k] += r; r += i + (j > s ? 0 : (j ? static_cast<u32>(_seed[j - 1]) : s)); state[l] += r; state[i] = r; } for (unsigned j = n; j; --j, i = i == n - 1 ? 0 : i + 1, k = k == n - 1 ? 0 : k + 1, l = l == n - 1 ? 0 : l + 1) { // Here r = state[(i - 1) mod n] // k = (i + (n - lag)/2) mod n // l = (i + (n - lag)/2 + lag) mod n r += state[i] + state[k]; r &= U32_MASK; r = u32(1566083941UL) * (r ^ r >> w - 5); r &= U32_MASK; state[k] ^= r; r -= i; r &= U32_MASK; state[l] ^= r; state[i] = r; } } // MT19937 implementation template<typename UIntType, unsigned BitWidth> void MT19937<UIntType, BitWidth>::Init() throw() { // On exit we have _ptr == N. // Convert the seed into state SeedToState<UIntType, BitWidth>(_state, N); // Perform the MT-specific sanity check on the resulting state ensuring // that the significant 19937 bits are not all zero. _state[0] &= UPPER_MASK; // Mask out unused bits unsigned i = 0; while (i < N && _state[i] == 0) ++i; if (i >= N) _state[0] = result_type(1) << width - 1; // with prob 2^-19937 // This sets the low R bits of _state[0] consistent with the rest of the // state. Needed to handle SetCount(-N); Ran32(); immediately following // reseeding. This wasn't required in the original code because a // NextBatch was always done first. result_type q = _state[N - 1] ^ _state[M - 1], s = q >> width - 1; q = (q ^ (s ? MATRIX_A : result_type(0))) << 1 | s; _state[0] = _state[0] & UPPER_MASK | q & LOWER_MASK; _rounds = -1; _ptr = N; } template<typename UIntType, unsigned BitWidth> void MT19937<UIntType, BitWidth>::StepCount(long long n) throw() { // On exit we have 0 <= _ptr <= N. if (_ptr == UNINIT) Init(); const long long ncount = n + Count(); // new Count() long long nrounds = ncount / N; int nptr = static_cast<int>(ncount - nrounds * N); if (nptr <= 0) { // We pick _ptr = N or _ptr = 0 depending on which choice involves the // least work. We thus avoid doing one (potentially unneeded) called to // NextBatch/PreviousBatch. --nrounds; nptr += N; } if (nrounds > _rounds) NextBatch(nrounds - _rounds); else if (nrounds < _rounds) { if (nptr == N) { nptr = 0; ++nrounds; } PreviousBatch(_rounds - nrounds); } _ptr = nptr; } template<typename UIntType, unsigned BitWidth> RandomSeed::u32 MT19937<UIntType, BitWidth>::Check(u32 version) const throw(std::out_of_range) { if (version != VERSIONID && version != VERSIONID - 1) throw std::out_of_range("MT19937: Unknown version"); u32 check = version; CheckSum<u32, 32u>(_seed.size(), check); for (std::vector<seed_type>::const_iterator n = _seed.begin(); n != _seed.end(); ++n) { if (*n != SeedMask(*n)) throw std::out_of_range("Illegal seed value"); CheckSum<u32, 32u>(*n, check); } if (version == VERSIONID - 1 && _ptr == UNINIT) CheckSum<u32, 32u>(N + 1, check); else CheckSum<u32, 32u>(_ptr, check); if (_stride == 0 || _stride > UNINIT/2) throw std::out_of_range("MT19937: Invalid stride"); if (version != VERSIONID - 1) CheckSum<u32, 32u>(_stride, check); if (_ptr != UNINIT) { if (_ptr >= N + _stride) throw std::out_of_range("MT19937: Invalid pointer"); CheckSum<u64, 64u>(static_cast<u64>(_rounds), check); result_type x = 0; for (unsigned i = 0; i < N; ++i) { CheckSum<result_type, width>(_state[i], check); x |= _state[i]; } if (x == 0) throw std::out_of_range("MT19937: All-zero state"); // There are only width*(N-1) + 1 = 19937 independent bits of state. // Thus the low width-1 bits of _state[0] are derivable from the other // bits in _state. Verify that the redundant bits bits are consistent. result_type q = _state[N - 1] ^ _state[M - 1], s = q >> width - 1; q = (q ^ (s ? MATRIX_A : result_type(0))) << 1 | s; if ((q ^ _state[0]) & LOWER_MASK) throw std::out_of_range("MT19937: Invalid state"); } return check; } // Save and restore. template<typename UIntType, unsigned BitWidth> void MT19937<UIntType, BitWidth>::Save(std::ostream& os, bool bin) const throw(std::ios::failure) { u32 check = Check(VERSIONID); int c = 0; Write32<u32, 32u>(os, bin, c, VERSIONID); Write32<u32, 32u>(os, bin, c, _seed.size()); for (std::vector<seed_type>::const_iterator n = _seed.begin(); n != _seed.end(); ++n) Write32<u32, 32u>(os, bin, c, *n); Write32<u32, 32u>(os, bin, c, _ptr); Write32<u32, 32u>(os, bin, c, _stride); if (_ptr != UNINIT) { Write32<u64, 64u>(os, bin, c, static_cast<u64>(_rounds)); for (unsigned i = 0; i < N; ++i) Write32<result_type, width>(os, bin, c, _state[i]); } Write32<u32, 32u>(os, bin, c, check); } template<typename UIntType, unsigned BitWidth> MT19937<UIntType, BitWidth>::MT19937(std::istream& is, bool bin) throw(std::ios::failure, std::out_of_range, std::bad_alloc) { u32 version, t; Read32<u32, 32u>(is, bin, version); Read32<u32, 32u>(is, bin, t); _seed.resize(static_cast<size_t>(t)); for (std::vector<seed_type>::iterator n = _seed.begin(); n != _seed.end(); ++n) { Read32<u32, 32u>(is, bin, t); *n = static_cast<seed_type>(t); } Read32<u32, 32u>(is, bin, t); // Don't need to worry about sign extension because _ptr is unsigned. _ptr = static_cast<unsigned>(t); if (version == VERSIONID - 1) { if (_ptr == N + 1) _ptr = UNINIT; _stride = 1; } else { Read32<u32, 32u>(is, bin, t); _stride = static_cast<unsigned>(t); } if (_ptr != UNINIT) { u64 p; Read32<u64, 64u>(is, bin, p); _rounds = static_cast<long long>(p); // Sign extension in case long long is bigger than 64 bits. _rounds <<= 63 - std::numeric_limits<long long>::digits; _rounds >>= 63 - std::numeric_limits<long long>::digits; for (unsigned i = 0; i < N; ++i) Read32<result_type, width>(is, bin, _state[i]); } Read32<u32, 32u>(is, bin, t); if (t != Check(version)) throw std::out_of_range("MT19937: Checksum failure"); } // Code for NextBatch is from // http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/emt19937ar.html // and http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt64.html. Here // is the copyright notice. // A C-program for MT19937, with initialization improved 2002/1/26. // Coded by Takuji Nishimura and Makoto Matsumoto. // // Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura, // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. The names of its contributors may not be used to endorse or promote // products derived from this software without specific prior written // permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Any feedback is very welcome. // http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html // email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space) // Let y[i] = _state[i] & UPPER_MASK | _state[i + 1] & LOWER_MASK, then // _state[N] depends on y[0] and _state[M}. // // The "state" does NOT depends on the low bits of _state[0]. However, after // calls to Init(), NextBatch() and PreviousBatch(), _state[0] needs to // contain the right whole word result since it's used (after tempering) as // one of the outputs of Ran32(). // // In MT19937_STEP, input is I, J = I + 1, K = I + M; output is I = I + N // (mod N) template<typename UIntType, unsigned BitWidth> void MT19937<UIntType, BitWidth>::Next() throw() { // On exit we have 0 <= _ptr < N. if (_ptr == UNINIT) // Init() has not been called Init(); NextBatch(_ptr/N); _ptr %= N; } #define MT19937_STEP(I, J, K) _state[I] = _state[K] ^ \ (_state[J] & result_type(1) ? MATRIX_A : result_type(0)) ^ \ (_state[I] & UPPER_MASK | _state[J] & LOWER_MASK) >> 1 template<typename UIntType, unsigned BitWidth> void MT19937<UIntType, BitWidth>::NextBatch(unsigned long long count) throw() { _rounds += count; for (; count; --count) { // This ONLY uses high bit of _state[0] unsigned i = 0; for (; i < N - M; ++i) MT19937_STEP(i, i + 1, i + M ); for (; i < N - 1; ++i) MT19937_STEP(i, i + 1, i + M - N); MT19937_STEP(N - 1, 0, M - 1); // i = N - 1 } } #undef MT19937_STEP // This undoes MT19937_STEP. This piece of coding is from revrand() by // Katsumi Hagita. See // // http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/VERSIONS/FORTRAN/REVmt19937b.f // // The code is cleaned up a little from the Fortran version by getting rid of // the unnecessary masking by YMASK and by using simpler logic to restore the // correct value of _state[0]. // // y[0] depends on _state[N] and _state[M]. // // Here input is J = I + N - 1, K = I + M - 1, and p = y[I] (only the high // bits are used); output _state[I] and p = y[I - 1]. #define MT19937_REVSTEP(I, J, K) { \ result_type q = _state[J] ^ _state[K], s = q >> width - 1; \ q = (q ^ (s ? MATRIX_A : result_type(0))) << 1 | s; \ _state[I] = p & UPPER_MASK | q & LOWER_MASK; \ p = q; \ } template<typename UIntType, unsigned BitWidth> void MT19937<UIntType, BitWidth>::PreviousBatch(unsigned long long count) throw() { _rounds -= count; for (; count; --count) { // This ONLY uses high bit of _state[0] result_type p = _state[0]; // Fix low bits of _state[0] and compute y[-1] MT19937_REVSTEP(0, N - 1, M - 1); // i = N unsigned i = N - 1; for (; i > N - M; --i) MT19937_REVSTEP(i, i - 1, i + M - 1 - N); for (; i ; --i) MT19937_REVSTEP(i, i - 1, i + M - 1 ); MT19937_REVSTEP(0, N - 1, M - 1); // i = 0 } } #undef MT19937_REVSTEP // The two standard instantiations template class MT19937<RandomSeed::u32, 32u>; // MT19937_32 = mt19937ar template class MT19937<RandomSeed::u64, 64u>; // MT19937_64 = mt19937-64 // RandomCanonical instantiations. template<> MRandom32 MRandom32::Global(std::vector<unsigned long>(0)); template<> MRandom64 MRandom64::Global(std::vector<unsigned long>(0)); // SFMT19937 implementation template<typename UIntType, unsigned BitWidth> void SFMT19937<UIntType, BitWidth>::Init() throw() { // On exit we have _ptr == N. // Make sure everything packs together properly. #if HAVE_SSE2 STATIC_ASSERT(sizeof(_state.w) == sizeof(_state.v)); #endif // Convert the seed into state SeedToState<u32, 128u>(_state.u, N128 * 4); // Carry out the Period Certification for SFMT19937 u32 inner = _state.u[0] & PARITY0 ^ _state.u[1] & PARITY1 ^ _state.u[2] & PARITY2 ^ _state.u[3] & PARITY3; for (unsigned s = 16; s; s >>= 1) inner ^= inner >> s; STATIC_ASSERT(PARITY_LSB < 32 && PARITY0 & 1u << PARITY_LSB); // Now inner & 1 is the parity of the number of 1 bits in w_0 & p. if ((inner & 1u) == 0) // Change bit of w_0 corresponding to LSB of PARITY _state.u[PARITY_LSB >> 5] ^= 1u << (PARITY_LSB & 31u); // Make sure that writing _state.w[0] will overwrite at most _state.u[0] // and _state.u[1]. STATIC_ASSERT(BitWidth <= 32u || std::numeric_limits<u64>::digits <= 2 * std::numeric_limits<u32>::digits); if (BitWidth > 32u) // Pack into 64-bit words with LSB ordering. The loop needs to be in // this order in case u32 is a 64-bit quantity. for (unsigned j = 0; j < N; ++j) _state.w[j] = result_type(u64(_state.u[2*j]) | u64(_state.u[2*j+1]) << 32); _rounds = -1; _ptr = N; } template<typename UIntType, unsigned BitWidth> void SFMT19937<UIntType, BitWidth>::StepCount(long long n) throw() { // On exit we have 0 <= _ptr <= N. if (_ptr == UNINIT) Init(); const long long ncount = n + Count(); // new Count() long long nrounds = ncount / N; int nptr = static_cast<int>(ncount - nrounds * N); if (nptr <= 0) { // We pick _ptr = N or _ptr = 0 depending on which choice involves the // least work. We thus avoid doing one (potentially unneeded) called to // NextBatch/PreviousBatch. --nrounds; nptr += N; } if (nrounds > _rounds) NextBatch(nrounds - _rounds); else if (nrounds < _rounds) { if (nptr == N) { nptr = 0; ++nrounds; } PreviousBatch(_rounds - nrounds); } _ptr = nptr; } template<typename UIntType, unsigned BitWidth> RandomSeed::u32 SFMT19937<UIntType, BitWidth>::Check(u32 version) const throw(std::out_of_range) { if (version != VERSIONID) throw std::out_of_range("SFMT19937: Unknown version"); u32 check = version; CheckSum<u32, 32u>(_seed.size(), check); for (std::vector<seed_type>::const_iterator n = _seed.begin(); n != _seed.end(); ++n) { if (*n != SeedMask(*n)) throw std::out_of_range("Illegal seed value"); CheckSum<u32, 32u>(*n, check); } if (version == VERSIONID - 1 && _ptr == UNINIT) CheckSum<u32, 32u>(N + 1, check); else CheckSum<u32, 32u>(_ptr, check); if (_stride == 0 || _stride > UNINIT/2) throw std::out_of_range("SFMT19937: Invalid stride"); if (version != VERSIONID - 1) CheckSum<u32, 32u>(_stride, check); if (_ptr != UNINIT) { if (_ptr >= N + _stride) throw std::out_of_range("SFMT19937: Invalid pointer"); CheckSum<u64, 64u>(static_cast<u64>(_rounds), check); result_type x = 0; for (unsigned i = 0; i < N; ++i) { CheckSum<result_type, width>(_state.w[i], check); x |= _state.w[i]; } if (x == 0) throw std::out_of_range("SFMT19937: All-zero state"); } return check; } // Save and restore. template<typename UIntType, unsigned BitWidth> void SFMT19937<UIntType, BitWidth>::Save(std::ostream& os, bool bin) const throw(std::ios::failure) { u32 check = Check(VERSIONID); int c = 0; Write32<u32, 32u>(os, bin, c, VERSIONID); Write32<u32, 32u>(os, bin, c, _seed.size()); for (std::vector<seed_type>::const_iterator n = _seed.begin(); n != _seed.end(); ++n) Write32<u32, 32u>(os, bin, c, *n); Write32<u32, 32u>(os, bin, c, _ptr); Write32<u32, 32u>(os, bin, c, _stride); if (_ptr != UNINIT) { Write32<u64, 64u>(os, bin, c, static_cast<u64>(_rounds)); for (unsigned i = 0; i < N; ++i) Write32<result_type, width>(os, bin, c, _state.w[i]); } Write32<u32, 32u>(os, bin, c, check); } template<typename UIntType, unsigned BitWidth> SFMT19937<UIntType, BitWidth>::SFMT19937(std::istream& is, bool bin) throw(std::ios::failure, std::out_of_range, std::bad_alloc) { u32 version, t; Read32<u32, 32u>(is, bin, version); Read32<u32, 32u>(is, bin, t); _seed.resize(static_cast<size_t>(t)); for (std::vector<seed_type>::iterator n = _seed.begin(); n != _seed.end(); ++n) { Read32<u32, 32u>(is, bin, t); *n = static_cast<seed_type>(t); } Read32<u32, 32u>(is, bin, t); // Don't need to worry about sign extension because _ptr is unsigned. _ptr = static_cast<unsigned>(t); if (version == VERSIONID - 1) { if (_ptr == N + 1) _ptr = UNINIT; _stride = 1; } else { Read32<u32, 32u>(is, bin, t); _stride = static_cast<unsigned>(t); } if (_ptr != UNINIT) { u64 p; Read32<u64, 64u>(is, bin, p); _rounds = static_cast<long long>(p); // Sign extension in case long long is bigger than 64 bits. _rounds <<= 63 - std::numeric_limits<long long>::digits; _rounds >>= 63 - std::numeric_limits<long long>::digits; for (unsigned i = 0; i < N; ++i) Read32<result_type, width>(is, bin, _state.w[i]); } Read32<u32, 32u>(is, bin, t); if (t != Check(version)) throw std::out_of_range("SFMT19937: Checksum failure"); } // Algorithm for NextBatch is from Saito's Master's Thesis // http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/SFMT/M062821.pdf // // This implements // // w_{i+N} = w_i A xor w_M B xor w_{i+N-2} C xor w_{i+N-1} D // // where w_i is a 128-bit word and // // w A = (w << 8)_128 xor w // w B = (w >> 11)_32 & MSK // w C = (w >> 8)_128 // w D = (w << 18)_32 // // Here the _128 means shift is of whole 128-bit word. _32 means the shifts // are independently done on each 32-bit word. // // In SFMT19937_STEP32 and SFMT19937_STEP64 input is I, J = I + M and output // is I = I + N (mod N). On input, s and r give state for I + N - 2 and I + // N - 1; on output s and r give state for I + N - 1 and I + N. The // implementation of 128-bit operations is open-coded in a portable fashion // (with LSB ordering). // // N.B. Here N and M are the lags in units of BitWidth words and so are 4 // (for u32 implementation) or 2 (for u64 implementation) times bigger than // defined in Saito's thesis. template<typename UIntType, unsigned BitWidth> void SFMT19937<UIntType, BitWidth>::Next() throw() { // On exit we have 0 <= _ptr < N. if (_ptr == UNINIT) // Init() has not been called Init(); NextBatch(_ptr/N); _ptr %= N; } #if !HAVE_SSE2 // The standard portable implementation #define SFMT19937_STEP32(I, J) { \ result_type t = _state.w[I] ^ _state.w[I] << 8 ^ \ _state.w[J] >> 11 & MSK0 ^ \ (s0 >> 8 | s1 << 24) ^ r0 << 18; \ s0 = r0; r0 = t & RESULT_MASK; \ t = _state.w[I + 1] ^ \ (_state.w[I + 1] << 8 | _state.w[I] >> 24) ^ \ _state.w[J + 1] >> 11 & MSK1 ^ \ (s1 >> 8 | s2 << 24) ^ r1 << 18; \ s1 = r1; r1 = t & RESULT_MASK; \ t = _state.w[I + 2] ^ \ (_state.w[I + 2] << 8 | _state.w[I + 1] >> 24) ^ \ _state.w[J + 2] >> 11 & MSK2 ^ \ (s2 >> 8 | s3 << 24) ^ r2 << 18; \ s2 = r2; r2 = t & RESULT_MASK; \ t = _state.w[I + 3] ^ \ (_state.w[I + 3] << 8 | _state.w[I + 2] >> 24) ^ \ _state.w[J + 3] >> 11 & MSK3 ^ s3 >> 8 ^ r3 << 18; \ s3 = r3; r3 = t & RESULT_MASK; \ _state.w[I ] = r0; _state.w[I + 1] = r1; \ _state.w[I + 2] = r2; _state.w[I + 3] = r3; \ } template<> void SFMT19937<RandomSeed::u32, 32u>::NextBatch(unsigned long long count) throw() { _rounds += count; // x[i+N] = g(x[i], x[i+M], x[i+N-2], x[i,N-1]) for (; count; --count) { result_type s0 = _state.w[N - 8], s1 = _state.w[N - 7], s2 = _state.w[N - 6], s3 = _state.w[N - 5], r0 = _state.w[N - 4], r1 = _state.w[N - 3], r2 = _state.w[N - 2], r3 = _state.w[N - 1]; unsigned i = 0; for (; i + M < N; i += R) SFMT19937_STEP32(i, i + M ); for (; i < N ; i += R) SFMT19937_STEP32(i, i + M - N); } } #undef SFMT19937_STEP32 #define SFMT19937_STEP64(I, J) { \ result_type t = _state.w[I] ^ _state.w[I] << 8 ^ \ _state.w[J] >> 11 & LMSK0 ^ \ (s0 >> 8 | s1 << 56) ^ r0 << 18 & LMSK18; \ s0 = r0; r0 = t & RESULT_MASK; \ t = _state.w[I + 1] ^ \ (_state.w[I + 1] << 8 | _state.w[I] >> 56) ^ \ _state.w[J + 1] >> 11 & LMSK1 ^ \ s1 >> 8 ^ r1 << 18 & LMSK18; \ s1 = r1; r1 = t & RESULT_MASK; \ _state.w[I] = r0; _state.w[I + 1] = r1; \ } template<> void SFMT19937<RandomSeed::u64, 64u>::NextBatch(unsigned long long count) throw() { _rounds += count; // x[i+N] = g(x[i], x[i+M], x[i+N-2], x[i,N-1]) for (; count; --count) { result_type s0 = _state.w[N - 4], s1 = _state.w[N - 3], r0 = _state.w[N - 2], r1 = _state.w[N - 1]; unsigned i = 0; for (; i + M < N; i += R) SFMT19937_STEP64(i, i + M ); for (; i < N ; i += R) SFMT19937_STEP64(i, i + M - N); } } #undef SFMT19937_STEP64 // This undoes SFMT19937_STEP. Trivially, we have // // w_i A = w_{i+N} xor w_{i+M} B xor w_{i+N-2} C xor w_{i+N-1} D // // Given w_i A we can determine w_i from the observation that A^16 = // identity, thus // // w_i = (w_i A) A^15 // // Because x A^(2^n) = x << (8*2^n) xor x, the operation y = x A^15 can be // implemented as // // y' = (x << 64)_128 xor x = x A^8 // y'' = (y' << 32)_128 xor y' = y' A^4 = x A^12 // y''' = (y'' << 16)_128 xor y'' = y'' A^2 = x A^14 // y = (y''' << 8)_128 xor y''' = y''' A = x A^15 // // Here input is I = I + N, J = I + M, K = I + N - 2, L = I + N -1, and // output is I = I. // // This is about 15-35% times slower than SFMT19937_STEPNN, because (1) there // doesn't appear to be a straightforward way of saving intermediate results // across calls as with SFMT19937_STEPNN and (2) w A^15 is slower to compute // than w A. #define SFMT19937_REVSTEP32(I, J, K, L) { \ result_type \ t0 = (_state.w[I] ^ _state.w[J] >> 11 & MSK0 ^ \ (_state.w[K] >> 8 | _state.w[K + 1] << 24) ^ \ _state.w[L] << 18) & RESULT_MASK, \ t1 = (_state.w[I + 1] ^ \ _state.w[J + 1] >> 11 & MSK1 ^ \ (_state.w[K + 1] >> 8 | _state.w[K + 2] << 24) ^ \ _state.w[L + 1] << 18) & RESULT_MASK, \ t2 = (_state.w[I + 2] ^ \ _state.w[J + 2] >> 11 & MSK2 ^ \ (_state.w[K + 2] >> 8 | _state.w[K + 3] << 24) ^ \ _state.w[L + 2] << 18) & RESULT_MASK, \ t3 = (_state.w[I + 3] ^ \ _state.w[J + 3] >> 11 & MSK3 ^ \ _state.w[K + 3] >> 8 ^ \ _state.w[L + 3] << 18) & RESULT_MASK; \ t3 ^= t1; t2 ^= t0; t3 ^= t2; t2 ^= t1; t1 ^= t0; \ t3 ^= t2 >> 16 | t3 << 16 & RESULT_MASK; \ t2 ^= t1 >> 16 | t2 << 16 & RESULT_MASK; \ t1 ^= t0 >> 16 | t1 << 16 & RESULT_MASK; \ t0 ^= t0 << 16 & RESULT_MASK; \ _state.w[I ] = t0 ^ t0 << 8 & RESULT_MASK; \ _state.w[I + 1] = t1 ^ (t0 >> 24 | t1 << 8 & RESULT_MASK); \ _state.w[I + 2] = t2 ^ (t1 >> 24 | t2 << 8 & RESULT_MASK); \ _state.w[I + 3] = t3 ^ (t2 >> 24 | t3 << 8 & RESULT_MASK); \ } template<> void SFMT19937<RandomSeed::u32, 32u>::PreviousBatch(unsigned long long count) throw() { _rounds -= count; for (; count; --count) { unsigned i = N; for (; i + M > N;) { i -= R; SFMT19937_REVSTEP32(i, i + M - N, i - 2 * R, i - R); } for (; i > 2 * R;) { i -= R; SFMT19937_REVSTEP32(i, i + M , i - 2 * R, i - R); } SFMT19937_REVSTEP32(R, M + R, N - R, 0 ); // i = R SFMT19937_REVSTEP32(0, M , N - 2 * R, N - R); // i = 0 } } #undef SFMT19937_REVSTEP32 // In combining the left and right shifts to simulate a 128-bit shift we // usually use or. However we can equivalently use xor (e.g., t1 << 8 ^ t0 // >> 56 instead of t1 ^ t1 << 8 | t0 >> 56) and this speeds up the code if // used in some places. #define SFMT19937_REVSTEP64(I, J, K, L) { \ result_type \ t0 = _state.w[I] ^ _state.w[J] >> 11 & LMSK0 ^ \ (_state.w[K] >> 8 | _state.w[K + 1] << 56 & RESULT_MASK) \ ^ _state.w[L] << 18 & LMSK18, \ t1 = _state.w[I + 1] ^ _state.w[J + 1] >> 11 & LMSK1 ^ \ _state.w[K + 1] >> 8 ^ _state.w[L + 1] << 18 & LMSK18; \ t1 ^= t0; \ t1 ^= t0 >> 32 ^ t1 << 32 & RESULT_MASK; \ t0 ^= t0 << 32 & RESULT_MASK; \ t1 ^= t0 >> 48 ^ t1 << 16 & RESULT_MASK; \ t0 ^= t0 << 16 & RESULT_MASK; \ _state.w[I ] = t0 ^ t0 << 8 & RESULT_MASK; \ _state.w[I + 1] = t1 ^ t0 >> 56 ^ t1 << 8 & RESULT_MASK; \ } template<> void SFMT19937<RandomSeed::u64, 64u>::PreviousBatch(unsigned long long count) throw() { _rounds -= count; for (; count; --count) { unsigned i = N; for (; i + M > N;) { i -= R; SFMT19937_REVSTEP64(i, i + M - N, i - 2 * R, i - R); } for (; i > 2 * R;) { i -= R; SFMT19937_REVSTEP64(i, i + M , i - 2 * R, i - R); } SFMT19937_REVSTEP64(R, M + R, N - R, 0 ); // i = R SFMT19937_REVSTEP64(0, M , N - 2 * R, N - R); // i = 0 } } #undef SFMT19937_REVSTEP64 #else // The SSE2 implementation // This is adapted from SFMT-sse.c in the SFMT 1.2 distribution. // The order of instructions has been rearranged to increase the // speed slightly #define SFMT19937_STEP128(I, J) { \ __m128i x = _mm_load_si128(_state.v + I), \ y = _mm_srli_epi32(_state.v[J], 11), \ z = _mm_srli_si128(s, 1); \ s = _mm_slli_epi32(r, 18); \ z = _mm_xor_si128(z, x); \ x = _mm_slli_si128(x, 1); \ z = _mm_xor_si128(z, s); \ y = _mm_and_si128(y, m); \ z = _mm_xor_si128(z, x); \ s = r; \ r = _mm_xor_si128(z, y); \ _mm_store_si128(_state.v + I, r); \ } template<typename UIntType, unsigned BitWidth> void SFMT19937<UIntType, BitWidth>::NextBatch(unsigned long long count) throw() { _rounds += count; for (; count; --count) { const __m128i m = _mm_set_epi32(MSK3, MSK2, MSK1, MSK0); __m128i s = _mm_load_si128(_state.v + N128 - 2), r = _mm_load_si128(_state.v + N128 - 1); unsigned i = 0; for (; i + M128 < N128; ++i) SFMT19937_STEP128(i, i + M128 ); for (; i < N128 ; ++i) SFMT19937_STEP128(i, i + M128 - N128); } } #undef SFMT19937_STEP128 #define SFMT19937_REVSTEP128(I, J, K, L) { \ __m128i x = _mm_load_si128(_state.v + I), \ y = _mm_srli_epi32(_state.v[J], 11), \ z = _mm_slli_epi32(_state.v[L], 18); \ y = _mm_and_si128(y, m); \ x = _mm_xor_si128(x, _mm_srli_si128(_state.v[K], 1)); \ x = _mm_xor_si128(x, z); \ x = _mm_xor_si128(x, y); \ x = _mm_xor_si128(_mm_slli_si128(x, 8), x); \ x = _mm_xor_si128(_mm_slli_si128(x, 4), x); \ x = _mm_xor_si128(_mm_slli_si128(x, 2), x); \ x = _mm_xor_si128(_mm_slli_si128(x, 1), x); \ _mm_store_si128(_state.v + I, x); \ } template<typename UIntType, unsigned BitWidth> void SFMT19937<UIntType, BitWidth>::PreviousBatch(unsigned long long count) throw() { _rounds -= count; for (; count; --count) { const __m128i m = _mm_set_epi32(MSK3, MSK2, MSK1, MSK0); unsigned i = N128; for (; i + M128 > N128;) { --i; SFMT19937_REVSTEP128(i, i + M128 - N128, i - 2, i - 1); } for (; i > 2;) { --i; SFMT19937_REVSTEP128(i, i + M128, i - 2, i - 1); } SFMT19937_REVSTEP128(1, M128 + 1, N128 - 1, 0 ); // i = 1 SFMT19937_REVSTEP128(0, M128 , N128 - 2, N128 - 1); // i = 0 } } #undef SFMT19937_REVSTEP128 #endif // HAVE_SSE2 // The two standard instantiations template class SFMT19937<RandomSeed::u32, 32u>; template class SFMT19937<RandomSeed::u64, 64u>; // RandomCanonical instantiations. template<> SRandom32 SRandom32::Global(std::vector<unsigned long>(0)); template<> SRandom64 SRandom64::Global(std::vector<unsigned long>(0)); // Power2 implementation #if RANDOM_POWERTABLE // Powers of two. Just use floats here. As long as there's no overflow // or underflow these are exact. In particular they can be cast to // doubles or long doubles with no error. const float Power2::power2[maxpow - minpow + 1] = { #if RANDOM_LONGDOUBLEPREC > 64 // It would be nice to be able to use the C99 notation of 0x1.0p-120 // for 2^-120 here. 1/1329227995784915872903807060280344576.f, // 2^-120 1/664613997892457936451903530140172288.f, // 2^-119 1/332306998946228968225951765070086144.f, // 2^-118 1/166153499473114484112975882535043072.f, // 2^-117 1/83076749736557242056487941267521536.f, // 2^-116 1/41538374868278621028243970633760768.f, // 2^-115 1/20769187434139310514121985316880384.f, // 2^-114 1/10384593717069655257060992658440192.f, // 2^-113 1/5192296858534827628530496329220096.f, // 2^-112 1/2596148429267413814265248164610048.f, // 2^-111 1/1298074214633706907132624082305024.f, // 2^-110 1/649037107316853453566312041152512.f, // 2^-109 1/324518553658426726783156020576256.f, // 2^-108 1/162259276829213363391578010288128.f, // 2^-107 1/81129638414606681695789005144064.f, // 2^-106 1/40564819207303340847894502572032.f, // 2^-105 1/20282409603651670423947251286016.f, // 2^-104 1/10141204801825835211973625643008.f, // 2^-103 1/5070602400912917605986812821504.f, // 2^-102 1/2535301200456458802993406410752.f, // 2^-101 1/1267650600228229401496703205376.f, // 2^-100 1/633825300114114700748351602688.f, // 2^-99 1/316912650057057350374175801344.f, // 2^-98 1/158456325028528675187087900672.f, // 2^-97 1/79228162514264337593543950336.f, // 2^-96 1/39614081257132168796771975168.f, // 2^-95 1/19807040628566084398385987584.f, // 2^-94 1/9903520314283042199192993792.f, // 2^-93 1/4951760157141521099596496896.f, // 2^-92 1/2475880078570760549798248448.f, // 2^-91 1/1237940039285380274899124224.f, // 2^-90 1/618970019642690137449562112.f, // 2^-89 1/309485009821345068724781056.f, // 2^-88 1/154742504910672534362390528.f, // 2^-87 1/77371252455336267181195264.f, // 2^-86 1/38685626227668133590597632.f, // 2^-85 1/19342813113834066795298816.f, // 2^-84 1/9671406556917033397649408.f, // 2^-83 1/4835703278458516698824704.f, // 2^-82 1/2417851639229258349412352.f, // 2^-81 1/1208925819614629174706176.f, // 2^-80 1/604462909807314587353088.f, // 2^-79 1/302231454903657293676544.f, // 2^-78 1/151115727451828646838272.f, // 2^-77 1/75557863725914323419136.f, // 2^-76 1/37778931862957161709568.f, // 2^-75 1/18889465931478580854784.f, // 2^-74 1/9444732965739290427392.f, // 2^-73 1/4722366482869645213696.f, // 2^-72 1/2361183241434822606848.f, // 2^-71 1/1180591620717411303424.f, // 2^-70 1/590295810358705651712.f, // 2^-69 1/295147905179352825856.f, // 2^-68 1/147573952589676412928.f, // 2^-67 1/73786976294838206464.f, // 2^-66 1/36893488147419103232.f, // 2^-65 #endif 1/18446744073709551616.f, // 2^-64 1/9223372036854775808.f, // 2^-63 1/4611686018427387904.f, // 2^-62 1/2305843009213693952.f, // 2^-61 1/1152921504606846976.f, // 2^-60 1/576460752303423488.f, // 2^-59 1/288230376151711744.f, // 2^-58 1/144115188075855872.f, // 2^-57 1/72057594037927936.f, // 2^-56 1/36028797018963968.f, // 2^-55 1/18014398509481984.f, // 2^-54 1/9007199254740992.f, // 2^-53 1/4503599627370496.f, // 2^-52 1/2251799813685248.f, // 2^-51 1/1125899906842624.f, // 2^-50 1/562949953421312.f, // 2^-49 1/281474976710656.f, // 2^-48 1/140737488355328.f, // 2^-47 1/70368744177664.f, // 2^-46 1/35184372088832.f, // 2^-45 1/17592186044416.f, // 2^-44 1/8796093022208.f, // 2^-43 1/4398046511104.f, // 2^-42 1/2199023255552.f, // 2^-41 1/1099511627776.f, // 2^-40 1/549755813888.f, // 2^-39 1/274877906944.f, // 2^-38 1/137438953472.f, // 2^-37 1/68719476736.f, // 2^-36 1/34359738368.f, // 2^-35 1/17179869184.f, // 2^-34 1/8589934592.f, // 2^-33 1/4294967296.f, // 2^-32 1/2147483648.f, // 2^-31 1/1073741824.f, // 2^-30 1/536870912.f, // 2^-29 1/268435456.f, // 2^-28 1/134217728.f, // 2^-27 1/67108864.f, // 2^-26 1/33554432.f, // 2^-25 1/16777216.f, // 2^-24 1/8388608.f, // 2^-23 1/4194304.f, // 2^-22 1/2097152.f, // 2^-21 1/1048576.f, // 2^-20 1/524288.f, // 2^-19 1/262144.f, // 2^-18 1/131072.f, // 2^-17 1/65536.f, // 2^-16 1/32768.f, // 2^-15 1/16384.f, // 2^-14 1/8192.f, // 2^-13 1/4096.f, // 2^-12 1/2048.f, // 2^-11 1/1024.f, // 2^-10 1/512.f, // 2^-9 1/256.f, // 2^-8 1/128.f, // 2^-7 1/64.f, // 2^-6 1/32.f, // 2^-5 1/16.f, // 2^-4 1/8.f, // 2^-3 1/4.f, // 2^-2 1/2.f, // 2^-1 1.f, // 2^0 2.f, // 2^1 4.f, // 2^2 8.f, // 2^3 16.f, // 2^4 32.f, // 2^5 64.f, // 2^6 128.f, // 2^7 256.f, // 2^8 512.f, // 2^9 1024.f, // 2^10 2048.f, // 2^11 4096.f, // 2^12 8192.f, // 2^13 16384.f, // 2^14 32768.f, // 2^15 65536.f, // 2^16 131072.f, // 2^17 262144.f, // 2^18 524288.f, // 2^19 1048576.f, // 2^20 2097152.f, // 2^21 4194304.f, // 2^22 8388608.f, // 2^23 16777216.f, // 2^24 33554432.f, // 2^25 67108864.f, // 2^26 134217728.f, // 2^27 268435456.f, // 2^28 536870912.f, // 2^29 1073741824.f, // 2^30 2147483648.f, // 2^31 4294967296.f, // 2^32 8589934592.f, // 2^33 17179869184.f, // 2^34 34359738368.f, // 2^35 68719476736.f, // 2^36 137438953472.f, // 2^37 274877906944.f, // 2^38 549755813888.f, // 2^39 1099511627776.f, // 2^40 2199023255552.f, // 2^41 4398046511104.f, // 2^42 8796093022208.f, // 2^43 17592186044416.f, // 2^44 35184372088832.f, // 2^45 70368744177664.f, // 2^46 140737488355328.f, // 2^47 281474976710656.f, // 2^48 562949953421312.f, // 2^49 1125899906842624.f, // 2^50 2251799813685248.f, // 2^51 4503599627370496.f, // 2^52 9007199254740992.f, // 2^53 18014398509481984.f, // 2^54 36028797018963968.f, // 2^55 72057594037927936.f, // 2^56 144115188075855872.f, // 2^57 288230376151711744.f, // 2^58 576460752303423488.f, // 2^59 1152921504606846976.f, // 2^60 2305843009213693952.f, // 2^61 4611686018427387904.f, // 2^62 9223372036854775808.f, // 2^63 18446744073709551616.f, // 2^64 }; #endif } // namespace RandomLib
35.759108
83
0.583936
[ "vector", "transform" ]
7754824784bf436a38fdb7a1f209a473ae371ee2
1,179
hpp
C++
graphs/lowest_common_ancestor.hpp
takata-daiki/algorithms
299f7379a2acf8a3e14bc3e3de6509e821eec115
[ "MIT" ]
null
null
null
graphs/lowest_common_ancestor.hpp
takata-daiki/algorithms
299f7379a2acf8a3e14bc3e3de6509e821eec115
[ "MIT" ]
null
null
null
graphs/lowest_common_ancestor.hpp
takata-daiki/algorithms
299f7379a2acf8a3e14bc3e3de6509e821eec115
[ "MIT" ]
1
2019-12-11T06:45:30.000Z
2019-12-11T06:45:30.000Z
#pragma once #include <bits/stdc++.h> #include "../data_structures/segment_tree.hpp" #include "../monoids/min_index.hpp" using namespace std; struct LowestCommonAncestor { using P = pair<int, int>; int n; vector<int> idx; vector<P> euler_tour; vector<vector<int>> g; SegmentTree<min_index_monoid<int>> seg; LowestCommonAncestor(int _n) : n(_n), idx(_n), g(_n) {} void add_edge(int s, int t) { g[s].push_back(t); g[t].push_back(s); } void build(int r) { dfs(r, -1, 0); seg = SegmentTree<min_index_monoid<int>>(begin(euler_tour), end(euler_tour)); } void dfs(int u, int par, int dep) { idx[u] = euler_tour.size(); euler_tour.push_back({dep, u}); for (auto&& v : g[u]) { if (v == par) continue; dfs(v, u, dep + 1); euler_tour.push_back({dep, u}); } } int query(int u, int v) { assert(0 <= u && u < n); assert(0 <= v && v < n); int i = idx[u]; int j = idx[v]; if (i > j) swap(i, j); return seg.query(i, j + 1).second; } };
26.795455
67
0.504665
[ "vector" ]
7759bae19cc24deb3dbff62f1d930282e9e60117
1,947
cpp
C++
Maple/textclass.cpp
mld2443/DX12-Samples
28fcd7ce82b659c2a2ab3a5eb3967606f6ce30b8
[ "MIT" ]
null
null
null
Maple/textclass.cpp
mld2443/DX12-Samples
28fcd7ce82b659c2a2ab3a5eb3967606f6ce30b8
[ "MIT" ]
null
null
null
Maple/textclass.cpp
mld2443/DX12-Samples
28fcd7ce82b659c2a2ab3a5eb3967606f6ce30b8
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// // Filename: textclass.cpp //////////////////////////////////////////////////////////////////////////////// #include "textclass.h" TextClass::TextClass() { m_brush = nullptr; m_format = nullptr; } TextClass::TextClass(const TextClass&) { } TextClass::~TextClass() { } bool TextClass::Initialize(IDWriteFactory* dwriteFactory, ID2D1DeviceContext* deviceContext, float fontSize, WCHAR* fontName) { HRESULT result; // Initialize drawing window. SetDrawWindow(0, 0, 100, 100); // Initialize empty text string SetTextString(L""); // Create our solid white brush. result = deviceContext->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &m_brush); if (FAILED(result)) { return false; } // Create our text format with specified parameters. result = dwriteFactory->CreateTextFormat(fontName, nullptr, DWRITE_FONT_WEIGHT_LIGHT, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL, fontSize, L"en-US", &m_format); if (FAILED(result)) { return false; } return true; } void TextClass::Shutdown() { // Release the format object. if (m_format) { m_format->Release(); m_format = nullptr; } // Release the brush object. if (m_brush) { m_brush->Release(); m_brush = nullptr; } return; } bool TextClass::Render(ID2D1DeviceContext* deviceContext) { HRESULT result; deviceContext->BeginDraw(); deviceContext->DrawTextW(m_string.c_str(), (UINT32)m_string.size(), m_format, m_drawWindow, m_brush); result = deviceContext->EndDraw(); if (FAILED(result)) { return false; } return true; } void TextClass::SetDrawWindow(float xLeft, float yTop, float xRight, float yBottom) { m_drawWindow = D2D1::RectF(xLeft, yTop, xRight, yBottom); } void TextClass::SetBrushColor(D2D1::ColorF& color) { m_brush->SetColor(color); } void TextClass::SetTextString(const std::wstring& text) { m_string = text; }
17.230088
102
0.658449
[ "render", "object", "solid" ]
775c37b5dcba859fa141b95073f50d88e9ab9869
1,997
cpp
C++
C++/count-fertile-pyramids-in-a-land.cpp
Priyansh2/LeetCode-Solutions
d613da1881ec2416ccbe15f20b8000e36ddf1291
[ "MIT" ]
3,269
2018-10-12T01:29:40.000Z
2022-03-31T17:58:41.000Z
C++/count-fertile-pyramids-in-a-land.cpp
Priyansh2/LeetCode-Solutions
d613da1881ec2416ccbe15f20b8000e36ddf1291
[ "MIT" ]
53
2018-12-16T22:54:20.000Z
2022-02-25T08:31:20.000Z
C++/count-fertile-pyramids-in-a-land.cpp
Priyansh2/LeetCode-Solutions
d613da1881ec2416ccbe15f20b8000e36ddf1291
[ "MIT" ]
1,236
2018-10-12T02:51:40.000Z
2022-03-30T13:30:37.000Z
// Time: O(m * n) // Space: O(n) class Solution { public: int countPyramids(vector<vector<int>>& grid) { return count(grid, false) + count(grid, true); } private: int count(const vector<vector<int>>& grid, int reverse) { auto get_grid = [&grid, &reverse](int i, int j) { return reverse ? grid[size(grid) - 1 - i][j] : grid[i][j]; }; int result = 0; vector<int> dp(size(grid[0])); for (int i = 1; i < size(grid); ++i) { vector<int> new_dp(size(grid[0])); for (int j = 1; j + 1 < size(grid[0]); ++j) { if (get_grid(i, j) == get_grid(i - 1, j - 1) && get_grid(i - 1, j - 1) == get_grid(i - 1, j) && get_grid(i - 1, j) == get_grid(i - 1, j + 1) && get_grid(i - 1, j + 1) == 1) { new_dp[j] = min(dp[j - 1], dp[j + 1]) + 1; } } dp = move(new_dp); result += accumulate(cbegin(dp), cend(dp), 0); } return result; } }; // Time: O(m * n) // Space: O(m * n) class Solution2 { public: int countPyramids(vector<vector<int>>& grid) { return count(grid) + count(vector<vector<int>>(rbegin(grid), rend(grid))); } private: int count(const vector<vector<int>>& grid) { int result = 0; vector<vector<int>> dp(size(grid), vector<int>(size(grid[0]))); for (int i = 1; i < size(grid); ++i) { for (int j = 1; j + 1 < size(grid[0]); ++j) { if (grid[i][j] == grid[i - 1][j - 1] && grid[i - 1][j - 1] == grid[i - 1][j] && grid[i - 1][j] == grid[i - 1][j + 1] && grid[i - 1][j + 1] == 1) { dp[i][j] = min({dp[i - 1][j - 1], dp[i - 1][j], dp[i - 1][j + 1]}) + 1; } } result += accumulate(cbegin(dp[i]), cend(dp[i]), 0); } return result; } };
32.737705
91
0.421632
[ "vector" ]
776121cbb6b916c64bc539068a8fef3dc48d8c12
584
hpp
C++
include/scene/Transformations.hpp
j0ntan/RayTracerChallenge
91e201b2d7f90032580101a1ccf18eb2d6e5b522
[ "Unlicense" ]
null
null
null
include/scene/Transformations.hpp
j0ntan/RayTracerChallenge
91e201b2d7f90032580101a1ccf18eb2d6e5b522
[ "Unlicense" ]
null
null
null
include/scene/Transformations.hpp
j0ntan/RayTracerChallenge
91e201b2d7f90032580101a1ccf18eb2d6e5b522
[ "Unlicense" ]
null
null
null
#ifndef TRANSFORMATIONS_HPP #define TRANSFORMATIONS_HPP #include <cmath> #include <math/Matrix.hpp> #include <math/Point.hpp> #include <math/Vector.hpp> #include <scene/Ray.hpp> const double PI = std::acos(-1); Matrix<4> translate(double x, double y, double z); Matrix<4> scale(double x, double y, double z); Matrix<4> rotate_x(double theta); Matrix<4> rotate_y(double theta); Matrix<4> rotate_z(double theta); Matrix<4> shear(double x_y, double x_z, double y_x, double y_z, double z_x, double z_y); Ray transform(const Ray &ray, const Matrix<4> &m); #endif
20.857143
75
0.710616
[ "vector", "transform" ]
7766d021da7c2f1a2223c895dc430a4fb03971aa
10,391
cpp
C++
eval.cpp
OllieBerzs/oca
cd845af687943b3a2181195dbddadb3f3a1de5cf
[ "MIT" ]
null
null
null
eval.cpp
OllieBerzs/oca
cd845af687943b3a2181195dbddadb3f3a1de5cf
[ "MIT" ]
null
null
null
eval.cpp
OllieBerzs/oca
cd845af687943b3a2181195dbddadb3f3a1de5cf
[ "MIT" ]
null
null
null
/* ollieberzs 2018 ** eval.cpp ** evaluate AST to value */ #include <iostream> #include "eval.hpp" #include "parse.hpp" #include "value.hpp" #include "oca.hpp" #include "error.hpp" OCA_BEGIN Evaluator::Evaluator(State* state) : state(state), current(nullptr) {} ValuePtr Evaluator::eval(ExprPtr expr, Scope& scope) { if (expr == nullptr) return Nil::in(&scope); else if (expr->type == Expression::SET) return set(expr, scope); else if (expr->type == Expression::CALL) return call(expr, scope); else if (expr->type == Expression::IF) return cond(expr, scope); else if (expr->type == Expression::ACCESS) return access(expr, scope); else if (expr->type == Expression::OPER) return oper(expr, scope); else if (expr->type == Expression::FILE) return file(expr, scope); else return value(expr, scope); } // ---------------------------- ValuePtr Evaluator::set(ExprPtr expr, Scope& scope) { auto tracker = current; current = expr; bool pub = expr->val == "pub"; bool any = expr->left == nullptr; std::vector<ExprPtr> lefts; if (!any) { ExprPtr it = expr->left; while (it->type == Expression::CALLS) { lefts.push_back(it->left); it = it->right; } lefts.push_back(it); } ValuePtr rightVal = eval(expr->right, scope); if (any) { scope.add(rightVal->scope); } else { uint counter = ARRAY_BEGIN_INDEX; for (auto& leftExpr : lefts) { std::string name = leftExpr->val; ValuePtr leftVal = Nil::in(&scope); if (leftExpr->type == Expression::ACCESS) { leftVal = eval(leftExpr, scope); if (leftVal->isNil()) throw Error(NEW_TABLE_KEY); name = leftVal->scope.parent->get(leftVal); } if (lefts.size() == 1) leftVal->scope.parent->set(name, rightVal, pub); else { ValuePtr rightValPart = rightVal->scope.get(std::to_string(counter), false); ++counter; if (rightValPart->isNil()) throw Error(CANNOT_SPLIT); leftVal->scope.parent->set(name, rightValPart, pub); } } } current = tracker; return rightVal; } ValuePtr Evaluator::call(ExprPtr expr, Scope& scope) { auto tracker = current; current = expr; ValuePtr val = state->global.get(expr->val, true); Scope* searchScope = &scope; while (val->isNil()) { val = searchScope->get(expr->val, true); if (!searchScope->parent && val->isNil()) throw Error(UNDEFINED); searchScope = searchScope->parent; } ValuePtr arg = eval(expr->right, scope); ValuePtr block = eval(expr->left, scope); Value& vref = *val; ValuePtr result = val; if (TYPE_EQ(vref, Func)) result = static_cast<Func&>(vref)(Table::from(scope), arg, block); if (TYPE_EQ(vref, Block)) result = static_cast<Block&>(vref)(Table::from(scope), arg, block); current = tracker; return result; } ValuePtr Evaluator::oper(ExprPtr expr, Scope& scope) { auto tracker = current; current = expr; std::map<std::string, std::string> operFuncs = { {"+", "__add"}, {"-", "__sub"}, {"*", "__mul"}, {"/", "__div"}, {"%", "__mod"}, {"^", "__pow"}, {"==", "__eq"}, {"!=", "__neq"}, {">", "__gr"}, {"<", "__ls"}, {">=", "__geq"}, {"<=", "__leq"}, {"..", "__ran"}, {"and", "__and"}, {"or", "__or"}, {"xor", "__xor"}, {"lsh", "__lsh"}, {"rsh", "__rsh"}}; ValuePtr left = eval(expr->left, scope); ValuePtr right = eval(expr->right, scope); ValuePtr func = left->scope.get(operFuncs[expr->val], false); if (func->isNil()) throw Error(UNDEFINED_OPERATOR); Value& funcref = *func; ValuePtr result = func; if (TYPE_EQ(funcref, Func)) result = static_cast<Func&>(funcref)(left, right, Nil::in(&scope)); if (TYPE_EQ(funcref, Block)) result = static_cast<Block&>(funcref)(left, right, Nil::in(&scope)); current = tracker; return result; } ValuePtr Evaluator::cond(ExprPtr expr, Scope& scope) { auto tracker = current; current = expr; ValuePtr conditional = eval(expr->left, scope); Value& cref = *conditional; if (!(TYPE_EQ(cref, Bool))) throw Error(IF_BOOL); bool trueness = static_cast<Bool&>(cref).val; current = tracker; ValuePtr branch = Nil::in(&scope); if (trueness) branch = eval(expr->right->left, scope); else if (expr->right->right) branch = eval(expr->right->right, scope); if (branch->isNil()) return branch; auto temp = Scope(&scope); ValuePtr result = Nil::in(&temp); ExprPtr it = static_cast<Block&>(*branch).val; while (it && it->left) { if (it->left->type == Expression::RETURN) { returning = true; result = eval(it->left->right, temp); break; } if (it->left->type == Expression::BREAK) break; result = eval(it->left, temp); it = it->right; } return result; } ValuePtr Evaluator::access(ExprPtr expr, Scope& scope) { auto tracker = current; current = expr->right; ValuePtr left = eval(expr->left, scope); bool super = expr->left->val == "super"; ValuePtr right = left->scope.get(expr->right->val, super); if (right->isNil()) throw Error(UNDEFINED_IN_TABLE); ValuePtr arg = eval(expr->right->right, scope); ValuePtr block = eval(expr->right->left, scope); Value& val = *right; ValuePtr result = right; if (TYPE_EQ(val, Func)) result = static_cast<Func&>(val)(left, arg, block); if (TYPE_EQ(val, Block)) result = static_cast<Block&>(val)(left, arg, block); current = tracker; return result; } ValuePtr Evaluator::file(ExprPtr expr, Scope& scope) { auto oldPath = state->eh.path; auto oldSource = state->eh.source; auto oldTokens = state->eh.tokens; auto oldScope = state->scope; std::string folder = ""; if (state->eh.path) { uint slash = state->eh.path->find_last_of("/"); folder = state->eh.path->substr(0, slash + 1); } state->scope = Scope(nullptr); state->runFile(folder + expr->val + ".oca"); auto val = Table::from(state->scope); state->eh.path = oldPath; state->eh.source = oldSource; state->eh.tokens = oldTokens; state->scope = oldScope; return val; } ValuePtr Evaluator::value(ExprPtr expr, Scope& scope) { auto tracker = current; current = expr; ValuePtr result = Nil::in(&scope); if (expr->type == Expression::TABL) { if (expr->right == nullptr && expr->val == "") return eval(expr->left, scope); result = std::make_shared<Table>(&scope); uint counter = ARRAY_BEGIN_INDEX; while (expr && expr->left) { std::string nam = ""; bool pub = (expr->val.find("pub ") != std::string::npos); bool any = (expr->val.find("*") != std::string::npos); if (!any) { if (expr->val == "") { pub = true; nam = std::to_string(counter); ++counter; ++static_cast<Table&>(*result).count; } if (pub && expr->val != "") nam = expr->val.substr(4); if (nam == "") nam = expr->val; ++static_cast<Table&>(*result).size; result->scope.set(nam, eval(expr->left, scope), pub); } else { result->scope.add(eval(expr->left, scope)->scope); } expr = expr->right; } } else if (expr->type == Expression::EMPTY_TABL) { result = std::make_shared<Table>(&scope); } else if ( expr->type == Expression::BLOCK || expr->type == Expression::MAIN || expr->type == Expression::ELSE) { result = std::make_shared<Block>(expr, &scope, this); } else if (expr->type == Expression::STR) { result = std::make_shared<String>(expr->val, &scope); } else if (expr->type == Expression::FSTR) { result = fstring(expr, scope); } else if (expr->type == Expression::INT) { result = std::make_shared<Integer>(std::stoll(expr->val), &scope); } else if (expr->type == Expression::REAL) { result = std::make_shared<Real>(std::stod(expr->val), &scope); } else if (expr->type == Expression::BOOL) { result = std::make_shared<Bool>(expr->val == "true", &scope); } current = tracker; return result; } ValuePtr Evaluator::fstring(ExprPtr expr, Scope& scope) { std::string string = expr->val; std::string formatted = ""; bool escape = false; bool inner = false; std::string innerStr = ""; for (char c : string) { if (escape) { switch (c) { case 'a': formatted += '\a'; break; case 'b': formatted += '\b'; break; case 'f': formatted += '\f'; break; case 'n': formatted += '\n'; break; case 'r': formatted += '\r'; break; case 't': formatted += '\t'; break; case 'v': formatted += '\v'; break; case '{': formatted += '{'; break; case '\\': formatted += '\\'; break; } escape = false; } else if (inner) { if (c == '}') { auto oldSource = state->eh.source; auto oldTokens = state->eh.tokens; auto oldScope = state->scope; state->scope = scope; formatted += state->runString(innerStr)->tos(); state->eh.source = oldSource; state->eh.tokens = oldTokens; state->scope = oldScope; inner = false; innerStr = ""; } else innerStr += c; } else { switch (c) { case '\\': escape = true; break; case '{': inner = true; break; default: formatted += c; break; } } } return std::make_shared<String>(formatted, &scope); } OCA_END
31.487879
94
0.531903
[ "vector" ]
776ce68319176a02f4b96ec2f5e120b62cbc02d2
11,541
cpp
C++
c2_store/src/mfx_c2_store.cpp
zhangyichix/MediaSDK_C2
c4bf4b51a91d4781b986226778c5d38be4b37d64
[ "MIT" ]
6
2020-09-22T01:36:58.000Z
2022-03-15T05:33:36.000Z
c2_store/src/mfx_c2_store.cpp
zhangyichix/MediaSDK_C2
c4bf4b51a91d4781b986226778c5d38be4b37d64
[ "MIT" ]
26
2021-11-01T07:01:04.000Z
2022-03-11T03:02:47.000Z
c2_store/src/mfx_c2_store.cpp
zhangyichix/MediaSDK_C2
c4bf4b51a91d4781b986226778c5d38be4b37d64
[ "MIT" ]
6
2020-06-12T21:49:48.000Z
2022-01-17T09:32:18.000Z
// Copyright (c) 2017-2021 Intel Corporation // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #include "mfx_c2_store.h" #include "mfx_defs.h" #include "mfx_c2_defs.h" #include "mfx_debug.h" #include "mfx_c2_debug.h" #include "mfx_c2_component.h" #include <cutils/properties.h> #include <dlfcn.h> #include <fstream> static const std::string FIELD_SEP = " : "; using namespace android; #undef MFX_DEBUG_MODULE_NAME #define MFX_DEBUG_MODULE_NAME "MfxC2ComponentStore" MfxC2ComponentStore* MfxC2ComponentStore::Create(c2_status_t* status) { MFX_DEBUG_TRACE_FUNC; MfxC2ComponentStore* store = new (std::nothrow)MfxC2ComponentStore(); if (store != nullptr) { c2_status_t read_xml_cfg_res = store->readXmlConfigFile(); c2_status_t read_cfg_res = store->readConfigFile(); if (read_cfg_res != C2_OK || read_xml_cfg_res != C2_OK) { *status = (read_cfg_res != C2_OK) ? read_cfg_res : read_xml_cfg_res; delete store; store = nullptr; } } else { *status = C2_NO_MEMORY; } MFX_DEBUG_TRACE__android_c2_status_t(*status); MFX_DEBUG_TRACE_P(store); return store; } C2String MfxC2ComponentStore::getName() const { MFX_DEBUG_TRACE_FUNC; return MFX_C2_COMPONENT_STORE_NAME; } c2_status_t MfxC2ComponentStore::createComponent(C2String name, std::shared_ptr<C2Component>* const component) { MFX_DEBUG_TRACE_FUNC; c2_status_t result = C2_OK; char szVendorIntelVideoCodec[PROPERTY_VALUE_MAX] = {'\0'}; if(property_get("vendor.intel.video.codec", szVendorIntelVideoCodec, NULL) > 0 ) { if (strncmp(szVendorIntelVideoCodec, "software", PROPERTY_VALUE_MAX) == 0 ) { ALOGI("Property vendor.intel.video.codec is %s in auto_hal.in and will not load hardware codec plugin", szVendorIntelVideoCodec); return C2_NOT_FOUND; } } if(component != nullptr) { auto it = m_componentsRegistry_.find(name); if(it != m_componentsRegistry_.end()) { auto dso_deleter = [] (void* handle) { dlclose(handle); }; std::unique_ptr<void, decltype(dso_deleter)> dso(loadModule(it->second.dso_name_), dso_deleter); if(dso != nullptr) { CreateMfxC2ComponentFunc* create_func = reinterpret_cast<CreateMfxC2ComponentFunc*>(dlsym(dso.get(), CREATE_MFX_C2_COMPONENT_FUNC_NAME)); if(create_func != nullptr) { std::shared_ptr<MfxC2ParamReflector> reflector; { std::lock_guard<std::mutex> lock(m_reflectorMutex); reflector = m_reflector; // safe copy } MfxC2Component* mfx_component = (*create_func)(name.c_str(), it->second.config_, std::move(reflector), &result); if(result == C2_OK) { void* dso_handle = dso.release(); // release handle to be captured into lambda deleter auto component_deleter = [dso_handle] (MfxC2Component* p) { delete p; dlclose(dso_handle); }; *component = std::shared_ptr<MfxC2Component>(mfx_component, component_deleter); } } else { MFX_LOG_ERROR("Module %s is invalid", it->second.dso_name_.c_str()); result = C2_NOT_FOUND; } } else { MFX_LOG_ERROR("Cannot load module %s", it->second.dso_name_.c_str()); result = C2_NOT_FOUND; } } else { MFX_LOG_ERROR("Cannot find component %s", name.c_str()); result = C2_NOT_FOUND; } } else { MFX_LOG_ERROR("output component ptr is null"); result = C2_BAD_VALUE; } MFX_DEBUG_TRACE__android_c2_status_t(result); return result; } c2_status_t MfxC2ComponentStore::createInterface(C2String name, std::shared_ptr<C2ComponentInterface>* const interface) { MFX_DEBUG_TRACE_FUNC; std::shared_ptr<C2Component> component; c2_status_t result = createComponent(name, &component); if(result == C2_OK) { *interface = component->intf(); } return result; } std::vector<std::shared_ptr<const C2Component::Traits>> MfxC2ComponentStore::listComponents() { MFX_DEBUG_TRACE_FUNC; std::vector<std::shared_ptr<const C2Component::Traits>> result; try { for(const auto& it_pair : m_componentsRegistry_ ) { std::unique_ptr<C2Component::Traits> traits = std::make_unique<C2Component::Traits>(); traits->name = it_pair.first; traits->domain = DOMAIN_VIDEO; traits->kind = it_pair.second.kind_; traits->mediaType = it_pair.second.media_type_; MFX_DEBUG_TRACE_S(traits->name.c_str()); MFX_DEBUG_TRACE_S(traits->mediaType.c_str()); result.push_back(std::move(traits)); } } catch(std::exception& e) { MFX_DEBUG_TRACE_MSG("Exception caught"); MFX_DEBUG_TRACE_S(e.what()); } return result; } c2_status_t MfxC2ComponentStore::copyBuffer(std::shared_ptr<C2GraphicBuffer> src, std::shared_ptr<C2GraphicBuffer> dst) { MFX_DEBUG_TRACE_FUNC; MFX_DEBUG_TRACE_MSG("Unimplemented method is called"); (void)src; (void)dst; return C2_OMITTED; } c2_status_t MfxC2ComponentStore::query_sm( const std::vector<C2Param*> &stackParams, const std::vector<C2Param::Index> &heapParamIndices, std::vector<std::unique_ptr<C2Param>>*const heapParams) const { MFX_DEBUG_TRACE_FUNC; MFX_DEBUG_TRACE_MSG("Unimplemented method is called"); (void)stackParams; (void)heapParamIndices; (void)heapParams; return C2_OMITTED; } c2_status_t MfxC2ComponentStore::config_sm( const std::vector<C2Param*> &params, std::vector<std::unique_ptr<C2SettingResult>>*const failures) { MFX_DEBUG_TRACE_FUNC; MFX_DEBUG_TRACE_MSG("Unimplemented method is called"); (void)params; (void)failures; return C2_OMITTED; } std::shared_ptr<C2ParamReflector> MfxC2ComponentStore::getParamReflector() const { MFX_DEBUG_TRACE_FUNC; std::shared_ptr<MfxC2ParamReflector> reflector; { std::lock_guard<std::mutex> lock(m_reflectorMutex); reflector = m_reflector; // safe copy } return reflector; } c2_status_t MfxC2ComponentStore::querySupportedParams_nb( std::vector<std::shared_ptr<C2ParamDescriptor>> * const params) const { MFX_DEBUG_TRACE_FUNC; MFX_DEBUG_TRACE_MSG("Unimplemented method is called"); (void)params; return C2_OMITTED; } c2_status_t MfxC2ComponentStore::querySupportedValues_sm( std::vector<C2FieldSupportedValuesQuery> &fields) const { MFX_DEBUG_TRACE_FUNC; MFX_DEBUG_TRACE_MSG("Unimplemented method is called"); (void)fields; return C2_OMITTED; } /* Searches in the given line field which is separated from other lines by * FILED_SEP characters, Returns std::string which includes the field and * its size. */ static void MfxC2GetField(const std::string &line, std::string *str, size_t *str_pos) { MFX_DEBUG_TRACE_FUNC; if (str == nullptr || str_pos == nullptr) return; *str = ""; if (line.empty() || *str_pos == std::string::npos) return; MFX_DEBUG_TRACE_S(line.c_str()); size_t pos = line.find_first_of(FIELD_SEP, *str_pos); size_t copy_size = (pos != std::string::npos) ? pos - *str_pos : line.size() - *str_pos; *str = line.substr(*str_pos, copy_size); *str_pos = (pos != std::string::npos) ? pos + FIELD_SEP.size() : std::string::npos; MFX_DEBUG_TRACE_I32(copy_size); MFX_DEBUG_TRACE_I32(*str_pos); } c2_status_t MfxC2ComponentStore::readConfigFile() { MFX_DEBUG_TRACE_FUNC; c2_status_t c2_res = C2_OK; std::string config_filename; config_filename.append(MFX_C2_CONFIG_FILE_PATH); config_filename.append("/"); config_filename.append(MFX_C2_CONFIG_FILE_NAME); std::ifstream config_file(config_filename.c_str(), std::ifstream::in); if (config_file) { MFX_DEBUG_TRACE_S(config_filename.c_str()); std::string line, str, name, module; while (std::getline(config_file, line)) { MFX_DEBUG_TRACE_S(line.c_str()); size_t pos = 0; // getting name MfxC2GetField(line, &str, &pos); if (str.empty()) continue; // line is empty or field is the last one name = str; MFX_DEBUG_TRACE_S(name.c_str()); // getting module MfxC2GetField(line, &str, &pos); if (str.empty()) continue; module = str; MFX_DEBUG_TRACE_S(module.c_str()); // getting optional flags MfxC2GetField(line, &str, &pos); int flags = 0; if (!str.empty()) { MFX_DEBUG_TRACE_S(str.c_str()); flags = strtol(str.c_str(), NULL, 16); } C2String media_type = m_xmlParser.getMediaType(name.c_str()); MFX_DEBUG_TRACE_S(media_type.c_str()); C2Component::kind_t kind = m_xmlParser.getKind(name.c_str()); MfxC2Component::CreateConfig config; config.flags = flags; config.dump_output = m_xmlParser.dumpOutputEnabled(name.c_str()); m_componentsRegistry_.emplace(name, ComponentDesc(module.c_str(), media_type.c_str(), kind, config)); } config_file.close(); } MFX_DEBUG_TRACE_I32(m_componentsRegistry_.size()); MFX_DEBUG_TRACE__android_c2_status_t(c2_res); return c2_res; } c2_status_t MfxC2ComponentStore::readXmlConfigFile() { MFX_DEBUG_TRACE_FUNC; c2_status_t c2_res = C2_OK; std::string config_filename = MFX_C2_CONFIG_XML_FILE_PATH; config_filename.append("/"); config_filename.append(MFX_C2_CONFIG_XML_FILE_NAME); c2_res = m_xmlParser.parseConfig(config_filename.c_str()); MFX_DEBUG_TRACE__android_c2_status_t(c2_res); return c2_res; } void* MfxC2ComponentStore::loadModule(const std::string& name) { MFX_DEBUG_TRACE_FUNC; MFX_DEBUG_TRACE_S(name.c_str()); void* result = nullptr; dlerror(); result = dlopen(name.c_str(), RTLD_NOW); if(result == nullptr) { MFX_LOG_ERROR("Module %s load is failed: %s", name.c_str(), dlerror()); } MFX_DEBUG_TRACE_P(result); return result; }
32.327731
141
0.657135
[ "vector" ]
777183f7a2fe9430aab5209c28390550d1b17412
1,977
cpp
C++
sources/hash_search.cpp
nikitaboal/lab-06-multithreads
ca68141648131bdd3064861f761813b8c0d65897
[ "MIT" ]
null
null
null
sources/hash_search.cpp
nikitaboal/lab-06-multithreads
ca68141648131bdd3064861f761813b8c0d65897
[ "MIT" ]
null
null
null
sources/hash_search.cpp
nikitaboal/lab-06-multithreads
ca68141648131bdd3064861f761813b8c0d65897
[ "MIT" ]
null
null
null
// Copyright 2021 Your Name <your_email> #include <hash_search.hpp> std::vector<hash_item> HashSearch::hash_list; bool HashSearch::flag; void HashSearch::hash_counting() { unsigned int temp = abs(static_cast<int>(std::clock())); int hash_source = rand_r(&temp); std::string hash = picosha2::hash256_hex_string(std::to_string(hash_source)); auto start = std::chrono::high_resolution_clock::now(); while (flag) { if (hash.substr(60) == "0000") { auto end = std::chrono::high_resolution_clock::now(); auto time = std::chrono::duration_cast<std::chrono::milliseconds>(end - start); BOOST_LOG_TRIVIAL(info) << "Search Time: " << time.count() << ", Hash: " << hash << ", Data: " << std::hex << hash_source; hash_item item{hash, hash_source, time.count()}; hash_list.push_back(item); } temp = abs(static_cast<int>(std::clock())); hash_source = rand_r(&temp); hash = picosha2::hash256_hex_string(std::to_string(hash_source)); } } void HashSearch::json_filling() { nlohmann::json j; std::stringstream stream; std::ofstream o("../log.json"); for (unsigned int i = 0; i < hash_list.size(); i++) { stream << std::hex << hash_list[i].hash_source; j = nlohmann::json{ {"DATA", stream.str()}, {"HASH", hash_list[i].hash_string}, {"SEARCH TIME", std::to_string(hash_list[i].search_time)}}; o << j << std::endl; stream.str(""); } } void HashSearch::start_hash_search(std::string threadsNum) { size_t num = std::stoi(threadsNum); if ((num > std::thread::hardware_concurrency()) || (num == 0)) num = std::thread::hardware_concurrency(); for (size_t i = 0; i < num; i++) { std::thread thread(hash_counting); thread.join(); } } void HashSearch::interrupt_handler(int interrupt) { json_filling(); std::cout << interrupt << std::endl; flag = false; } auto example() -> void { throw std::runtime_error("not implemented"); }
30.415385
79
0.632777
[ "vector" ]
77718552f13848fc7e8207f7ca1a89a0539d5b92
2,074
cpp
C++
union-find.cpp
Surya-06/My-Solutions
58f7c7f1a0a3a28f25eff22d03a09cb2fbcf7806
[ "MIT" ]
null
null
null
union-find.cpp
Surya-06/My-Solutions
58f7c7f1a0a3a28f25eff22d03a09cb2fbcf7806
[ "MIT" ]
null
null
null
union-find.cpp
Surya-06/My-Solutions
58f7c7f1a0a3a28f25eff22d03a09cb2fbcf7806
[ "MIT" ]
null
null
null
#include <algorithm> #include <iostream> #include <vector> using namespace std; typedef long long int llint; llint **dis_set; llint find(llint ed) { if (dis_set[ed][1] == -1) return dis_set[ed][0]; else return find(dis_set[ed][1]); } void uni(llint node, llint parent) { llint np = find(node); llint pp = find(parent); dis_set[np][1] = pp; return; } llint find_min_edge(llint **edg, llint ne) { llint min = -1, minind = -1; for (llint i = 0; i < ne; i++) { if (edg[i][2] != -1) { if ((min != -1 and edg[i][2] < min) or min == -1) { min = edg[i][2]; minind = i; } } } return minind; } llint use_edges(llint **edg, llint ne) { llint sum = 0; for (llint i = 0; i < ne; i++) { llint index = find_min_edge(edg, ne); if (index == -1) return sum; if (find(edg[index][0]) == find(edg[index][1])) { edg[index][2] = -1; } else { // // cout<<"the edge between "<<edg[index][0]<<" and "<<edg[index][1]<<" // is included"<<endl; // // cout<<"values are "<<find(edg[index][0])<<" and // "<<find(edg[index][1])<<endl; uni(edg[index][0], edg[index][1]); sum += edg[index][2]; edg[index][2] = -1; } } return sum; } int main() { llint num; // // cout<<"enter the number of nodes"<<endl; cin >> num; dis_set = new llint *[num]; for (llint i = 0; i < num; i++) { dis_set[i] = new llint[2]; dis_set[i][0] = i; dis_set[i][1] = -1; } llint ne; // // cout<<"enter the number of edges"<<endl; cin >> ne; llint **edg = new llint *[ne]; // // cout<<"enter the values of the edges"<<endl; for (llint i = 0; i < ne; i++) { llint a, b, c; cin >> a >> b >> c; edg[i] = new llint[3]; edg[i][0] = a - 1; edg[i][1] = b - 1; edg[i][2] = c; } // // cout<<"starting the search for the minimum spanning tree"<<endl; cout << use_edges(edg, ne) << endl; // // cout<<"program terminated"<<endl; return 0; }
24.116279
80
0.496143
[ "vector" ]
a57f97f15a5f5dc965990a1d3942eab378ea8f33
4,127
cpp
C++
src/QoreZSock.cpp
qorelanguage/module-zmq
134aa7388f8bb07eb4195f727f71ee6ec9c13d78
[ "MIT" ]
null
null
null
src/QoreZSock.cpp
qorelanguage/module-zmq
134aa7388f8bb07eb4195f727f71ee6ec9c13d78
[ "MIT" ]
1
2017-12-19T06:27:16.000Z
2017-12-19T06:27:16.000Z
src/QoreZSock.cpp
qorelanguage/module-zmq
134aa7388f8bb07eb4195f727f71ee6ec9c13d78
[ "MIT" ]
null
null
null
/* -*- mode: c++; indent-tabs-mode: nil -*- */ /** @file QoreZSock.cpp defines the QoreZSock C++ class */ /* Qore Programming Language Copyright (C) 2017 - 2018 Qore Technologies, s.r.o. 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 St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "zmq-module.h" #include "QC_ZSocket.h" #include <regex> #include <string> #include <vector> #include <stdlib.h> #include <strings.h> #include <ctype.h> #include <string.h> static std::regex url_port_regex("^tcp://.*:(\\d+|\\*)$", std::regex_constants::ECMAScript | std::regex_constants::icase | std::regex_constants::optimize); int QoreZSock::poll(short events, int timeout_ms, const char* meth, ExceptionSink *xsink) { zmq_pollitem_t p = { sock, 0, events, 0 }; int rc; while (true) { rc = zmq_poll(&p, 1, timeout_ms); if (rc == -1 && errno == EINTR) continue; break; } if (rc > 0) return 0; if (!rc) xsink->raiseException("ZSOCKET-TIMEOUT", "timeout waiting %d ms in %s() for data%s on the socket", timeout_ms, meth, events & ZMQ_POLLOUT ? " to be sent" : ""); else zmq_error(xsink, "ZSOCKET-TIMEOUT", "error in zmq_poll() in %s()", meth); return -1; } // like czmq's zsock_attach() int QoreZSock::attach(ExceptionSink *xsink, const char* endpoints, bool do_bind) { assert(endpoints); // get a vector of all endpoints with regex_token_iterator std::regex re(","); // passing -1 as the submatch index parameter performs splitting std::cregex_token_iterator first{endpoints, endpoints + strlen(endpoints), re, -1}, last; std::vector<std::string> vec = {first, last}; // iterate all endpoints for (auto& str : vec) { if (str[0] == '@') { if (bind(xsink, &str.c_str()[1]) == -1) return -1; } else if (str[0] == '>') { if (connect(xsink, &str.c_str()[1])) return -1; } else if (do_bind) { if (bind(xsink, str.c_str()) == -1) return -1; } else if (connect(xsink, str.c_str())) return -1; } return 0; } int QoreZSock::bind(ExceptionSink *xsink, const char* endpoint, const char* err) { std::cmatch match; if (regex_search(endpoint, match, url_port_regex)) { assert(match.ready()); assert(match.size() == 2); if (!zmq_bind(sock, endpoint)) { // get port specification std::string str = match[1]; int port = atoi(str.c_str()); if (!port) { // get actual port bound char le[1024]; size_t size = sizeof(le); if (!getSocketOption(ZMQ_LAST_ENDPOINT, &le, &size)) { const char* p = strrchr(le, ':'); if (p) port = atoi(p + 1); } } return port; } } else if (!zmq_bind(sock, endpoint)) { // NOTE: zmq_bind() is not affected by EINTR return 0; } zmq_error(xsink, err, "failed to bind to \"%s\"", endpoint); return -1; } int QoreZSock::connect(ExceptionSink *xsink, const char* endpoint, const char* err) { // NOTE: zmq_connect() is not affected by EINTR int rc = zmq_connect(sock, endpoint); if (rc) zmq_error(xsink, err, "failed to connect to \"%s\"", endpoint); return rc; }
33.282258
168
0.587352
[ "vector" ]