Beispiel #1
0
// Attempts to add the parameterized function to the formation,
// returning true if successful, false otherwise.
bool Formation::addFunction(const Function f)
{
    if (f == NULL) return false;
    push_back(f);
    return true;
}
Beispiel #2
0
 inline list_inserter< assign_detail::call_push_back< std::deque<V,A> >, V > 
 operator+=( std::deque<V,A>& c, V2 v )
 {
     return push_back( c )( v );
 }
bool CModules::LoadModule(const CString& sModule, const CString& sArgs, CUser* pUser, CString& sRetMsg) {
	sRetMsg = "";

	if (FindModule(sModule) != NULL) {
		sRetMsg = "Module [" + sModule + "] already loaded.";
		return false;
	}

	bool bSuccess;
	GLOBALMODULECALL(OnModuleLoading(sModule, sArgs, bSuccess, sRetMsg), pUser, NULL, return bSuccess);

	CString sModPath, sDataPath;
	CString sDesc;
	bool bVersionMismatch;
	bool bIsGlobal;

	if (!FindModPath(sModule, sModPath, sDataPath)) {
		sRetMsg = "Unable to find module [" + sModule + "]";
		return false;
	}

	ModHandle p = OpenModule(sModule, sModPath, bVersionMismatch, bIsGlobal, sDesc, sRetMsg);

	if (!p)
		return false;

	if (bVersionMismatch) {
		dlclose(p);
		return false;
	}

	if ((pUser == NULL) != bIsGlobal) {
		dlclose(p);
		sRetMsg = "Module [" + sModule + "] is ";
		sRetMsg += (bIsGlobal) ? "" : "not ";
		sRetMsg += "a global module.";
		return false;
	}

	CModule* pModule = NULL;

	if (pUser) {
		typedef CModule* (*fp)(ModHandle, CUser* pUser,
				const CString& sModName, const CString& sDataPath);
		fp Load = (fp) dlsym(p, "ZNCModLoad");

		if (!Load) {
			dlclose(p);
			sRetMsg = "Could not find ZNCModLoad() in module [" + sModule + "]";
			return false;
		}

		pModule = Load(p, pUser, sModule, sDataPath);
	} else {
		typedef CModule* (*fp)(ModHandle, const CString& sModName,
				const CString& sDataPath);
		fp Load = (fp) dlsym(p, "ZNCModLoad");

		if (!Load) {
			dlclose(p);
			sRetMsg = "Could not find ZNCModLoad() in module [" + sModule + "]";
			return false;
		}

		pModule = Load(p, sModule, sDataPath);
	}

	pModule->SetDescription(sDesc);
	pModule->SetGlobal(bIsGlobal);
	pModule->SetArgs(sArgs);
	pModule->SetModPath(CDir::ChangeDir(CZNC::Get().GetCurPath(), sModPath));
	push_back(pModule);

	bool bLoaded;
	try {
		bLoaded = pModule->OnLoad(sArgs, sRetMsg);
	} catch (CModule::EModException) {
		bLoaded = false;
		sRetMsg = "Caught an exception";
	}

	if (!bLoaded) {
		UnloadModule(sModule, sModPath);
		if (!sRetMsg.empty())
			sRetMsg = "Module [" + sModule + "] aborted: " + sRetMsg;
		else
			sRetMsg = "Module [" + sModule + "] aborted.";
		return false;
	}

	if (!sRetMsg.empty()) {
		sRetMsg = "Loaded module [" + sModule + "] [" + sRetMsg + "] [" + sModPath + "]";
	} else {
		sRetMsg = "Loaded module [" + sModule + "] [" + sModPath + "]";
	}
	return true;
}
Beispiel #4
0
void StringList::insert( AutoStr2 * pDir )
{
    push_back( pDir );
    sort();
}
Beispiel #5
0
void QSoundManagerSounds::add(CWaveFile *waveFile, int iChannel, CEndTalkerFn endFn, TTtalker *talker) {
    push_back(new QSoundManagerSound(waveFile, iChannel, endFn, talker));
}
Beispiel #6
0
bool CModules::LoadModule(const CString& sModule, const CString& sArgs, CModInfo::EModuleType eType, CUser* pUser, CIRCNetwork *pNetwork, CString& sRetMsg) {
	sRetMsg = "";

	if (FindModule(sModule) != NULL) {
		sRetMsg = "Module [" + sModule + "] already loaded.";
		return false;
	}

	bool bSuccess;
	_GLOBALMODULECALL(OnModuleLoading(sModule, sArgs, eType, bSuccess, sRetMsg), pUser, pNetwork, NULL, return bSuccess);

	CString sModPath, sDataPath;
	bool bVersionMismatch;
	CModInfo Info;

	if (!FindModPath(sModule, sModPath, sDataPath)) {
		sRetMsg = "Unable to find module [" + sModule + "]";
		return false;
	}

	ModHandle p = OpenModule(sModule, sModPath, bVersionMismatch, Info, sRetMsg);

	if (!p)
		return false;

	if (bVersionMismatch) {
		dlclose(p);
		sRetMsg = "Version mismatch, recompile this module.";
		return false;
	}

	if (!Info.SupportsType(eType)) {
		dlclose(p);
		sRetMsg = "Module [" + sModule + "] does not support module type ["
			+ CModInfo::ModuleTypeToString(eType) + "].";
		return false;
	}

	if (!pUser && eType == CModInfo::UserModule) {
		dlclose(p);
		sRetMsg = "Module [" + sModule + "] requires a user.";
		return false;
	}

	if (!pNetwork && eType == CModInfo::NetworkModule) {
		dlclose(p);
		sRetMsg = "Module [" + sModule + "] requires a network.";
		return false;
	}

	CModule* pModule = Info.GetLoader()(p, pUser, pNetwork, sModule, sDataPath);
	pModule->SetDescription(Info.GetDescription());
	pModule->SetType(eType);
	pModule->SetArgs(sArgs);
	pModule->SetModPath(CDir::ChangeDir(CZNC::Get().GetCurPath(), sModPath));
	push_back(pModule);

	bool bLoaded;
	try {
		bLoaded = pModule->OnLoad(sArgs, sRetMsg);
	} catch (CModule::EModException) {
		bLoaded = false;
		sRetMsg = "Caught an exception";
	}

	if (!bLoaded) {
		UnloadModule(sModule, sModPath);
		if (!sRetMsg.empty())
			sRetMsg = "Module [" + sModule + "] aborted: " + sRetMsg;
		else
			sRetMsg = "Module [" + sModule + "] aborted.";
		return false;
	}

	if (!sRetMsg.empty()) {
		sRetMsg += "[" + sRetMsg + "] ";
	}
	sRetMsg += "[" + sModPath + "]";
	return true;
}
Beispiel #7
0
 static void call(utree const& val, utree& attr)
 {
     push_back(attr, val);
 }
Beispiel #8
0
Sudoku SudokuSolver::solve_impl(const Sudoku& sudoku, bool randomized) const {
  if (!sudoku.is_valid()) {
    throw std::runtime_error("solve(): Invalid sudoku");
  }

  const SudokuType& type = sudoku.type();
  unsigned n = type.n();
  auto pack = [&](unsigned a, unsigned b) -> unsigned { return a * n + b; };
  auto id_cell = [&](unsigned x, unsigned y) -> unsigned { return pack(x, y); };
  auto id_col = [&](unsigned x, unsigned d) -> unsigned { return type.size() + pack(x, d); };
  auto id_row = [&](unsigned y, unsigned d) -> unsigned { return 2 * type.size() + pack(y, d); };
  auto id_region = [&](unsigned i, unsigned d) -> unsigned { return 3 * type.size() + pack(i, d); };

  std::vector<unsigned> cell_taken(type.size());
  std::vector<unsigned> col_taken(type.size());
  std::vector<unsigned> row_taken(type.size());
  std::vector<unsigned> region_taken(type.size());
  for (unsigned i = 0; i < type.size(); ++i) {
    if (sudoku[i] != 0) {
      unsigned x = i % n;
      unsigned y = i / n;
      unsigned d = sudoku[i] - 1;
      ++cell_taken[pack(x, y)];
      ++col_taken[pack(x, d)];
      ++row_taken[pack(y, d)];
      ++region_taken[pack(type.region(x, y), d)];
    }
  }

  std::vector<std::vector<unsigned>> matrix;
  for (unsigned i = 0; i < n; ++i) {
    for (unsigned j = 0; j < n; ++j) {
      if (cell_taken[pack(i, j)]) matrix.push_back({id_cell(i, j)});
      if (col_taken[pack(i, j)]) matrix.push_back({id_col(i, j)});
      if (row_taken[pack(i, j)]) matrix.push_back({id_row(i, j)});
      if (region_taken[pack(i, j)]) matrix.push_back({id_region(i, j)});
    }
  }

  std::unordered_map<unsigned, unsigned> row_position, row_digit;
  for (unsigned y = 0; y < n; ++y) {
    for (unsigned x = 0; x < n; ++x) {
      for (unsigned d = 0; d < n; ++d) {
        if (cell_taken[pack(x, y)]
            || col_taken[pack(x, d)]
            || row_taken[pack(y, d)]
            || region_taken[pack(type.region(x, y), d)])
        {
          continue;
        }
        unsigned row_index = matrix.size();
        row_position[row_index] = y * n + x;
        row_digit[row_index] = d;
        matrix.push_back({
          id_cell(x, y),
          id_col(x, d),
          id_row(y, d),
          id_region(type.region(x, y), d)
        });
      }
    }
  }

  AlgorithmDLX dlx(ExactCoverProblem(4 * type.size(), matrix));
  auto options = AlgorithmDLX::Options();
  if (randomized) {
    static std::random_device rd;
    static auto engine = std::mt19937(rd());
    options.choose_random_column = randomized;
    options.random_engine = &engine;
  }
  options.max_solutions = randomized ? 1 : 2;
  auto result = dlx.search(options);
  auto solutions = std::vector<Sudoku>();
  for (const auto& rows : result.solutions) {
    Sudoku solved(sudoku);
    for (auto i : rows) {
      auto pos = row_position.find(i);
      if (pos != row_position.end()) {
        solved[pos->second] = row_digit[i] + 1;
      }
    }
    solutions.push_back(std::move(solved));
  }

  if (solutions.empty()) {
    throw std::runtime_error("No solution");
  }
  if (solutions.size() > 1) {
    throw std::runtime_error("Multiple solutions");
  }
  return solutions[0];
}
Beispiel #9
0
void
add_base_prop_view(
	UI::ObjectView& object_view,
	unsigned const index
) {
	auto const root = object_view.root();
	auto& session = object_view.m_session;
	auto& object = object_view.m_object;

	// Slug property
	auto field_slug = UI::Field::make(root, object.slug());
	auto& field_slug_ref = *field_slug;
	field_slug->geometry().set_sizing(UI::Axis::horizontal, UI::Axis::horizontal);
	UI::bind_field_describer(field_slug, "slug");
	field_slug->signal_user_modified.bind([&session, &object](
		UI::Field::SPtr const& field_slug,
		bool const accept
	) {
		if (accept) {
			// NB: signal_notify_command handles result
			Hord::Cmd::Object::SetSlug{session}(
				object, field_slug->text()
			);
		} else {
			field_slug->set_text(object.slug());
		}
	});

	// Metadata property
	auto grid_metadata = UI::TableGrid::make(
		root, session, object,
		object.metadata().table()
	);
	auto& grid_metadata_ref = *grid_metadata;
	grid_metadata->signal_event_filter.bind([&session, &object, &grid_metadata_ref](
		UI::Widget::SPtr const& widget,
		UI::Event const& event
	) -> bool {
		if (grid_metadata_ref.has_input_control()) {
			return false;
		} else if (event.type != UI::EventType::key_input) {
			return s_grid_metadata_describer(widget, event);
		}
		auto const* kim_match = key_input_match(event.key_input, s_kim_erase_metafield);
		if (kim_match) {
			Hord::Cmd::Object::RemoveMetaField c_remove{session};
			if (grid_metadata_ref.row_count() <= 0) {
				return false;
			}
			if (&s_kim_erase_metafield[0] != kim_match) {
				c_remove(object, grid_metadata_ref.m_cursor.row);
			}
			for (signed index = grid_metadata_ref.row_count() - 1; index >= 0; --index) {
				if (grid_metadata_ref.m_sel[index]) {
					c_remove(object, index);
				}
			}
			return true;
		} else if (event.key_input.cp == 'i' || event.key_input.cp == 'n') {
			Hord::Cmd::Object::SetMetaField{session}(
				object, "new" + std::to_string(grid_metadata_ref.row_count()), {}, true
			);
			return true;
		}
		return false;
	});
	grid_metadata->signal_cell_edited.bind([&session, &object](
		Hord::Data::Table::Iterator& it,
		UI::index_type col,
		String const& string_value,
		Hord::Data::ValueRef& new_value
	) {
		if (col == 0) {
			Hord::Cmd::Object::RenameMetaField{session}(
				object, it.index, string_value
			);
		} else if (col == 1) {
			Hord::Cmd::Object::SetMetaField{session}(
				object, it.index, new_value
			);
		}
	});

	auto view = UI::PropView::make(root, "base", UI::Axis::vertical);
	view->signal_notify_command.bind([&object, &field_slug_ref, &grid_metadata_ref](
		UI::View* const /*parent_view*/,
		UI::PropView& /*prop_view*/,
		Hord::Cmd::UnitBase const& command,
		Hord::Cmd::TypeInfo const& type_info
	) {
		if (command.object_id() != object.id()) {
			return;
		}
		switch (type_info.id) {
		case Hord::Cmd::Object::SetSlug::COMMAND_ID:
			field_slug_ref.set_text(object.slug());
			break;
		}

		if (!command.ok_action()) {
			return;
		}
		switch (type_info.id) {
		case Hord::Cmd::Object::SetMetaField::COMMAND_ID: {
			auto const& c = static_cast<Hord::Cmd::Object::SetMetaField const&>(command);
			if (c.created()) {
				grid_metadata_ref.insert_before(c.field_index(), 1);
			} else {
				grid_metadata_ref.notify_cell_changed(c.field_index(), 1);
			}
		}	break;

		case Hord::Cmd::Object::RenameMetaField::COMMAND_ID: {
			auto const& c = static_cast<Hord::Cmd::Object::RenameMetaField const&>(command);
			grid_metadata_ref.notify_cell_changed(c.field_index(), 0);
		}	break;

		case Hord::Cmd::Object::RemoveMetaField::COMMAND_ID: {
			auto const& c = static_cast<Hord::Cmd::Object::RemoveMetaField const&>(command);
			grid_metadata_ref.erase(c.field_index(), 1);
		}	break;
		}
	});

	view->push_back(std::move(field_slug));
	view->push_back(std::move(grid_metadata));
	object_view.add_prop_view(std::move(view), index);
}
Beispiel #10
0
bool mod_manager::copy_mod_contents(const t_mod_list &mods_to_copy,
                                    const std::string &output_base_path)
{
    if (mods_to_copy.empty()) {
        // nothing to copy, so technically we succeeded already!
        return true;
    }
    std::vector<std::string> search_extensions;
    search_extensions.push_back(".json");

    DebugLog( D_INFO, DC_ALL ) << "Copying mod contents into directory: " << output_base_path;

    if (!assure_dir_exist(output_base_path)) {
        DebugLog( D_ERROR, DC_ALL ) << "Unable to create or open mod directory at [" << output_base_path <<
                                    "] for saving";
        return false;
    }

    std::ostringstream number_stream;
    for (size_t i = 0; i < mods_to_copy.size(); ++i) {
        number_stream.str(std::string());
        number_stream.width(5);
        number_stream.fill('0');
        number_stream << (i + 1);
        MOD_INFORMATION *mod = mod_map[mods_to_copy[i]];
        size_t start_index = mod->path.size();

        // now to get all of the json files inside of the mod and get them ready to copy
        auto input_files = get_files_from_path(".json", mod->path, true, true);
        auto input_dirs  = get_directories_with(search_extensions, mod->path, true);

        if (input_files.empty() && mod->path.find(MOD_SEARCH_FILE) != std::string::npos) {
            // Self contained mod, all data is inside the modinfo.json file
            input_files.push_back(mod->path);
            start_index = mod->path.find_last_of("/\\");
            if (start_index == std::string::npos) {
                start_index = 0;
            }
        }

        if (input_files.empty()) {
            continue;
        }

        // create needed directories
        std::stringstream cur_mod_dir;
        cur_mod_dir << output_base_path << "/mod_" << number_stream.str();

        std::queue<std::string> dir_to_make;
        dir_to_make.push(cur_mod_dir.str());
        for( auto &input_dir : input_dirs ) {
            dir_to_make.push( cur_mod_dir.str() + "/" + input_dir.substr( start_index ) );
        }

        while (!dir_to_make.empty()) {
            if (!assure_dir_exist(dir_to_make.front())) {
                DebugLog( D_ERROR, DC_ALL ) << "Unable to create or open mod directory at [" <<
                                            dir_to_make.front() << "] for saving";
            }

            dir_to_make.pop();
        }

        std::ofstream fout;
        // trim file paths from full length down to just /data forward
        for( auto &input_file : input_files ) {
            std::string output_path = input_file;
            output_path = cur_mod_dir.str() + output_path.substr(start_index);

            std::ifstream infile( input_file.c_str(), std::ifstream::in | std::ifstream::binary );
            // and stuff it into ram
            std::istringstream iss(
                std::string(
                    (std::istreambuf_iterator<char>(infile)),
                    std::istreambuf_iterator<char>()
                )
            );
            infile.close();

            fout.open(output_path.c_str());
            fout << iss.str();
            fout.close();
        }
    }
    return true;
}
Beispiel #11
0
 SuperTuxWeaponConfig()
 {
   push_back(new UintConfigElement("speed", &speed, 600, 100, 1000));
 }
Beispiel #12
0
StringtokenizerVectorized::StringtokenizerVectorized( wxStringTokenizer tokenizer )
{
    reserve( tokenizer.CountTokens() );
    while ( tokenizer.HasMoreTokens() )
        push_back( tokenizer.GetNextToken() );
}
Beispiel #13
0
int _rsZoneReport(rsComm_t* _comm, bytesBuf_t** _bbuf)
{
    bytesBuf_t* bbuf = 0;
    int status = rsServerReport(_comm, &bbuf);
    if ( status < 0 ) {
        freeBBuf(bbuf);
        rodsLog(LOG_ERROR, "_rsZoneReport - rsServerReport failed %d", status);
        return status;
    }

    json cat_svr;

    try {
        cat_svr = json::parse(std::string(static_cast<char*>(bbuf->buf), bbuf->len));
        freeBBuf(bbuf);
    }
    catch (const json::type_error& e) {
        rodsLog(LOG_ERROR, "_rsZoneReport - json::parse failed [%s]", e.what());
        return ACTION_FAILED_ERR;
    }

    json coord_resc;
    irods::error ret = get_coordinating_resources( _comm, coord_resc );
    if ( !ret.ok() ) {
        rodsLog(LOG_ERROR, "_rsZoneReport - get_server_reports failed, status = %d", ret.code());
        return ret.code();
    }

    json svr_arr;
    ret = get_server_reports( _comm, svr_arr );
    if ( !ret.ok() ) {
        rodsLog(LOG_ERROR, "_rsZoneReport - get_server_reports failed, status = %d", ret.code());
        return ret.code();
    }

    cat_svr["coordinating_resources"] = coord_resc;

    auto zone_obj = json::object();
    zone_obj["servers"] = svr_arr;
    zone_obj["icat_server"] = cat_svr;

    auto zone_arr = json::array();
    zone_arr.push_back(zone_obj);

    auto zone = json::object();
    zone["schema_version"] = (boost::format("%s/%s/zone_bundle.json")
         % irods::get_server_property<const std::string>("schema_validation_base_uri")
         % irods::get_server_property<const std::string>("schema_version")).str();

    zone["zones"] = zone_arr;

    const auto zr = zone.dump(4);
    char* tmp_buf = new char[zr.length() + 1]{};
    std::strncpy(tmp_buf, zr.c_str(), zr.length());

    *_bbuf = (bytesBuf_t*) malloc(sizeof(bytesBuf_t));
    if (!*_bbuf) {
        delete [] tmp_buf;
        rodsLog( LOG_ERROR, "_rsZoneReport: failed to allocate _bbuf" );
        return SYS_MALLOC_ERR;
    }

    (*_bbuf)->buf = tmp_buf;
    (*_bbuf)->len = zr.length();

    return 0;
} // _rsZoneReport
Beispiel #14
0
 lazy_mapped_files_t(int nb_files, char *argv[]) {
   for(int j = 0; j < nb_files; j++)
     push_back(lazy_mapped_file_t(argv[j]));
 }
// Inserts the list at the back of a list.
void DividedFlashCardList :: push_back(const List<FlashCard> & other, const CardList & cl) {
	for (auto it = other.begin(); it != other.end(); ++it) push_back(*it, cl);
}
Beispiel #16
0
LanczosBounds<real_t> minmax_eigenvalues(SparseMatrixX<scalar_t> const& matrix,
                                         double precision_percent) {
    auto const precision = static_cast<real_t>(precision_percent / 100);
    auto const matrix_size = static_cast<int>(matrix.rows());

    auto left = VectorX<scalar_t>{VectorX<scalar_t>::Zero(matrix_size)};
    auto right_previous = VectorX<scalar_t>{VectorX<scalar_t>::Zero(matrix_size)};

    auto right = num::make_random<VectorX<scalar_t>>(matrix_size);
    right.normalize();

    // Alpha and beta are the diagonals of the tridiagonal matrix.
    // The final size is not known ahead of time, but it will be small.
    auto alpha = std::vector<real_t>();
    alpha.reserve(100);
    auto beta = std::vector<real_t>();
    beta.reserve(100);

    // Energy values from the previous iteration. Used to test convergence.
    // Initial values as far away from expected as possible.
    auto previous_min = std::numeric_limits<real_t>::max();
    auto previous_max = std::numeric_limits<real_t>::lowest();

    constexpr auto loop_limit = 1000;
    // This may iterate up to matrix_size, but since only the extreme eigenvalues are required it
    // will converge very quickly. Exceeding `loop_limit` would suggest something is wrong.
    for (int i = 0; i < loop_limit; ++i) {
        // PART 1: Calculate tridiagonal matrix elements a and b
        // =====================================================
        // left = h_matrix * right
        // matrix-vector multiplication (the most compute intensive part of each iteration)
        compute::matrix_vector_mul(matrix, right, left);

        auto const a = std::real(compute::dot_product(left, right));
        auto const b_prev = !beta.empty() ? beta.back() : real_t{0};

        // left -= a*right + b_prev*right_previous;
        compute::axpy(scalar_t{-a}, right, left);
        compute::axpy(scalar_t{-b_prev}, right_previous, left);
        auto const b = left.norm();

        right_previous.swap(right);
        right = (1/b) * left;

        alpha.push_back(a);
        beta.push_back(b);

        // PART 2: Check if the largest magnitude eigenvalues have converged
        // =================================================================
        auto const eigenvalues = compute::tridiagonal_eigenvalues(eigen_cast<ArrayX>(alpha),
                                                                  eigen_cast<ArrayX>(beta));
        auto const min = eigenvalues.minCoeff();
        auto const max = eigenvalues.maxCoeff();
        auto const is_converged_min = abs((previous_min - min) / min) < precision;
        auto const is_converged_max = abs((previous_max - max) / max) < precision;

        if (is_converged_min && is_converged_max) {
            return {min, max, i};
        }

        previous_min = min;
        previous_max = max;
    };

    throw std::runtime_error{"Lanczos algorithm did not converge for the min/max eigenvalues."};
}
Beispiel #17
0
    DeckItem ParserItemScan(const ParserItemType * self, RawRecord& rawRecord ) {
        auto deckItem = DeckItem::make< ValueType >( self->name(), rawRecord.size() );

        if (self->sizeType() == ALL) {
            while (rawRecord.size() > 0) {
                auto token = rawRecord.pop_front();

                std::string countString;
                std::string valueString;
                if (isStarToken(token, countString, valueString)) {
                    StarToken st(token, countString, valueString);
                    ValueType value;

                    if (st.hasValue()) {
                        value = readValueToken<ValueType>(st.valueString());
                        deckItem.push_back( value , st.count());
                    } else {
                        value = self->getDefault();
                        for (size_t i=0; i < st.count(); i++)
                            deckItem.push_backDefault( value );
                    }
                } else {
                    deckItem.push_back( readValueToken<ValueType>( token ) );
                }
            }
        } else {
            if (rawRecord.size() == 0) {
                // if the record was ended prematurely,
                if (self->hasDefault()) {
                    // use the default value for the item, if there is one...
                    deckItem.push_backDefault( self->getDefault() );
                } else {
                    // ... otherwise indicate that the deck item should throw once the
                    // item's data is accessed.
                    deckItem.push_backDummyDefault();
                }
            } else {
                // The '*' should be interpreted as a repetition indicator, but it must
                // be preceeded by an integer...
                auto token = rawRecord.pop_front();
                std::string countString;
                std::string valueString;
                if (isStarToken(token, countString, valueString)) {
                    StarToken st(token, countString, valueString);

                    if (!st.hasValue()) {
                        if (self->hasDefault())
                            deckItem.push_backDefault( self->getDefault() );
                        else
                            deckItem.push_backDummyDefault();
                    } else
                        deckItem.push_back(readValueToken<ValueType>(st.valueString()));

                    const auto value_start = token.size() - valueString.size();
                    // replace the first occurence of "N*FOO" by a sequence of N-1 times
                    // "FOO". this is slightly hacky, but it makes it work if the
                    // number of defaults pass item boundaries...
                    // We can safely make a string_view of one_star because it
                    // has static storage
                    static const char* one_star = "1*";
                    string_view rep = !st.hasValue()
                                    ? string_view{ one_star }
                                    : string_view{ token.begin() + value_start, token.end() };

                    rawRecord.prepend( st.count() - 1, rep );
                } else {
                    deckItem.push_back( readValueToken<ValueType>( token ) );
                }
            }
        }

        return deckItem;
    }
bool MessageDispatch::lua_read_value(td_proto::Values& value, lua_State* lua, td_proto::Config& config, i32 index, const char* arg)
{
#define CHECK_TYPE_VAILD(fn, index) \
	if (!fn(lua, index)) { \
		return false; \
	}
	auto t = td_proto::get_type_by_name(arg);
	auto success = true;
	switch (t) {
	case td_proto::TYPE_NIL:
		break;
	case td_proto::TYPE_U8:
		CHECK_TYPE_VAILD(lua_isnumber, index);
		value = td_proto::Values((u8)lua_tonumber(lua, index));
		break;
	case td_proto::TYPE_I8:
		CHECK_TYPE_VAILD(lua_isnumber, index);
		value = td_proto::Values((i8)lua_tonumber(lua, index));
		break;
	case td_proto::TYPE_U16:
		CHECK_TYPE_VAILD(lua_isnumber, index);
		value = td_proto::Values((u16)lua_tonumber(lua, index));
		break;
	case td_proto::TYPE_I16:
		CHECK_TYPE_VAILD(lua_isnumber, index);
		value = td_proto::Values((i16)lua_tonumber(lua, index));
		break;
	case td_proto::TYPE_U32:
		CHECK_TYPE_VAILD(lua_isnumber, index);
		value = td_proto::Values((u32)lua_tonumber(lua, index));
		break;
	case td_proto::TYPE_I32:
		CHECK_TYPE_VAILD(lua_isnumber, index);
		value = td_proto::Values((i32)lua_tonumber(lua, index));
		break;
	case td_proto::TYPE_FLOAT:
		CHECK_TYPE_VAILD(lua_isnumber, index);
		value = td_proto::Values((float)lua_tonumber(lua, index));
		break;
	case td_proto::TYPE_STR:
		CHECK_TYPE_VAILD(lua_isstring, index);
		value = td_proto::Values(new std::string(lua_tostring(lua, index)));
		break;
	case td_proto::TYPE_RAW: {
		CHECK_TYPE_VAILD(lua_isstring, index);
		size_t size = 0;
		auto info = lua_tolstring(lua, index, &size);
		auto vecs = new std::vector<char>(size);
		memcpy(&vecs[0], info, size);
		value = td_proto::Values(vecs);
	}
		break;
	case td_proto::TYPE_MAP: {
		auto val = new std::map<std::string, td_proto::Values>();
		value = td_proto::Values(val);
		lua_pushnil(lua);
		auto t = index >= 0 ? index : index - 1;
		while (lua_istable(lua, t) && lua_next(lua, t) != 0) {
			CHECK_TYPE_VAILD(lua_isstring, -2);
			std::string key = lua_tostring(lua, -2);
			auto field = config.get_field_by_name(key);
			if (field != nullptr) {
				td_proto::Values sub_val;
				auto success = lua_read_value(sub_val, lua, config, -1, field->pattern.c_str());
				if (!success) {
					return false;
				}
				val->insert(make_pair(key, std::move(sub_val)));
			}
			lua_pop(lua, 1);
		}
		break;
	}
	case td_proto::TYPE_AU8:
	case td_proto::TYPE_AI8:
	case td_proto::TYPE_AU16:
	case td_proto::TYPE_AU32:
	case td_proto::TYPE_AI32:
	case td_proto::TYPE_AFLOAT:
	case td_proto::TYPE_ASTR:
	case td_proto::TYPE_ARAW:
	case td_proto::TYPE_AMAP: {
		auto val = new std::vector<td_proto::Values>();
		value = td_proto::Values(val, t);
		CHECK_TYPE_VAILD(lua_istable, index);
		auto len = lua_rawlen(lua, index);
		for (unsigned int i = 1; i < len + 1; i++) {
			lua_pushnumber(lua, i);
			auto new_index = index >= 0 ? index : index - 1;
			lua_gettable(lua, new_index);
			td_proto::Values sub_val;
			auto success = lua_read_value(sub_val, lua, config, -1, td_proto::get_name_by_type(t - (td_proto::TYPE_AU8 - td_proto::TYPE_U8)));
			if (!success) {
				return false;
			}
			val->push_back(std::move(sub_val));
			lua_pop(lua, 1);
		}
		break;
	}
	default:
		return false;
	}
	return true;
}
	void KDTreeResultVector::push_element_and_heapify(KDTreeResult& e) {
		push_back(e); // what a vector does.
		push_heap(begin(), end()); // and now heapify it, with the new elt.
	}
Beispiel #20
0
template < class TProblemSolution > bool TListSet < TProblemSolution >::Update(TSolution & Solution)
{
    //cout << "updating pareto set" << endl;
    bool bEqual, bDominated, bDominating;

    bool bAdded = false;

    if (size() == 0)
    {
        bAdded = true;
        TProblemSolution *pPattern = (TProblemSolution *) & Solution;
        TProblemSolution *pNewSolution = new TProblemSolution(*pPattern);
        push_back(pNewSolution);
        UpdateIdealNadir();
    } else
    {
        bEqual = bDominated = bDominating = false;

        volatile unsigned int i;
        for (i = 0; (i < size()) && !bEqual && !bDominated; i++)
        {
            //cout << ">update: compare" << endl;
            TCompare ComparisonResult = Solution.Compare(*(*this)[i]);
            //cout << "<update: compare" << endl;

            switch (ComparisonResult)
            {
            case _Dominating:
                //if (Solution.ObjectiveValues[1] > (*(*this)[i]).ObjectiveValues[1]  )
                //    cout << "(" << Solution.ObjectiveValues[0] << ", " << Solution.ObjectiveValues[1] << ", " << Solution.ObjectiveValues[2] << ")" << " dominates " << "(" << (*(*this)[i]).ObjectiveValues[0] << ", " << (*(*this)[i]).ObjectiveValues[1] << ", " << (*(*this)[i]).ObjectiveValues[2] << ")" << endl;
                UpdateNadir(i);
                delete(*this)[i];
                erase(begin() + i);
                i--;
                bDominating = true;
                break;
            case _Dominated:
                bDominated = true;
                break;
            case _Nondominated:
                break;
            case _Equal:
                bEqual = true;
                break;
            }
        }

        if (bDominated && bDominating)
        {
            // Exception
            cout << Solution.ObjectiveValues[0] << "  " << Solution.ObjectiveValues[1] << "  ";
            cout << "Exception\n";
            cout << "void TListSet::Update (TPoint& Point)\n";
            cout << "bDominated && bDominating\n";
            exit(0);
        }

        if (!bDominated && !bEqual)
        {
            TProblemSolution *pPattern = (TProblemSolution *) & Solution;
            TProblemSolution *pNewSolution = new TProblemSolution(*pPattern);
            UpdateIdealNadir(*pNewSolution);
            push_back(pNewSolution);
            bAdded = true;
        }

    }

    iSetSize = size();
    iListSize = size();



////////////////////
    /*        bEqual = bDominated = bDominating = false;
            unsigned int i;
            for (i = 0; (i < size()) && !bEqual && !bDominated; i++)
            {

                TCompare ComparisonResult = Solution.Compare(*(*this)[i]);

                switch (ComparisonResult)
                {
                  case _Dominating:
                      bDominating = true;
                      break;
                  case _Dominated:
                      bDominated = true;
                      break;
                  case _Nondominated:
                      break;
                  case _Equal:
                      bEqual = true;
                      break;
                }
            }

            if (!bDominated && !bEqual)
            {
                cout << "HATA!!! eklenmis olmaliydi!" << endl;
            }
    */

    //if(bAdded) cout << "added to pareto set" << endl;
    //else  cout << "not added to pareto set" << endl;
    return bAdded;
}
Beispiel #21
0
/**
   @brief yields a set of proposls for integrating a category  
 */
std::vector<std::unique_ptr<AbstractProposal> >
ProposalRegistry::getSingleParameterProposals(Category cat, const BlockProposalConfig &config, const TreeAln &traln, ParallelSetup& pl, ParameterList &params) const 
{
  auto result = std::vector<unique_ptr<AbstractProposal> >{} ; 

  auto numNodeAges = traln.getNumberOfInnerNodes(true);

  auto&& proposals = ProposalTypeFunc::getSingleParameterProposalsForCategory(cat ) ; 
  for(auto& p : proposals)
    {     

      double userWeight = 1; 
      if(config.wasSetByUser(p))
	{
	  userWeight = config.getProposalWeight(p); 
	  if( not FLOAT_IS_INITIALIZED(userWeight))
	    continue; 
	} 
      else if( not ProposalTypeFunc::isDefaultInstantiate(p)  )		
	continue;       

      auto&& proposal = std::unique_ptr<AbstractProposal>{}; 

      switch(p)
	{
	case ProposalType::DIVRATE_SLIDER: 
	  {
	    // tout << "init: divrateslider " << std::endl; 
	    proposal = make_unique<DivRateSlider>();
	  }
	  break;
	case ProposalType::DIVTIME_SLIDER: 
	  {
	    // tout << "init: divtimeslider " << std::endl; 
	    proposal = make_unique<DivTimeSlider>(DivTimeSlider::defaultWeight / numNodeAges); 
	  }
	  break; 
	case ProposalType::ST_NNI: 
	  {
	    auto tmp = make_unique<GenericTopoProposal>(  make_unique<StatNniProposer>(), "stNNI", 6., config.getMoveOptMode() ) ;
	    if(config.hasUseMultiplier())
	      tmp->enableUseMultiplier();
	    proposal = std::move(tmp);
	  }
	  break; 
	case ProposalType::BRANCH_LENGTHS_MULTIPLIER:	      
	  proposal = make_unique< BranchLengthMultiplier>( initBranchLengthMultiplier) ; 
	  break; 
	case ProposalType::NODE_SLIDER:
	  proposal = make_unique<NodeSlider> (initNodeSliderMultiplier); 
	  break; 
	case ProposalType::TL_MULT:
	  proposal = make_unique< TreeLengthMultiplier> (  ProposalRegistry::initTreeLengthMultiplier); 
	  break; 
	case ProposalType::E_TBR: 
	  {
	    auto&& tmp = make_unique<GenericTopoProposal>(  make_unique<ExtendedTbrProposer>(config.getEtbrStopProb()) , "eTBR", 5., config.getMoveOptMode());
	    if(config.hasUseMultiplier())
	      tmp->enableUseMultiplier();
	    proposal = std::move(tmp); 
	  }
	  break; 
	case ProposalType::E_SPR: 
	  {
	    auto tmp = make_unique<GenericTopoProposal>( make_unique<ExtendedSprProposer>(config.getEsprStopProp()), "eSPR", 6. , config.getMoveOptMode());
	    if(config.hasUseMultiplier())
	      tmp->enableUseMultiplier();
	    proposal = std::move(tmp);
	  }
	  break; 
	case ProposalType::LIKE_SPR: 
	  {
	    int rad =  config.getLikeSprMaxRadius(); 
	    if(rad == -1)
	      rad = int(std::ceil(std::log(traln.getNumberOfTaxa()) / std::log(2))); 

	    proposal = make_unique<GenericTopoProposal>( make_unique<LikehoodSprProposer>(rad , config.getLikeSprWarp(), config.getMoveOptMode()),
							 "likeSPR", 2., config.getMoveOptMode());
	  }
	  break; 
	case ProposalType::PARSIMONY_SPR:	
	  {
	    // decide upon radius 
	    int radius = config.getParsSPRRadius(); 
	    nat numTax = traln.getNumberOfTaxa(); 
	    if(radius == -1)
	      radius = int(std::floor( std::log(numTax) * 2   ));
	    auto&& tmp  = make_unique<GenericTopoProposal>( make_unique<ParsSprProposer>(config.getParsimonyWarp(),radius, pl.getChainComm()), "parsSpr", 6. , config.getMoveOptMode()); 
	    if(config.hasUseMultiplier())
	      tmp->enableUseMultiplier();
	    proposal = std::move(tmp);
	  }
	  break; 
	case ProposalType::REVMAT_SLIDER: 
	  proposal = make_unique<ParameterProposal>  (Category::SUBSTITUTION_RATES, "revMatSlider", true, 
						      make_unique<SlidingProposer>(BoundsChecker::rateMin, BoundsChecker::rateMax, true),
						      initRateSlidingWindow,1,   1e-5,1 ) ; 
	  break; 
	case ProposalType::FREQUENCY_SLIDER:
	  proposal = make_unique<ParameterProposal>  (Category::FREQUENCIES, "freqSlider", true, 
						      std::unique_ptr<SlidingProposer>( new SlidingProposer(BoundsChecker::freqMin, std::numeric_limits<double>::max(), false)), 
						      initFrequencySlidingWindow,0.5,     1e-5, 1 ) ; 
	  break; 		  
	case ProposalType::RATE_HET_MULTI: 
	  proposal = make_unique<ParameterProposal>  (Category::RATE_HETEROGENEITY, "rateHetMulti", false, 
						      std::unique_ptr<MultiplierProposer>(new MultiplierProposer(BoundsChecker::alphaMin, BoundsChecker::alphaMax)),
						      initGammaMultiplier,1,  1e-4, 1e2 ) ; 
	  break; 
	case ProposalType::RATE_HET_SLIDER: 
	  proposal = make_unique<ParameterProposal>  (Category::RATE_HETEROGENEITY, "rateHetSlider", false, 
						      std::unique_ptr<SlidingProposer>(new SlidingProposer(BoundsChecker::alphaMin, BoundsChecker::alphaMax, false)),   
						      initGammaSlidingWindow,0, 1e-4, 1e2 ) ; 
	  break; 
	case ProposalType::FREQUENCY_DIRICHLET: 
	  proposal = make_unique<ParameterProposal>  (Category::FREQUENCIES, "freqDirich", true, 
						      std::unique_ptr<DirichletProposer	>(new DirichletProposer	(BoundsChecker::freqMin, std::numeric_limits<double>::max(), false)), 
						      initDirichletAlpha,0.5, 1e-3, 1e4 ) ; 
	  break; 
	case ProposalType::REVMAT_DIRICHLET: 
	  proposal = make_unique<ParameterProposal>  (Category::SUBSTITUTION_RATES, "revMatDirich", true, 
						      std::unique_ptr<DirichletProposer	>(new DirichletProposer	 (BoundsChecker::rateMin, BoundsChecker::rateMax, true)), 
						      initDirichletAlpha,1, 1e-3, 1e4) ; 
	  break; 
	case ProposalType::DIRICH_REVMAT_PER_RATE:
	  {
	    proposal = make_unique<ParameterProposal>(Category::SUBSTITUTION_RATES, "revMatDirichRate", true,
						      make_unique<RateDirichletProposer>( BoundsChecker::rateMin, BoundsChecker::rateMax),
						      initDirichletProtAlpha, 
						      // 4, 
						      1, 
						      1e-3, 1e4
						      );
	    proposal->setForProteinsOnly(true); 
	  }
	  break; 
	case ProposalType::SLIDING_REVMAT_PER_RATE:
	  {
	    proposal = make_unique<ParameterProposal>(Category::SUBSTITUTION_RATES, "revMatSliderRate", true,
						      make_unique<RateSlidingProposer>( BoundsChecker::rateMin, BoundsChecker::rateMax),
						      initRateSlidingWindow, 0.5, 0,0 // TODO !!! 
						      );
	    
	    // TODO not ready yet   
	    assert(0); 
	  }
	  break; 
	case ProposalType::AMINO_MODEL_JUMP: 
	  proposal = make_unique<AminoModelJump>();
	  break; 
	case ProposalType::BRANCH_DIST_GAMMA: 
	  proposal = make_unique<DistributionBranchLength<GammaProposer> >();
	  break;
	case ProposalType::BL_DIST_WEIBULL: 
	  proposal = make_unique< DistributionBranchLength<WeibullProposer> >();
	  break; 
	case ProposalType::DIV_TIME_DIRICH:
	  proposal = make_unique<DivTimeProposal>(DivTimeProposal::defaultWeight / numNodeAges ); 
	  break; 
        default :
	  {
	    cerr << "you did not implement case " << int(p) << " in ProposalRegistry.cpp" << endl; 
	    assert(0); 
	  }
	} 
      
      proposal->setParams(&params);

      if(config.wasSetByUser(p))
	proposal->setRelativeWeight(userWeight);       
      
      result.push_back((std::move(proposal))); 	
    }

  return result; 
} 
 static bool call(optional<Container>& c, T const& val)
 {
     if (!c)
         c = Container();
     return push_back(boost::get<Container>(c), val);
 }
void btContactArray::merge_contacts(
	const btContactArray & contacts, bool normal_contact_average)
{
	clear();

	int i;
	if(contacts.size()==0) return;


	if(contacts.size()==1)
	{
		push_back(contacts[0]);
		return;
	}

	btAlignedObjectArray<CONTACT_KEY_TOKEN> keycontacts;

	keycontacts.reserve(contacts.size());

	//fill key contacts

	for ( i = 0;i<contacts.size() ;i++ )
	{
		keycontacts.push_back(CONTACT_KEY_TOKEN(contacts[i].calc_key_contact(),i));
	}

	//sort keys
	keycontacts.quickSort(CONTACT_KEY_TOKEN_COMP());

	// Merge contacts
	int coincident_count=0;
	btVector3 coincident_normals[MAX_COINCIDENT];

	unsigned int last_key = keycontacts[0].m_key;
	unsigned int key = 0;

	push_back(contacts[keycontacts[0].m_value]);

	GIM_CONTACT * pcontact = &(*this)[0];

	for( i=1;i<keycontacts.size();i++)
	{
	    key = keycontacts[i].m_key;
		const GIM_CONTACT * scontact = &contacts[keycontacts[i].m_value];

		if(last_key ==  key)//same points
		{
			//merge contact
			if(pcontact->m_depth - CONTACT_DIFF_EPSILON > scontact->m_depth)//)
			{
				*pcontact = *scontact;
                coincident_count = 0;
			}
			else if(normal_contact_average)
			{
				if(btFabs(pcontact->m_depth - scontact->m_depth)<CONTACT_DIFF_EPSILON)
                {
                    if(coincident_count<MAX_COINCIDENT)
                    {
                    	coincident_normals[coincident_count] = scontact->m_normal;
                        coincident_count++;
                    }
                }
			}
		}
		else
		{//add new contact

		    if(normal_contact_average && coincident_count>0)
		    {
		    	pcontact->interpolate_normals(coincident_normals,coincident_count);
		        coincident_count = 0;
		    }

		    push_back(*scontact);
		    pcontact = &(*this)[this->size()-1];
        }
		last_key = key;
	}
}
 bool push_back_impl(Container& c, mpl::true_) const
 {
     return push_back(c, t_);
 }
Beispiel #25
0
Ptr<ModelBase> by_type(std::string type, usage use, Ptr<Options> options) {
  Ptr<ExpressionGraph> graph = nullptr; // graph unknown at this stage
  // clang-format off
  if(type == "s2s" || type == "amun" || type == "nematus") {
    return models::encoder_decoder()(options)
        ("usage", use)
        ("original-type", type)
            .push_back(models::encoder()("type", "s2s"))
            .push_back(models::decoder()("type", "s2s"))
            .construct(graph);
  }

  if(type == "transformer") {
    return models::encoder_decoder()(options)
        ("usage", use)
        .push_back(models::encoder()("type", "transformer"))
        .push_back(models::decoder()("type", "transformer"))
        .construct(graph);
  }

  if(type == "transformer_s2s") {
    return models::encoder_decoder()(options)
        ("usage", use)
        ("original-type", type)
            .push_back(models::encoder()("type", "transformer"))
            .push_back(models::decoder()("type", "s2s"))
            .construct(graph);
  }

  if(type == "lm") {
    auto idx = options->has("index") ? options->get<size_t>("index") : 0;
    std::vector<int> dimVocabs = options->get<std::vector<int>>("dim-vocabs");
    int vocab = dimVocabs[0];
    dimVocabs.resize(idx + 1);
    std::fill(dimVocabs.begin(), dimVocabs.end(), vocab);

    return models::encoder_decoder()(options)
        ("usage", use)
        ("type", "s2s")
        ("original-type", type)
            .push_back(models::decoder()
                       ("index", idx)
                       ("dim-vocabs", dimVocabs))
            .construct(graph);
  }

  if(type == "multi-s2s") {
    size_t numEncoders = 2;
    auto ms2sFactory = models::encoder_decoder()(options)
        ("usage", use)
        ("type", "s2s")
        ("original-type", type);

    for(size_t i = 0; i < numEncoders; ++i) {
      auto prefix = "encoder" + std::to_string(i + 1);
      ms2sFactory.push_back(models::encoder()("prefix", prefix)("index", i));
    }

    ms2sFactory.push_back(models::decoder()("index", numEncoders));

    return ms2sFactory.construct(graph);
  }

  if(type == "shared-multi-s2s") {
    size_t numEncoders = 2;
    auto ms2sFactory = models::encoder_decoder()(options)
        ("usage", use)
        ("type", "s2s")
        ("original-type", type);

    for(size_t i = 0; i < numEncoders; ++i) {
      auto prefix = "encoder";
      ms2sFactory.push_back(models::encoder()("prefix", prefix)("index", i));
    }

    ms2sFactory.push_back(models::decoder()("index", numEncoders));

    return ms2sFactory.construct(graph);
  }

  if(type == "multi-transformer") {
    size_t numEncoders = 2;
    auto mtransFactory = models::encoder_decoder()(options)
        ("usage", use)
        ("type", "transformer")
        ("original-type", type);

    for(size_t i = 0; i < numEncoders; ++i) {
      auto prefix = "encoder" + std::to_string(i + 1);
      mtransFactory.push_back(models::encoder()("prefix", prefix)("index", i));
    }
    mtransFactory.push_back(models::decoder()("index", numEncoders));

    return mtransFactory.construct(graph);
  }

  if(type == "shared-multi-transformer") {
    size_t numEncoders = 2;
    auto mtransFactory = models::encoder_decoder()(options)
        ("usage", use)
        ("type", "transformer")
        ("original-type", type);

    for(size_t i = 0; i < numEncoders; ++i) {
      auto prefix = "encoder";
      mtransFactory.push_back(models::encoder()("prefix", prefix)("index", i));
    }
    mtransFactory.push_back(models::decoder()("index", numEncoders));

    return mtransFactory.construct(graph);
  }

  if(type == "lm-transformer") {
    auto idx = options->has("index") ? options->get<size_t>("index") : 0;
    std::vector<int> dimVocabs = options->get<std::vector<int>>("dim-vocabs");
    int vocab = dimVocabs[0];
    dimVocabs.resize(idx + 1);
    std::fill(dimVocabs.begin(), dimVocabs.end(), vocab);

    return models::encoder_decoder()(options)
        ("usage", use)
        ("type", "transformer")
        ("original-type", type)
            .push_back(models::decoder()
                       ("index", idx)
                       ("dim-vocabs", dimVocabs))
            .construct(graph);
  }

  if(type == "bert") {                           // for full BERT training
    return models::encoder_classifier()(options) //
        ("original-type", "bert")                // so we can query this
        ("usage", use)                           //
        .push_back(models::encoder()             //
                    ("type", "bert-encoder")     // close to original transformer encoder
                    ("index", 0))                //
        .push_back(models::classifier()          //
                    ("prefix", "masked-lm")      // prefix for parameter names
                    ("type", "bert-masked-lm")   //
                    ("index", 0))                // multi-task learning with MaskedLM
        .push_back(models::classifier()          //
                    ("prefix", "next-sentence")  // prefix for parameter names
                    ("type", "bert-classifier")  //
                    ("index", 1))                // next sentence prediction
        .construct(graph);
  }

  if(type == "bert-classifier") {                // for BERT fine-tuning on non-BERT classification task
    return models::encoder_classifier()(options) //
        ("original-type", "bert-classifier")     // so we can query this if needed
        ("usage", use)                           //
        .push_back(models::encoder()             //
                    ("type", "bert-encoder")     //
                    ("index", 0))                // close to original transformer encoder
        .push_back(models::classifier()          //
                    ("type", "bert-classifier")  //
                    ("index", 1))                // next sentence prediction
        .construct(graph);
  }

#ifdef COMPILE_EXAMPLES
  // @TODO: examples should be compiled optionally
  if(type == "mnist-ffnn") {
    auto mnist = New<MnistFeedForwardNet>(options);
    if(use == usage::scoring)
      return New<Scorer>(mnist, New<MNISTLogsoftmax>());
    else if(use == usage::training)
      return New<Trainer>(mnist, New<MNISTCrossEntropyCost>());
    else
      return mnist;
  }
#endif

#ifdef CUDNN
#ifdef COMPILE_EXAMPLES
  if(type == "mnist-lenet") {
    auto mnist = New<MnistLeNet>(options);
    if(use == usage::scoring)
      return New<Scorer>(mnist, New<MNISTLogsoftmax>());
    else if(use == usage::training)
      return New<Trainer>(mnist, New<MNISTCrossEntropyCost>());
    else
      return mnist;
  }
#endif
  if(type == "char-s2s") {
    return models::encoder_decoder()(options)
        ("usage", use)
        ("original-type", type)
            .push_back(models::encoder()("type", "char-s2s"))
            .push_back(models::decoder()("type", "s2s"))
            .construct(graph);
  }
#endif

  // clang-format on
  ABORT("Unknown model type: {}", type);
}
void board_up( map &m, int sx, int sy, int dx, int dy )
{
    std::vector<point> furnitures1;
    std::vector<point> furnitures2;
    std::vector<point> boardables;
    for( int x = sx; x < sx + dx; x++ ) {
        for( int y = sy; y < sy + dy; y++ ) {
            bool must_board_around = false;
            const ter_id t = m.ter( x, y );
            if( t == t_window_domestic || t == t_window ) {
                // Windows are always to the outside and must be boarded
                must_board_around = true;
                m.ter_set( x, y, t_window_boarded );
            } else if( t == t_door_c || t == t_door_locked || t == t_door_c_peep ) {
                // Only board up doors that lead to the outside
                if( m.is_outside( x + 1, y ) || m.is_outside( x - 1, y ) ||
                    m.is_outside( x, y + 1 ) || m.is_outside( x, y - 1 ) ) {
                    m.ter_set( x, y, t_door_boarded );
                    must_board_around = true;
                } else {
                    // internal doors are opened instead
                    m.ter_set( x, y, t_door_o );
                }
            }
            if( must_board_around ) {
                // Board up the surroundings of the door/window
                add_boardable( m, point( x + 1, y ), boardables );
                add_boardable( m, point( x - 1, y ), boardables );
                add_boardable( m, point( x, y + 1 ), boardables );
                add_boardable( m, point( x, y - 1 ), boardables );
                add_boardable( m, point( x + 1, y + 1 ), boardables );
                add_boardable( m, point( x - 1, y + 1 ), boardables );
                add_boardable( m, point( x + 1, y - 1 ), boardables );
                add_boardable( m, point( x - 1, y - 1 ), boardables );
            }
        }
    }
    // Find all furniture that can be used to board up some place
    for( int x = sx; x < sx + dx; x++ ) {
        for( int y = sy; y < sy + dy; y++ ) {
            if( std::find( boardables.begin(), boardables.end(), point( x, y ) ) != boardables.end() ) {
                continue;
            }
            if( !m.has_furn( x, y ) ) {
                continue;
            }
            // If the furniture is movable and the character can move it, use it to barricade
            // g->u is workable here as NPCs by definition are not starting the game.  (Let's hope.)
            if( (m.furn_at( x, y ).move_str_req > 0) && (m.furn_at( x, y ).move_str_req < g->u.get_str() )) {
                if( m.furn_at( x, y ).movecost == 0 ) {
                    // Obstacles are better, prefer them
                    furnitures1.push_back( point( x, y ) );
                } else {
                    furnitures2.push_back( point( x, y ) );
                }
            }
        }
    }
    while( ( !furnitures1.empty() || !furnitures2.empty() ) && !boardables.empty() ) {
        const point fp = furnitures1.empty() ?
            get_random_from_vec( furnitures2 ) : get_random_from_vec( furnitures1 );
        const point bp = get_random_from_vec( boardables );
        m.furn_set( bp.x, bp.y, m.furn( fp.x, fp.y ) );
        m.furn_set( fp.x, fp.y, f_null );
        auto destination_items = m.i_at(bp.x, bp.y);
        for( auto moved_item : m.i_at(fp.x, fp.y) ) {
            destination_items.push_back( moved_item );
        }
        m.i_clear( fp.x, fp.y );
    }
}
Beispiel #27
0
inline value_vector& value_vector::operator,(const value& rhs)
{
    push_back(rhs);
    return *this;
}
Beispiel #28
0
    scanner::token_type scanner::scan_head()
    {
      t_char c = skip_whitespace();

      if(c == '>') { c_scan = &scanner::scan_body; return scan_body(); }
      if(c == '/')
      {
         t_char t = get_t_char();
         if(t == '>')   { c_scan = &scanner::scan_body; return TT_TAG_END_EMPTY; }
         else { push_back(t); return TT_ERROR; } // erroneous situtation - standalone '/'
      }

      attr_name_length = 0;
      value_length = 0;

      // attribute name...
      while(c != '=') 
      {
        if( c == 0) return TT_EOF;
        if( c == '>' ) { push_back(c); return TT_ATTR; } // attribute without value (HTML style)
        if( is_whitespace(c) )
        {
          c = skip_whitespace();
          if(c != '=') { push_back(c); return TT_ATTR; } // attribute without value (HTML style)
          else break;
        }
        if( c == '<') return TT_ERROR;
        append_attr_name(c);
        c = get_t_char();
      }

      c = skip_whitespace();
      // attribute value...
      
      if(c == '\"')
        while((c = get_t_char()))
        {
            if(c == '\"') return TT_ATTR;
            if(c == '&') c = scan_entity();
            append_value(c);
        }
      else if(c == '\'') // allowed in html
        while((c = get_t_char()))
        {
            if(c == '\'') return TT_ATTR;
            if(c == '&') c = scan_entity();
            append_value(c);
        }
      else  // scan token, allowed in html: e.g. align=center
        do
        {
            if( is_whitespace(c) ) return TT_ATTR;
            /* these two removed in favour of better html support:
            if( c == '/' || c == '>' ) { push_back(c); return TT_ATTR; }
            if( c == '&' ) c = scan_entity();*/
            if( c == '>' ) { push_back(c); return TT_ATTR; }
            append_value(c);
        } while((c = get_t_char()));

      return TT_ERROR;
    }
	bool
	FilteredTrace::parse_nmea_string(const std::string& nmea_string)
	{
		/* Guarantees that no spaces are inside nmea_string */
		/* ... */
		/** @todo Think about that later (is it necessary???) */
		
		const std::string ENDLINE = "\n";
		const std::string GPGGA_PREFIX("$GPGGA");
		const std::string GPRMC_PREFIX("$GPRMC");
		const int PREFIX_BEGIN_INDEX = 0;
		const int PREFIX_LENGTH = 6;
		const int TIME_BEGIN_INDEX = 7;
		const int TIME_LENGTH = 6;

		bool use_gpgga_string = true;
		bool found_gprmc_string = false;
		bool found_gpgga_string = false;
		std::string gpgga_string;
		std::string gprmc_string;
		std::string time_string;

		GPSPoint gps_point;
		int found_gps_points = 0;	
			
		std::string::size_type begin_index = nmea_string.find_first_not_of(ENDLINE);
		if (begin_index == std::string::npos)	return false;
		std::string::size_type end_index = nmea_string.find_first_of(ENDLINE, begin_index);
		
		while(end_index != std::string::npos)
		{
			std::string nmea_prefix(
				nmea_string.substr(begin_index + PREFIX_BEGIN_INDEX, PREFIX_LENGTH)
			);
			
//			std::cout << "nmea_prefix=" << nmea_prefix << "; ";
			if (nmea_prefix == GPRMC_PREFIX)
			{
//				std::cout << "GPRMC; ";
				if (use_gpgga_string)
				{
//					std::cout << "!found_gprmc_string; ";
					if (!found_gprmc_string)
					{
						if (!found_gpgga_string)
						{
//							std::cout << "!found_gpgga_string; ";
							time_string.append(nmea_string.substr(begin_index + TIME_BEGIN_INDEX, TIME_LENGTH));
							gprmc_string.append(nmea_string.substr(begin_index, end_index - begin_index));
							found_gprmc_string = true;
						} else // explicit: if (found_gpgga_string)
						{
//							std::cout << "found_gpgga_string; ";
							gprmc_string.append(nmea_string.substr(begin_index, end_index - begin_index));
							
							if (nmea_string.substr(begin_index + TIME_BEGIN_INDEX, TIME_LENGTH) == time_string)
							{
//								std::cout << "same_time; ";
								if (gps_point.parse_nmea_string(gpgga_string, gprmc_string))
								{
//									std::cout << "parse_gps_point ok; ";
									push_back(gps_point);
									++found_gps_points;
								} else
								{
									mlog(MLog::debug, "FilteredTrace::parse_from_nmea")
										<< "Parsing of NMEA strings fails! (GPGGA and GPRMC strings follows) "
										<< gpgga_string << " " << gprmc_string << "\n";
								}
								
								found_gprmc_string = false;
								found_gpgga_string = false;
								gpgga_string.erase();
								gprmc_string.erase();
								time_string.erase();
							} else // explicit: if (nmea_string.substr(begin_index + TIME_BEGIN_INDEX, TIME_LENGTH) != time_string)
							{
//								std::cout << "!same_time; ";
								gpgga_string.erase();
								found_gpgga_string = false;
								found_gprmc_string = true;
								time_string.erase();
								time_string.append(
									nmea_string.substr(begin_index + TIME_BEGIN_INDEX, TIME_LENGTH)
								);
							} // end: if (nmea_string.substr(begin_index + TIME_BEGIN_INDEX, TIME_LENGTH) == time_string)
						} // end: if (!found_gpgga_string)
						
					} else // explicit: if(found_gprmc_string)
					{
						mlog(MLog::info, "FilteredTrace") << "Switching to \"No-GPGGA-Modus\".\n";
						use_gpgga_string = false;
						_gps_points_have_valid_altitudes = false;
						
						if (size() > 0)
						{
							mlog(MLog::debug, "FilteredTrace") << "Must review GPSPoints.\n";
							iterator iter = begin();
							iterator iter_end = end();
							for (; iter != iter_end; ++iter)
							{
								iter->set_altitude(-1.0);
								/** @todo Define a value for a invalid altitude
								 * (perhaps -1000000, because this value is never reached in
								 * real world!) */
							}
						}
						
						if (gps_point.parse_nmea_string("", gprmc_string))
						{
							push_back(gps_point);
							++found_gps_points;
						}
						
						if (gps_point.parse_nmea_string("", nmea_string.substr(begin_index, end_index - begin_index)))
						{
							push_back(gps_point);
							++found_gps_points;
						}
					}
					
				} else // explicit: if (!use_gpgga_string)
				{
//					std::cout << "found_gprmc_string; ";
					if (gps_point.parse_nmea_string("", nmea_string.substr(begin_index, end_index - begin_index)))
					{
						push_back(gps_point);
						++found_gps_points;
					}
				} // end: if (use_gpgga_string)
				
			} else if (use_gpgga_string && (nmea_prefix == GPGGA_PREFIX))
			{
//				std::cout << "GPGGA; ";
				if (!found_gpgga_string)
				{
//					std::cout << "!found_gpgga_string; ";
					if (!found_gprmc_string)
					{
//						std::cout << "!found_gprmc_string; ";
						time_string.append(nmea_string.substr(begin_index + TIME_BEGIN_INDEX, TIME_LENGTH));
						gpgga_string.append(nmea_string.substr(begin_index, end_index- begin_index));
						found_gpgga_string = true;
					} else // explicit: if (found_gprmc_string)
					{
//						std::cout << "found_gprmc_string; ";
						gpgga_string.append(nmea_string.substr(begin_index, end_index - begin_index));
						
						if (nmea_string.substr(begin_index + TIME_BEGIN_INDEX, TIME_LENGTH) == time_string)
						{
//							std::cout << "same_time; ";
							if (gps_point.parse_nmea_string(gpgga_string, gprmc_string))
							{
//								std::cout << "parse_gps_point ok; ";
								push_back(gps_point);
								++found_gps_points;
							} else
							{
								mlog(MLog::debug, "FilteredTrace::parse_from_nmea")
									<< "Parsing of NMEA strings fails! (GPGGA and GPRMC strings follows) "
									<< gpgga_string << " " << gprmc_string << "\n";
							}
							
							found_gprmc_string = false;
							found_gpgga_string = false;
							gpgga_string.erase();
							gprmc_string.erase();
							time_string.erase();
						} else // explicit: if (nmea_string.substr(begin_index + TIME_BEGIN_INDEX, TIME_LENGTH) != time_string)
						{
//							std::cout << "!same_time; ";
							gprmc_string.erase();
							found_gprmc_string = false;
							found_gpgga_string = true;
							time_string.erase();
							time_string.append(
								nmea_string.substr(begin_index + TIME_BEGIN_INDEX, TIME_LENGTH)
							);
						} // end: if (nmea_string.substr(begin_index + TIME_BEGIN_INDEX, TIME_LENGTH) == time_string)
					} // end: if (!found_gprmc_string)
				} else // explicit: if (found_gpgga_string)
				{
//					std::cout << "found_gpgga_string; ";
					gpgga_string.erase();
					gpgga_string.append(nmea_string.substr(begin_index, end_index - begin_index));
					time_string.erase();
					time_string.append(nmea_string.substr(begin_index + TIME_BEGIN_INDEX, TIME_LENGTH));
				} // end: if (!found_gpgga_string)
			} // end: if (nmea_prefix == *)
			
			begin_index = nmea_string.find_first_not_of(ENDLINE, end_index);
			if (begin_index == std::string::npos)	break;
			end_index = nmea_string.find_first_of(ENDLINE, begin_index);
			
		} // end: while
		
//		std::cout << std::endl;
		
		return (found_gps_points > 0);
	}
Beispiel #30
0
/**
* Main program execution
*/
int main (int argc, char *argv[]) {
	TOKENIZER *tokenizer;
	char string[1024] = "";
	char *tok;
	int br;

	int most_recent_job = 0;

	ProcessMap *jobs = new_map();

	//Set up signal handling
	signal(SIGINT, SIG_IGN);
	signal(SIGTSTP, SIG_IGN);
	signal(SIGTTOU, SIG_IGN);
	signal(SIGTTIN, SIG_IGN);
	signal(SIGTERM, SIG_IGN);


	string[1023] = '\0';	   /* ensure that string is always null-terminated */
	printf("\nEnter a command or type ctrl-d to end session.\n" );
	write(1, "\nmy-sh$ ", 8);

	//Input loop
	while ((br = read( STDIN_FILENO, string, 1023 )) > 0) {

		if (br <= 1) {
			write(1, "my-sh$ ", 8);
			continue;
		}

		string[br-1] = '\0';
		tokenizer = init_tokenizer(string);

		//Create linked list of tokens
		LinkedList *input_command = new_list(256);
		while( (tok = get_next_token( tokenizer )) != NULL ) {
			push_back(input_command, tok);
			free(tok);
		}
		free_tokenizer(tokenizer);


		int executed = 0;
		int error = 0;
		//Checks for fg or bg
		if (get_length(input_command) == 1) {
			char *only_token = pop_back(input_command);

			if (compare_strings(only_token, "fg")) {
				if (move_to_foreground(jobs, &most_recent_job) == -1)
					error = 1;
				executed = 1;
					
			} else if (compare_strings(only_token, "bg")) {
				if (move_to_background(jobs, &most_recent_job) == -1)
					error = 1;
				executed = 1;
			} else {
				push_back(input_command, only_token);
			}
			free(only_token);
		}


		//Process input for pipes or background if an error has already been detected, go to the next command
		if (!executed && !error) {

			//Sees if a background ampersand is detected
			bool is_background = determine_background(input_command);

			LinkedList *full_command = copy_list(input_command);

			if (is_background) {
				printf("Running: ");
				print_list(input_command);
			}

			//Test for pipes
			bool is_pipe = false;
			LinkedList *first_command_list = new_list(50);
			LinkedList *second_command_list = new_list(50);
			int valid_pipe = find_piping(input_command, &is_pipe, first_command_list, second_command_list);

			//Command blocks are created from the command lists
			CommandBlock *first_command = new_command_block(first_command_list);
			CommandBlock *second_command = new_command_block(second_command_list);

			//Runs a function to check that there are no invalid redirections in the case of a piping
			if (is_pipe) {
				valid_pipe = valid_pipe && check_pipe(first_command, second_command);
			}

			//Notifies user of any incorrect pipe commands
			if (!is_pipe && !first_command->valid) {
				printf("Invalid command structure\n");
			} else if (is_pipe && (!first_command->valid || !second_command->valid || !valid_pipe) ) {
				printf("Invalid command structure\n");
			}


			//If it is a pipe and all necessary conditions are valid, then the piping occurs
			if (is_pipe && first_command->valid && second_command->valid && valid_pipe) {
				
				if (pipe_job (first_command, second_command, is_background, full_command, jobs, &most_recent_job) 
					== -1)
					error = 1;

			} 
			// No piping
			else if (!is_pipe && first_command->valid) {

				if (job (first_command, is_background, full_command, jobs, &most_recent_job) == -1)
					error = 1;
			}

			destroy_list(first_command_list);
			destroy_list(second_command_list);
			destroy_block(first_command);
			destroy_block(second_command);
			destroy_list(full_command);
		}

		destroy_list(input_command);

		
		monitor_background_jobs (jobs, &most_recent_job);

		if (error)
			perror("ERROR ");

		write(1, "my-sh$ ", 8);
	}

	destroy_map(jobs);

	
	
	printf( "\nSession ended\n" );
	return 0;
}