java – Ensuring if an object is Assignable from a class type

I am trying to ensure type in the below method. How to reduce its cognitive complexity to below 15 from the current 27? It looks more readable as it is? Is there a way to break this down to make it more readable?

Shifting some of the checks to separate method will be one way but is there a better way?

private Object ensureType(Class<?> expectedClass, Object value) {
    if (value == null)
        return null;
    Class<?> valueClass = value.getClass();
    if (expectedClass.isAssignableFrom(valueClass))
        return value;

    if (expectedClass.isAssignableFrom(String.class)) {
        return value.toString();
    if (expectedClass.isAssignableFrom(Date.class)) {
        if (Number.class.isAssignableFrom(valueClass)) {
            return new Date(((Number) value).intValue());
        try {
            return formatter.parse(value.toString());
        } catch (ParseException e) {
            throw new ClassCastException("argument " + value + " of type " + valueClass + " cannot be converted to "
                    + expectedClass + ":" + e);
    if (expectedClass.isAssignableFrom(Integer.class)) {
        if (Number.class.isAssignableFrom(valueClass))
            return ((Number) value).intValue();
        return Integer.parseInt(value.toString());
    if (expectedClass.isAssignableFrom(Double.class)) {
        if (Number.class.isAssignableFrom(valueClass))
            return ((Number) value).doubleValue();
        return Double.parseDouble(value.toString());
    if (expectedClass.isAssignableFrom(Float.class)) {
        if (Number.class.isAssignableFrom(valueClass))
            return ((Number) value).floatValue();
        return Float.parseFloat(value.toString());
    if (expectedClass.isAssignableFrom(Short.class)) {
        if (Number.class.isAssignableFrom(valueClass))
            return ((Number) value).shortValue();
        return Short.parseShort(value.toString());
    if (expectedClass.isAssignableFrom(Byte.class)) {
        if (Number.class.isAssignableFrom(valueClass))
            return ((Number) value).byteValue();
        return Byte.parseByte(value.toString());
    if (expectedClass.isAssignableFrom(Long.class)) {
        if (Number.class.isAssignableFrom(valueClass))
            return ((Number) value).longValue();
        return Long.parseLong(value.toString());
    if (expectedClass.isAssignableFrom(Boolean.class)) {
        return Boolean.parseBoolean(value.toString());

    throw new ClassCastException(
            "argument " + value + " of type " + valueClass + " cannot be converted to " + expectedClass);

PS: I am moving this question from Stackoverflow to CR as it was suggested in the comments.

c# – design pattern for ensuring that a container object has at most one instance of an editor

My application (VSTO/C#) handles excel files editing some cells and inserting some rows.
My problem is more generlaized than this though, and is about defensive coding the class that acts as edtior.

The design is based on a wrapper object for the worksheet, let’s call it SheetTable; it contains the fixed data like the positions of the columns and so on.
When I want to change data in my sheet I use another wrapper object, a TableRange that has a property of SheetTable and so knows the table structure inside the sheet.
This is the editor object i was talking about.

When it writes down to the worksheet it handles with particular care operations like inserting rows and deleting rows, because they can invalidate some fix references that the application may hold.
If there are multiple TableRange object, they can mess-up with such references.
That’s why I’m looking for a well established pattern for allowing at most one instance of TableRange per TableSheet at a time.
The problem per-se is easy, but i’m interested in some details.

The reason why TableRange is not implemented as a part of TableSheet (the 1-1 relation would suggest so) is that I want to be able of throwing away the state of TableRange in the case of canceled updates without affecting the state of TableSheet. So, if the reference of the single TableRange is held by the TableSheet, I need an explicit way of get rid of it.
Something like the following

public class TableSheet {

    private TableRange editingRange;

    public TableSheet EditingRange {
            if (editingRange==null) {
                editingRange = new TableRange(this);
         return editingRange;

    public void CancelEdit() {
        editingRange = null;

Here, the TableRange is lazy initialized when accessing the EditingRange property. This is to reduce the number of states of the object from a client perspective.

I could get rid of the TableRange instance the very same way via a setter and assigning null.

public TableSheet EditingRange {
   get {...}
   set editingRange = value;

This would allow the user to assign null. But it would allow the user to assign also another TableRange instance (provided that she can create one, that shouldn’t be the case since the constructor should be internal).
Not only that, but if the need of adding deinitialization code should arise, I wouldn’t have a place to put it and I should redesign the API. That why I come up with the CancelEdit() method.

So these are my basic ideas on this pattern. what do you think? Do they address the main concerns of this problem? Would you change something? Is there a well-established design pattern for such a problem?

windows – How do I run a software(with VM detection capability) on a VM while ensuring the software doesn’t detect it’s being run on a VM?

Yeah, so I have this web browser(like SEB browser) application that claims it can detect when it’s in a virtual environment rather than a native one and would refuse to run properly on successful detection. Is there a bypass to this? In this case i’d like to alter perhaps the VM/OS and not the application itself. The VM is on-site and the application is only available on windows, macOS AND iOS. A solution for any of all of these platforms would do.

website design – Ensuring users’ email addresses are kept up to date

My site needs users to register with email addresses that are not freely available, like company or university email addresses. When users register, they get sent an email containing a link to click on so that we know the address is valid at that time. However, after a while, people are going to move companies, leave university etc. I would like to ensure that these email addresses are kept up to date. How can I do that whilst being as least annoying as I can? (eg every X months I could send an email saying please verify this is still your email address, but it seems fraught with danger.)

probability – Ensuring continuity of random processes

I have been exploring probability and random variables a little more in depth recently as I only got a very rudimentary education on probability theory in my undergrad, and I am curious how one would ensure continuity for a continuous random process. For a function $f: t rightarrow mathbb{R}$ to be continuous at a point $t_0$, we must have:

$$ lim_{t rightarrow t_0} f(t) = f(t_0) $$

Right? But when dealing with the sample path of a continuous random process, how can one ensure that this will occur as one approaches $t_0$? Couldn’t the random variable theoretically fluctuate indefinitely as one approaches $t_0$ thereby making the limit undefined? If that is true, then how is this addressed to produce a mathematically sound theory of continuous random processes?

c # – How to send messages in the order they were queued, while ensuring that client B does not have to wait until client A has received his message?

I have a simplified producer / consumer pattern implemented below. The code outputs:


1 second delay


1 second delay


1 second delay


What approach can I take here to get rid of the 1 second delay between different letters?

What I'm looking for is something like



1 second delay



It is important that clients A and B receive the messages in the order they were queued, but I do not want other clients to be blocked while processing for a client takes a long time. Using two BlockingCollections and two threads of consumption is not an option, because the user count is dynamic.

using System;
using System.Collections.Concurrent;
using System.Threading.Tasks;

namespace ConsumerProducer
    public enum ClientId

    class WebSocketMessage
        public ClientId ClientId { get; }

        public WebSocketMessage(ClientId clientId)
            ClientId = clientId;

        public async Task LongRunningSend()
            await Task.Delay(TimeSpan.FromSeconds(1));

    class Program
        public static BlockingCollection Messages = new BlockingCollection();

        static async Task Main(string() args)
            var consumer = Task.Run(async () =>
                foreach (var message in Messages.GetConsumingEnumerable())
                    await message.LongRunningSend();

            ClientId clientId = ClientId.B;
            while (true)
                // Flip between A and B
                clientId = clientId == ClientId.A ? ClientId.B : ClientId.A;

                Messages.Add(new WebSocketMessage(clientId));

                await Task.Delay(TimeSpan.FromMilliseconds(100));

sql – Ensuring referential integrity in the child, group relationship

I'm not going to lie: Sql Server is not in the top 10 of my skill set, but it's something I have to do from time to time.

Also, I'm using Entity Framework, so a solution is required because it does not yet support foreign key relationships.

In this scenario, I have 3 tables, which represent certain content, stacked in a & # 39; grouped & # 39 ;. relationship. I use the term grouped because a child can be in several groups instead of being alone with a single parent.


Contains information about keywords.

A keyword can only be assigned to a page, but a page can have several associated keywords.

CREATE TABLE [dbo].[TopicKeyword] (
    [Id]      SMALLINT NO NULL,
    [Keyword] VARCHAR (100) NOT NULL,
    [Volume]  INT NO NULA,
RESTRICTION [FK_TopicKeyword_PageMeta] EXTERNAL KEY ([PageId]) REFERENCES [dbo].[PageMeta] ([Id])

    IN [dbo].[TopicKeyword]([PageId] ASC);

    IN [dbo].[TopicKeyword]([Id] ASC, [PageId] ASC);

The next two tables represent the parent-child relationship.

SubjectContent (boy)

Contains keywords for a & # 39; Cluster & # 39;

KeywordId must exist in the TopicKeywords table.
ParentKeywordId must exist in the TopicCluster table.

Each ParentKeywordId / KeywordId combination must be unique; In addition, both can not be the same.

CREATE TABLE [dbo].[TopicContent] (
    [ParentKeywordId] SMALLINT NO NULL,
    [KeywordId]       SMALLINT NO NULL,
RESTRICTION [PK_TopicContent] PRIMARY CLUTCH KEY ([ParentKeywordId] ASC, [KeywordId] ASC),
RESTRICTION [FK_TopicContent_TopicCluster] EXTERNAL KEY ([ParentKeywordId]) REFERENCES [dbo].[TopicCluster] ([KeywordId])
RESTRICTION [FK_TopicContent_TopicKeyword] EXTERNAL KEY ([KeywordId]) REFERENCES [dbo].[TopicKeyword] ([Id])
RESTRICTION [CK_TopicContent_ParentKeywordId] CHECK[ParentKeywordId]<>[KeywordId])

    IN [dbo].[TopicContent]([KeywordId] ASC);

TopicCluster (father)

Contains the cluster entity / parent / group.

The KeywordId must exist in the TopicKeywords table, and the KeywordId / PageId combination must be valid.

KeywordId must be unique.

A page (PageId) can only own a TopicCluster, so, in theory, it must be unique.

CREATE TABLE [dbo].[TopicCluster] (
    [KeywordId] SMALLINT NO NULL,
    [PageId]    SMALLINT NO NULL,
RESTRICTION [FK_TopicCluster_TopicKeyword] EXTERNAL KEY ([KeywordId]) REFERENCES [dbo].[TopicKeyword] ([Id])
RESTRICTION [FK_TopicCluster_TopicKeyword2] EXTERNAL KEY ([KeywordId], [PageId]) REFERENCES [dbo].[TopicKeyword] ([Id], [PageId])

    IN [dbo].[TopicCluster]([KeywordId] ASC, [PageId] ASC);

This is my attempt at & # 39; novice & # 39; I would appreciate any advice and suggestions for improvement.

dns – Ensuring a public Pi-Hole?

I'm using these instructions to set up a Pi-Hole on a Google Calculator server always free.

The ultimate goal is to route DNS requests from my home Google Wi-Fi router, as well as be able to use it through my phone when I'm away. (Also giving access to friends and family)

I can not set up a VPN with the Google Wi-Fi router: only custom DNS, but it seems that I could restrict access to the process instance by only allowing access to my home network through the Compute firewall rules. Google. (The home network has a static IP)

The problem with that, is that I would be excluded from using it with my phone.

I think I am attacking the problem in the wrong way. I would love to be able to simply point my phone and home network to the process instance through custom DNS. The problem with that is that I am endangering the Internet if I allow the server to be public access.

Is there another, perhaps more creative, way to do this?

In the comments on this page, there is a suggestion to use some iptable tools such as fail2ban. Is that good practice?

First domain name: ensuring the availability of the name in the future.

Your question is relevant, but for the most part it does not have a definitive answer in any way. Nothing is everlasting: the records may change and the eligibility rules may change. The policies regarding infringement of disputes and trademarks may also change.

First you must divide the world between the gTLDs versus the ccTLDs and make sure to take into account perimeter cases, such as .TV or .co that are administratively ccTLD but that are executed and commercialized as gTLD.

All gTLDs are governed by ICANN rules and policies. You can see the list of these policies at:

Among those with the UDRP (and URS for newer gTLDs) that basically provides a first step out of the court mechanism for trademark owners to dispute some domain names.

This is mostly stable for now, the specific points in the policy to define if a domain is infringing a trademark have not changed. Of course, this is in addition to any procedure before a court, which can occur in any TLD.

With the UDRP it also happens that there are "reverse sequestration" attempts: entities that claim to have a registered trademark, which in fact was registered after the domain name in an attempt to recover the domain name. Sometimes this is seen, sometimes not. Take a look at to see examples of this.

Often, gTLDs are more open than ccTLDs: ccTLDs often impose restrictions on who can apply for a domain name based (typically) on the applicant's citizenship or place of residence (which must be within the country related to it). the ccTLD, or the relevant surroundings). target level, such as the European Union for European ccTLDs).

Technically, any ccTLD could change its restrictions. It happened in the past, but more often it is lifting the restrictions so as not to add more.

The gTLDs can also change their eligibility rules, but they should only go through some ICANN procedures.

It also has TLDs that went bankrupt and stopped to operate. Some, especially gTLDs, are covered by "backup operators" so that existing domains do not suddenly disappear, however, a TLD failure can happen and some predict that it will happen more and more in the waves of many new and new TLDs. futures.

Another important point that is often forgotten completely: depending on the TLD you use, it can be under different national laws.

For gTLDs, at least it can always depend on US laws. UU (Because ICANN at the end of the day is a U.S. entity.) But then you must take into account the jurisdiction of the registry and the jurisdiction of the registrar!

If you buy a .CAT for example, a domain name (technically a gTLD), through a Canadian registrar where you can depend on:
– The laws of EE. UU They are due to ICANN and they are a gTLD.
– Spanish laws because .CAT is administered by a Spanish entity
– Canadian laws because you are using a Canadian registrar.

And your own nationality can add its own laws.

They were added together, which can create a difficult mix of trademark rules, as their treatments are not uniform. For example, the priorities between the rights to names for individuals and trademarks are not the same everywhere. As for celebrities. case that showed at least in France that trademark rights are "higher" than the rights of personal names.

It is often not well known (for example, if you register a .COM people do not necessarily understand that they will depend on all US laws. UU., Including things like DMCA, for example) and they are not very clear because in the best case it is added in the contract by reference (like the registrar that says that it depends on the jurisdiction X and the disputes will be resolved in court Z of place Y, but by reference it includes the registry agreement that may have similar clauses and if the registry is for a gTLD, then it includes by reference its own contract with ICANN).

Therefore, for a comprehensive overview you may need to handle this as well.


  • carefully read the registration rules on eligibility for the given TLDs that interest you
  • "I'm always sure to keep the domain name whenever I renew it on time": technically never, because if you read all the contracts you will often find fine footprints like "the registry can revoke any domain name at any time and for any reason, as security, etc. "(it is written less clearly than that, but the effects are the same). Also look at the registrar contracts, since (almost) never deal directly with a registry, and in the past there are registrars who abandon a client for any reason, such as the bad press attracted by some websites.
  • If you are not openly infringing a trademark at the time of registration, it should be fine, if you pay on time and if nothing changes, but this will never be a 100% guarantee.