sql server – Long Running Query Optimization

I need to optimize this query as this query is taking minutes of time in execution.
Below is the query. i’m giving date parameters and shift id is optional.
as query is returning same in and out from attendance table based on shift ID.

“SELECT E.EmpCode,E.EmpName,e.DesignationName,D.DeptName, CONVERT(Date, A.TimeIn) AS Date, a.TimeIn,a.TimeOut, DATEPART(WEEKDAY, CONVERT(date, A.TimeIn)) AS Day,sh.ShiftID,CONVERT(TIME,sh.TimeIn) AS STimeIN,CONVERT(TIME,sh.TimeOut) AS STimeOut,sh.ShiftName,
CASE WHEN CONVERT(TIME,a.TimeIn) < CONVERT(TIME,DATEADD(HOUR,4,sh.TimeIn)) THEN ‘MarkOut’ ELSE ‘MarkIN’ END AS Status
FROM dbo.Attendance AS A
INNER JOIN dbo.Employee E ON A.EmpID = E.EmpID
INNER JOIN dbo.Department D ON E.DeptID = d.DeptID

                                     INNER JOIN dbo.Shifts sh ON sh.ShiftID = (SELECT s.ShiftID FROM dbo.Shifts s , employee emp WHERE s.ShiftID = isnull((select ShiftID from EmpWiseShiftAllot where CONVERT(date,DateFrom) = CONVERT(date, A.TimeIn) and IsActive =1 and IsCancel =0 and empid = E.empid), 
                                    (select top 1 ShiftID from DeptStrengthLimit L where L.DeptID = E.DeptID and L.CompanyID = 2 AND L.IsCurrent = 1            
                                    AND CONVERT(date, A.TimeIn)  between L.WithEffectFrom and CONVERT(date, A.TimeIn) order by L.shiftid desc)) and empid = E.empid )

                                     WHERE (A.TimeIn BETWEEN '2020-11-17'  AND '2020-11-21' ) AND (DATEDIFF(MINUTE, A.TimeIn, A.TimeOut) = 0) 
                                         AND 
                                        (A.EmpID NOT IN (SELECT M.EmpID FROM dbo.LeaveApplicationD AS D INNER JOIN  dbo.LeaveApplication AS M ON D.LeaveMID = M.EmpLeaveID
                                          WHERE        (D.IsActive = 1) AND (D.IsCancel = 0) AND (M.IsActive = 1) AND (M.IsCancel = 0) AND (D.Date = CONVERT(date, A.TimeIn) ))) 
                                          AND (DATEPART(WEEKDAY, CONVERT(date, A.TimeIn)) <> 1)
                                                    AND (E.CompanyID = 2) AND (E.IsActive = 1) AND (E.IsCancel = 0) 
                                              AND sh.ShiftID = 5 ORDER BY date"

python – Why does tf.keras.layers.Conv2D take so long at inference in tflite models?

I have a resnet31 (coded in TF2.3, a subclassed tf.keras.Layer) which is running quickly when exported as a savedmodel, but when I try to convert the savemodel to a tflite model, it is very slow. I used the benchmark tool provided in tflite to compute inference time for each kind of layers and it turns out that CONV_2D are very slow, I don’t understand why.

Here is the output of the benchmark tool, you can see that it takes 16s to run CONV_2D:

Number of nodes executed: 89
============================== Summary by node type ==============================
                 (Node type)      (count)     (avg ms)      (avg %)     (cdf %)   (mem KB)  (times called)
                     CONV_2D           33    16353.751      99.844%     99.844%      0.000         33
                       WHILE            2       20.836       0.127%     99.971%      0.000          2
                         ADD           11        1.956       0.012%     99.983%      0.000         11
                 MAX_POOL_2D            3        1.496       0.009%     99.992%      0.000          3
                  REDUCE_MAX            1        0.881       0.005%     99.997%      0.000          1
             FULLY_CONNECTED           13        0.339       0.002%     99.999%      0.000         13
                  REVERSE_V2            2        0.029       0.000%    100.000%      0.000          2
                   TRANSPOSE            2        0.020       0.000%    100.000%      0.000          2
                        FILL            4        0.016       0.000%    100.000%      0.000          4
               STRIDED_SLICE            5        0.011       0.000%    100.000%      0.000          5
                        PACK            5        0.011       0.000%    100.000%      0.000          5
                         MUL            2        0.004       0.000%    100.000%      0.000          2
               CONCATENATION            1        0.003       0.000%    100.000%      0.000          1
                       SHAPE            3        0.002       0.000%    100.000%      0.000          3
                     ONE_HOT            1        0.001       0.000%    100.000%      0.000          1
                     RESHAPE            1        0.000       0.000%    100.000%      0.000          1

I converted the savedmodel this way:

converter = tf.lite.TFLiteConverter.from_saved_model(saved_model_dir)
converter.optimizations = (tf.lite.Optimize.OPTIMIZE_FOR_LATENCY)
converter.target_spec.supported_ops = (
  tf.lite.OpsSet.TFLITE_BUILTINS, # enable TensorFlow Lite ops.
  tf.lite.OpsSet.SELECT_TF_OPS # enable TensorFlow ops.
)

tflite_model = converter.convert()

The resnet31 is coded this way:

import tensorflow as tf

from tensorflow.python.keras import Sequential
from tensorflow.python.keras.layers import Conv2D, BatchNormalization, Lambda, MaxPool2D, AveragePooling2D, Dense, Layer
from tensorflow.keras import Model




class ResnetIdentityV1(Layer):

    """
    
    https://arxiv.org/pdf/1512.03385.pdf
    This function is a the basic resnet V1 block (with bottleneck)

    """

    def __init__(self, filters, conv_shortcut):

        """

        Parameters
        ----------
        conv_shortcut
        filters

        """

        super(ResnetIdentityV1, self).__init__()
        self.filters = filters
        # conv 1 
        self.conv1 = Conv2D(filters=filters,
                            kernel_size=(3, 3),
                            strides=1,
                            padding='same')
        self.bn1 = BatchNormalization()

        # conv 2
        self.conv2 = Conv2D(filters=filters,
                            kernel_size=(3,3),
                            strides=1,
                            padding='same')
        self.bn2 = BatchNormalization()


        # down-sampling
        self.downsample = Sequential()
        if conv_shortcut:
            self.downsample.add(Conv2D(filters=filters,
                                       kernel_size=(1, 1),
                                       strides=1))
            self.downsample.add(BatchNormalization())
        else:
            self.downsample.add(Lambda(lambda x: x))


    def call(self, inputs, training=False, **kwargs):

        """

        Parameters

        input_tensor is a 4-d tensor : NHWC
        training a boolean (used for batch normalization)

        """

        shortcut = self.downsample(inputs, training=training)

        # first conv-bn-relu 
        x = self.conv1(inputs)
        x = self.bn1(x, training=training)
        x = tf.nn.relu(x)

        # second conv-bn-relu
        x = self.conv2(x)
        x = self.bn2(x, training=training)
        x = tf.nn.relu(x + shortcut)

        return x


class ResnetBlock31V1(Layer):

    """

    Block of a resnet31 with n identity blocks in it
    https://arxiv.org/pdf/1512.03385.pdf

    """


    def __init__(self, filters, blocks):
        super(ResnetBlock31V1, self).__init__()
 
        self.identity_block = ResnetIdentityV1
        self.res_block = Sequential()
        self.res_block.add(self.identity_block(filters, conv_shortcut=True))
        for _ in range(1, blocks):
            self.res_block.add(self.identity_block(filters, conv_shortcut=False))
             
    def call(self, inputs, training=False, **kwargs):
        x = self.res_block(inputs, training=training)
        return x


class ResNet31V1(Layer):

    """

    Resnet31 Model 
    https://arxiv.org/pdf/1512.03385.pdf
    downsampling of 4x8
    
    """


    def __init__(self, blocks_filters, blocks_repetition, 
                 num_classes=None):

        super(ResNet31V1, self).__init__()

        self.conv1 = Conv2D(filters=64,kernel_size=3,strides=1,padding='same')
        self.conv2 = Conv2D(filters=128,kernel_size=3,strides=1,padding='same')

        self.bn1 = BatchNormalization()
        self.bn2 = BatchNormalization()

        self.pool1 = MaxPool2D(pool_size=2,strides=2,padding='valid')

        self.resnet_layers = ()
        for f, b in zip(blocks_filters, blocks_repetition):
            self.resnet_layers.append(
                ResnetBlock31V1(filters=f, blocks=b))

        self.n_layers = len(self.resnet_layers)

        self.conv3 = Conv2D(filters=256,kernel_size=3,strides=1,padding='same')
        self.bn3 = BatchNormalization()
        self.pool2 = MaxPool2D(pool_size=2,strides=2,padding='valid')

        self.conv4 = Conv2D(filters=256,kernel_size=3,strides=1,padding='same')
        self.bn4 = BatchNormalization()
        self.pool3 = MaxPool2D(pool_size=(2,1),strides=(2,1),padding='valid')

        self.conv5 = Conv2D(filters=512,kernel_size=3,strides=1,padding='same')
        self.bn5 = BatchNormalization()
        self.conv6 = Conv2D(filters=512,kernel_size=3,strides=1,padding='same')
        self.bn6 = BatchNormalization()

    def call(self, inputs, training=False, **kwargs):

        x = self.conv1(inputs)
        x = self.bn1(x, training=training)
        x = tf.nn.relu(x)
        x = self.conv2(x)
        x = self.bn2(x, training=training)
        x = tf.nn.relu(x)
        x = self.pool1(x)

        x = self.resnet_layers(0)(x, training=training)
        x = self.conv3(x)
        x = self.bn3(x, training=training)
        x = tf.nn.relu(x)
        x = self.pool2(x)

        x = self.resnet_layers(1)(x, training=training)
        x = self.conv4(x)
        x = self.bn4(x, training=training)
        x = tf.nn.relu(x)
        x = self.pool3(x)

        x = self.resnet_layers(2)(x, training=training)
        x = self.conv5(x)
        x = self.bn5(x, training=training)
        x = tf.nn.relu(x)

        x = self.resnet_layers(3)(x, training=training)
        x = self.conv6(x)
        x = self.bn6(x, training=training)
        x = tf.nn.relu(x)

        return x

def resnet_v1_31(num_classes=None):
    model = ResNet31V1(blocks_filters=(256, 256, 512, 512),
                     blocks_repetition=(1, 2, 5, 3),
                     num_classes=num_classes)
    return model

Thank you in advance for your help !

dnd 5e – What does “no long range” mean on the soulknife rogue subclass mean?

One of my players just hit level 3 and is taking the soulknife rogue subclass, as written in Tasha’s Cauldron of Everything.

The weapon granted by the class has a weird specification that it has “no long range.” I’m curious how this should be interpreted, seeing as I can’t find other examples of such a property.

This is what Tasha’s says:

You can manifest your psionic power as shimmering blades of psychic energy. Whenever you take the Attack action, you can manifest a psychic blade from your free hand and make the attack with that blade. This magic blade is a simple melee weapon with the finesse and thrown properties. It has a normal range of 60 feet and no long range, and on a hit, it deals psychic damage equal to 1d6 plus the ability modifier you used for the attack roll. The blade vanishes immediately after it hits or misses its target, and it leaves no mark on its target if it deals damage.

There are two possibilities in my mind:

  1. The knife simply can’t go beyond 60 feet, just like the range of a ranged spell attack.

  2. The knife can go arbitrarily far, and after 60 feet the attack is at disadvantage.

I’m inclined to lean for the first choice since an infinitely long ranged attack seems dumb. Though I suppose there’s an argument to be made that the manifested blade is a “psychic attack” so you can attack someone so long as you can see them.

This is the language of ranged weapon attacks, per the PHB:

A weapon that can be used to make a ranged Attack has a range in parentheses after the Ammunition or thrown property. The range lists two numbers. The first is the weapon’s normal range in feet, and the second indicates the weapon’s long range. When attacking a target beyond normal range, you have disadvantage on the Attack roll. You can’t Attack a target beyond the weapon’s long range.

dnd 5e – Can magic items let you cast spells with long casting times as actions?

If a specific rule contradicts a general rule, the specific rule wins.

Here, you are giving examples of items that are giving specific rule that contradicts the general rule on casting times.

The DMG even states that some magic items can modify the casting times:

(A spell cast from a magic item) uses its normal casting time, range, and duration, and the user of the item must concentrate if the spell requires concentration. Certain items make exceptions to these rules, changing the casting time, duration, or other parts of a spell. (DMG p. 141)

The Staff of the Woodlands is indeed one of those exceptional items. It says:

You can use an action to expend 1 or more of the staff’s charges to cast one of the following spells from it (…)

The rule for this staff says that you use an action to cast a spell. The fact that one of those spells is awaken (normal casting time 8 hours) does not matter. That casting time is now superseded by the effect of the magic item.

Thus, any similar magic item that has some effect in it that modifies the casting time, will similarly override the general rule. In this way, magic items can indeed allow you to cast spells using a shorter casting time than normal.

Other effects can modify casting times as well

Spells (eg Wish), metamagic, and other features already exist to modify the casting times of spells. So magic item use is far from the only example of a specific effect overriding spells’ casting times.


Jeremy Crawford also explicitly agrees with this:

The staff of the woodlands allows you to cast the awaken spell as an action, superseding the spell’s normal casting time of 8 hours. Some magic items make exceptions like that, as noted on page 141 of the Dungeon Master’s Guide (see the “Spells” section on that page).

And he also agrees in the very similar case of the necklace of prayer beads:

A necklace of prayer beads lets you cast a spell it contains as a bonus action, regardless of the spell’s normal casting time. For more about how the necklace works, see page 182 of the Dungeon Master’s Guide.

How Long Will It Take To See Results From Social Media Marketing?

How long will it take to see results from social media marketing?

How to get youtube results which more than hour long?

How to get YouTube results which more than hour long? From YouTube filters you only get more than 20 minutes long videos. I heard there was some trick to get more than an hour long videos only

Applying again to visit UK, long term visit visa

I had a UK 6 month visit visa last year which was expired on February 2020.
On my previous application I mentioned that I wanted to visit London but after getting the visa I travelled to Manchester 2 times.
First was for 10 days and second one for 3 days.

Now I want to apply for a long time 2 years visit visa. My friend recently moved to the UK with his Europian passport so on my visit I will meet him but I will pay all my costs I am working and my monthly income is more than 1500£ everything is OK with my bank statement.

I want to know that should my friend have to send me a inviation letter or should I attach it because I will stay at hotel and will visit tourist places together. My plan is to apply on January for going to UK for 6-7 days in February.

My nationality is Bangladeshi and I’m living in Spain as a residence. I have never have been denied any visas. My last visa application was successful. I want to make new appication as my last visa expired.

How long does the identification process take?

I started a separate page as a Santa to be able to contact families as Santa because of all the COVID restrictions. I went to sign in and it’s asking for ID etc. well of course I gave my real ID. It’s been 2 days and I have had no response. If someone from Facebook is reading this my profile is Santa MacClaus.

How long does this process take?

Thank you all in advance.

c# – CodeWars kata Fusc function running too long, but very fast locally

I have a solution to this CodeWars challenge that’s being rejected as “too slow”.

Basically, write public static BigInteger Fusc(BigInteger n) given:

  1. fusc(0) = 0
  2. fusc(1) = 1
  3. fusc(2 * n) = fusc(n)
  4. fusc(2 * n + 1) = fusc(n) + fusc(n + 1)

— CodeWars description (from part 1, which is formatted slightly nicer IMO)

I have the class below. FuscInner is a literal, naïve implementation, to offer a “known good” answer if needed; it’s slow, but that’s fine. The trouble that I’m running into is that FuscInnerTest runs against my test driver in a quarter second, but times out on CodeWars.

While I’m open to any suggestionst for cleaning up FuscInnerTest or MediumInt, my primary goal is to ascertain why it’s running so poorly when I submit to CodeWars (of course, I don’t know how many test cases it runs…).

using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;

public class FuscSolution {
    public static BigInteger Fusc(BigInteger n) {
        //var timer = System.Diagnostics.Stopwatch.StartNew();
        var answer = FuscInnerTest(n);
        //timer.Stop();
        //Console.WriteLine($"{n} {answer} : {timer.Elapsed}");
        //timer.Restart();
        //answer = FuscInner(n);
        //timer.Stop();
        //Console.WriteLine($"{n} {answer} : {timer.Elapsed}");
        return answer;
    }

    private static BigInteger FuscInner(BigInteger n) {
        if (n == BigInteger.Zero) {
            return BigInteger.Zero;
        }
        if (n == BigInteger.One) {
            return BigInteger.One;
        }

        if (n % 2 == BigInteger.Zero) {
            return FuscInner(n / 2);
        }
        var half = n / 2;
        return FuscInner(half) + FuscInner(half + 1);
    }

    private static readonly Dictionary<BigInteger, BigInteger> _dict = new Dictionary<BigInteger, BigInteger> {
        { BigInteger.Zero, BigInteger.Zero },
        { BigInteger.One, BigInteger.One },
        { new BigInteger(3), new BigInteger(2) },
        { new BigInteger(5), new BigInteger(3) },
    };

    private static BigInteger FuscInnerTest(BigInteger n) {
        // note: making this a Dictionary<BigInteger, BigInteger> worked quickly locally, too
        // the "MediumInt" is an attempt to reduce the number of BigInteger allocations, since
        // they're immutable
        var queue = new Dictionary<BigInteger, MediumInt> {
            { n, new MediumInt(1) },
        };

        BigInteger answer = BigInteger.Zero;

        while (queue.Any()) {
            var current = queue.Keys.Max();
            if (_dict.ContainsKey(current)) {
                answer += _dict(current) * queue(current).ToBigInt();
                queue.Remove(current);
            } else {
                Dequeue(current);
                var half = current / 2;
                Enqueue(half, current);
                if (!current.IsEven) {
                    Enqueue(half + 1, current);
                }
                queue.Remove(current);
            }
        }

        return answer;

        void Dequeue(BigInteger toRemove) {
            if (queue.ContainsKey(toRemove)) {
                if (queue(toRemove).IsPositive()) {
                    queue(toRemove).Decriment();
                } else {
                    queue.Remove(toRemove);
                }
            }
        }

        void Enqueue(BigInteger toAdd, BigInteger parent) {
            if (queue.ContainsKey(toAdd)) {
                queue(toAdd).Incriment();
            } else {
                queue(toAdd) = new MediumInt(1);
            }
            if (parent != null) {
                if (queue.ContainsKey(parent)) {
                    queue(toAdd).Add(queue(parent));
                }
            }
        }
    }

    private class MediumInt {
        private const int max = 2_000_000;
        private const int min = -2_000_000;

        private BigInteger big = BigInteger.Zero;
        private int current = 0;

        public MediumInt(int initialValue) {
            current = initialValue;
            Normalize();
        }

        public bool IsZero() {
            return big == BigInteger.Zero && current == 0;
        }

        public bool IsPositive() {
            if (IsZero()) {
                return false;
            }
            if (current == 0 && big <= 0) {
                return false;
            }
            if (big == BigInteger.Zero && current <= 0) {
                return false;
            }

            if (big == BigInteger.Zero) {
                return current > 0;
            }

            if (big > BigInteger.Zero && big > Math.Abs(current)) {
                return true;
            }
            if (big < BigInteger.Zero && big < Math.Abs(current)) {
                return true;
            }
            throw new Exception("IsPositive unknown state");
        }

        public void Incriment() {
            ++current;
            Normalize();
        }

        public void Decriment() {
            --current;
            Normalize();
        }

        public void Add(MediumInt value) {
            current += value.current;
            big += value.big;
            Normalize();
        }

        public BigInteger ToBigInt() {
            return big + current; ;
        }

        private void Normalize() {
            if (current > max || current < min) {
                big += current;
                current = 0;
            }
        }
    }
}

Driver code:

Assert.AreEqual(BigInteger.Zero, FuscSolution.Fusc(BigInteger.Zero));
Assert.AreEqual(BigInteger.One, FuscSolution.Fusc(BigInteger.One));
Assert.AreEqual(BigInteger.One, FuscSolution.Fusc(new BigInteger(4)));
Assert.AreEqual(new BigInteger(2), FuscSolution.Fusc(new BigInteger(3)));
Assert.AreEqual(new BigInteger(3), FuscSolution.Fusc(new BigInteger(10)));
Assert.AreEqual(new BigInteger(3), FuscSolution.Fusc(5));
Assert.AreEqual(new BigInteger(3), FuscSolution.Fusc(20));
Assert.AreEqual(new BigInteger(8), FuscSolution.Fusc(21));
Assert.AreEqual(new BigInteger(53), FuscSolution.Fusc(9007199254740991L));

// You need to pass these tests very quickly
BigInteger twoPThous = BigInteger.Pow(2, 1000);
Assert.AreEqual(new BigInteger(1001), FuscSolution.Fusc(twoPThous + BigInteger.One));
Assert.AreEqual(new BigInteger(1000), FuscSolution.Fusc(twoPThous - BigInteger.One));
Assert.AreEqual(new BigInteger(2996), FuscSolution.Fusc(twoPThous + 5));
Assert.AreEqual(new BigInteger(7973), FuscSolution.Fusc(twoPThous + 21));
Assert.AreEqual(new BigInteger(50245), FuscSolution.Fusc(twoPThous + 9007199254740991L));
var e = BigInteger.Parse("40441312560834288620677930197198699407914760287917495887121626854370117030034851815445037809554113527157810884542426113562558179684997500659084090344407986124994461497183");
var a = BigInteger.Parse("4496047232746033439866332574607641115185289828815659836877207557974698638551430698226403383854431074455323285812344476437334109742500243442945967768558521790671067401423809250553312923996658420643391496408098163895264498830090255970293513331630261702288646149000136895514918279039816543329290294321200");
Assert.AreEqual(e, FuscSolution.Fusc(a));

spellcasting – Can Spells with long casting times be disrupted by being transformed?

bit of a dense and complex question here. My character was trying to cast leomund’s tiny hut as a ritual, which because it has a long casting time, requires her to maintain concentration. The group was ambushed (though we all passed perception checks so no surprise), and the DM assumed that if he were to polymorph my character, she would lose concentration, and wouldn’t be able to finish the spell because she no longer has a spell list as a CR 0 cat.

I know concentration shouldn’t matter, but is he right about the second part? Could she finish casting the spell as a cat? Does she have to turn back into a kobold first before the spell can resolve? Does anything change if she is casting Glyph of Warding, which isn’t a ritual?

Likewise, in a similar situation, if she later gets true polymorph and turns into a Planatar, while casting raise dead would break concentration as it takes more than 1 action, would she still be able to resolve the casting at the end of 1 hour, if she maintained concentration the whole time?