How to optimize my batch?

In the submitForm of MembershipSettings, I run a batch:

      $operations = ();

      << some query on an custom entity >>
      $results = $query->execute();
      foreach ($results as $key => $result) {
        $operations() = ('DrupalassociationFormMembershipSettings::updateMember', ($result, $enddate));

      $ids = Drupal::entityQuery('user')
        ->condition('roles', 'member')
      $users = User::loadMultiple($ids);
      foreach ($users as $user) {
        $operations() = ('DrupalassociationFormMembershipSettings::updateUser', ($user));

      $operations() = ('DrupalassociationFormMembershipSettings::removeRole', ());

      $batch = (
        'operations' => $operations,
        'title'      => t('Renew membership: Period Closure'),
        'init_message' => t('Process is starting...'),
        'finished'   => 'DrupalassociationFormMembershipSettings::endofPeriodClosure',

  public static function updateMember($result, $enddate, &$context)
    $id = $result->id;
    $storage = Drupal::entityTypeManager()->getStorage('member');
    $member = $storage->load($id);
    if ($member) {
      $member->set("status", -1);
      $member->set("enddate", $enddate);
      $context('results')('member')() = $id;
      $context('message') = t('Updating status for member @id', ('@id' => $id));

  public static function updateUser($user, &$context)
    $id = $user->uid->value;
    $context('results')('user')() = $id;
    $context('message') = t('Updating user @id', ('@id' => $id));

  public static function removeRole(&$context)
    $role = Role::load('member');
    $context('results')() = 'member';
    $context('message') = t('Removing role @id', ('@id' => 'member'));

In updateMember(), I load the content entity to update it.
In updateUser(), I remove a specific role from the user.
In removeRole(), I delete the specific role once there is no more user who has this role.

updateMember() and updateUser() are quite long to process…
Is there another way to do that that would save time?

I will create an SEO Optimize Facebook page. for $6

I will create an SEO Optimize Facebook page.

Are you looking for an attractive and professional business page? Then you are in the proper place.

I will create and setup SEO optimize FB page for your business that helps with Facebook promotion, Facebook advertising and FB ads, FB store/shop.

Which Services I’m Providing:

FB Fan Page/Business page

Business Page Creation

Cover & Profile Picture Setup & resizing

CTA Button

Linkup other Social Platform

Add website, phone & email

Why me?

  • Friendly communication
  • 100% professional
  • Quick delivery
  • Quality service
  • Full support free for One month
  • 100% Satisfaction
  • Unlimited Revisions
    >>NOTE: If you have any queries or need to help then feel free to message me. I will be happy to help you.


javascript – Optimize “nearest” Element query prototype

if (Element.prototype.nearest === undefined) {
  const nearest = (el, selector) => {
    if (el == null) return undefined;
    const prev = el.previousElementSibling;
    if (prev?.matches(selector)) return prev;
    const next = el.nextElementSibling;
    if (next?.matches(selector)) return prev;
    const parent = el.parentElement;
    if (parent?.matches(selector)) return parent;
    const relative = parent.querySelector(selector);
    if (relative) return relative;
    return nearest(el.parentElement, selector);
  Element.prototype.nearest = function(selector) {
    return nearest(this, selector);

const handleClick = (e) => {
  const btn =;

document.querySelectorAll('.btn').forEach(btn =>
  btn.addEventListener('click', handleClick));
.parent {
  display: flex;
<div class="grand-parent">
  <div class="parent">
    <div class="child" id="child-1">
      <button class="btn">
    <div class="child" id="child-2">
      <button class="btn">

mysql – How can I optimize my PHP code for better performance

I am very new to PHP and have tried various techniques but I am constantly getting a 500 error when clicking on the export button to download a csv report. I’m not sure why the previous developer did it this way.

Is there a better why in PHP to make this code better? Willing to understand and learn from an PHP expert.

The database is MYSQL.

This is the backend code:

            $coursefilterid = $_GET('course');

            $conn = new mysqli($host, $username, $password, $database);
            if ($conn->connect_error) {
                die("Connection failed: " . $conn->connect_error);

            $sqluserenrolled = "select mdl_user.username, mdl_user_enrolments.userid as enrolleduserid, mdl_enrol.courseid from mdl_user_enrolments
    Inner Join
    on = mdl_user_enrolments.enrolid
    Inner Join
    on = mdl_user_enrolments.userid
    mdl_enrol.courseid = '" . $coursefilterid . "'
    order by mdl_user.username

            $queryenrolleduser = mysqli_query($conn, $sqluserenrolled);



    <form method="post"
        action="<?php echo "userlistssiexport.php?id=$coursefilterid"?>">
        <input type="hidden" name="exportcourseid"
            value="<?php echo $coursefilterid;?>"> <input type="hidden"
            name="sessid" value="<?php echo $USER->sesskey;?>"> <input
            class="btn btn-primary" type="submit" name="submit"
            value="<?php echo "Export";?>">

            $noteid = "";
            $cmId = "";
    <table class="data-table">
        <caption class="title">User info</caption>
                <th>Last login</th>
                <th>Certificate Request Date</th>


            while ($row = mysqli_fetch_array($queryenrolleduser)) {

                $enrolleduserid = $row('enrolleduserid');

                $sql = "select mdl_user.username as username, 
        mdl_user.firstname as firstname,
        mdl_user.lastname as lastname, as email,
       mdl_user.lastlogin as lastaccess,
        mdl_user.timecreated as createddate, as position 
        from mdl_user
        Inner Join 
        mdl_user_info_data.userid =
        Inner Join
        on = mdl_user_info_data.fieldid
        Inner Join
        mdl_user_lastaccess.userid =
        where = 1
        mdl_user.deleted = 0
        and = '" . $enrolleduserid . "'
        group by mdl_user.username
        order by mdl_user.username
                $query = mysqli_query($conn, $sql);

                if (! $query) {
                    die('SQL Error: ' . mysqli_error($conn));
                } else {}


                $no = 1;
                $total = 0;
                $username = '';
                $coursename = '';
                $content = '';
                $modulename = '';
                $organization = '';
                $userid = '';
                $certificatedate = '';
                $userrole = '';
                $enrolleduserid = '';

                while ($row = mysqli_fetch_array($query)) {
                    // Do something here
                    $username = $row('username');
                    $coursename = $row('coursename');
                    $content = $row('content');
                    $noteid = $row('noteid');
                    // $notedatetime = date("d/m/y g:i (A)", $row('notedate'));
                    $notedatetime = date("D M j Y G:i A", $row('notedate'));
                    $lastaccess = date("D M j Y G:i A", $row('lastaccess'));
                    $createddate = date("D M j Y G:i A", $row('createddate'));
                    $datafile = $username . $coursename . $content;

                    echo '<tr>      
                    <td>' . $row('username') . '</td>
                    <td>' . $row('firstname') . '</td>
                    <td>' . $row('lastname') . '</td>
                    <td>' . $row('email') . '</td>                          
                    <td>' . $lastaccess . '</td>                                    
                    <td>' . $createddate . '</td>   
                    <td>' . $row('position') . '</td>    
                    $modid = $row('contextid');
                    // Get module name

                    $sqlmodule = "select mdl_user.username as username, 
        mdl_user.firstname as firstname,
        mdl_user.lastname as lastname, as email,
        FROM_UNIXTIME(mdl_user_lastaccess.timeaccess) as lastaccess,
        FROM_UNIXTIME(mdl_user.timecreated) as createddate, as organization 
        from mdl_user
        Inner Join 
        mdl_user_info_data.userid =
        Inner Join
        on = mdl_user_info_data.fieldid
        Inner Join
        mdl_user_lastaccess.userid =
        where = 3
        mdl_user.deleted = 0
        mdl_user.username ='" . $username . "'";

                    $querymodule = mysqli_query($conn, $sqlmodule);
                    $modulenamelink = "";
                    while ($row = mysqli_fetch_array($querymodule)) {

                        $organization = $row('organization');

                    echo '<td>' . $organization . '</td>';

                    $sqlCertificateDateuid = "select id from mdl_user where username = '" . $username . "'";

                    $queryCertificateDateuid = mysqli_query($conn, $sqlCertificateDateuid);
                    while ($row = mysqli_fetch_array($queryCertificateDateuid)) {

                        $userid = $row('id');

                    $sqlcertificatedate = "select * from mdl_certificateemail where userid = '" . $userid . "'
        and courseid = '" . $coursefilterid . "'";

                    $querycertificaterequestdate = mysqli_query($conn, $sqlcertificatedate);
                    while ($row = mysqli_fetch_array($querycertificaterequestdate)) {

                         $certificatedate = date("D M j Y g:i:s A", $row('unixdatetimecertificate'));
                    echo '<td>' . $certificatedate . '</td>';

                    $sqluserrole = "select mdl_role_assignments.userid, mdl_role_assignments.roleid,mdl_course_modules.course, mdl_role.shortname as rolename,FROM_UNIXTIME(mdl_role_assignments.timemodified)  from mdl_role_assignments 
        Inner Join
        on = mdl_role_assignments.contextid
        Inner Join
        mdl_course_modules.instance = mdl_context.instanceid
        Inner Join
        on = mdl_role_assignments.roleid
        where mdl_course_modules.course = '" . $coursefilterid . "'
        mdl_role_assignments.userid = '" . $userid . "'
        group by
        order by mdl_role_assignments.timemodified

                    $userlistrole = '';
                    $queryuserrole = mysqli_query($conn, $sqluserrole);
                    while ($row = mysqli_fetch_array($queryuserrole)) {

                        $userrole = $row('rolename');
                        $userlistrole = array(
                        // echo '<td>'.$userrole.'</td>';

                    foreach ($userlistrole as $listrole) {

                        // echo $listrole;

                    $teacherrole = array(
                    foreach ($teacherrole as $rolename) {
                        $role = $DB->get_record('role', array(
                            'shortname' => $rolename
                        $context = get_context_instance(CONTEXT_COURSE, $coursefilterid);
                        // $context = context_course::instance($cid1);
                        $teachers = get_role_users($role->id, $context);

                        foreach ($teachers as $teacher) {

                            $teacherid = $teacher->id;
                            if ($teacherid == $userid) {
                                echo '<td>student</td>';

                    $teacherrole = array(
                    foreach ($teacherrole as $rolename) {
                        $role = $DB->get_record('role', array(
                            'shortname' => $rolename
                        $context = get_context_instance(CONTEXT_COURSE, $coursefilterid);
                        // $context = context_course::instance($cid1);
                        $teachers = get_role_users($role->id, $context);

                        foreach ($teachers as $teacher) {

                            $teacherid = $teacher->id;
                            if ($teacherid == $userid) {
                                echo '<td></td>';
                                echo '<td>editingteacher</td>';

                    $teacherrole = array(
                    foreach ($teacherrole as $rolename) {
                        $role = $DB->get_record('role', array(
                            'shortname' => $rolename
                        $context = get_context_instance(CONTEXT_COURSE, $coursefilterid);
                        // $context = context_course::instance($cid1);
                        $teachers = get_role_users($role->id, $context);

                        foreach ($teachers as $teacher) {

                            $teacherid = $teacher->id;
                            if ($teacherid == $userid) {
                                echo '<td>manager</td>';
                    echo '</tr>';





else {
    // echo "something";

else {



?>enter code here

postgresql – How to optimize query by preventing repetitive subquery

I have query that uses a subquery (select min/max(date) from stage.stage_net_subscription_010_filter_and_net_pds) to find min and max dates of a table.

It seems that the subqueries are repeated very often.

  1. Is there a way to rewrite the query without CTEs such that the subqueries do not get executed for every loop
  2. One other option to speed up the query is see, would be to use generate series in stead of selecting the dates from a table with dates. Any clue if that will make a difference?


         , stage_net_subscription_020_classes.client_id AS client_id
         , stage_net_subscription_020_classes.product_id AS product_id
  FROM star.dim_date dim_date
  CROSS JOIN stage.stage_net_subscription_020_classes stage_net_subscription_020_classes
  where date >= (select min(date) from stage.stage_net_subscription_010_filter_and_net_pds)
  and   date <= (select max(date) from stage.stage_net_subscription_010_filter_and_net_pds);

query performance – How to optimize MySQL InnoDB engine

I have 2 million rows of time series data in one table let’s say items. I am trying to generate an analysis dashboard, but the read query is very slow. btw I also did indexing for my table.

I am using DigitalOChean VPS:

My VPS Config:

  • OS: Ubuntu 20.04 LTS
  • VPS RAM: 4 GB and 2vCPUs
  • VPS SSD: 80 GB
  • MySQL Version: 8.0

I increase InnoDB buffer pool size 128M to 2G, got some better performance but it’s not enough.

| Variable_name                            | Value                  |
| innodb_adaptive_flushing                 | ON                     |
| innodb_adaptive_flushing_lwm             | 10                     |
| innodb_adaptive_hash_index               | ON                     |
| innodb_adaptive_hash_index_parts         | 8                      |
| innodb_adaptive_max_sleep_delay          | 150000                 |
| innodb_api_bk_commit_interval            | 5                      |
| innodb_api_disable_rowlock               | OFF                    |
| innodb_api_enable_binlog                 | OFF                    |
| innodb_api_enable_mdl                    | OFF                    |
| innodb_api_trx_level                     | 0                      |
| innodb_autoextend_increment              | 64                     |
| innodb_autoinc_lock_mode                 | 2                      |
| innodb_buffer_pool_chunk_size            | 134217728              |
| innodb_buffer_pool_dump_at_shutdown      | ON                     |
| innodb_buffer_pool_dump_now              | OFF                    |
| innodb_buffer_pool_dump_pct              | 25                     |
| innodb_buffer_pool_filename              | ib_buffer_pool         |
| innodb_buffer_pool_in_core_file          | ON                     |
| innodb_buffer_pool_instances             | 8                      |
| innodb_buffer_pool_load_abort            | OFF                    |
| innodb_buffer_pool_load_at_startup       | ON                     |
| innodb_buffer_pool_load_now              | OFF                    |
| innodb_buffer_pool_size                  | 2147483648             |
| innodb_change_buffer_max_size            | 25                     |
| innodb_change_buffering                  | all                    |
| innodb_checksum_algorithm                | crc32                  |
| innodb_cmp_per_index_enabled             | OFF                    |
| innodb_commit_concurrency                | 0                      |
| innodb_compression_failure_threshold_pct | 5                      |
| innodb_compression_level                 | 6                      |
| innodb_compression_pad_pct_max           | 50                     |
| innodb_concurrency_tickets               | 5000                   |
| innodb_data_file_path                    | ibdata1:12M:autoextend |
| innodb_data_home_dir                     |                        |
| innodb_deadlock_detect                   | ON                     |
| innodb_dedicated_server                  | OFF                    |
| innodb_default_row_format                | dynamic                |
| innodb_directories                       |                        |
| innodb_disable_sort_file_cache           | OFF                    |
| innodb_doublewrite                       | ON                     |
| innodb_doublewrite_batch_size            | 0                      |
| innodb_doublewrite_dir                   |                        |
| innodb_doublewrite_files                 | 2                      |
| innodb_doublewrite_pages                 | 4                      |
| innodb_extend_and_initialize             | ON                     |
| innodb_fast_shutdown                     | 1                      |
| innodb_file_per_table                    | ON                     |
| innodb_fill_factor                       | 100                    |
| innodb_flush_log_at_timeout              | 1                      |
| innodb_flush_log_at_trx_commit           | 1                      |
| innodb_flush_method                      | fsync                  |
| innodb_flush_neighbors                   | 0                      |
| innodb_flush_sync                        | ON                     |
| innodb_flushing_avg_loops                | 30                     |
| innodb_force_load_corrupted              | OFF                    |
| innodb_force_recovery                    | 0                      |
| innodb_fsync_threshold                   | 0                      |
| innodb_ft_aux_table                      |                        |
| innodb_ft_cache_size                     | 8000000                |
| innodb_ft_enable_diag_print              | OFF                    |
| innodb_ft_enable_stopword                | ON                     |
| innodb_ft_max_token_size                 | 84                     |
| innodb_ft_min_token_size                 | 3                      |
| innodb_ft_num_word_optimize              | 2000                   |
| innodb_ft_result_cache_limit             | 2000000000             |
| innodb_ft_server_stopword_table          |                        |
| innodb_ft_sort_pll_degree                | 2                      |
| innodb_ft_total_cache_size               | 640000000              |
| innodb_ft_user_stopword_table            |                        |
| innodb_idle_flush_pct                    | 100                    |
| innodb_io_capacity                       | 200                    |
| innodb_io_capacity_max                   | 2000                   |
| innodb_lock_wait_timeout                 | 50                     |
| innodb_log_buffer_size                   | 16777216               |
| innodb_log_checksums                     | ON                     |
| innodb_log_compressed_pages              | ON                     |
| innodb_log_file_size                     | 50331648               |
| innodb_log_files_in_group                | 2                      |
| innodb_log_group_home_dir                | ./                     |
| innodb_log_spin_cpu_abs_lwm              | 80                     |
| innodb_log_spin_cpu_pct_hwm              | 50                     |
| innodb_log_wait_for_flush_spin_hwm       | 400                    |
| innodb_log_write_ahead_size              | 8192                   |
| innodb_log_writer_threads                | ON                     |
| innodb_lru_scan_depth                    | 1024                   |
| innodb_max_dirty_pages_pct               | 90.000000              |
| innodb_max_dirty_pages_pct_lwm           | 10.000000              |
| innodb_max_purge_lag                     | 0                      |
| innodb_max_purge_lag_delay               | 0                      |
| innodb_max_undo_log_size                 | 1073741824             |
| innodb_monitor_disable                   |                        |
| innodb_monitor_enable                    |                        |
| innodb_monitor_reset                     |                        |
| innodb_monitor_reset_all                 |                        |
| innodb_numa_interleave                   | OFF                    |
| innodb_old_blocks_pct                    | 37                     |
| innodb_old_blocks_time                   | 1000                   |
| innodb_online_alter_log_max_size         | 134217728              |
| innodb_open_files                        | 4000                   |
| innodb_optimize_fulltext_only            | OFF                    |
| innodb_page_cleaners                     | 4                      |
| innodb_page_size                         | 16384                  |
| innodb_parallel_read_threads             | 4                      |
| innodb_print_all_deadlocks               | OFF                    |
| innodb_print_ddl_logs                    | OFF                    |
| innodb_purge_batch_size                  | 300                    |
| innodb_purge_rseg_truncate_frequency     | 128                    |
| innodb_purge_threads                     | 4                      |
| innodb_random_read_ahead                 | OFF                    |
| innodb_read_ahead_threshold              | 56                     |
| innodb_read_io_threads                   | 4                      |
| innodb_read_only                         | OFF                    |
| innodb_redo_log_archive_dirs             |                        |
| innodb_redo_log_encrypt                  | OFF                    |
| innodb_replication_delay                 | 0                      |
| innodb_rollback_on_timeout               | OFF                    |
| innodb_rollback_segments                 | 128                    |
| innodb_sort_buffer_size                  | 1048576                |
| innodb_spin_wait_delay                   | 6                      |
| innodb_spin_wait_pause_multiplier        | 50                     |
| innodb_stats_auto_recalc                 | ON                     |
| innodb_stats_include_delete_marked       | OFF                    |
| innodb_stats_method                      | nulls_equal            |
| innodb_stats_on_metadata                 | OFF                    |
| innodb_stats_persistent                  | ON                     |
| innodb_stats_persistent_sample_pages     | 20                     |
| innodb_stats_transient_sample_pages      | 8                      |
| innodb_status_output                     | OFF                    |
| innodb_status_output_locks               | OFF                    |
| innodb_strict_mode                       | ON                     |
| innodb_sync_array_size                   | 1                      |
| innodb_sync_spin_loops                   | 30                     |
| innodb_table_locks                       | ON                     |
| innodb_temp_data_file_path               | ibtmp1:12M:autoextend  |
| innodb_temp_tablespaces_dir              | ./#innodb_temp/        |
| innodb_thread_concurrency                | 0                      |
| innodb_thread_sleep_delay                | 10000                  |
| innodb_tmpdir                            |                        |
| innodb_undo_directory                    | ./                     |
| innodb_undo_log_encrypt                  | OFF                    |
| innodb_undo_log_truncate                 | ON                     |
| innodb_undo_tablespaces                  | 2                      |
| innodb_use_native_aio                    | ON                     |
| innodb_validate_tablespace_paths         | ON                     |
| innodb_version                           | 8.0.23                 |
| innodb_write_io_threads                  | 4                      |
146 rows in set (0.00 sec)

dnd 3.5e – How to optimize a TWF Barbarian Elf

OK, so, to begin: you are going to get +2 Dexterity, which is nice-ish, −2 Constitution, which sucks but at least you’ll get bonuses and d12 HD, and you will get a bunch of other stuff that barely matters at all. For reasons, you probably will not be using any traditional elven weapons (though the less traditional elven-specific weapons in Races of the Wild are solid options in a couple of cases). Thus, your elven race would be a moderately-large downside, a sort of mediocre ability score bonus, and not much else.

The solution to this is taking advantage of various elf-only options. That means you are going to need Races of the Wild, since that’s where most of them are, and Tome of Battle, because there’s two excellent things in there for you.

There are three primary prestige classes I have in mind: champion of Corellon Larethian, eternal blade, and wildrunner. They do not all work together, sadly, at least not completely, but we can still work with this.

  • Champion of Corellon Larethian—more knightly/paladin-y than you’re looking for, but two levels do allow you to add your Dexterity bonus to damage with certain weapons. That’s very valuable. Unfortunately, requires a stupid number of feats, too many to make workable, and the elegant strikes feature (read: the reason we care about the class at all) is incompatible with Shadow Blade (which does the same thing for a different set of weapons, and for fewer and better feats) unless you get a favorable ruling about elven lightblades and Shadow Blade.

  • Eternal Blade—this thing just oozes cool—it’s basically Link, Hero of Time. Furthermore, the capstone is extremely useful: once per fight, take two full-attacks in a row. You will be a crazy frenzy of blades.

  • Wildrunner—this is the big one, the crazy elven barbarian. It gains a “primal scream” class feature, which works very similar to rage, and stacks with that. Notably, it has a big +6 bonus to Dexterity.


Your first feat has to be Weapon Finesse. You have a bonus to Dexterity, this build relies on Dexterity, and you have to be able to hit things. What this means is, unless you have Flaws from Unearthed Arcana, you will not be able to get the Two-Weapon Fighting feat until later. Even with them, because of the feats you need to get that are not fighter-bonus-feats, with flaws I still recommend delaying Two-Weapon Fighting in order to ensure other feats on time.

If you do not have Two-Weapon Fighting, you should not attempt to use the two-weapon fighting combat option. Sorry, but you only get one feat, you are going to have to be Dex-focused, and without Weapon Finesse a Dex-focused melee fighter isn’t going to hit anything.

After Weapon Finesse and Two-Weapon Fighting, the next priority is Shadow Blade, from Tome of Battle. This allows you to add your Dexterity bonus to damage when using one of a selection of weapons—the short sword is the one for you. The issue is getting a Shadow Hand stance to use it with. This either means Martial Study and Martial Stance before you can get it, or taking a level in swordsage. The problem with the latter is it will slow down entry into eternal blade, and make its capstone impossible pre-epic.

Extra Rage from Complete Warrior is a good idea; barbarian itself gives more uses of rage only slowly.

Improved Two-Weapon Fighting can be gotten from the gloves of the balanced hand item from Magic Item Compendium. The same book has rules for adding enhancement bonuses to Dexterity to this same item without a cost penalty; obviously, Dexterity is your most important score. This build is very feat-starved, so the item makes more sense than picking up another feat. You can always pick the feat up later to replace the item.

It’s not a feat, but Twisted Charge from Complete Scoundrel will do you well.


Shadow Blade only works with a select group of weapons, and you require Weapon Focus for eternal blade, so it makes the most sense to use paired short swords: they’re the best items available for dual-wielding that work with Shadow Blade. Before you get those feats, though, any combination of weapons you want to use works.

Note that Expedition to Castle Ravenloft has a sun sword, a +1 short sword that deals the damage of a bastard sword. It’s basically the sun blade without all the extra crap you don’t need; instead it costs 3,000 gp. As in, not quite 700 gp more than a +1 short sword usually would. This makes an excellent weapon to build off of; that d10 represents a +3 damage bonus over a short sword, on average. The sun blade itself is saddled with too many weak enhancements and just costs way too much money. Make sure your DM agrees that the sun sword works with Shadow Blade, too.

This doesn’t work for the OP, since he cannot use Dragon material, but for other readers: If you cannot get the sun sword or it doesn’t work with Shadow Blade, you might also consider elven lightblades, which are kind of like combo short sword/rapiers. Again, check with your DM that they are short sword enough for Shadow Blade; strict RAW, they’re not. These are exotic weapons not even remotely worth the feat you’d normally need to use them, but you’re taking a couple of levels of fighter anyway for feats, and the exoticist fighter variant from Dragon vol. 310 can get you proficiency effectively for free. Note that elven lightblades are the only possible way to have one weapon get bonuses from both elegant strikes and Shadow Blade; see the “Champion” build below for that.

Otherwise, just use short swords. The actual weapon you use is really not that important as long as it is light and works for Shadow Blade.

The gloves of the balanced hand have already been mentioned; making them double as gloves of dexterity is also an obvious priority. Also, you still do add half your Strength to damage, and your HP is on the low end, so a belt of giant strength and periapt of vitality are worthwhile, albeit at a lower priority than Dexterity. Get the best cloak of resistance generally available. Magic armor, probably angling for the fortitude or soulfire line of special abilities, is obvious. Mithral is probably your special material of choice, considering your high Dexterity.

You are going to want a speed weapon if you cannot get haste reliably cast on you. With your Dexterity, it may be difficult for your wizard to even have time to cast it before you go, and you want it for your first turn. The collision property is nice in that it multiplies on a critical hit, and various energy damage properties aren’t awful. But don’t ignore utility on your weapons; eager and warning are excellent about letting you go first, and there are weapons that improve rage or what have you, and so on. There are a lot of guides about which weapon properties you should use; this build does not have any special needs here.

Aside from that, keep up with your list of necessary magic items and peruse Bunko’s Bargain Basement for spending the rest of your money. This build does not include any built-in flight; if your alignment is flexible but your game is enforcing alignment-based rules, it’s worth being Evil just to have access to the feathered wings graft.

Barbarian 1

Your first level, your iconic level. You get rage and fast movement. You should be trading away both of these.

Rage Variant

For rage, your options are either ferocity (gain bonuses to Strength and Dexterity rather than Strength and Constitution, activate as an immediate action) or whirling frenzy (gain an extra attack). I like whirling frenzy better, but both are very solid options. Whirling frenzy will allow you to “pretend” two-weapon fighting without the feat, though.

Spiritual Totem—Lion

Complete Champion has a series of alternate class features to trade away Fast Movement for something else based on a spiritual totem. The Lion option is pounce. You need this. This is the difference from a mediocre damage build with no mobility, and a mobile damage build that is hard to pin down.

Barbarian 1/Fighter 1

Stepping aside into fighter, because you need feats. If you don’t have flaws, this is where you get Two-Weapon Fighting.

Hit-and-Run Tactics

You also take the hit-and-run tactics variant from Drow of the Underdark—you don’t need to be drow, and it allows you to add your Dexterity to damage rolls when made against flat-footed targets. That’s pretty cool, and it only costs the armor and shield proficiencies you wouldn’t use anyway. And you get +2 to Initiative, to boot.


This variant from Dragon vol. 310 isn’t available to the OP, but for others it may be useful. It gets you four exotic weapon proficiencies instead of all martial weapon proficiencies. You already have the latter from barbarian, so that’s no loss, and elven lightblades arguably function as short swords for the purpose of Shadow Blade. It’s a small bonus, but it’s basically free. And if you do manage to get into champion of Corellon Larethian, it works with elegant strikes, and thus the benefit is no longer anything like “small.”


This variant, also from Dragon vol. 310, focuses on unarmed strikes, which you won’t use much (though you could, since they are Shadow Hand weapons), but it importantly grants Improved Unarmed Strike and Endurance as free bonus feats, on top of your usual 1st-level bonus feat. It conflicts with hit-and-run tactics, and it doesn’t offer the opportunity to use elven lightblades (at least, not for free), but you need Endurance for wildrunner, so that is a pretty big deal.

Barbarian 2/Fighter 1

Uncanny dodge is nice enough. Not much to say here, class-wise.

However, it is 3rd level. Time to pick up Endurance, to qualify for wildrunner on time. Unless you went with pugilist, in which case you can actually accelerate some of your other feats. This option is best if you don’t think you’ll finish up your feats.

Barbarian 2/Fighter 2

Back to fighter, because you need feats that badly. Trap Sense is near-worthless; though Flaws can eliminate the need for fighter here, I still don’t recommend barbarian.

The feat you need here is Martial Study for a Shadow Hand maneuver. This allows you to get Hide in-class (which you’ll need for wildrunner), and you need a Shadow Hand manuever for Shadow Blade. Your options are shadow blade technique, which could easily be refluffed as a two-weapon technique, and clinging shadow strike, which gives the target a 20% chance to miss for the round after you hit.

Alternatively: Barbarian 1/Fighter 1/Ranger 2

Skills are a problem; wildrunner requires a ton of them, and barbarian and fighter are not high-skill classes. You can do well with half-decent Intelligence (eternal blade gives you a few bonuses based on it), but it’s worth noting that we’re getting Two-Weapon Fighting and Endurance—bonus feat options for Ranger 2 and 3. Thus, you can replace two levels of fighter with those two levels of ranger, which is a high-skill class (the elf substitution level in Races of the Wild even give you 8+Int!). The obvious problem is you can’t just jump to Ranger 2, so you also lose a level of barbarian as well.

We also really do want a level of fighter for hit-and-run tactics, lightblades, and/or Endurance, so trading one level of fighter rather than both, and only going to Ranger 2, is advantageous. That probably ends up being the best choice: you lose out on uncanny dodge, and an average of 3 HP (4 HP if you do take the elf substitution level, since it has d6 HD), but you retain hit-and-run tactics.

Ultimately, this works out to a lot more skills, better saves, a favored enemy, and Track and wild empathy, at the aforementioned cost of uncanny dodge, and 3 HP.

Barbarian 2/Fighter 2/Crusader 1

You gain five manuevers, a stance, and the ability to delay a small amount of damage you take for a round, gaining bonuses when you do so. Very barbarian-esque. Two of the maneuvers (or one maneuver, and the stance) need to be Devoted Spirit for eternal blade. Note that, since you’ll want to use a Shadow Hand stance in order to use Shadow Blade, your choice of stance matters only until you get that feat (which sadly won’t be for a while unless you went with pugilist).

Note that, if you like any of the 1st- or 2nd-level Stone Dragon maneuvers, now is the time to pick them up; Eternal Blade doesn’t get the discipline as an option. So definitely get mountain hammer (though its out-of-combat utility means that would be my recommendation anyway), and any others you like.

Battle leader’s charge gets a fairly sizable damage bonus (+10) on “your charge attack.” Ask your DM how pounce interacts with this; it’s completely unclear. If you cannot benefit from pounce while initiating battle leader’s charge, it’s not worth it; your other attacks should add more than 10 damage. If you can get pounce, and the +10 applies to all of those attacks, your DM is insane and this is by-far the most powerful thing you could grab right now. If I were your DM, I’d give you the +10 on the first attack, and let you have the rest as normal.

Beyond that, I like tactical strike for a decent damage bonus if you can’t full-attack or charge, plus it lets your allies reposition, which is nice. Crusader’s strike is solid enough if you need emergency healing.

Alternatively: Barbarian 2/Fighter 2/Warblade 1

(or Barbarian 1/Fighter 1/Ranger 2/Warblade 1)

In theory, you could take warblade instead of crusader; that does get you that nice d12 HD. The problem is that warblade only learns 3 maneuvers and 1 stance, and eternal blade requires two from Devoted Spirit or Diamond Mind—of which, the warblade can only access Diamond Mind, and those maneuvers often involve Concentration checks you can’t make while in a rage. In fact, your only options that don’t involve Concentration are stance of clarity and emerald razor. That takes the stance, and one manuever.

For your second and third maneuvers, there are roughly three options.

First, wolf fang strike would allow you to attack with each weapon as a standard action; that’s a far cry from the frenzy of blades you get on a full-attack, but if you have to use a standard action, it’s something. More importantly, it would allow you to then get sudden leap, which can be a source of swift-action movement once per fight; that can mean a full-attack where you otherwise couldn’t have. But ultimately pounce means that most of the time, charging will get you where you want to go and let you full-attack, so these are not as crucial as they otherwise would be.

Barring that pair, I’d definitely grab mountain hammer for the same reasons I would with crusader. In fact, considering that we have pounce, I’d much prefer mountain hammer. For your third maneuver, battle leader’s charge remains the same option it was for crusader, while wall of blades is a solid defensive option that also means you’ll be able to take Iron Heart maneuvers that require you to already have one when you enter eternal blade. That’s really nice.

Actually, on that point, it’s well worth asking your DM if you can qualify for eternal blade with a pair of Iron Heart maneuvers. If yes, punishing stance and wall of blades are my suggestions (along with mountain hammer and hopefully battle leader’s charge). At that point, warblade becomes a very serious contender compared to crusader.

Barbarian 2/Fighter 2/Crusader 1/Wildrunner 5

First level of wildrunner is lackluster, but you’re in! Congratulations, that’s awesome. From there, we just keep taking levels. None of the class features present options, but the primal scream feature is the big one to look for, especially the initial 2nd-level version. Hide in plain sight certainly isn’t terrible.

Your sixth-level and ninth-level feats need to be Weapon Focus (short sword is your best bet) and Martial Stance for something Shadow Hand, respectively. If you wait until 9th level, you can take assassin’s stance for +2d6 Sneak Attack damage, but the 1st-level child of shadows and thicket of blades options are both quite good as well. For that matter, the other 3rd-level stance, dance of the spider, is pretty damn cool.

Note that if your DM allows some houserules that make it possible to get into champion of Corellon Larethian, trading two levels of wildrunner for two levels of that is very much worth it.

Barbarian 2/Fighter 2/Crusader 1/Wildrunner 5/Eternal Blade 10

At eleventh level, start taking eternal blade levels instead of wildrunner levels; you have the best things from wildrunner, and eternal blade is an awesome prestige class. I suggest focusing on either Iron Heart or Devoted Spirit maneuvers, but feel free to take whatever looks cool; it will be. Avoid Diamond Mind, as it is incompatible with rage.

The feats you have left to get are Shadow Blade (finally) and Extra Rage (finally). Both of these may have been gotten much earlier if you have Flaws.

Level Class Special Feat
1st Barbarian Lion spirit totem, ferocity or whirling frenzy Weapon Finesse
2nd Exoticist¹ Elven lightblade proficiency,¹ hit-n-run tactics Two-Weapon Fighting
3rd Bar 2 Uncanny dodge Endurance
4th Ftr 2 Martial Study (Shadow Hand)
5th Crusader Maneuvers
6th Wildrunner Martial Stance (Shadow Hand) or Weapon Focus (short sword)
7th Primal scream
9th Weapon Focus (short sword) or Martial Stance (Shadow Hand)
10th Hide in plain sight
11th Eternal Blade Blade guide, eternal training, maneuvers
12th Guided strike Shadow Blade
13th Armored uncanny dodge
14th Eternal knowledge
15th Extra Rage
16th Defensive insight
18th Tactical insight any
20th Island in time
  1. The exoticist variant fighter requires Dragon content and is unavailable to the querent. In that case, regular fighter is fine, elven lightblades don’t really add that much anyway. If you can get a pair of sun swords, you may not even want them.

Final Build with Flaws

Flaws dramatically improve things by allowing you to take Shadow Blade and Extra Rage much sooner.

Level Class Special Feat
1st Barbarian Lion spirit totem, ferocity or whirling frenzy Martial Study (Shadow Hand), Martial Stance (island of blades), Shadow Blade
2nd Exoticist¹ Elven lightblade proficiency,¹ hit-n-run tactics Weapon Finesse
3rd Ranger Favored enemy Endurance
4th Two-Weapon Fighting
5th Crusader Maneuvers
6th Wildrunner Extra Rage
7th Primal scream
9th Weapon Focus (short sword)
10th Hide in plain sight
11th Eternal Blade Blade guide, eternal training, maneuvers
12th Guided strike any
13th Armored uncanny dodge
14th Eternal knowledge
15th any
16th Defensive insight
18th Tactical insight any
20th Island in time
  1. Exoticist requires Dragon content and is unavailable to the querent. In that case, regular fighter is fine, elven lightblades don’t really add that much anyway. If you can get a pair of sun swords, you may not even want them.

“Starting high” Champion build with Flaws

This build has two conditions before I’d consider it:

  • The game is starting at a minimum of 10th level.
  • The DM allows the elven lightblade to not just count as a short sword for the listed feats, but also for Shadow Blade.

It also relies on Dragon, which the OP explicitly cannot use.

Anyway, the idea is to use an elven lightblade rather than a short sword (or sun sword), and thus get Dex-to-damage from both Shadow Blade, and the champion of Correlon Larethian’s elegant strikes feature. That’s a pretty big deal, a much bigger deal that the sun sword’s bastard sword damage (+3 vs. something in the 15-17 range at 20th).

Qualifying for champion of Corellon Larethian remains inherently problematic, though. I’d very strongly consider whether or not I could do more with three feats than elegant strikes does. I probably could. Dodge, Combat Expertise, and Mounted Combat are not good feats. Combat Expertise doesn’t even work while using rage.

Fighter does help a lot here, though; the exoticist variant from Dragon vol. 310 gets Exotic Weapon Proficiency four times. This is important because we want to use an elven lightblade, but we also need proficiency in elven thinblades or courtblades for champion of Corellon Larethian.1 Which you choose, and what you do with the other two proficiencies, doesn’t much matter since this build relies heavily on those elven lightblades.

We can also add back that second level of fighter (or third level of ranger, if ignoring multiclass penalties; I tend to feel 4 skill points is well-worth an average 1 HP) to get another feat, since Wildrunner 3 isn’t exactly an amazing level.

Note that warblade is no longer an option; we need crusader for heavy armor proficiency. We have to skip hit-n-run tactics for the same reason: it prevents us from gaining heavy armor proficiency from multiclassing, we would have to actually take Heavy Armor Proficiency as a feat and we can’t afford to. Not that we would be caught dead in heavy armor (or equivalently, being caught in heavy armor would be a death sentence), but champion requires it so have it we must.

You can also delay Martial Stance until 9th, for the option of taking assassin’s stance, which opens up Craven (Champions of Ruin) for a large damage boost when you attack opponents in a sneak attack situation. Attacking a flat-footed foe with hit-and-run tactics, elegant strikes, Shadow Blade, assassin’s stance, and Craven is looking at +75 damage per attack (with a high-crit weapon and only 2d6 of that damage doesn’t get multiplied on a crit).

By the way, in case that last line didn’t suggest it, a pair of scabbards of keen edge are good high-level investments. Improved Critical is fairly-obviously not a great choice, seeing how feat-starved we are, and keen is more expensive in the long run (keen is cheaper on a +4-equivalent weapon, but more expensive on a +5-equivalent or higher).

In general, crit-fishing is a fairly low-power strategy, but we have several things going for us here. We are already maximizing our attacks per round (TWF, pounce, whirling frenzy, speed or haste, island in time), we are already using high-crit weapons, and we already have a ton of unrolled (read: crit-multiplied) damage. When 16k becomes cheap at high levels, doubling our already-solid chances of getting a crit that’s going to hit ridiculously hard without us doing anything extra for chump change is a no-brainer.

Level Class Special Feat
1st Barbarian Lion spirit totem, ferocity or whirling frenzy Combat Expertise, Expeditious Dodge, Weapon Finesse
2nd Exoticist Elven lightblade proficiency Weapon Focus (short sword)¹
3rd Ranger Favored enemy Mounted Combat
4th Two-Weapon Fighting
5th Endurance
6th Crusader Maneuvers Martial Study (cloak of deception or shadow jaunt)
7th Wildrunner
8th Primal scream
9th Champion of Corellon Larethian Martial Stance (assassin’s stance)
10th Elegant strikes
11th Eternal Blade Blade guide, eternal training, maneuvers
12th Guided strike Shadow Blade
13th Armored uncanny dodge
14th Eternal knowledge
15th Craven?
16th Defensive insight
18th Tactical insight Extra Rage?
20th Island in time

1 Weapon Focus (longsword) is another option, and it would pull double-duty qualifying for eternal blade, but we don’t use longswords, and getting the proficiency free gives us more latitude in when to pick up that Weapon Focus feat.

c# – How to implement Interface and optimize load of data?

I’m new to .NET and find it hard to connect all pieces from Youtube tutorials. The code below works, but I assume it can be (greatly?) improved?

Basically I want to display a product category and the products within. I guess loading the data could be improved? And I can’t figure out how to implement an Interface?

Desired output: Loading the models with data


public IActionResult Index()
   var data = CollectionData.GetCollectionById(1);
   return View(data);


public class CollectionData
   public static CollectionModel GetCollectionById(int id)
       SqlDataAccess sql = new SqlDataAccess();
       var p = new { id = id };

       var output = sql.LoadData<CollectionModel, dynamic>("collection_get_by_id", p, "DefaultConnection");
       output(0).CollectionProducts = sql.LoadData<CollectionProducts, dynamic>("products_get_by_collectionid", p, "DefaultConnection");

       return output(0);


public class CollectionModel
    public string Title { get; set; }
    public string SubTitle { get; set; }
    // Additional properties removed
    public List<CollectionProducts> CollectionProducts { get; set; }

public class CollectionProducts
    public string Title { get; set; }
    public decimal Price { get; set; }
    // Additional properties removed

mathematical optimization – How to optimize variables in a function to minimize its difference with the desired behaviour function

So lets say I have a function f(x,y,z,b) and a function g(x) that represents the desired behaviour of function f. How do I optimize the variables y,z,b in function f to get as close as possible to the function g(x)? x varies from 0 to 360.
So basically i want integral of (f(x,y,z,b)-g(x))dx from 0 to 360 to be as close to zero as possible. My end goal is to set y,z and b as constants in f to fit the behaviour of function g as close as possible.

Thank you!

python – How to optimize this majority vote method

I have the following code to do a majority vote for data in a dataframe:

def vote(df, systems):
    test = df.drop_duplicates(subset=('begin', 'end', 'case', 'system'))
    n = int(len(systems)/2)
    data = ()
    for row in test.itertuples():
        # get all matches
        fx = test.loc((test.begin == row.begin) & (test.end == row.end) & ( ==
        fx = fx.loc(fx.system.isin(systems))

        # keep if in a majority of systems   
        if len(set(fx.system.tolist())) > n:
    out = pd.concat(data, axis=0, ignore_index=True)
    out = out.drop_duplicates(subset=('begin', 'end', 'case'))
    return out(('begin', 'end', 'case'))  

The data look like:

systems = ('A', 'B', 'C', 'D', 'E')

df = begin,end,system,case

The expected output should be:

out = begin,end,case

IOW, if desired elements begin, end, case appear in a majority of systems, we accumulate them and return them as a dataframe.

The algorithm works perfectly fine, but since there are hundreds of thousands of rows in it, this is taking quite a while to process.

One optimization I can think of, but am unsure of how to implement is in the itertuples iteration: If, for the first instance of a filter set begin, end, case there are matches in

fx = test.loc((test.begin == row.begin) & (test.end == row.end) & ( == & (fx.system.isin(systems)))

then, it would be beneficial to not iterate over the other rows in the itertuples iterable that match on this filter. For example, for the first instance of 10,14,A,0365 there is no need to check the next two rows, since they’ve already been evaluated. However, since the iterable is already fixed, there is no way to skip these of which I can think.