java – Can I replace instanceof if I cannot use a common interface (third pary API)?

I’m using Telegram API and I’ve different methods wich returns different type of information like this:

public SendMessage getTextMessage(Long chatId, String text) {
        return new SendMessage()
                .enableMarkdown(false)
                .setChatId(chatId)
                .setText(text);
    }

public AnswerCallbackQuery getPopUpAnswer(String callbackId, String text) {
        return new AnswerCallbackQuery()
                .setCallbackQueryId(callbackId)
                .setText(text)
                .setShowAlert(true);
    }

public EditMessageText getEditedMessage(Long chatId, Integer messageId, String text){
        return new EditMessageText()
                .setChatId(chatId)
                .setMessageId(messageId)
                .setText(text);
    }

public SendPhoto getPhotoMessage(Long chatId, GooglePlayGame game) {
        return new SendPhoto().setChatId(chatId)
                .setPhoto(game.getPictureURL())
                .setCaption(game.toString());
    }

They have one parent PartialBotApiMethod.
In main method I handle and execute (send) them:

PartialBotApiMethod<?> responseToUser = updateReceiver.handleUpdate(update);
try {
     execute(responseToUser); //error
    }
catch (TelegramApiException e){
     e.printStackTrace();
    }

But I can’t execute PartialBotApiMethod object, only BotApiMethod and their subs. SendPhoto is not in one hierarchy with others, that’s why I can’t put SendPhoto result to BotApiMethod type variable.
And I can’t cast like this:

try {
     execute((BotApiMethod)responseToUser);
    }
catch (TelegramApiException e){
     e.printStackTrace();
    }

Because SendPhoto doesn’t extends BotApiMethod and I’ll give a ClassCastEx.

So I gonna use instanceof and cast “personally”:

PartialBotApiMethod<?> responseToUser = updateReceiver.handleUpdate(update);
        if (responseToUser instanceof SendMessage) {
            try {
                execute((SendMessage)responseToUser);
            } catch (TelegramApiException e) {
                e.printStackTrace();
            }
        }
        else if (responseToUser instanceof SendPhoto) {
            try {
                execute((SendPhoto) responseToUser);
            } catch (TelegramApiException e) {
                e.printStackTrace();
            }
        }
        else if (responseToUser instanceof AnswerCallbackQuery) {
            try {
                execute((AnswerCallbackQuery)responseToUser);
            } catch (TelegramApiException e) {
                e.printStackTrace();
            }
        }
        else if (responseToUser instanceof EditMessageText) {
            try {
                execute((EditMessageText)responseToUser);
            } catch (TelegramApiException e) {
                e.printStackTrace();
            }
        }

Do I’ve better options or just stay with instanceof?

functions – Replace word in “the_content” only for index.php

I have some posts with video tag that contains autoplay (they should autoplay when you access the post page).

I am using the the_content to show these videos on index page.

The problem is that when you access the home page, all the videos start playing.

I have used the following function to remove it:

function replace_ap($text){
    $replace = array(
        'autoplay=""' => ''
    );
    $text = str_replace(array_keys($replace), $replace, $text);
    return $text;
}
 
add_filter('the_content', 'replace_ap');

but now the “autoplay” attribute is removed from the post pages also.

How can I remove it only from the index ?

My thought was to create a function that gets the content and add the filter to this function, then call it from index.php instead of “the_content”, but I don’t know how or if it’s possible

Thank you!

forms – Drupal 8 form_alter Ajax suffix replace

I’m trying to rewrite a form item’s suffix on an AJAX callback and it keeps prepending the first choice and then doing nothing else. My code:

function my_dashboard_form_alter(&$form, DrupalCoreFormFormStateInterface $form_state, $form_id){
  if($form_id == 'node_job_listing_owner_job_form_form'){
    $tid = $form_state->getValue('field_job_description')(0)('target_id');
    if(empty($tid)){
      $tid = $form('field_job_description')('widget')('#default_value')(0);
    }
    $link = null;
    if(!empty($tid)){
      $link_url = DrupalCoreUrl::fromRoute('entity.taxonomy_term.canonical', (
        'taxonomy_term' => $tid
      ), (
        'attributes' => (
          'class' => ('use-ajax'),
          'data-dialog-type' => 'dialog',
          'data-dialog-options' => DrupalComponentSerializationJson::encode(('width' => 420)),
          'data-dialog-renderer' => 'off_canvas',
        ),
      ));
      $link = Drupal::l('Preview Job Description...'.$tid, $link_url);
    }

    $form('field_job_description')('#suffix') = $link;
    $form('field_job_description')('widget')('#ajax') = (
      'callback' => 'updateJobDescriptionPreviewLink',
      'wrapper' => 'edit-field-job-description-wrapper',
      'event' => 'change',
    );
  }
}

function updateJobDescriptionPreviewLink(&$form, DrupalCoreFormFormStateInterface $form_state){
  return $form('field_job_description');
}

Basically, I’m trying to put a link below the “Job Description” drop down to preview the description of that term. I have the term id appended to the link text temporarily so I can see what happens. When I edit an existing node, it renders the link correctly the first time (i.e. “Preview Job Description…102”). But then, if I select a different option, it prepends another link to the existing suffix (i.e. “Preview Job Description…99 Preview Job Description…102”). Both links work correctly, but obviously two links aren’t what I want. And also after that, it won’t change anymore no matter what I select.

I feel like there’s something simple I’m overlooking, but I confess Drupal AJAX has always confused me somewhat. Any ideas? Thanks!

email server – How can I replace part of a body with an empty string using Postfix?

I’ve set up a Linux server running Postfix that I’m using to send and relay emails, and one of the tasks that my mail server does is take incoming emails that are sent to specific addresses and forward them to email addresses that belong to another domain. I used this tutorial to set it up, and I’ve confirmed that the mail forwarding works as intended. However, some of the incoming emails have a confidentiality notice, and I want to strip those before forwarding the emails because the email address that the emails are forwarded to handles the emails differently based on the content of the body, and if the body contains the notice, the email will not be handled properly.

To give an example, I set up an alias called forwarding@example.com that sends email to an external address. I was then able to find and replace part of the confidentiality notice, but I am unable to replace it with an empty string, and I am unable to replace the entire notice. I added the following line in /etc/postfix/main.cf:

body_checks = pcre:/etc/postfix/body_checks

And the file `/etc/postfix/body_checks contains the following:

/CONFIDENTIALITY NOTICE:.*/ REPLACE ""
/Testing/ REPLACE ""

I’m able to send emails to forwarding@example.com, but instead of replacing the found strings with an empty space, the strings are replaced by the literal characters "". I’ve tried putting an empty space there instead, but when I do that I get the error warning: REPLACE action without text in body_checks map when I restart Postfix. I read the documentation, but could not find any examples of a string being replaced with an empty string. Does anyone know how to replace the found text with an empty string? Please let me know if you need any more information, and I’ll be happy to provide it.

linux – How can I replace numbers in filenames with leading zero in bash?

There are similar questions about how to add numbers with leading zero etc. but in my case my filename has two numbers which is the number of chapter and the number of page. Both lack the leading zero, so they aren’t sorted alphabetically. Using rename or any other method I want to convert files like these:

file_1_1 to file_01_01
file_1_12 to file_01_12
file_12_1 to file_12_01
...

I tried this:

rename 's/d+/sprintf("%02d",$&)/e' *.mp3

but it just add leading zero to the chapter number.

list manipulation – Inverting replace direction

When we have a long list of rules it would be resonable choosing a functional approach, which is much faster than rule based one. In such cases consider e.g.

Reverse /@ rep

Sometimes it would be more efficient using Transpose twice than Map once, e.g.

Rule @@@ Transpose @ Reverse @ Transpose[ List @@@ rep]

Nonetheless ususally we need not to play with long lists and a simple pattern matching is quite sufficient, and so another approach might be e.g.

rep /. Rule[a_, b_] :> Rule[b, a]
 {b1 -> a1, b2 -> a2, b3 -> a3}

Mind using RuleDelayed in cases when it matters instead of Rule.

dnd 5e – Does a multiclassed Hexblade warlock/paladin’s Cha modifier stack with their Str or Dex modifier for attack rolls? Or does it replace Str/Dex mods?

I’m creating a fun villainous figure for my campaign. The choice has fallen on a Paladin-Warlock hybrid. The general idea is to take 2 levels in Paladin for Divine Smite, and then pound 4-5 levels into Hexblade Warlock. Blade-summoning for the flavour, good at all distances, quite mobile, and pretty tanky due to allowed armour-class.

Since Hexblade warlock can use his Cha for attack rolls, will it stack with his Str or Dex modifier depending on the weapon? Or will I have to add my Cha mod instead of those stats?

dnd 5e – If a feature gives proficiency in a skill you are proficient with, can you always choose any skill to replace that proficiency?

The quoted text applies only to backgrounds

That text is found in chapter 4: Personality and Background which tells us right from the start that the rules found here most likely only apply to backgrounds.

Furthermore, the text in question states in full (emphasis mine):

Each background gives a character proficiency in two skills. Skills are described in the Using Ability Scores section.

In addition, most backgrounds give a character proficiency with one or more tools. Tools and tool proficiencies are detailed in the Equipment section.

If a character would gain the same proficiency from two different sources, he or she can choose a different proficiency of the same kind (skill or tool) instead.

The previous two paragraphs are specifically about backgrounds so it makes sense to assume the third is as well.


Another reason to believe this is not a general rule is its location. Why would such a rule appear in the section on backgrounds and then not in the rules on “Proficiency Bonus” where one would really expect to find it?


However, the greatest piece of evidence is various features that do let you choose another proficiency if you already have one:

The various Artificer subclasses grant you a tool proficiency, and explicitly state that if are already proficient in that tool you can pick a different tool to gain proficiency in.

If there were a general rule that acquiring the same proficiency again meant you could pick a new one, then there would be no need for this feature to state what it does. The same logic applies to the Samurai Fighter’s Elegant Courtier feature and the Gloom Stalker Ranger’s Iron Mind feature though both grant saving throw proficiencies, so one could potentially argue they aren’t actually covered by the text in chapter 4.


If you’d really like to see a tweet from lead rules designer Jeremy Crawford, that exists too:

The proficiency rule for backgrounds applies when you gain your background at 1st level. It has no relevance outside that context.

dnd 5e – Would it be unbalanced to let a Tempest Cleric replace one of their domain spells for the 4th-level spell Storm Sphere?

As a DM I would call it slightly imbalanced

Since domain spells are considered always prepared, there is a quick trick to figure out value/balance; reverse the conditions.

At 7th level, a Tempest cleric gets two domain spells; Control Water and Ice Storm. These are always prepared above and beyond what the cleric can have prepared. This means that if they want to also have Storm Sphere they would have to use up one of their prepared spots.

For the sake of argument, we’ll say that they can prepare 11 non-domain spells (level 7 + 4 for an 18 Wisdom)

If we reversed the spells, Control Water must be manually prepared and Storm Sphere is a “freebie”, what is the likelihood that the cleric would choose Control Water as one of those 11?

Unless you were specifically going on an adventure where there is a great chance to encounter a large body of water, I would imagine the chance being very low. Whereas Storm Sphere can be a useful attack no matter what.

So you would be trading a niche spell, Control Water, for an always useful attack spell, Storm Sphere. To me, it sounds like the player is just looking to not be stuck with a rarely used “freebie”. They should feel sorry for Arcana clerics that are stuck with Nystul’s magic aura and Leomund’s secret chest

Now, is it going to change the world? No

Will it give the player any great advantage? Unless you’re going through a water campaign, it’s basically an extra spell they can prepare.

javascript – Use TypeScript in backend to replace Python web framework

My webservice runs on Nginx to deliver static files and redirects all /api/v1/ calls to a Python Flask backend (by acting as a reverse proxy for these calls). My frontend is written with Angular, and therefore written in TypeScript.

Since Angular was my first dive into the JavaScript/TypeScript world, I would like to update my experience on the backend for this as well. So far I always used Python or C++. Considering the fact that I never worked with JS/TS on the backend, where do I start? What are my options here?

Could I use Node.js to replace my Python backend? After two weeks of working with Angular, I still don’t know if Angular even has a proper backend system. Or do I need purely Node.js here? Can anyone shed some light for me on this?

E.g. there are a variety of functionalities the frontend and backend use, e.g. to check if an email address is valid. At the moment one implementation is in TypeScript, the other is in Python, so quite redundant.