Vector getPosition() const { return F->output(); }
Filter::Filter( Filter &filter ) : Mlt::Service( filter ), instance( filter.get_filter( ) ) { inc_ref( ); }
int CmdDuplicate::execute (std::string&) { int rc = 0; int count = 0; // Apply filter. Filter filter; std::vector <Task> filtered; filter.subset (filtered); if (filtered.size () == 0) { context.footnote (STRING_FEEDBACK_NO_TASKS_SP); return 1; } // Accumulated project change notifications. std::map <std::string, std::string> projectChanges; for (auto& task : filtered) { // Duplicate the specified task. Task dup (task); dup.id = 0; // Reset, and TDB2::add will set. dup.set ("uuid", uuid ()); // Needs a new UUID. dup.remove ("start"); // Does not inherit start date. dup.remove ("end"); // Does not inherit end date. dup.remove ("entry"); // Does not inherit entry date. // When duplicating a child task, downgrade it to a plain task. if (dup.has ("parent")) { dup.remove ("parent"); dup.remove ("recur"); dup.remove ("until"); dup.remove ("imask"); std::cout << format (STRING_CMD_DUPLICATE_NON_REC, task.id) << "\n"; } // When duplicating a parent task, create a new parent task. else if (dup.getStatus () == Task::recurring) { dup.remove ("mask"); std::cout << format (STRING_CMD_DUPLICATE_REC, task.id) << "\n"; } dup.setStatus (Task::pending); // Does not inherit status. // Must occur after Task::recurring check. dup.modify (Task::modAnnotate); if (permission (format (STRING_CMD_DUPLICATE_CONFIRM, task.id, task.get ("description")), filtered.size ())) { context.tdb2.add (dup); ++count; feedback_affected (STRING_CMD_DUPLICATE_TASK, task); if (context.verbose ("new-id")) std::cout << format (STRING_CMD_ADD_FEEDBACK, dup.id) + "\n"; else if (context.verbose ("new-uuid")) std::cout << format (STRING_CMD_ADD_FEEDBACK, dup.get ("uuid")) + "\n"; if (context.verbose ("project")) projectChanges[task.get ("project")] = onProjectChange (task); } else { std::cout << STRING_CMD_DUPLICATE_NO << "\n"; rc = 1; if (_permission_quit) break; } } // Now list the project changes. for (auto& change : projectChanges) if (change.first != "") context.footnote (change.second); feedback_affected (count == 1 ? STRING_CMD_DUPLICATE_1 : STRING_CMD_DUPLICATE_N, count); return rc; }
// Increase minimal distance between vertices void MoleculeLayoutGraph::_refineCoordinates (const BiconnectedDecomposer &bc_decomposer, const ObjArray<MoleculeLayoutGraph> &bc_components, const Array<int> &bc_tree) { RefinementState beg_state(*this); RefinementState best_state(*this); RefinementState new_state(*this); QS_DEF(Array<int>, branch); int v1, v2; int v1c, v2c; int i, j, n; v1c = v1 = vertexBegin(); v2c = v2 = vertexNext(v1); // Calculate initial energy beg_state.copyFromGraph(); beg_state.calcEnergy(); beg_state.calcDistance(v1, v2); best_state.copy(beg_state); new_state.copy(beg_state); // Look through all vertex pairs which are closer than 0.6 bool improved = true; QS_DEF(RedBlackSet<int>, edges); QS_DEF(Array<int>, components1); QS_DEF(Array<int>, components2); EnumContext context; context.edges = &edges; context.graph = this; context.maxIterationNumber = max_iterations; int max_improvements = max_iterations * max_iterations; int n_improvements = 0; while (improved) { if (max_improvements > 0 && n_improvements > max_improvements) break; n_improvements++; improved = false; edges.clear(); int n_edges = 0; int n_enumerations = 0; bool to_break = false; for (v1 = vertexBegin(); v1 < vertexEnd() && !to_break; v1 = vertexNext(v1)) for (v2 = vertexNext(v1); v2 < vertexEnd(); v2 = vertexNext(v2)) { new_state.calcDistance(v1, v2); if (new_state.dist > 0.36f) continue; // Check if they are from the same component bool next_pair = false; bc_decomposer.getVertexComponents(v1, components1); bc_decomposer.getVertexComponents(v2, components2); for (i = 0; i < components1.size() && !next_pair; i++) for (j = 0; j < components2.size(); j++) { int comp1 = components1[i]; int comp2 = components2[j]; if (comp1 == comp2 && !bc_components[comp1].isSingleEdge() && !bc_components[comp2].isSingleEdge()) { next_pair = true; break; } } if (next_pair) continue; // check iterations limit if (max_iterations > 0 && n_enumerations > max_iterations) { to_break = true; break; } n_enumerations++; // Find acyclic edges on the all paths between v1 and v2 PathEnumerator path_enum(*this, v1, v2); path_enum.cb_check_edge = _edge_check; path_enum.cb_handle_path = _path_handle; path_enum.context = &context; context.iterationNumber = 0; try { path_enum.process(); } catch (Error) { // iterations limit reached } if (edges.size() == n_edges) continue; n_edges = edges.size(); if (beg_state.dist - 0.00001 > new_state.dist) { beg_state.dist = new_state.dist; v1c = v1; v2c = v2; } } if (edges.size() == 0) { //beg_state.applyToGraph(); break; } // Flipping // Look through found edges for (i = edges.begin(); i < edges.end(); i = edges.next(i)) { if (max_improvements > 0 && n_improvements > max_improvements) break; n_improvements++; // Try to flip branch const Edge &edge = getEdge(edges.key(i)); if (_molecule != 0 && _molecule->cis_trans.getParity(_molecule_edge_mapping[_layout_edges[edges.key(i)].ext_idx]) != 0) continue; if (getVertex(edge.beg).degree() == 1 || getVertex(edge.end).degree() == 1) continue; Filter filter; _makeBranches(branch, edges.key(i), filter); new_state.flipBranch(filter, beg_state, edge.beg, edge.end); new_state.calcEnergy(); if (new_state.energy < best_state.energy - 0.00001) { improved = true; best_state.copy(new_state); } } if (improved) { beg_state.copy(best_state); continue; } // Rotations // Look through found edges for (i = edges.begin(); i < edges.end(); i = edges.next(i)) { if (max_improvements > 0 && n_improvements > max_improvements) break; n_improvements += 3; // Try to rotate one branch by 10 degrees in both directions around both vertices const Edge &edge = getEdge(edges.key(i)); if (_molecule != 0 && _molecule->cis_trans.getParity(_molecule_edge_mapping[_layout_edges[edges.key(i)].ext_idx]) != 0) continue; Filter filter; _makeBranches(branch, edges.key(i), filter); bool around_beg = _allowRotateAroundVertex(edge.beg); bool around_end = _allowRotateAroundVertex(edge.end); if (around_beg) { new_state.rotateBranch(filter, beg_state, edge.beg, 10); new_state.calcDistance(v1c, v2c); new_state.calcEnergy(); if (new_state.dist > beg_state.dist && new_state.energy < best_state.energy - 0.00001) { improved = true; best_state.copy(new_state); } new_state.rotateBranch(filter, beg_state, edge.beg, -10); new_state.calcDistance(v1c, v2c); new_state.calcEnergy(); if (new_state.dist > beg_state.dist && new_state.energy < best_state.energy - 0.00001) { improved = true; best_state.copy(new_state); } } if (around_end) { new_state.rotateBranch(filter, beg_state, edge.end, 10); new_state.calcDistance(v1c, v2c); new_state.calcEnergy(); if (new_state.dist > beg_state.dist && new_state.energy < best_state.energy - 0.00001) { improved = true; best_state.copy(new_state); } new_state.rotateBranch(filter, beg_state, edge.end, -10); new_state.calcDistance(v1c, v2c); new_state.calcEnergy(); if (new_state.dist > beg_state.dist && new_state.energy < best_state.energy - 0.00001) { improved = true; best_state.copy(new_state); } } // Stretching // Try to stretch each edge with 1.6 ratio if ((n = filter.count(*this)) != 1 && n != vertexCount() - 1) { new_state.stretchBranch(filter, beg_state, edge.beg, edge.end, 6); new_state.calcDistance(v1c, v2c); new_state.calcEnergy(); if (new_state.dist > beg_state.dist && new_state.energy + 20 < beg_state.energy && new_state.energy < best_state.energy - 0.00001) { improved = true; best_state.copy(new_state); } } } if (improved) beg_state.copy(best_state); } if (_n_fixed == 0) { int center = -1; long max_code = 0; for (i = vertexBegin(); i < vertexEnd(); i = vertexNext(i)) if (getLayoutVertex(i).morgan_code > max_code) { center = i; max_code = getLayoutVertex(i).morgan_code; } beg_state.calcHeight(); for (float angle = -90.f; angle < 90.f + EPSILON; angle += 30.f) { new_state.rotateLayout(beg_state, center, angle); new_state.calcHeight(); if (new_state.height < beg_state.height - EPSILON) beg_state.copy(new_state); } } beg_state.applyToGraph(); _excludeDandlingIntersections(); }
void _validate(bool) { filter.initialize(); copy_info(); }
void ParameterizedFilter::RoughMakeProjections(int to_dim, bool update_reduced) { MEASURE_FET("ParameterizedFilter::RoughMakeProjections(...)"); int total_excluded = 0; vector<int> dims_reduced = rough_mind->GetReducedDimensions(); vector<int>::const_iterator dim1; for(dim1 = dims_reduced.begin(); dim1 != dims_reduced.end(); ++dim1) { if(*dim1 == to_dim) continue; // find all descriptors which may potentially influence other dimensions vector<Descriptor> local_desc; for(uint i = 0; i < descriptors.Size(); i++) { if(descriptors[i].done || descriptors[i].IsDelayed()) continue; if(descriptors[i].IsOuter()) return; // do not make any projections in case of outer joins present if(!descriptors[i].attr.vc || descriptors[i].attr.vc->GetDim() == -1 || !descriptors[i].val1.vc || descriptors[i].val1.vc->GetDim() == -1) continue; //only SingleColumns processed here DimensionVector dims(mind->NoDimensions()); descriptors[i].DimensionUsed(dims); if(descriptors[i].attr.vc && dims[*dim1] && dims[to_dim] && dims.NoDimsUsed() == 2) local_desc.push_back(descriptors[i]); } // make projection to another dimension for(int i = 0; i < local_desc.size(); i++) { // find the other dimension Descriptor& ld = local_desc[i]; DimensionVector dims(mind->NoDimensions()); ld.DimensionUsed(dims); PackOrderer po; VirtualColumn* matched_vc; MIDummyIterator local_mit(mind); if(*dim1 == ld.attr.vc->GetDim()) { po.Init(ld.attr.vc, PackOrderer::RangeSimilarity, rough_mind->GetRSValueTable(ld.attr.vc->GetDim())); matched_vc = ld.val1.vc; } else { po.Init(ld.val1.vc, PackOrderer::RangeSimilarity, rough_mind->GetRSValueTable(ld.val1.vc->GetDim())); matched_vc = ld.attr.vc; } // for each dim2 pack, check whether it may be joined with anything nonempty on dim1 for(int p2 = 0; p2 < rough_mind->NoPacks(to_dim); p2++) { if(rough_mind->GetPackStatus(to_dim, p2) != RS_NONE) { bool pack_possible = false; local_mit.SetPack(to_dim, p2); // if(po.IsValid()) po.RewindToMatch(matched_vc, local_mit); // else // po.RewindToCurrent(); while(po.IsValid()) { // for(int p1 = 0; p1 < rmind.NoPacks(dim1); p1++) // if(rmind.GetPackStatus(dim1, p1) != RS_NONE) { if(rough_mind->GetPackStatus(*dim1, po.Current()) != RS_NONE) { local_mit.SetPack(*dim1, po.Current()); // set a dummy position, just for transferring pack number if(ld.attr.vc->RoughCheck(local_mit, ld) != RS_NONE) { pack_possible = true; break; } } ++po; } if(!pack_possible) { rough_mind->SetPackStatus(to_dim, p2, RS_NONE); total_excluded++; } } } } if(update_reduced) rough_mind->UpdateReducedDimension(*dim1); local_desc.clear(); } if(total_excluded > 0) { rccontrol.lock(mind->m_conn->GetThreadID()) << "Packrows excluded by rough multidimensional projections: " << total_excluded << unlock; rough_mind->UpdateLocalRoughFilters(to_dim); for(dim1 = dims_reduced.begin(); dim1 != dims_reduced.end(); ++dim1) { Filter *f = mind->GetUpdatableFilter(*dim1); if(f) { for(int b = 0; b < rough_mind->NoPacks(*dim1); b++) { if(rough_mind->GetPackStatus(*dim1, b) == RS_NONE) f->ResetBlock(b); } } } mind->UpdateNoTuples(); } }
void FilterList::convert(const std::vector<std::string> & ruleList, const std::set<std::string> & disabled_list, std::vector<RegExpFilter *> & regexpList, std::vector<ElemHideSelector *> & elemHideFilter) { static const char * ELEMHIDE_PATTERN = "^([^\\/\\*\\|\\@\"]*?)#(?:([\\w\\-]+|\\*)((?:\\([\\w\\-]+(?:[$^*]?=[^\\(\\)\"]*)?\\))*)|#([^{}]+))$"; static const char * REGEXPR_PATTERN = "^\\/(.*)\\/$"; static const char * OPTIONS_PATTERN = "\\$(~?[\\w\\-]+(?:=[^,\\s]+)?(?:,~?[\\w\\-]+(?:=[^,\\s]+)?)*)$"; for ( auto iter = ruleList.begin(); iter != ruleList.end(); iter++ ) { std::string rule( * iter ); if ( disabled_list.find(rule) != disabled_list.end() ) { // 被禁用的规则,不做任何处理 continue; } auto pos = knownFilters.find(rule); if ( pos != knownFilters.end() ) { Filter * p = pos->second; if ( p ) { RegExpFilter * regexpFilter = dynamic_cast<RegExpFilter *>(p); if ( regexpFilter ) { regexpList.push_back(regexpFilter); // 加引用计数, 以免被释放 regexpFilter->AddRef(); } else { ElemHideSelector * selector = dynamic_cast<ElemHideSelector *>(p); if ( selector ) { elemHideFilter.push_back(selector); // 加引用计数, 以免被释放 selector->AddRef(); } else { // 不应该走到这里, 但是如果真到这里了, 把 p 从 map 里面去掉 knownFilters.erase(pos); p->Release(); } } continue; } } // 元素隐藏规则 std::string results[4]; if ( regexpr_match(ELEMHIDE_PATTERN, rule.c_str(), FALSE, results, 4) ) { const std::string & domain = results[0]; const std::string & tagName = results[1]; const std::string & attrRules = results[2]; const std::string & selector = results[3]; if ( ElemHideSelector * filter = ElemHideSelector::fromText(domain, tagName, attrRules, selector) ) { elemHideFilter.push_back(filter); knownFilters[rule] = filter; } } else { std::string re_rule(rule); // 访问过滤规则 std::string options_str; if ( regexpr_match(OPTIONS_PATTERN, re_rule.c_str(), FALSE, &options_str, 1) ) { // 把参数部分去掉 regexpr_replace(OPTIONS_PATTERN, re_rule.c_str(), "", re_rule); } if ( regexpr_match(REGEXPR_PATTERN, re_rule.c_str(), FALSE, results, 1) ) { re_rule = results[0]; } else { // 将 adblockplus 规则转换成正则表达式规则 regexpr_replace("\\*+", re_rule.c_str(), "*", re_rule, TRUE); regexpr_replace("\\^\\|$", re_rule.c_str(), "^", re_rule, FALSE); regexpr_replace("(\\W)", re_rule.c_str(), "\r\\1", re_rule, TRUE); string_replace(re_rule, "\r", "\\"); regexpr_replace("\\\\\\*", re_rule.c_str(), ".*", re_rule, TRUE); regexpr_replace("\\\\\\^", re_rule.c_str(), "(?:[^\rw\r-.%\ru0080-\ruFFFF]|$)", re_rule, TRUE); regexpr_replace("^\\\\\\|\\\\\\|", re_rule.c_str(), "^[\rw\r-]+:\r/+(?!\r/)(?:[^\r/]+\r.)?", re_rule, FALSE); string_replace(re_rule, "\r", "\\"); regexpr_replace("^\\\\\\|", re_rule.c_str(), "^", re_rule, FALSE); regexpr_replace("\\\\\\|$", re_rule.c_str(), "$", re_rule, FALSE); regexpr_replace("^(\\.\\*)", re_rule.c_str(), "", re_rule, FALSE); regexpr_replace("(\\.\\*)$", re_rule.c_str(), "", re_rule, FALSE); } if ( RegExpFilter * filter = RegExpFilter::fromText(re_rule, options_str) ) { regexpList.push_back(filter); knownFilters[rule] = filter; } } } }
int main (int argc, char** argv) { // Initialize ROS ros::init (argc, argv, "objectMaster"); ros::NodeHandle n; ros::Rate waiting_rate(30); //strat a traver and wait for its ready cloudTraver ct(n); while(!ct.isReady()) { ros::spinOnce(); waiting_rate.sleep(); } cvNamedWindow("CurrentImage",CV_WINDOW_AUTOSIZE); cv::Mat image; pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloudP; Mat src, dst, color_dst; std::string objectNameTemp="TEMP"; int count=0; while(ros::ok()) { while(!ct.isReady()) { ros::spinOnce(); } image=ct.getImage(); cloudP=ct.getCloud(); if(cloudP->empty()) { std::cout<<"No pointCloud passed into this process, f**k you no points you play MAOXIAN!"<<std::endl; continue; } pcl::PointCloud<PointType>::Ptr cloud_RGBA(new pcl::PointCloud<PointType>); *cloud_RGBA=*cloudP; Filter filter; cloud_RGBA=filter.PassThrough(cloud_RGBA); cloud_RGBA=filter.DeSamping(cloud_RGBA); cloud_RGBA=filter.RemovePlane(cloud_RGBA); if(cloud_RGBA->empty()) { std::cout<<"No pointCloud left after the samping"<<std::endl; continue; } std::vector<pcl::PointIndices> cluster_indices; filter.ExtractionObject(cloud_RGBA,cluster_indices); if(cluster_indices.size()!=0) { std::cout<<cluster_indices.size()<<"clusters extraced"<<std::endl; pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud_f (new pcl::PointCloud<pcl::PointXYZRGBA>); pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud_filtered (new pcl::PointCloud<pcl::PointXYZRGBA>); pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud = cloud_RGBA; //voxelgrid并不是产生球面空洞的原因 pcl::VoxelGrid<pcl::PointXYZRGBA> vg; vg.setInputCloud (cloud); vg.setLeafSize (0.01f, 0.01f, 0.01f); vg.filter (*cloud_filtered); //Create the segmentation object for the planar model and set all the parameters pcl::SACSegmentation<pcl::PointXYZRGBA> seg; pcl::PointIndices::Ptr inliers (new pcl::PointIndices); pcl::ModelCoefficients::Ptr coefficients (new pcl::ModelCoefficients); pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud_plane (new pcl::PointCloud<pcl::PointXYZRGBA> ()); pcl::PCDWriter writer; seg.setOptimizeCoefficients (true); seg.setModelType (pcl::SACMODEL_PLANE); seg.setMethodType (pcl::SAC_RANSAC); seg.setMaxIterations (100); seg.setDistanceThreshold (0.02); //......... int i=0, nr_points = (int) cloud_filtered->points.size (); while (cloud_filtered->points.size () > 0.3 * nr_points) { // Segment the largest planar component from the remaining cloud seg.setInputCloud (cloud_filtered); seg.segment (*inliers, *coefficients); if (inliers->indices.size () == 0) { std::cout << "Could not estimate a planar model for the given dataset." << std::endl; break; } // Extract the planar inliers from the input cloud pcl::ExtractIndices<pcl::PointXYZRGBA> extract; extract.setInputCloud (cloud_filtered); extract.setIndices (inliers); extract.setNegative (false); // Get the points associated with the planar surface extract.filter (*cloud_plane); //std::cout << "PointCloud representing the planar component: " << cloud_plane->points.size () << " data points." << std::endl; // Remove the planar inliers, extract the rest extract.setNegative (true); extract.filter (*cloud_f); *cloud_filtered = *cloud_f; } //cloud filter ! pcl::search::KdTree<pcl::PointXYZRGBA>::Ptr tree (new pcl::search::KdTree<pcl::PointXYZRGBA>); if ( !cloud_filtered->empty())tree->setInputCloud (cloud_filtered); std::vector<pcl::PointIndices> cluster_indices; pcl::EuclideanClusterExtraction<pcl::PointXYZRGBA> ec; ec.setClusterTolerance (0.04); // 4cm ec.setMinClusterSize (200); ec.setMaxClusterSize (1000); ec.setSearchMethod (tree); ec.setInputCloud (cloud_filtered); ec.extract (cluster_indices); int j = 0; int cnt = 0,inlaw = 0; //start detect for (std::vector<pcl::PointIndices>::const_iterator it = cluster_indices.begin (); it != cluster_indices.end (); ++it) { pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud_cluster (new pcl::PointCloud<pcl::PointXYZRGBA>); for (std::vector<int>::const_iterator pit = it->indices.begin (); pit != it->indices.end (); ++pit) cloud_cluster->points.push_back (cloud_filtered->points[*pit]); //* cloud_cluster->width = cloud_cluster->points.size (); cloud_cluster->height = 1; cloud_cluster->is_dense = true; //std::cout << "PointCloud representing the Cluster: " << cloud_cluster->points.size () << " data points." << std::endl; //std::stringstream ss; //ss << "cloud_cluster_" << j << ".pcd"; //writer.write<pcl::PointXYZ> (ss.str (), *cloud_cluster, false); //* j++; cout <<"......................................................."<<endl; cout << "cloud_cluster_" << j << endl; if ( match(cloud_cluster)) { cout << ++cnt << " sphere have been detected " <<endl; unsigned int red,green,blue; for (int i=0,red = 0,green =0,blue = 0; i < cloud_cluster->points.size(); i++) { red =cloud_cluster->points[i].r; green =cloud_cluster->points[i].g; blue =cloud_cluster->points[i].b; if(getDistance(red,green,blue))inlaw++; } unsigned int tot = cloud_cluster->points.size(); red /=tot; blue /=tot; green /=tot; /// compared with standard red ! int dis = 0; dis = (red-255)*(red-255)+(blue-0)*(blue-0)+(green-0)*(green-0); if(inlaw > cloud_cluster->points.size()*0.7) { cout <<"This is red ball ! "<<endl; } else { cout <<"Sorry it's not red ball ...."<<endl; cout <<"#Average -> R :"<<red<<" G: "<<green<<" B: "<<blue<<endl; } cout <<"------------------------------------------------------"<<endl; //viewer.showCloud(cloud_cluster); } } } viewer.showCloud(cloud_RGBA); // --------OpenCV---------- Mat src, dst, color_dst; cvtColor(image, image, CV_BGR2GRAY); //sharpenImage1(image, image); GaussianBlur(image, image, Size(5, 5), 1.5); //sharpenImage1(image, image); vector<Vec3f> circles; HoughCircles(image, circles, CV_HOUGH_GRADIENT,2,120,220,70,25, 300); vector<Vec3f>::iterator itc = circles.begin(); while(itc != circles.end()) { cout << "x:" << (*itc)[0] << "y:" << (*itc)[1] << endl; circle(image,Point((*itc)[0], (*itc)[1]),(*itc)[2],Scalar(255),2); //颜色//厚度 x_position[count] = (*itc)[0]; //cout << "x_position" << count << ":" << x_position << endl; count++; if (count == 5) { sort(x_position, x_position + 5); int mid_value = x_position[2];//每5帧的中位数 cout << "mid_value:" << mid_value << endl; cout << "............................." << endl; double r = (*itc)[2]; //double d = 640 * 230/(2 * r) - 271; int l = (mid_value - 320); double theta = (double)52 / 640 * l; cout << "theta:" << theta << endl; if (mid_value > 410) { cout << "need to turn right" << endl; direction = 1; } else if (mid_value < 230) { cout << "need to turn left" << endl; direction = -1; } else { cout << "succeed" << endl; direction = 0; } count = 0; mid_value = 0; } ++itc; } // viewerS.showCloud(cloudP); cv::imshow("CurrentImage", image); //U must wait a second to let the image show on the screen char temp=cvWaitKey(0); if (temp ==27)break; //wait for new datas } }
void Tractor::plant_filter( Filter &filter, int track ) { mlt_field_plant_filter( mlt_tractor_field( get_tractor( ) ), filter.get_filter( ), track ); }
BOOL OpMenuLoad::LoadFile(CCLexFile* pFileToLoad, UINT32 nPrefFilter) { // Make sure we have a valid file to load. /* TRACEUSER( "JustinF", _T("In OpMenuLoad::LoadFile(%p, %u)\n"), (LPVOID) pFileToLoad, nPrefFilter); */ ERROR3IF(!pFileToLoad, "Null CCLexFile* in OpMenuLoad::LoadFile"); // Find out the position of the filter selected by the user in the open dialog INT32 SelectedPos = 0; #if !defined(EXCLUDE_FROM_RALPH) && !defined(EXCLUDE_FROM_XARALX) SelectedPos = BaseFileDialog::SelectedFilter; #endif // Go get the first filter in the list Filter* pFilter = Filter::GetFirst(); // Do we know which filter was used? (we know nothing about things in the recent file // list). If we don't, then use the preferred one, by default the generic filter. if (nPrefFilter != FILTERID_USERCHOICE || SelectedPos == 0) { // We know nothing. We will have to go and have a look at all the possibles // We will find the Filter Family and ask it to try and load the file. UINT32 nID = (nPrefFilter != FILTERID_USERCHOICE) ? nPrefFilter : FILTERID_GENERIC; while (pFilter != NULL && pFilter->FilterID != nID) { // Try the next filter pFilter = Filter::GetNext(pFilter); } } else { // We know which type of filter the user had selected in the file dialog // Find the filter that the user chose. while (pFilter != NULL) { // This is the filter? if (pFilter->GetFlags().CanImport && pFilter->pOILFilter->Position == SelectedPos) break; // Try the next filter pFilter = Filter::GetNext(pFilter); } } // Check that the Filter existed if (pFilter == NULL) { // It did not... InformError(_R(IDT_CANT_FIND_FILTER)); return FALSE; } // Get pointer to current doc 'cos we'll need it several times... Document* pCurDoc = Document::GetCurrent(); // If this is not a filter family, check for compatibility before asking // filter to load the file. // This means the user has chosen an explicit filter to handle the import PathName Path = pFileToLoad->GetPathName(); String_256 FilePath = Path.GetPath(); // FilePath will be null if a pathname is not valid if (!pFilter->IS_KIND_OF(FilterFamily) && !FilePath.IsEmpty()) { UINT32 Size = 1024; size_t FileSize; ADDR FilterBuf = pFilter->LoadInitialSegment(Path, &Size, &FileSize); // If there has been a problem in the load initial segment then fail now. if (FilterBuf == NULL) { // Tell the user about the problem and get out now while the goings good InformError(); return FALSE; } // Inform any filters that we are about to do a HowCompatible call. // This would allow a set of filters which have common functionality hidden in a // filter that cannot import and cannot export handle this call and hence set // itself up. This would allow it to maybe cache a result which should only be // checked by the first filter in the group. pFilter->PreHowCompatible(); // Change this to be less than 8 as the filters like the Accusoft forms return // 8 and 9 to make sure that they are last in the chain. if (pFilter->HowCompatible(Path, FilterBuf, Size, UINT32(FileSize)) < 8) { // Not 100% happy with this file - ask for confirmation. ErrorInfo Question; Question.ErrorMsg = _R(IDW_OPENQUERY_NOTSURE); Question.Button[0] = _R(IDB_OPENQUERY_OPEN); Question.Button[1] = _R(IDB_OPENQUERY_DONTOPEN); if ((ResourceID)AskQuestion(&Question) != _R(IDB_OPENQUERY_OPEN)) { // User asked for this to be cancelled. TRACEUSER( "Tim", _T("Filter compatibility was less than 10\n")); // Close the file, report the abort and finish. CCFree(FilterBuf); //InformMessage(_R(IDT_IMP_USERABORT)); return FALSE; } } // Get rid of initial file header CCFree(FilterBuf); } // we have to try and open the file try { // Found the Filter, so ask it to import the file please if (!pFilter->DoImport(this, pFileToLoad, pCurDoc)) { // Something went a bit wrong - tell the user what it was. // Only tell them if not special user cancelled error message if (Error::GetErrorNumber() != _R(IDN_USER_CANCELLED)) { // Only supress the error if not the special user abort error // ***** For now use the native EPS filter if (pFilter->FilterID == FILTERID_NATIVE_EPS && Error::GetErrorNumber() != _R(IDT_IMPORT_USERABORT)) { Error::ClearError(); InformError(_R(IDS_ERRORINARTFILE)); } else { // Tell the user what the problem was InformError(); wxMessageDialog dlg( NULL, _T( "Xara LX failed to load the design.\n\n") _T( "This is an early demonstration version of the program which does ") _T( "not yet support all of the data types that can appear in XAR designs."), _T("Load failed"), wxOK ); dlg.ShowModal() ; } } else { // otherwise remove the error so it won't get reported Error::ClearError(); } // and fail return FALSE; } } // See if there was a file io errir catch( CFileException ) { // Report the error if no one else did, otherwise clear it. if (Error::GetErrorNumber() != _R(IDN_USER_CANCELLED)) InformError(); else Error::ClearError(); // and fail return FALSE; } // Success. return TRUE; }
void OpMenuSave::Do(OpDescriptor* pOpDesc) { //First get the selected document Document* pdocToSave=Document::GetSelected(); CCamDoc* pccamdocToSave = pdocToSave->GetOilDoc(); if (pdocToSave==NULL || pccamdocToSave==NULL) { ERROR2RAW("No default document!"); return; } //And we'll need a pointer to the application Application* pCamelot = GetApplication(); CTemplateManager& TemplateManager( pCamelot->GetTemplateManager() ); //And put the default templates path in the dialog PathName pathToPutInDialog = TemplateManager.GetTemplatesPath(); FileUtil::RecursiveCreateDirectory( pathToPutInDialog.GetPath() ); //Now create the dialog SaveTemplateDialog dialogToDisplay(pathToPutInDialog); //And show it if (dialogToDisplay.ShowModal() == wxID_OK) { //Then get the path they specified, using this amazingly bad, confusing and //undocumented file dialog code //The "CString" reference should ideally go in Winoil PathName pathToSaveTo; dialogToDisplay.GetChosenFileName(&pathToSaveTo); wxString cstrPathToSaveTo=pathToSaveTo.GetPath(FALSE); dialogToDisplay.AppendExtension(&cstrPathToSaveTo); String_256 strPathToSaveTo=cstrPathToSaveTo; pathToSaveTo=strPathToSaveTo; // Create the save file. CCDiskFile file(pathToSaveTo, ios::out | ios::binary | ios::trunc); // First find the filter. Filter *pFilter = FindFilter ( FILTERID_NATIVE ); // Tell it to save attributes. pFilter->SetSaveAttributes ( TRUE ); // Then save the image to the file. Save ( pFilter, &file ); //Now, if we should make that path the default path if (SaveTemplateDialog::m_fUseAsDefault) { if (pdocToSave->IsAnimated()) { CTemplateManager::SetDefaultAnimationTemplate( strPathToSaveTo ); } else { CTemplateManager::SetDefaultDrawingTemplate( strPathToSaveTo ); } } if (SaveTemplateDialog::m_fDefaultTemplatesFolder) { String_256 strDefaultPath = pathToSaveTo.GetLocation( TRUE ); CTemplateManager::SetTemplatesPath( strDefaultPath ); } } // Finished the operation End(); }
void publishState(void) { uint8_t buf[10]; const int ret = libusb_control_transfer(dev, 0xC0, 0x32, 0x0, 0x0, buf, 10, 0); if (ret != 10) { ROS_ERROR_STREAM("Error in accelerometer reading, libusb_control_transfer returned " << ret); ros::shutdown(); } const uint16_t ux = ((uint16_t)buf[2] << 8) | buf[3]; const uint16_t uy = ((uint16_t)buf[4] << 8) | buf[5]; const uint16_t uz = ((uint16_t)buf[6] << 8) | buf[7]; const double accelerometer_x = (int16_t)ux; const double accelerometer_y = (int16_t)uy; const double accelerometer_z = ((int16_t)uz); const int8_t tilt_angle = (int8_t)buf[8]; const uint8_t tilt_status = buf[9]; // publish IMU sensor_msgs::Imu imu_msg; if (pub_imu.getNumSubscribers() > 0) { imu_msg.header.stamp = ros::Time::now(); imu_msg.linear_acceleration.x = filters[0].getValue(interpolators[0].getValue(accelerometer_x) * GRAVITY); imu_msg.linear_acceleration.y = filters[1].getValue(interpolators[1].getValue(accelerometer_y) * GRAVITY); imu_msg.linear_acceleration.z = filters[2].getValue(interpolators[2].getValue(accelerometer_z) * GRAVITY); imu_msg.linear_acceleration_covariance[0] = imu_msg.linear_acceleration_covariance[4] = imu_msg.linear_acceleration_covariance[8] = 0.01; // @todo - what should these be? imu_msg.angular_velocity_covariance[0] = -1; // indicates angular velocity not provided imu_msg.orientation_covariance[0] = -1; // indicates orientation not provided double magnitude = sqrt((imu_msg.linear_acceleration.x * imu_msg.linear_acceleration.x) + (imu_msg.linear_acceleration.y * imu_msg.linear_acceleration.y) + (imu_msg.linear_acceleration.z + imu_msg.linear_acceleration.z)); //Only publish when the summed magnitued is within 15% of the expected force due to gravity double error = magnitude - GRAVITY; double delta = magnitude - lastForce; double deltaExpected = deltaFilter.getValue(delta); if(abs(delta - deltaExpected) < (0.1 * GRAVITY) && abs(error) < (GRAVITY * ERROR_MARGIN)){ tf::Quaternion q; double pitch = -atan2( imu_msg.linear_acceleration.z, sqrt((imu_msg.linear_acceleration.x * imu_msg.linear_acceleration.x) + (imu_msg.linear_acceleration.y * imu_msg.linear_acceleration.y)) ); double roll = atan2( imu_msg.linear_acceleration.x, sqrt((imu_msg.linear_acceleration.z * imu_msg.linear_acceleration.z) + (imu_msg.linear_acceleration.y * imu_msg.linear_acceleration.y)) ); q.setRPY( roll, pitch, 0.0 ); imu_msg.header.frame_id = "/camera_link"; imu_msg.orientation.x = q.x(); imu_msg.orientation.y = q.y(); imu_msg.orientation.z = q.z(); imu_msg.orientation.w = q.w(); pub_imu.publish(imu_msg); } } // publish tilt angle and status if (pub_tilt_angle.getNumSubscribers() > 0) { std_msgs::Float64 tilt_angle_msg; tilt_angle_msg.data = double(tilt_angle) / 2.; pub_tilt_angle.publish(tilt_angle_msg); } if (pub_tilt_status.getNumSubscribers() > 0) { std_msgs::UInt8 tilt_status_msg; tilt_status_msg.data = tilt_status; pub_tilt_status.publish(tilt_status_msg); } }
ColumnPtr ColumnArray::filterString(const Filter & filt, ssize_t result_size_hint) const { size_t col_size = getOffsets().size(); if (col_size != filt.size()) throw Exception("Size of filter doesn't match size of column.", ErrorCodes::SIZES_OF_COLUMNS_DOESNT_MATCH); if (0 == col_size) return ColumnArray::create(data); auto res = ColumnArray::create(data->cloneEmpty()); const ColumnString & src_string = typeid_cast<const ColumnString &>(*data); const ColumnString::Chars & src_chars = src_string.getChars(); const Offsets & src_string_offsets = src_string.getOffsets(); const Offsets & src_offsets = getOffsets(); ColumnString::Chars & res_chars = typeid_cast<ColumnString &>(res->getData()).getChars(); Offsets & res_string_offsets = typeid_cast<ColumnString &>(res->getData()).getOffsets(); Offsets & res_offsets = res->getOffsets(); if (result_size_hint < 0) /// Other cases are not considered. { res_chars.reserve(src_chars.size()); res_string_offsets.reserve(src_string_offsets.size()); res_offsets.reserve(col_size); } Offset prev_src_offset = 0; Offset prev_src_string_offset = 0; Offset prev_res_offset = 0; Offset prev_res_string_offset = 0; for (size_t i = 0; i < col_size; ++i) { /// Number of rows in the array. size_t array_size = src_offsets[i] - prev_src_offset; if (filt[i]) { /// If the array is not empty - copy content. if (array_size) { size_t chars_to_copy = src_string_offsets[array_size + prev_src_offset - 1] - prev_src_string_offset; size_t res_chars_prev_size = res_chars.size(); res_chars.resize(res_chars_prev_size + chars_to_copy); memcpy(&res_chars[res_chars_prev_size], &src_chars[prev_src_string_offset], chars_to_copy); for (size_t j = 0; j < array_size; ++j) res_string_offsets.push_back(src_string_offsets[j + prev_src_offset] + prev_res_string_offset - prev_src_string_offset); prev_res_string_offset = res_string_offsets.back(); } prev_res_offset += array_size; res_offsets.push_back(prev_res_offset); } if (array_size) { prev_src_offset += array_size; prev_src_string_offset = src_string_offsets[prev_src_offset - 1]; } } return res; }
int Fixture::getFilter(State & state, b2Fixture * object){ Filter * interfaceFilter = state.getInterface<Filter>("LuaBox2D_Filter"); interfaceFilter->push(new b2Filter(object->GetFilterData()), true); return 1; }
int CmdCustom::execute (std::string& output) { int rc = 0; // Load report configuration. std::string reportColumns = context.config.get ("report." + _keyword + ".columns"); std::string reportLabels = context.config.get ("report." + _keyword + ".labels"); std::string reportSort = context.config.get ("report." + _keyword + ".sort"); std::string reportFilter = context.config.get ("report." + _keyword + ".filter"); if (reportFilter != "") reportFilter = "( " + reportFilter + " )"; std::vector <std::string> columns; split (columns, reportColumns, ','); validateReportColumns (columns); std::vector <std::string> labels; split (labels, reportLabels, ','); if (columns.size () != labels.size () && labels.size () != 0) throw format (STRING_CMD_CUSTOM_MISMATCH, _keyword); std::vector <std::string> sortOrder; split (sortOrder, reportSort, ','); validateSortColumns (sortOrder); // Prepend the argument list with those from the report filter. context.cli.addRawFilter (reportFilter); // Apply filter. handleRecurrence (); Filter filter; std::vector <Task> filtered; filter.subset (filtered); // Sort the tasks. std::vector <int> sequence; for (unsigned int i = 0; i < filtered.size (); ++i) sequence.push_back (i); sort_tasks (filtered, sequence, reportSort); // Configure the view. ViewTask view; view.width (context.getWidth ()); view.leftMargin (context.config.getInteger ("indent.report")); view.extraPadding (context.config.getInteger ("row.padding")); view.intraPadding (context.config.getInteger ("column.padding")); Color label (context.config.get ("color.label")); view.colorHeader (label); Color label_sort (context.config.get ("color.label.sort")); view.colorSortHeader (label_sort); Color alternate (context.config.get ("color.alternate")); view.colorOdd (alternate); view.intraColorOdd (alternate); // Capture columns that are sorted. std::vector <std::string> sortColumns; // Add the break columns, if any. std::vector <std::string>::iterator so; for (so = sortOrder.begin (); so != sortOrder.end (); ++so) { std::string name; bool ascending; bool breakIndicator; context.decomposeSortField (*so, name, ascending, breakIndicator); if (breakIndicator) view.addBreak (name); sortColumns.push_back (name); } // Add the columns and labels. for (unsigned int i = 0; i < columns.size (); ++i) { Column* c = Column::factory (columns[i], _keyword); if (i < labels.size ()) c->setLabel (labels[i]); bool sort = std::find (sortColumns.begin (), sortColumns.end (), c->name ()) != sortColumns.end () ? true : false; view.add (c, sort); } // How many lines taken up by table header? int table_header = 0; if (context.verbose ("label")) { if (context.color () && context.config.getBoolean ("fontunderline")) table_header = 1; // Underlining doesn't use extra line. else table_header = 2; // Dashes use an extra line. } // Report output can be limited by rows or lines. int maxrows = 0; int maxlines = 0; context.getLimits (maxrows, maxlines); // Adjust for fluff in the output. if (maxlines) maxlines -= table_header + (context.verbose ("blank") ? 1 : 0) + (context.verbose ("footnote") ? context.footnotes.size () : 0) + (context.verbose ("affected") ? 1 : 0) + context.config.getInteger ("reserved.lines"); // For prompt, etc. // Render. std::stringstream out; if (filtered.size ()) { view.truncateRows (maxrows); view.truncateLines (maxlines); out << optionalBlankLine () << view.render (filtered, sequence) << optionalBlankLine (); // Print the number of rendered tasks if (context.verbose ("affected")) { out << (filtered.size () == 1 ? STRING_CMD_CUSTOM_COUNT : format (STRING_CMD_CUSTOM_COUNTN, filtered.size ())); if (maxrows && maxrows < (int)filtered.size ()) out << ", " << format (STRING_CMD_CUSTOM_SHOWN, maxrows); if (maxlines && maxlines < (int)filtered.size ()) out << ", " << format (STRING_CMD_CUSTOM_TRUNCATED, maxlines - table_header); out << "\n"; } } else { context.footnote (STRING_FEEDBACK_NO_MATCH); rc = 1; } feedback_backlog (); output = out.str (); return rc; }
static void filter(Filter& f, PointView& view) { f.filter(view); }
int CmdModify::execute (std::string& output) { int rc = 0; int count = 0; // Apply filter. Filter filter; std::vector <Task> filtered; filter.subset (filtered); if (filtered.size () == 0) { context.footnote (STRING_FEEDBACK_NO_TASKS_SP); return 1; } // TODO Complain when no modifications are specified. // Accumulated project change notifications. std::map <std::string, std::string> projectChanges; std::vector <Task>::iterator task; for (task = filtered.begin (); task != filtered.end (); ++task) { Task before (*task); task->modify (Task::modReplace); if (taskDiff (before, *task)) { // Perform some logical consistency checks. if (task->has ("recur") && !task->has ("due") && !before.has ("due")) throw std::string (STRING_CMD_MODIFY_NO_DUE); if (before.has ("recur") && before.has ("due") && (!task->has ("due") || task->get ("due") == "")) throw std::string (STRING_CMD_MODIFY_REM_DUE); if (before.has ("recur") && (!task->has ("recur") || task->get ("recur") == "")) throw std::string (STRING_CMD_MODIFY_REC_ALWAYS); // Delete the specified task. std::string question; if (task->id != 0) question = format (STRING_CMD_MODIFY_CONFIRM, task->id, task->get ("description")); else question = format (STRING_CMD_MODIFY_CONFIRM, task->get ("uuid"), task->get ("description")); if (permission (*task, taskDifferences (before, *task) + question, filtered.size ())) { updateRecurrenceMask (*task); dependencyChainOnModify (before, *task); ++count; feedback_affected (STRING_CMD_MODIFY_TASK, *task); feedback_unblocked (*task); context.tdb2.modify (*task); if (context.verbose ("project")) projectChanges[task->get ("project")] = onProjectChange (before, *task); // Task potentially has siblings - modify them. if (task->has ("parent")) { if ((context.config.get ("recurrence.confirmation") == "prompt" && confirm (STRING_CMD_MODIFY_RECUR)) || context.config.getBoolean ("recurrence.confirmation")) { std::vector <Task> siblings = context.tdb2.siblings (*task); std::vector <Task>::iterator sibling; for (sibling = siblings.begin (); sibling != siblings.end (); ++sibling) { Task alternate (*sibling); sibling->modify (Task::modReplace); updateRecurrenceMask (*sibling); dependencyChainOnModify (alternate, *sibling); ++count; feedback_affected (STRING_CMD_MODIFY_TASK_R, *sibling); feedback_unblocked (*sibling); context.tdb2.modify (*sibling); if (context.verbose ("project")) projectChanges[sibling->get ("project")] = onProjectChange (alternate, *sibling); } // Modify the parent Task parent; context.tdb2.get (task->get ("parent"), parent); parent.modify (Task::modReplace); context.tdb2.modify (parent); } } // Task potentially has child tasks - modify them. else if (task->get ("status") == "recurring") { std::vector <Task> children = context.tdb2.children (*task); if (children.size () && (! context.config.getBoolean ("recurrence.confirmation") || confirm (STRING_CMD_MODIFY_RECUR))) { std::vector <Task>::iterator child; for (child = children.begin (); child != children.end (); ++child) { Task alternate (*child); child->modify (Task::modReplace); updateRecurrenceMask (*child); context.tdb2.modify (*child); dependencyChainOnModify (alternate, *child); if (context.verbose ("project")) projectChanges[child->get ("project")] = onProjectChange (alternate, *child); ++count; feedback_affected (STRING_CMD_MODIFY_TASK_R, *child); } } } } else { std::cout << STRING_CMD_MODIFY_NO << "\n"; rc = 1; if (_permission_quit) break; } } } // Now list the project changes. std::map <std::string, std::string>::iterator i; for (i = projectChanges.begin (); i != projectChanges.end (); ++i) if (i->first != "") context.footnote (i->second); feedback_affected (count == 1 ? STRING_CMD_MODIFY_1 : STRING_CMD_MODIFY_N, count); return rc; }
void INIParser::process(const wstring& line, bool eof) { static const RegExp re1 = L"/^(\\w+)=(.*)$/"; static const RegExp re2 = L"/^\\s*\\[(.+)\\]\\s*$/"; static const RegExp re3 = L"/\\\\\\[/g"; static const wstring strTitle = L"title"; static const wstring strDisabled = L"disabled"; static const wstring strTrue = L"true"; static const wstring strLeftBracket = L"["; RegExpMatch match; bool ret = false; if (wantObj && re1.exec(match, line)) { curObj[match.substrings[1]] = match.substrings[2]; } else if (eof || (ret = re2.exec(match, line))) { wstring strSection; if (ret) { strSection = toLowerCase(match.substrings[1]); } if (wantObj ? curObj.size() : curList.size()) { // Process current object before going to next section switch (curSection) { case FILTER: case PATTERN: // create the filter, with certain properties set up // do not insert it into the filters set // if it's active, it'll be inserted in some subscription we'll later parse persistedFilters.insert(Filter::fromObject(curObj)); break; case SUBSCRIPTION: // not supported, just record whether the whole subscription is disabled or not { auto iter = curObj.find(strDisabled); subscriptionDisabled = iter != curObj.end() && iter->second == strTrue; if (hasExcludedSubscriptions) { auto iterTitle = curObj.find(strTitle); subscriptionExcluded = iterTitle != curObj.end() && reExcludedSubscriptions.test(iterTitle->second); } else { subscriptionExcluded = false; } } break; case SUBSCRIPTION_FILTERS: case SUBSCRIPTION_PATTERNS: case USER_PATTERNS: if (!subscriptionDisabled && !subscriptionExcluded) { for (size_t i = 0; i < curList.size(); i++) { const wstring& text = curList[i]; Filter* filter = Filter::fromText(text); // need to reset the disabled property since we don't clear // the global filter list between reloads ActiveFilter* activeFilter = filter->toActiveFilter(); if (activeFilter) { // Only reset disabled property for those not persisted yet if (persistedFilters.find(filter) == persistedFilters.end()) activeFilter->setDisabled(false); // just put the filter in INIParser::filters filters.insert(activeFilter); } } } subscriptionDisabled = false; subscriptionExcluded = false; } } // Do clean-up curSection = OTHER; if (wantObj) curObj.clear(); else curList.clear(); if (eof) { subscriptionDisabled = false; subscriptionExcluded = false; return; } auto iter = sectionMapper.find(strSection); if (iter != sectionMapper.end()) { curSection = iter->second; switch (curSection) { case FILTER: case PATTERN: case SUBSCRIPTION: wantObj = true; break; case SUBSCRIPTION_FILTERS: case SUBSCRIPTION_PATTERNS: case USER_PATTERNS: default: wantObj = false; } } } else if (!wantObj && line.length() && !subscriptionDisabled && !subscriptionExcluded) { curList.push_back(replace(line, re3, strLeftBracket)); } }
ColumnPtr ColumnArray::filterString(const Filter & filt, ssize_t result_size_hint) const { size_t col_size = getOffsets().size(); if (col_size != filt.size()) throw Exception("Size of filter doesn't match size of column.", ErrorCodes::SIZES_OF_COLUMNS_DOESNT_MATCH); if (0 == col_size) return std::make_shared<ColumnArray>(data); auto res = std::make_shared<ColumnArray>(data->cloneEmpty()); const ColumnString & src_string = typeid_cast<const ColumnString &>(*data); const ColumnString::Chars_t & src_chars = src_string.getChars(); const Offsets_t & src_string_offsets = src_string.getOffsets(); const Offsets_t & src_offsets = getOffsets(); ColumnString::Chars_t & res_chars = typeid_cast<ColumnString &>(res->getData()).getChars(); Offsets_t & res_string_offsets = typeid_cast<ColumnString &>(res->getData()).getOffsets(); Offsets_t & res_offsets = res->getOffsets(); if (result_size_hint < 0) /// Остальные случаи не рассматриваем. { res_chars.reserve(src_chars.size()); res_string_offsets.reserve(src_string_offsets.size()); res_offsets.reserve(col_size); } Offset_t prev_src_offset = 0; Offset_t prev_src_string_offset = 0; Offset_t prev_res_offset = 0; Offset_t prev_res_string_offset = 0; for (size_t i = 0; i < col_size; ++i) { /// Количество строк в массиве. size_t array_size = src_offsets[i] - prev_src_offset; if (filt[i]) { /// Если массив не пуст - копируем внутренности. if (array_size) { size_t chars_to_copy = src_string_offsets[array_size + prev_src_offset - 1] - prev_src_string_offset; size_t res_chars_prev_size = res_chars.size(); res_chars.resize(res_chars_prev_size + chars_to_copy); memcpy(&res_chars[res_chars_prev_size], &src_chars[prev_src_string_offset], chars_to_copy); for (size_t j = 0; j < array_size; ++j) res_string_offsets.push_back(src_string_offsets[j + prev_src_offset] + prev_res_string_offset - prev_src_string_offset); prev_res_string_offset = res_string_offsets.back(); } prev_res_offset += array_size; res_offsets.push_back(prev_res_offset); } if (array_size) { prev_src_offset += array_size; prev_src_string_offset = src_string_offsets[prev_src_offset - 1]; } } return res; }
bool Filter::operator==(const Filter& filter) const { return GetProperty("text")->AsString() == filter.GetProperty("text")->AsString(); }
/** * The playback thread code * \internal */ void *narrator_thread(void *narrator) { //Narrator *n = static_cast<Narrator *>(narrator); Narrator *n = (Narrator*)narrator; int queueitems; // Set initial values to 0 so that they get updated when thread gets play signal float gain = 0; float tempo = 0; float pitch = 0; PortAudio portaudio; Filter filter; Narrator::threadState state = n->getState(); LOG4CXX_INFO(narratorLog, "Starting playback thread"); do { queueitems = n->numPlaylistItems(); if(queueitems == 0) { // Wait a little before calling callback long waitms = portaudio.getRemainingms(); if(waitms != 0) { LOG4CXX_DEBUG(narratorLog, "Waiting " << waitms << " ms for playback to finish"); while(waitms > 0 && queueitems == 0) { usleep(100000); queueitems = n->numPlaylistItems(); waitms -= 100; } } // Break if we during the pause got some more queued items to play if(queueitems == 0) { if(state != Narrator::DEAD) n->audioFinishedPlaying(); n->setState(Narrator::WAIT); LOG4CXX_INFO(narratorLog, "Narrator in WAIT state"); portaudio.stop(); while(queueitems == 0) { state = n->getState(); if(state == Narrator::EXIT) break; usleep(10000); queueitems = n->numPlaylistItems(); } } LOG4CXX_INFO(narratorLog, "Narrator starting playback"); } if(state == Narrator::EXIT) break; n->setState(Narrator::PLAY); n->bResetFlag = false; Narrator::PlaylistItem pi; pthread_mutex_lock(n->narratorMutex); if(n->mPlaylist.size() > 0) { pi = n->mPlaylist.front(); n->mPlaylist.pop(); } else { LOG4CXX_ERROR(narratorLog, "Narrator started playback thread without playlistitems"); pthread_mutex_unlock(n->narratorMutex); continue; } string lang = n->mLanguage; pthread_mutex_unlock(n->narratorMutex); // If trying to play a file, open it if(pi.mClass == "file") { LOG4CXX_DEBUG(narratorLog, "Playing file: " << pi.mIdentifier); AudioStream *audioStream; std::string fileExtension = getFileExtension(pi.mIdentifier); if (fileExtension == "ogg") { audioStream = new OggStream; } else if (fileExtension == "mp3") { audioStream = new Mp3Stream; } else { LOG4CXX_ERROR(narratorLog, "extension '" << fileExtension << "' not supported"); continue; } if(!audioStream->open(pi.mIdentifier)) { LOG4CXX_ERROR(narratorLog, "error opening audio stream: " << pi.mIdentifier); audioStream->close(); continue; } if (portaudio.getRate() != audioStream->getRate()) { long waitms = portaudio.getRemainingms(); if (waitms != 0) { LOG4CXX_DEBUG(narratorLog, "Waiting for current playback to finish"); while (waitms > 0) { usleep(100000); waitms -= 100; } } } if(!portaudio.open(audioStream->getRate(), audioStream->getChannels())) { LOG4CXX_ERROR(narratorLog, "error initializing portaudio, (rate: " << audioStream->getRate() << " channels: " << audioStream->getChannels() << ")"); continue; } if(!filter.open(audioStream->getRate(), audioStream->getChannels())) { LOG4CXX_ERROR(narratorLog, "error initializing filter"); continue; } LOG4CXX_DEBUG(narratorLog, "Audio stream has " << audioStream->getChannels() << " channel(s) and rate " << audioStream->getRate() << " Hz"); int inSamples = 0; soundtouch::SAMPLETYPE* buffer = new soundtouch::SAMPLETYPE[audioStream->getChannels()*BUFFERSIZE]; //buffer = (short*)malloc(sizeof(short) * 2 * BUFFERSIZE); // long totalSamplesRead = 0; do { // change gain, tempo and pitch adjustGainTempoPitch(n, filter, gain, tempo, pitch); // read some stuff from the audio stream inSamples = audioStream->read(buffer, BUFFERSIZE/**audioStream->getChannels()*/); LOG4CXX_TRACE(narratorLog, "got " << inSamples << " samples"); //printf("Read %d samples from audio stream\n", inSamples); if(inSamples != 0) { filter.write(buffer, inSamples); // One sample contains data for all channels here writeSamplesToPortaudio( n, portaudio, filter, buffer ); } else { LOG4CXX_INFO(narratorLog, "Flushing soundtouch buffer"); filter.flush(); } state = n->getState(); } while (inSamples != 0 && state == Narrator::PLAY && !n->bResetFlag); if(buffer != NULL) delete [] (buffer); audioStream->close(); delete audioStream; } // Else try opening from database else { vector <MessageAudio> vAudioQueue; // Get a list of MessageAudio objects to play Message *m = pi.mMessage; if(m==NULL){ LOG4CXX_ERROR(narratorLog, "Message was null"); } m->setLanguage(lang); m->load(pi.mIdentifier, pi.mClass); if(!m->compile() || !m->hasAudio()) { LOG4CXX_ERROR(narratorLog, "Narrator translation not found: could not find audio for '" << pi.mIdentifier << "'"); } else { vAudioQueue = m->getAudioQueue(); } // Play what we got if(vAudioQueue.size() > 0) { vector <MessageAudio>::iterator audio; audio = vAudioQueue.begin(); do { LOG4CXX_INFO(narratorLog, "Saying: " << audio->getText()); AudioStream *audioStream; std::string encoding = ((MessageAudio&)*audio).getEncoding(); if (encoding == "ogg") { audioStream = new OggStream; } else if (encoding == "mp3") { audioStream = new Mp3Stream; } else { LOG4CXX_ERROR(narratorLog, "encoding '" << encoding << "' not supported"); audio++; continue; } if(!audioStream->open(*audio)) { LOG4CXX_ERROR(narratorLog, "error opening audio stream"); audioStream->close(); break; } if (portaudio.getRate() != audioStream->getRate()) { long waitms = portaudio.getRemainingms(); if (waitms != 0) { LOG4CXX_DEBUG(narratorLog, "Waiting for current playback to finish"); while (waitms > 0) { usleep(100000); waitms -= 100; } } } if(!portaudio.open(audioStream->getRate(), audioStream->getChannels())) { LOG4CXX_ERROR(narratorLog, "error initializing portaudio"); break; } if(!filter.open(audioStream->getRate(), audioStream->getChannels())) { LOG4CXX_ERROR(narratorLog, "error initializing filter"); break; } int inSamples = 0; soundtouch::SAMPLETYPE* buffer = new soundtouch::SAMPLETYPE[audioStream->getChannels()*BUFFERSIZE]; do { // change gain, tempo and pitch adjustGainTempoPitch(n, filter, gain, tempo, pitch); // read some stuff from the audio stream inSamples = audioStream->read(buffer, BUFFERSIZE*audioStream->getChannels()); if(inSamples != 0) { filter.write(buffer, inSamples); writeSamplesToPortaudio( n, portaudio, filter, buffer ); } else { LOG4CXX_INFO(narratorLog, "Flushing soundtouch buffer"); filter.flush(); } state = n->getState(); } while (inSamples != 0 && state == Narrator::PLAY && !n->bResetFlag); if(buffer != NULL) delete [] (buffer); audioStream->close(); audio++; } while(audio != vAudioQueue.end() && state == Narrator::PLAY && !n->bResetFlag); } //Cleanup message object delete(pi.mMessage); } // Abort stream? if(n->bResetFlag) { n->bResetFlag = false; portaudio.stop(); filter.clear(); } } while(state != Narrator::EXIT); LOG4CXX_INFO(narratorLog, "Shutting down playbackthread"); pthread_exit(NULL); return NULL; }
IntSize FEGaussianBlur::calculateKernelSize(const Filter& filter, const FloatPoint& stdDeviation) { FloatPoint stdFilterScaled(filter.applyHorizontalScale(stdDeviation.x()), filter.applyVerticalScale(stdDeviation.y())); return calculateUnscaledKernelSize(stdFilterScaled); }
NoOptionsPipe() { or2_ = new Filter; or2_->set_opt_value("min-fragment", 10); add(or2_); }
int SDLCALL watch_filter(void* filter, SDL_Event* event) { Filter* f = static_cast<Filter*>(filter); return f->ask_input(event); }
void MainWindow::onFilterBtnClicked() { Filter *fd = new Filter(this, *dbh, this); fd->show(); }
IMAGE *process_pipeline(IMAGE *image){ if(!image){ /// "Не задано входное изображение" ERRX(_("No input image given")); } if(!farray || !farray_size){ /// "Не заданы параметры конвейера" WARNX(_("No pipeline parameters given")); } size_t i; Filter **far = farray; IMAGE *in = copyFITS(image); // copy original image to leave it unchanged IMAGE *processed = NULL; for(i = 0; i < farray_size; ++i, ++far){ Filter *f = *far; DBG("Got filter #%d: w=%d, h=%d, sx=%g, sy=%g\n", f->FilterType, f->w, f->h, f->sx, f->sy); printf("try filter %zd\n", i); Itmarray oarg = {NULL, 0}; processed = f->imfunc(in, f, &oarg); /// "Ошибка в обработке конвейера" if(!processed) ERRX(_("Error on pipeline processing!")); // TODO: what should I do with oarg??? if(oarg.size){ size_t i, l = oarg.size; //if(verbose_level){ green("got oarg: \n"); for(i = 0; i < l; ++i){ printf("%5zd: %g\n", i, oarg.data[i]); } //} char tabname[80]; snprintf(tabname, 80, "%s_CONVERSION", f->name); FITStable *tab = table_new(processed, tabname); if(tab){ table_column col = { .width = sizeof(int32_t), .repeat = l, .coltype = TINT }; int32_t *levls = MALLOC(int32_t, l); for(i = 0; i < l; ++i) levls[i] = (int32_t) i; col.contents = levls; sprintf(col.colname, "level"); *col.unit = 0; table_addcolumn(tab, &col); FREE(levls); col.contents = oarg.data; col.coltype = TDOUBLE; col.width = sizeof(double), sprintf(col.colname, "value"); sprintf(col.unit, "ADU"); table_addcolumn(tab, &col); printf("Create table:\n"); table_print(tab); } FREE(oarg.data); } processed->keylist = in->keylist; char changes[FLEN_CARD]; snprintf(changes, FLEN_CARD, "HISTORY modified by routine %s", f->name); list_add_record(&(processed->keylist), changes); //list_print(processed->keylist); in->keylist = NULL; // prevent deleting global keylist imfree(&in); in = processed; } return processed; }
int Field::plant_filter( Filter &filter, int track ) { return mlt_field_plant_filter( get_field( ), filter.get_filter( ), track ); }
void BiconnectedDecomposer::getComponent (int idx, Filter &filter) const { filter.init(_components[idx]->ptr(), Filter::EQ, 1); }
void set_scaling_method(Filter & filter, scaling_method_e scaling_method, double filter_factor) { switch(scaling_method) { case SCALING_BILINEAR: filter.calculate(agg::image_filter_bilinear(), true); break; case SCALING_BICUBIC: filter.calculate(agg::image_filter_bicubic(), true); break; case SCALING_SPLINE16: filter.calculate(agg::image_filter_spline16(), true); break; case SCALING_SPLINE36: filter.calculate(agg::image_filter_spline36(), true); break; case SCALING_HANNING: filter.calculate(agg::image_filter_hanning(), true); break; case SCALING_HAMMING: filter.calculate(agg::image_filter_hamming(), true); break; case SCALING_HERMITE: filter.calculate(agg::image_filter_hermite(), true); break; case SCALING_KAISER: filter.calculate(agg::image_filter_kaiser(), true); break; case SCALING_QUADRIC: filter.calculate(agg::image_filter_quadric(), true); break; case SCALING_CATROM: filter.calculate(agg::image_filter_catrom(), true); break; case SCALING_GAUSSIAN: filter.calculate(agg::image_filter_gaussian(), true); break; case SCALING_BESSEL: filter.calculate(agg::image_filter_bessel(), true); break; case SCALING_MITCHELL: filter.calculate(agg::image_filter_mitchell(), true); break; case SCALING_SINC: filter.calculate(agg::image_filter_sinc(filter_factor), true); break; case SCALING_LANCZOS: filter.calculate(agg::image_filter_lanczos(filter_factor), true); break; case SCALING_BLACKMAN: filter.calculate(agg::image_filter_blackman(filter_factor), true); break; default: break; } }
Vector move(const Vector &v) { return F->filt(I.integrate(v)); }