Example #1
0
unique_ptr<Graph> ConstructGraph(map<int, Vertex> &vertex_dict, map<int, int> &name_dict, vector<Edge> &edges_vec) {
    auto graph_ptr = make_unique<Graph>();
    auto edge_weight_map = boost::get(boost::edge_weight, *graph_ptr);
    for (auto &my_edge : edges_vec) {
        if (vertex_dict.find(my_edge.src_index_) == vertex_dict.end()) {
            Vertex vertex = boost::add_vertex(*graph_ptr);
            vertex_dict.emplace(my_edge.src_index_, vertex);
        }
        if (vertex_dict.find(my_edge.dst_index_) == vertex_dict.end()) {
            Vertex vertex = boost::add_vertex(*graph_ptr);
            vertex_dict.emplace(my_edge.dst_index_, vertex);
        }
        auto edge_flag_pair = add_edge(vertex_dict[my_edge.src_index_], vertex_dict[my_edge.dst_index_], *graph_ptr);
        if (edge_flag_pair.second) {
            edge_weight_map[edge_flag_pair.first] = my_edge.edge_weight_;
//            cout << my_edge;
        }
    }

    auto vertex_index_map = boost::get(boost::vertex_index, *graph_ptr);
    for (auto iter = vertex_dict.begin(); iter != vertex_dict.end(); ++iter) {
        name_dict.emplace(vertex_index_map[iter->second], iter->first);
    }
    return graph_ptr;
}
Example #2
0
 void set(int key, int value) 
 {
     ++op_count;
     if (map_kv.find(key) == map_kv.end())
     // insert new key
     {
         if (map_kv.size() == capacity)
         {
             map<int, int>::iterator it = map_tk.begin();
             int k = it->second;
             
             map_tk.erase(map_tk.begin());
             map_kt.erase(map_kt.find(k));
             map_kv.erase(map_kv.find(k));
         }
         
         map_kv.emplace(key, value);
         map_tk.emplace(op_count, key);
         map_kt.emplace(key, op_count);
     }
     else
     {
         int old_time = map_kt[key];
         map_tk.erase(map_tk.find(old_time));
         map_tk.emplace(op_count, key);
         
         map_kt[key] = op_count;
         map_kv[key] = value;
     }
 }
/** Scan lines for bank IDs
  * @param lines :: vector of string of all non-empty lines in input file;
  * @param useFileBankIDs :: use bank IDs as given in file rather than ordinal
 * number of bank
  * @param banks :: [output] vector of integers for existing banks in .irf file;
  * @param bankstartindexmap :: [output] map to indicate the first line of each
 * bank in vector lines.
  * @param bankendindexmap :: [output] map to indicate the last line of each
 * bank in vector lines
  */
void LoadFullprofResolution::scanBanks(const vector<string> &lines,
                                       const bool useFileBankIDs,
                                       vector<int> &banks,
                                       map<int, int> &bankstartindexmap,
                                       map<int, int> &bankendindexmap) {
  int startindex = -1;
  int endindex = -1;
  int bankid = 0;
  for (size_t i = 0; i < lines.size(); ++i) {
    string line = lines[i];
    if (line.find("Bank") != string::npos) {
      // A new line found
      if (startindex >= 0) {
        // Previous line is in a bank range.  Then finish the previous bank
        // range
        endindex = static_cast<int>(i) - 1;
        bankstartindexmap.emplace(banks.back(), startindex);
        bankendindexmap.emplace(banks.back(), endindex);
      }

      // Start the new pair
      startindex = static_cast<int>(i);
      endindex = -1;

      // Get bank ID
      if (useFileBankIDs) { // Get bank ID from line
        vector<string> level1s;
        boost::split(level1s, line, boost::is_any_of("Bank"));
        vector<string> level2s;
        string bankterm = level1s.back();
        boost::algorithm::trim(bankterm);
        boost::split(level2s, bankterm, boost::is_any_of(" "));
        bankid = atoi(level2s[0].c_str());
      } else { // Get bank ID as ordinal number of bank
        bankid++;
      }
      banks.push_back(bankid);
    }
  }
  if (startindex >= 0) {
    endindex = static_cast<int>(lines.size()) - 1;
    bankstartindexmap.emplace(banks.back(), startindex);
    bankendindexmap.emplace(banks.back(), endindex);
  }

  g_log.debug() << "[DB1112] Number of bank IDs = " << banks.size() << ", "
                << "Number of ranges = " << bankstartindexmap.size() << endl;
  for (auto &bank : banks) {
    g_log.debug() << "Bank " << bank << " From line " << bankstartindexmap[bank]
                  << " to " << bankendindexmap[bank] << endl;
  }

  return;
}
Example #4
0
void init_stage_map(map<float, shared_ptr<Stage>> &stage_map) {
	float acute_max = (float) Parameters::instance()->getDoubleParameter(ACUTE_RANGE_MAX_NUMERATOR);
	float chronic_max = (float) Parameters::instance()->getDoubleParameter(CHRONIC_RANGE_MAX_NUMERATOR);
	float late_max = (float) Parameters::instance()->getDoubleParameter(LATE_RANGE_MAX_NUMERATOR);
	float acute_mult = (float) Parameters::instance()->getDoubleParameter(ACUTE_MULTIPLIER);
	float late_mult = (float) Parameters::instance()->getDoubleParameter(LATE_MULTIPLIER);
	float baseline_infectivity = (float) Parameters::instance()->getDoubleParameter(MIN_CHRONIC_INFECTIVITY_UNADJ);

	stage_map.emplace(acute_max, make_shared<AcuteStage>(baseline_infectivity, acute_mult, Range<float>(1, acute_max)));
	stage_map.emplace(chronic_max,
			make_shared<ChronicStage>(baseline_infectivity, Range<float>(acute_max, chronic_max)));
	stage_map.emplace(late_max,
			make_shared<LateStage>(baseline_infectivity, late_mult, Range<float>(chronic_max, late_max)));
}
Example #5
0
	void RegisterType(string strKey, std::function<T* ()> creator)
	{
		if (m_creatorMap.find(strKey) != m_creatorMap.end())
			throw std::invalid_argument("this key has already exist!");

		m_creatorMap.emplace(strKey, creator);
	}
    DoctypeFixture *addDocType(const std::string &name, bool isGlobal = false) {
        DocumenttypesConfigBuilder::Documenttype dt;
        dt.bodystruct = -1270491200;
        dt.headerstruct = 306916075;
        dt.id = idcounter--;
        dt.name = name;
        dt.version = 0;
        documenttypesBuilder.documenttype.push_back(dt);

        ProtonConfigBuilder::Documentdb db;
        db.inputdoctypename = name;
        db.configid = configId + "/" + name;
        db.global = isGlobal;
        protonBuilder.documentdb.push_back(db);

        DoctypeFixture::UP fixture = std::make_unique<DoctypeFixture>();
        set.addBuilder(db.configid, &fixture->attributesBuilder);
        set.addBuilder(db.configid, &fixture->rankProfilesBuilder);
        set.addBuilder(db.configid, &fixture->rankingConstantsBuilder);
        set.addBuilder(db.configid, &fixture->indexschemaBuilder);
        set.addBuilder(db.configid, &fixture->summaryBuilder);
        set.addBuilder(db.configid, &fixture->summarymapBuilder);
        set.addBuilder(db.configid, &fixture->juniperrcBuilder);
        set.addBuilder(db.configid, &fixture->importedFieldsBuilder);
        return dbConfig.emplace(std::make_pair(name, std::move(fixture))).first->second.get();
    }
Example #7
0
void hftable::prime_compatibles(const cpset& M, const map<cp,cpset>& C, map<int,cp>& P) {
    cpset done;
    bool prime = false;
    int index = 1;
    done.clear();
    int max_size = 0;
    for(auto& m : M)
        if(m.size() > max_size)
            max_size = m.size();
    for(int k = max_size; k >= 1; --k) {
        for(auto& m : M)
            if(m.size() == k)
                P.emplace(index++,m);
        for(auto& p : P) {
            if(p.second.size() == k) {
                cpset cs;
                cs.clear();
                //check if class set is empty.
                if(class_set(p.second, C).empty())
                    continue;
                for(auto& s : max_subsets(p.second)) {
                    if(done.find(s) != done.end()) {
                        continue;
                    }
                    cs = class_set(s, C);
                    prime = true;
                    map<int,cp>::iterator it1;
                    for(it1 = P.begin(); it1 != P.end(); ++it1) {
                        if(it1->second.size() >= k) {
                            if(subset(it1->second,s)) {
                                cpset cq = class_set(it1->second, C);
                                if(subset(cs,cq)) {
                                    prime = false;
                                    break;
                                }
                            }
                        }
                    }
                    if(prime) {
                        P.emplace(index++,s);
                        done.emplace(s);
                    }
                }
            }
        }
    }
}
Example #8
0
/// <summary>
/// Loads settings.
/// </summary>
void CreateCoverart(LPCTSTR name) {
  if (gCoverArt.find(name) == gCoverArt.end()) {
    gCoverArt.emplace(std::piecewise_construct, std::forward_as_tuple(name),
        std::forward_as_tuple(name));
  } else {
    ErrorHandler::Error(ErrorHandler::Level::Critical,
        L"Attempt to (re)create the already existing CoverArt %s!", name);
  }
}
// store the map from grid point offset to mask used in phase correlation peak finding
static void storeHintToMask(map<GridPtOff, Mat> &hintToMask, const Size &imSz, const Point2f &absHint, const MaxDists &dists) {
	for (int xOff = -1; xOff <= 1; xOff++) {
		for (int yOff = -1; yOff <= 1; yOff++) {
			if (!xOff && !yOff) {
				continue;
			}

			int maxDist;
			if (xOff) {
				if (yOff) {
					maxDist = dists.xy;
				} else {
					maxDist = dists.x;
				}
			} else {
				maxDist = dists.y;
			}

			Mat mask = Mat::zeros(Size(imSz.width + 2, imSz.height), CV_8UC1);

			Point baseXY(fround(absHint.x * xOff), fround(absHint.y * yOff));
			if (baseXY.x > imSz.width) {
				baseXY.x -= imSz.width;
			} else if (baseXY.x < 0) {
				baseXY.x += imSz.width;
			}
			if (baseXY.y > imSz.height) {
				baseXY.y -= imSz.height;
			} else if (baseXY.y < 0) {
				baseXY.y += imSz.height;
			}

			if (xOff) {
				if (yOff) {
					circle(mask, baseXY, maxDist, Scalar(255, 255, 255, 255), -1);
				} else {
					for (int y = baseXY.y - imSz.height; y <= baseXY.y + imSz.height; y += imSz.height) {
						circle(mask, Point(baseXY.x, y), maxDist, Scalar(255, 255, 255, 255), -1);
					}
				}
			} else {
				for (int x = baseXY.x - imSz.width; x <= baseXY.x + imSz.width; x += imSz.width) {
					circle(mask, Point(x, baseXY.y), maxDist, Scalar(255, 255, 255, 255), -1);
				}
			}

			//			Mat tmp;
			//			resize(mask, tmp, Size(), 0.4, 0.4);
			//			imshow("m", tmp);
			//			waitKey(0);

			hintToMask.emplace(makeOff(xOff, yOff), mask);
		}
	}
}
Example #10
0
/** Parses a sequence of key-value pairs of the form KEY=VALUE or KEY="VALUE".
 *  If parameter 'requireValues' is false, attributes may also consist of a key only.
 *  @param[out] attr the scanned atributes
 *  @param[in] requireValues true if all attributes require a value
 *  @param[in] quotechars recognized quote characters used to enclose the attribute values
 *  @return number of attributes scanned */
int InputReader::parseAttributes (map<string,string> &attr, bool requireValues, const char *quotechars) {
	while (!eof()) {
		string key;
		skipSpace();
		if (!isalpha(peek()))  // first character of attribute name must be a letter
			break;
		key += char(get());
		while (isalnum(peek()) || strchr("-:._", peek()))
			key += char(get());
		skipSpace();
		if (peek() == '=') {
			get();
			skipSpace();
			string val = getQuotedString(quotechars);
			attr.emplace(std::move(key), std::move(val));
		}
		else if (!requireValues)
			attr.emplace(std::move(key), "");
	}
	return attr.size();
}
Example #11
0
//************************************************************************************************
//*** mount()
//*** Called by Scilab's slMount()
//***
//************************************************************************************************
DLLIMPORT void mount ( int *handle, int *OK )
{
	*OK = 0;
	
	// In the past, the <handle>, given by the Scilab call, created exactly this handle and
	// returned 1 to <OK> if everything went fine (0 otherwise).
	// Now, we return either 0, on failure or the number of the handle created or
	// any number >0, representing the handle itself.
	// Notice that there is _no_ (practical) limit to the amount of handles serial interface
	// classes ano more. The code limit is set to 32000 8-)

	// New behaviour, 4/2014: find next free number (the hard way, for now ;-) and
	// return it as the new handle.
	// For compatibility, we first check if the requested handle number (if any)
	// is available...
	
	if(  ( *handle != 0 ) && ( mPort.find( *handle ) == mPort.end() )  )
	{
		// compatibility mode; check if requested handle is available
		mPort.emplace( *handle, new asSerial() );
		*OK = *handle;
	}
	else
	{
		// find first, free handle number >0
		// I guess, 32000 interfaces are sufficient ;-)
		for( int i=1; i<32000; ++i )
		{
			if( mPort.find( i ) == mPort.end() )
			{
				mPort.emplace( i, new asSerial() );
				*OK = i;
				break;
			}
		}// END for all possible handles
	}//END else

}// END DLLIMPORT void mount
Example #12
0
 int get(int key) 
 {
     ++op_count;
     if (map_kv.find(key) == map_kv.end()) return -1;
     else
     {
         int old_time = map_kt[key];
         map_tk.erase(map_tk.find(old_time));
         map_tk.emplace(op_count, key);
         
         map_kt[key] = op_count;
         
         return map_kv[key];
     }
 }
Example #13
0
void combine_load_costs(map<string, Expr> &result, const map<string, Expr> &partial) {
    for (const auto &kv : partial) {
        auto iter = result.find(kv.first);
        if (iter == result.end()) {
            result.emplace(kv.first, kv.second);
        } else {
            if (!iter->second.defined()) {
                continue;
            } else if (!kv.second.defined()) {
                iter->second = Expr();
            } else {
                iter->second = simplify(iter->second + kv.second);
            }
        }
    }
}
Example #14
0
static
void remapTops(const TamaInfo &tamaInfo,
               vector<u32> &top_base,
               map<pair<const NFA *, u32>, u32> &out_top_remap) {
    u32 i = 0;
    u32 cur = 0;
    for (const auto &sub : tamaInfo.subengines) {
        u32 base = cur;
        top_base.push_back(base + MQE_TOP_FIRST);
        DEBUG_PRINTF("subengine:%u\n", i);
        for (const auto &t : tamaInfo.tops[i++]) {
            cur = base + t;
            DEBUG_PRINTF("top remapping %u:%u\n", t ,cur);
            out_top_remap.emplace(make_pair(sub, t), cur++);
        }
    }
}
Example #15
0
void buildDic(map<string, string> &dic,string word){
    string key,value;
    int len = (int)word.size();
    int flag = false;
    for(int i = 0; i < len; i++){
        if(word[i] == '_'){
            flag = true;
            continue;
        }
        if(flag){
            value.push_back(word[i]);
        }else{
            key.push_back(word[i]);
        }
    }
    dic.emplace(key,value);
}
Example #16
0
namespace detail {
auto memo = [](auto f) {
    return [=](auto... args) {
        using args_t = std::tuple<decltype(args)...>;
        using return_t = decltype(f(args...));
        static map<args_t, return_t> m;

        auto argsTuple = make_tuple(args...);
        auto it = m.find(argsTuple);
        if (it != m.end()) {
            return it->second;
        }
        return m.emplace(move(argsTuple),
                         f(forward<decltype(args)>(args)...)).first->second;
    };
};
};
Example #17
0
void connect(int left, int right) {
	cout << "connect" << " " << left << " " << right << endl;

	if(left > right)
		swap(left, right);

	auto it = roads.find(make_pair(left, right));
	if(it == roads.end()) {
		auto &lc = cities[left], &rc = cities[right];
		double dx = (lc.first - rc.first), dy = (lc.first - rc.first);

		double dist = sqrt(dx * dx + dy * dy);
		Slope slope = make_pair(abs(dy), (dx * dy) > 0 ? abs(dx) : -abs(dx));
		Road road {left, right, slope, dist};

		roads.emplace(make_pair(left, right), road);	
		road_slopes[slope].emplace_front(&roads.back());
	}
}
Example #18
0
void Machine::make_rules(vector<string> rule_list)
{
    for (string rule : rule_list) {
        string before_state;
        char before_sym;
        string equals;
        string after_state;
        char after_sym;
        char dir;
        
        istringstream iss(rule);
        iss >> before_state >> before_sym >> equals
            >> after_state >> after_sym >> dir;

        tuple<string,char> before = make_tuple(before_state, before_sym);
        tuple<string,char,char> after = make_tuple(after_state, after_sym, dir);

        _rules.emplace(before, after);
    }
}
Example #19
0
	void get(const Key &key, Val &out, Func getVal) {
		if (m.count(key)) {
			auto it = m[key];
			out = it->second;
			l.push_front(*it);
			m[key] = l.begin();
			l.erase(it);
			return;
		}

		if (l.size() == sz) {
			m.erase(l.back().first);
			l.pop_back();
		}

		getVal(key, out);
		ListElem e(key, out);
		l.push_front(e);
		m.emplace(key, l.begin());
	}
Example #20
0
ode_solver::ODE_result ode_solver::solve_backward(rp_box b) {
    DREAL_LOG_INFO << "ODE_Solver::solve_backward()";
    ODE_result ret = ODE_result::SAT;
    update(b);

    static map<vector<double>, tuple<ODE_result, vector<pair<interval, IVector>>>> cache;
    vector<pair<interval, IVector>> bucket;

    if (m_config.nra_ODE_cache) {
        // Check Cache
        vector<double> currentXtT = extract_XtT(b);
        auto cache_it = cache.find(currentXtT);
        if (cache_it != cache.end()) {
            // HIT
            g_hit++;
            ODE_result cached_ret = get<0>(cache_it->second);
            if (cached_ret == ODE_result::UNSAT ||
                cached_ret == ODE_result::EXCEPTION ||
                cached_ret == ODE_result::TIMEOUT) {
                return cached_ret;
            }
            bucket = get<1>(cache_it->second);
        } else {
            // NoHit
            g_nohit++;
            // Compute
            ret = compute_backward(bucket);
            // Save to cache
            cache.emplace(currentXtT, make_tuple(ret, bucket));
        }
    } else {
        ret = compute_backward(bucket);
    }
    if (ret == ODE_result::SAT) {
        return prune_backward(bucket);
    } else {
        return ret;
    }
}
Example #21
0
/** Merge the group of graphs in \p cluster where possible. The (from, to)
 * mapping of merged graphs is returned in \p merged. */
void mergeNfaCluster(const vector<NGHolder *> &cluster,
                     const ReportManager *rm,
                     map<NGHolder *, NGHolder *> &merged,
                     const CompileContext &cc) {
    if (cluster.size() < 2) {
        return;
    }

    DEBUG_PRINTF("new cluster, size %zu\n", cluster.size());
    merged.clear();

    priority_queue<NfaMergeCandidateH> pq;
    buildNfaMergeQueue(cluster, &pq);

    while (!pq.empty()) {
        NGHolder &pholder = *pq.top().first;
        NGHolder &vholder = *pq.top().second;
        pq.pop();

        if (contains(merged, &pholder) || contains(merged, &vholder)) {
            DEBUG_PRINTF("dead\n");
            continue;
        }

        if (!mergeNfaPair(vholder, pholder, rm, cc)) {
            DEBUG_PRINTF("merge failed\n");
            continue;
        }

        merged.emplace(&vholder, &pholder);

        // Seek closure.
        for (auto &m : merged) {
            if (m.second == &vholder) {
                m.second = &pholder;
            }
        }
    }
}
Example #22
0
File: main.cpp Project: CCJY/coliru
bool CMailBox::NewFolder( const string &folderName ) {
    auto res = m_Mails.emplace( folderName, list<CMail>() );
    
    return res.second;
}
Example #23
0
 int operator()(int i) {
   if (mp.count(i) == 0) {
     mp.emplace(i, mp.size());
   }
   return mp[i];
 }
Example #24
0
		void
		addXrefEntry(int objID)
		{
			xrefEntries.emplace(objID, out.tellp());
		}
Example #25
0
void Timing::start(TimingAction action) {
    timepoint now = chrono::high_resolution_clock::now();
    assert(TimingLast.count(action) == 0);
    TimingLast.emplace(action,now);
}
Example #26
0
		// 去Epsilon边的算法。
		Automaton::Ref EpsilonNfaToNfa(Automaton::Ref source, 
									   bool(*epsilonChecker)(Transition *), 
									   map<State*, State*>& nfaStateMap)
		{
			Automaton::Ref target = shared_ptr<Automaton>(new Automaton);
			map<State*, State*> stateMap;	//source->target
			vector<State*> epsilonStates;	//每次迭代当前状态的epsilon闭包
			vector<Transition*> transitions;//每次迭代当前状态的epsilon闭包的转换集合

			// target 一开始是空的。
			stateMap.emplace(source->startState, target->NewState());
			// target里新建一个结点,对应source里的开始结点
			nfaStateMap.emplace(stateMap[source->startState], source->startState);
			// 跟stateMap是反着的
			target->startState = target->states[0].get();// 这个把刚刚建的结点命名赋给开始结点


			// 一开始只有一个开始结点。
			// 每次只要考虑一个结点的闭包。
			for (int i = 0;i < target->states.size();i++)
			{
				//清空epsilonStates并包含自己
				State* targetState = target->states[i].get();
				State* sourceState = nfaStateMap[targetState];
				if (sourceState->finalState)
				{
					targetState->finalState = true;
				}
				// 每次迭代,清空。来存epsilon边的闭包
				epsilonStates.clear();// 找出来的epsilon状态的结合
				transitions.clear(); // 当前结点的边的集合

				// 对所有产生的epsilonStates进行遍历,计算出该状态的一次epsilon直接目标加进去,
				// 并继续迭代
				CollectEpsilon(targetState, sourceState, epsilonChecker, epsilonStates, transitions);

				//遍历所有epsilon闭包转换
				for (int j = 0;j < transitions.size();j++)
				{
					Transition* transition = transitions[j];
					// 当发现找到的这个结点,不在stateMap里的时候。
					// 就把这个结点,加到stateMap里面去。
					// 然后,状态机里也新建一个结点,下次循环要用的,但是这个结点的信息是空的
					// 其实每次迭代的当前结点,信息都是空的
					// 寻找到一个非epsilon闭包的时候更新映射
					if (stateMap.find(transition->target)==stateMap.end())
					{
						stateMap.emplace(transition->target, target->NewState());
						nfaStateMap.emplace(stateMap[transition->target], transition->target);
					}
					//将该转换复制到新状态机里
					Transition* newTransition = target->NewTransition(targetState, stateMap
																	  [transition->target]);
					// 从当前结点指向,找到的带字符边的结点

					// 下面就是把边的剩余的信息都复制过去
					newTransition->range = transition->range;
					newTransition->type = transition->type;

					// 一次迭代,完成的工作有,找出当前结点的非epsilon闭包
					// 新建对应的空的结点,建立它们和空结点的映射,并把空的
					// 结点加到新的状态机里的States集合里,下次迭代要用的时候,
					// 就可以用映射关系取出来
				}
			}
			return target;
		}
Example #27
0
int main(int argc,char *argv[])
{
    //Seed RNG
    srand(time(NULL));
    //get socket
    listenfd = socket(AF_INET, SOCK_STREAM, 0);
    if (listenfd == -1)
        err(1, "socket");
    int g = 1;

    signal(SIGPIPE, SIG_IGN);
    //ignore sigpipes
    setsockopt(listenfd,SOL_SOCKET,SO_REUSEADDR,&g,sizeof(int));
    //force drop other applications on the same port
    //fcntl(listenfd, F_SETFL, O_NONBLOCK);

    memset(&serv_addr, '0', sizeof(serv_addr));

    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    serv_addr.sin_port = htons(6667);

    if (bind(listenfd, (struct sockaddr*)&serv_addr,sizeof(serv_addr)) == -1)
        err(1, "bind to port %d", ntohs(serv_addr.sin_port));

    if(listen(listenfd, 10) == -1){
        printf("Failed to listen\n");
        return -1;
    }
    thread z(ControlServer);
    z.detach();
    //again  because we spawned a thread
    signal(SIGPIPE, SIG_IGN);

    while(true)
    {
        {
            mutex_guard lock(connections_mutex);

            auto dead_connections = std::remove_if(connections.begin(), connections.end(),
                        [&](User const *u){ return u->dead; });
            for (auto it = dead_connections; it != connections.end(); it++)
                delete *it;
            connections.erase(dead_connections, connections.end());

            for (User *puser : connections)
            {
                User &user = *puser;
                string command_str = user.try_read();
                if (user.dead) continue;

                chop_newline_off(command_str);
                vector<string> command = parse_irc_command(command_str);
                if (!command.empty())
                {
                    cout << "\033[91m← " << user.username << "\t" << command_str << "\033[m" << endl;
                    if(command[0] == "USER")
                    {
                        //stub incase anyone wants to implement authentication
                    }
                    else if(command[0] == "PING")
                    {
                        user.write(":tinyirc PONG :" + command[1] + "\r\n");
                    }
                    else if(command[0] == "PONG" && user.status != User::ConnectStatus::NICKSET)
                    {
                        //reset anti-drop
                        user.dontkick = true;
                        user.rticks = 0;
                    }
                    else if(command[0] == "PONG" && user.status == User::ConnectStatus::NICKSET)
                    {
                        //oh nice, you accepted our PING, welcome to the party
                        user.write(":tinyirc 001 " + user.username + " :Hello!" + "\r\n");
                        user.write(":tinyirc 002 " + user.username + " :This server is running TinyIRC pre-alpha!" + "\r\n");
                        user.write(":tinyirc 003 " + user.username + " :This server doesn't have date tracking." + "\r\n");
                        user.write(":tinyirc 004 " + user.username + " tinyirc " + " tinyirc(0.0.1) " + "CDGNRSUWagilopqrswxyz" + " BCIMNORSabcehiklmnopqstvz" + " Iabehkloqv" + "\r\n");
                        user.write(":tinyirc 005 " + user.username + " CALLERID CASEMAPPING=rfc1459 DEAF=D KICKLEN=180 MODES=4 PREFIX=(qaohv)~&@%+ STATUSMSG=~&@%+ EXCEPTS=e INVEX=I NICKLEN=30 NETWORK=tinyirc MAXLIST=beI:250 MAXTARGETS=4 :are supported by this server\r\n");
                        user.write(":tinyirc 005 " + user.username + " CHANTYPES=# CHANLIMIT=#:500 CHANNELLEN=50 TOPICLEN=390 CHANMODES=beI,k,l,BCMNORScimnpstz AWAYLEN=180 WATCH=60 NAMESX UHNAMES KNOCK ELIST=CMNTU SAFELIST :are supported by this server\r\n");
                        user.write(":tinyirc 251 " + user.username + " :LUSERS is unimplemented." + "\r\n");
                        user.status = User::ConnectStatus::READY;

                        user.dontkick = true;
                    }
                    else if(command[0] == "NICK")
                    {
                        string new_nick = remove_erase_if(command[1], ".,#\r");
                        if(new_nick.size() > 225 || new_nick.size() == 0)
                            new_nick = "F****T" + to_string(rand() % 9000);

                        bool inuse = false;
                        if (usersbyname.find(new_nick) != usersbyname.end())
                            inuse = true;

                        //if not authed, set username and PING, else set username
                        if(user.status == User::ConnectStatus::CONNECTED)
                        {
                            user.username = new_nick;
                            if(inuse)
                            {
                                user.kill("Nick already in use");
                                continue;
                            }
                            user.write("PING :" + user.username + "\r\n");
                            user.status = User::ConnectStatus::NICKSET;
                            usersbyname[new_nick] = &user;
                        }
                        else
                        {
                            if(inuse)
                                user.write(":tinyirc " "NOTICE :*** Name already in use..." "\r\n");
                            else
                            {
                                // Update nick in all channels
                                for (string const &channelname : user.channel)
                                {
                                    Channel &channel = channels.at(channelname);
                                    channel.users.erase(user.username);
                                    channel.users.insert(new_nick);
                                }
                                usersbyname[new_nick] = &user;
                                usersbyname.erase(user.username);
                                user.broadcast(":" + user.username + " NICK " + new_nick + "\r\n");
                                user.username = new_nick;
                            }
                        }
                    }
                    else if(command[0] == "JOIN")
                    {
                        string channame = command[1];
                        // TODO handle comma separated chan joins?
                        channame = remove_erase_if(channame,":,. \r");
                        if(channame [0] != '#')
                            channame.insert(0,"#");

                        Channel &channel = channels.emplace(piecewise_construct, forward_as_tuple(channame), forward_as_tuple(channame)).first->second;
                        user.channel.insert(channame);
                        channel.users.insert(user.username);
                        channel.broadcast(":" + user.username + " JOIN " + channame + "\r\n");
                        user.write(":tinyirc MODE :" + channame + " +n" + "\r\n");
                        user.write(":tinyirc 332 " + user.username + " " + channame +  " :" + channel.topic + "\r\n");
                        string msgf(":tinyirc 353 " + user.username + " = " + channame + " :");
                        for(string const &chanuser : channel.users)
                        {
                            msgf += chanuser;
                            msgf += " ";
                        }
                        msgf.erase(msgf.end() - 1);
                        msgf += "\r\n";
                        user.write(msgf);
                        user.write(":tinyirc 366 " + user.username + " " + channame + " :Sucessfully joined channel." +"\r\n");
                    }
                    else if(command[0] == "TOPIC")
                    {
                        auto channel_iter = channels.find(command[1]);
                        if (channel_iter == channels.end())
                        {
                            user.write(":tinyirc 403 " + user.username + " " + command[1] + " :No such channel\r\n");
                        }
                        else
                        {
                            Channel &channel = channel_iter->second;
                            if (command.size() > 2)
                            {
                                channel.topic = command[2];
                                channel.broadcast(":" + user.username + " TOPIC " + command[1] + " :" + command[2] + "\r\n");
                            }
                            else
                            {
                                user.write(":tinyirc 332 " + user.username + " " + command[1] + " :" + channel.topic + "\r\n");
                            }
                        }
                    }
                    else if(command[0] == "PRIVMSG")
                    {
                        //send privmsg to all other users in channel
                        // TODO: warning if channel/user doesn't exist
                        string recip = command[1];
                        string msg = command[2];
                        if (recip.size() == 0) break;

                        string buf(":" + user.username + " PRIVMSG " + recip + " :" + msg + "\r\n");
                        try
                        {
                            if (recip[0] == '#')
                                for (string username : channels.at(recip).users)
                                {
                                    User *chanuser = usersbyname.at(username);
                                    if (&user != chanuser)
                                        usersbyname.at(username)->write(buf);
                                }
                            else
                                usersbyname.at(recip)->write(buf);
                        }
                        catch (out_of_range e)
                        {
                           user.write(":tinyirc 401 " + user.username + " " + recip + " :No such nick/channel\r\n");
                        }
                    }
                    else if(command[0] == "MODE")
                    {
                        //set user mode, required for some irc clients to think you're fully connected(im looking at you xchat)
                        //+i means no messages from people outside the channel and that mode reflects how the server works
                        string const& channel = command[1];
                        if(user.channel.size() != 0)
                        {
                            user.write(":tinyirc 324 " + user.username + " " + channel + " +n" + "\r\n");
                            user.write(":tinyirc 329 " + user.username + " " + channel + " 0 0" + "\r\n");
                        }
                        else
                        {
                            user.detectautisticclient = true;
                            user.write(":" + user.username + " MODE " + user.username + " :+i" + "\r\n");
                        }
                    }
                    else if(command[0] == "WHO")
                    {
                        auto const channel_iter = channels.find(command[1]);
                        if (channel_iter != channels.end())
                            for(string const &chanuser : channel_iter->second.users)
                                user.write(":tinyirc 352 " + user.username + " " + command[1] + " tinyirc " + chanuser + "\r\n");
                        user.write(":tinyirc 315 " + user.username + " " + command[1] + " :End of /WHO list.\r\n");
                    }
                    else if(command[0] == "QUIT")
                    {
                        user.kill("Quit");
                    }
                    else if(command[0] == "PART")
                    {
                        vector<string> ctol;
                        split_string(string(command[1]),",",ctol);
                        string reason = command.size() > 2 ? command[2] : "Leaving";

                        for (string &chantopart : ctol)
                        {
                            auto channeliter = channels.find(chantopart);
                            if (channeliter == channels.end())
                                continue; // Don't part a channel that doesn't exist

                            Channel &channel = channeliter->second;
                            channel.notify_part(user, reason);
                            channel.remove_user(user);
                        }
                    }
                    else if(command[0] == "PROTOCTL")
                    {
                        //gives capabilities of the server, some irc clients dont send one for some reason (im looking at you two irssi and weechat)
                        user.write(":tinyirc 252 " + user.username + " 0 :IRC Operators online" + "\r\n");
                        user.write(":tinyirc 253 " + user.username + " 0 :unknown connections" + "\r\n");
                        user.write(":tinyirc 254 " + user.username + " 0 :LUSERS is unimplmented" + "\r\n");
                        user.write(":tinyirc 255 " + user.username + " :LUSERS is unimplmented" + "\r\n");
                        user.write(":tinyirc 265 " + user.username + " 1 1 :LUSERS is unimplmented" + "\r\n");
                        user.write(":tinyirc 266 " + user.username + " 1 1 :LUSERS is unimplmented" + "\r\n");
                        user.write(":tinyirc 375 " + user.username + " 1 1 :Welcome to tinyirc pre-alpha!" + "\r\n");
                        user.write(":tinyirc 372 " + user.username + " :Padding call" + "\r\n");
                        user.write(":tinyirc 376 " + user.username + " :Ended" + "\r\n");
                        if(!user.detectautisticclient)
                            user.write(":" + user.username + " MODE " + user.username + " :+i" + "\r\n");
                    }
                    else
                    {
                        user.write(":tinyirc 421 " + user.username + " " + command[0] + " :Unknown command\r\n");
                    }
                }

                if(!user.dontkick)
                    user.rticks++;
                if(!user.dontkick && user.rticks == 192)
                {
                    user.kill("Ping timed out");
                    continue;
                }
                if(rand() % 480 == 42 && user.status == User::ConnectStatus::READY)
                {
                    string buf = "PING :" + user.username + "\r\n";
                    send(user.connfd,buf.c_str(),buf.size(),MSG_NOSIGNAL);
                    user.dontkick = false;
                }
            }
        }
        connections_mutex.lock();
        pollfd *pollfds = new pollfd[connections.size() + 1];
        pollfds[0].fd = listenfd;
        pollfds[0].events = POLLIN;
        int i = 1;
        for (User *user : connections)
        {
            pollfds[i].fd = user->connfd;
            pollfds[i].events = POLLIN;
            i++;
        }
        connections_mutex.unlock();

        poll(pollfds, i, 30000);

        if (pollfds[0].revents & POLLIN)
        {
            int connfd = accept(listenfd, nullptr, nullptr);
            if(connfd != -1)
            {
                mutex_guard lock(connections_mutex);
                connections.push_back(new User(connfd)); // accept awaiting request
            }
        }
        delete[] pollfds;
    }
    return 0;
}
Example #28
0
		void addStyle(string name, shared_ptr<Style> style)
		{
			styles.emplace(name, style);
		}
Example #29
0
 void pin(K key, V val) {
   Mutex::Locker l(lock);
   pinned.emplace(std::move(key), std::move(val));
 }
Example #30
0
int main(){
	try{
		PopulateFromGraph(model, s, c);

		model.add(IloMinimize(env, s[n]));

		c.add(s[1] - s[0] >= T);
		c.add(s[3] - s[2] >= T);
		c.add(s[4] - s[1] >= T);
		c.add(s[5] - s[3] >= T);
		c.add(s[6] - s[4] >= T);
		c.add(s[7] - s[5] >= T);
		c.add(s[8] - s[6] >= T);
		c.add(s[9] - s[7] >= T);
		c.add(s[10] - s[8] >= T);
		c.add(s[11] - s[9] >= T);
		c.add(s[n] - s[10] >= 0); //OUTPUT
		c.add(s[n] - s[11] >= 0); //OUTPUT


		BoolVarMatrix Y(env, E);
		Create2DArray(model, Y);

		IloExprArray sum2(env); 

		sum2.add(IloExpr(env));
		for(int t = 0; t < T_MAX; t++){
			Y[0].add(IloBoolVar(env));
			sum2[0] +=  Y[0][t];
			c.add( t - (s[0] + T) - T_MAX*(Y[0][t]-1)  >= 0);
			c.add(-t +  s[1]      - T_MAX*(Y[0][t]-1)  >= 1);
		}
		c.add(sum2[0] - (s[1]-(s[0]+T)) == 0);

		sum2.add(IloExpr(env));
		for(int t = 0; t < T_MAX; t++){
			Y[1].add(IloBoolVar(env));
			sum2[1] +=  Y[1][t];
			c.add( t - (s[2] + T) - T_MAX*(Y[1][t]-1)  >= 0);
			c.add(-t +  s[3]      - T_MAX*(Y[1][t]-1)  >= 1);
		}
		c.add(sum2[1] - (s[3]-(s[2]+T)) == 0);

		sum2.add(IloExpr(env));
		for(int t = 0; t < T_MAX; t++){
			Y[2].add(IloBoolVar(env));
			sum2[2] +=  Y[2][t];
			c.add( t - (s[1] + T) - T_MAX*(Y[2][t]-1)  >= 0);
			c.add(-t +  s[4]      - T_MAX*(Y[2][t]-1)  >= 1);
		}
		c.add(sum2[2] - (s[4]-(s[1]+T)) == 0);

		sum2.add(IloExpr(env));
		for(int t = 0; t < T_MAX; t++){
			Y[3].add(IloBoolVar(env));
			sum2[3] +=  Y[3][t];
			c.add( t - (s[3] + T) - T_MAX*(Y[3][t]-1)  >= 0);
			c.add(-t +  s[5]      - T_MAX*(Y[3][t]-1)  >= 1);
		}
		c.add(sum2[3] - (s[5]-(s[3]+T)) == 0);

		sum2.add(IloExpr(env));
		for(int t = 0; t < T_MAX; t++){
			Y[4].add(IloBoolVar(env));
			sum2[4] +=  Y[4][t];
			c.add( t - (s[4] + T) - T_MAX*(Y[4][t]-1)  >= 0);
			c.add(-t +  s[6]      - T_MAX*(Y[4][t]-1)  >= 1);
		}
		c.add(sum2[4] - (s[6]-(s[4]+T)) == 0);

		sum2.add(IloExpr(env));
		for(int t = 0; t < T_MAX; t++){
			Y[5].add(IloBoolVar(env));
			sum2[5] +=  Y[5][t];
			c.add( t - (s[5] + T) - T_MAX*(Y[5][t]-1)  >= 0);
			c.add(-t +  s[7]      - T_MAX*(Y[5][t]-1)  >= 1);
		}
		c.add(sum2[5] - (s[7]-(s[5]+T)) == 0);

		sum2.add(IloExpr(env));
		for(int t = 0; t < T_MAX; t++){
			Y[6].add(IloBoolVar(env));
			sum2[6] +=  Y[6][t];
			c.add( t - (s[6] + T) - T_MAX*(Y[6][t]-1)  >= 0);
			c.add(-t +  s[8]      - T_MAX*(Y[6][t]-1)  >= 1);
		}
		c.add(sum2[6] - (s[8]-(s[6]+T)) == 0);

		sum2.add(IloExpr(env));
		for(int t = 0; t < T_MAX; t++){
			Y[7].add(IloBoolVar(env));
			sum2[7] +=  Y[7][t];
			c.add( t - (s[7] + T) - T_MAX*(Y[7][t]-1)  >= 0);
			c.add(-t +  s[9]      - T_MAX*(Y[7][t]-1)  >= 1);
		}
		c.add(sum2[7] - (s[9]-(s[7]+T)) == 0);

		sum2.add(IloExpr(env));
		for(int t = 0; t < T_MAX; t++){
			Y[8].add(IloBoolVar(env));
			sum2[8] +=  Y[8][t];
			c.add( t - (s[8] + T) - T_MAX*(Y[8][t]-1)  >= 0);
			c.add(-t +  s[10]      - T_MAX*(Y[8][t]-1)  >= 1);
		}
		c.add(sum2[8] - (s[10]-(s[8]+T)) == 0);

		sum2.add(IloExpr(env));
		for(int t = 0; t < T_MAX; t++){
			Y[9].add(IloBoolVar(env));
			sum2[9] +=  Y[9][t];
			c.add( t - (s[9] + T) - T_MAX*(Y[9][t]-1)  >= 0);
			c.add(-t +  s[11]      - T_MAX*(Y[9][t]-1)  >= 1);
		}
		c.add(sum2[9] - (s[11]-(s[9]+T)) == 0);

		BoolVarMatrix X(env, n);
		Create2DArray(model, X);
		CreateSchedulingConstraint(model, X, Y, s, c);

		BoolVarMatrix M(env, n_m);
		Create2DArray(model, M);
		CreateMixingBindingConstraint(model, M, Y, X, s, c);

		BoolVar3DMatrix L(env, n_m);
		Create3DArray(model, L, n);
		BoolVar3DMatrix R(env, n_m);
		Create3DArray(model, R, E);
		CreateStorageBindingConstraint(model, L,  M, X, R, Y, c);

		model.add(c);

		cplex.exportModel("../../model/BS.lp");
		cplex.solve();

		env.out() << "Status: " << cplex.getStatus();

		start_time.emplace("O1", 0);
		start_time.emplace("O3", 1);
		start_time.emplace("O2", 2);
		start_time.emplace("O4", 3);
		start_time.emplace("O3", 4);
		start_time.emplace("O5", 4);
		start_time.emplace("O4", 5);
		start_time.emplace("O6", 5);
		start_time.emplace("O5", 6);
		start_time.emplace("O7", 6);
		start_time.emplace("O6", 7);
		start_time.emplace("O8", 7);
		start_time.emplace("O7", 8);
		start_time.emplace("O9", 8);
		start_time.emplace("O8", 9);
		start_time.emplace("O10", 9);
		start_time.emplace("O9", 10);
		start_time.emplace("O11", 10);
		start_time.emplace("O10", 11);
		start_time.emplace("O12", 11);
		start_time.emplace("O11", 12);
		start_time.emplace("O12", 12);

		edge.first = 0;
		edge.second = 1;
		edges.emplace_back(edge);
		edge.first = 2;
		edge.second = 3;
		edges.emplace_back(edge);
		edge.first = 1;
		edge.second = 4;
		edges.emplace_back(edge);
		edge.first = 3;
		edge.second = 5;
		edges.emplace_back(edge);
		edge.first = 4;
		edge.second = 6;
		edges.emplace_back(edge);
		edge.first = 5;
		edge.second = 7;
		edges.emplace_back(edge);
		edge.first = 6;
		edge.second = 8;
		edges.emplace_back(edge);
		edge.first = 7;
		edge.second = 9;
		edges.emplace_back(edge);
		edge.first = 8;
		edge.second = 10;
		edges.emplace_back(edge);
		edge.first = 9;
		edge.second = 11;
		edges.emplace_back(edge);
		edge.first = 10;
		edge.first = 11;

		PrintResults(s, M, R, cplex);
	} 
	catch(IloException& e){ 
		cerr << "Error: " << e << endl; 
	} 
	catch(...){
		cerr << "Unknown" << endl;
	}
	env.end();
	return 0;
}