问:
Determining if an Object is of primitive type
I have an Object[] array, and I am trying to find the ones that are primitives. I've tried to use Class.isPrimitive(), but it seems I'm doing something wrong:

```<code>int i = 3;
Object o = i;

System.out.println(o.getClass().getName() + ", " +
                   o.getClass().isPrimitive());
</code>```

prints java.lang.Integer, false.

Is there a right way or some alternative?

答:
Just so you can see that is is possible for isPrimitive to return true (since you have enough answers showing you why it is false):

```<code>public class Main
{
    public static void main(final String[] argv)
    {
        final Class clazz;

        clazz = int.class;
        System.out.println(clazz.isPrimitive());
    }
}
</code>```

This matters in reflection when a method takes in "int" rather than an "Integer".

This code works:

```<code>import java.lang.reflect.Method;

public class Main
{
    public static void main(final String[] argv)
        throws Exception
    {
        final Method method;

        method = Main.class.getDeclaredMethod("foo", int.class);
    }

    public static void foo(final int x)
    {
    }
}
</code>```

This code fails (cannot find the method):

```<code>import java.lang.reflect.Method;

public class Main
{
    public static void main(final String[] argv)
        throws Exception
    {
        final Method method;

        method = Main.class.getDeclaredMethod("foo", Integer.class);
    }

    public static void foo(final int x)
    {
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have an Object[] array, and I am trying to find the ones that are primitives. I've tried to use Class.isPrimitive(), but it seems I'm doing something wrong:

int i = 3;
Object o = i;

System.out.println(o.getClass().getName() + ", " +
                   o.getClass().isPrimitive());

prints java.lang.Integer, false.

Is there a right way or some alternative?

Body:
Just so you can see that is is possible for isPrimitive to return true (since you have enough answers showing you why it is false):

public class Main
{
    public static void main(final String[] argv)
    {
        final Class clazz;

        clazz = int.class;
        System.out.println(clazz.isPrimitive());
    }
}

This matters in reflection when a method takes in "int" rather than an "Integer".

This code works:

import java.lang.reflect.Method;

public class Main
{
    public static void main(final String[] argv)
        throws Exception
    {
        final Method method;

        method = Main.class.getDeclaredMethod("foo", int.class);
    }

    public static void foo(final int x)
    {
    }
}

This code fails (cannot find the method):

import java.lang.reflect.Method;

public class Main
{
    public static void main(final String[] argv)
        throws Exception
    {
        final Method method;

        method = Main.class.getDeclaredMethod("foo", Integer.class);
    }

    public static void foo(final int x)
    {
    }
}

OwnerDisplayName: TofuBeer


来源: stackexchange

问:
Java Remote kill user session
How I can kill a user sessionId from a web administration panel? I mean, I have multiple users entering a website with jboss 4.2 and struts 1.3 and I want to close a session of some of these users remotely from same website. What is the best strategy?

One possible solution is to associate the JSESSIONID to the user in the database and set the JSESSIONID. Then for each transaction to ask if I remove user session.

I try to handle it by using context.xml in jboss side with FileStore session, but if I delete the session file (eg 2B6609A6CA38E35EEDF21BF3F3253BC8.session) the session is still active.

```<code><Manager className="org.apache.catalina.session.PersistentManager" saveOnRestart="false">
    <Store  className="org.apache.catalina.session.FileStore" directory="\tmp\">
    </Store>
 </Manager>
</code>```

Any suggestions? thanks

答:
One of the ways is to just collect those sessions yourself with help of a HttpSessionListener:

```<code>public class SessionManager implements HttpSessionListener {

    private static Map<String, HttpSession> sessions = new ConcurrentHashMap<String, HttpSession>();

    @Override
    public void sessionCreated(HttpSessionEvent event) {
        sessions.put(event.getSession().getId(), event.getSession());
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent event) {
        sessions.remove(event.getSession().getId());
    }

    public static boolean invalidate(String sessionId) {
        HttpSession session = sessions.get(sessionId);

        if (session != null) {
            session.invalidate();
            return true;
        } else {
            return false;
        }
    }

}
</code>```

It allows you for doing something like this in your webadmin panel's code:

```<code>SessionManager.invalidate(someSessionId);
</code>```

Perhaps you're already using a HttpSessionListener to sync the sessions with the database. That would be totally superfluous this way then.

ContentLicense: CC BY-SA 3.0

Title: Java Remote kill user session

Body:
How I can kill a user sessionId from a web administration panel? I mean, I have multiple users entering a website with jboss 4.2 and struts 1.3 and I want to close a session of some of these users remotely from same website. What is the best strategy?

One possible solution is to associate the JSESSIONID to the user in the database and set the JSESSIONID. Then for each transaction to ask if I remove user session.

I try to handle it by using context.xml in jboss side with FileStore session, but if I delete the session file (eg 2B6609A6CA38E35EEDF21BF3F3253BC8.session) the session is still active.

<Manager className="org.apache.catalina.session.PersistentManager" saveOnRestart="false">
    <Store  className="org.apache.catalina.session.FileStore" directory="\tmp\">
    </Store>
 </Manager>

Any suggestions? thanks

Body:
One of the ways is to just collect those sessions yourself with help of a HttpSessionListener:

public class SessionManager implements HttpSessionListener {

    private static Map<String, HttpSession> sessions = new ConcurrentHashMap<String, HttpSession>();

    @Override
    public void sessionCreated(HttpSessionEvent event) {
        sessions.put(event.getSession().getId(), event.getSession());
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent event) {
        sessions.remove(event.getSession().getId());
    }

    public static boolean invalidate(String sessionId) {
        HttpSession session = sessions.get(sessionId);

        if (session != null) {
            session.invalidate();
            return true;
        } else {
            return false;
        }
    }

}

It allows you for doing something like this in your webadmin panel's code:

SessionManager.invalidate(someSessionId);

Perhaps you're already using a HttpSessionListener to sync the sessions with the database. That would be totally superfluous this way then.

ContentLicense: CC BY-SA 4.0


问:
SvelteKit: config.kit.target is no longer required, and should be removed
Compile time error - config.kit.target is no longer required, and should be removed

When you runs the svelteKit app.

答: Remove the 'target' option under kit in your project's root 'svelte.config.js' and it resolve the error.</p>


答:
I think you could use a final layer like this one:</p>
```<code>tf.keras.layers.Lambda(lambda x: tf.math.l2_normalize(x, axis=1))
</code>```

Title: L2 normalised output with keras

Body:
I would like to build a neural net with Keras with Tensorflow backend which outputs an L2 normalized vector. I have tried the following but for some reason it does not normalize the output:

import keras.backend as K
input = Input(shape=input_shape)
...
dense7 = Dense(output_dim=3)(flatten6)
l2_norm = Lambda(lambda  x: K.l2_normalize(x,axis=1))(dense7)
return Model(input=input, output=l2_norm)

So here the output is a 3D vector and I would like to make sure that the length of this vector is 1. Can anybody help me out? Also can you tell me why my solution fails?

Example:

output: [  8.27677908e-08   2.64180613e-07  -2.81542953e-07]
required: [ 0.20961709  0.6690619  -0.71303362]

Model summary:

____________________________________________________________________________________________________
Layer (type)                     Output Shape          Param #     Connected to
====================================================================================================
input_1 (InputLayer)             (None, 224, 224, 3)   0
____________________________________________________________________________________________________
convolution2d_1 (Convolution2D)  (None, 112, 112, 64)  9472        input_1[0][0]
____________________________________________________________________________________________________
batchnormalization_1 (BatchNormal(None, 112, 112, 64)  128         convolution2d_1[0][0]
____________________________________________________________________________________________________
maxpooling2d_1 (MaxPooling2D)    (None, 56, 56, 64)    0           batchnormalization_1[0][0]
____________________________________________________________________________________________________
convolution2d_2 (Convolution2D)  (None, 56, 56, 64)    4160        maxpooling2d_1[0][0]
____________________________________________________________________________________________________
batchnormalization_2 (BatchNormal(None, 56, 56, 64)    128         convolution2d_2[0][0]
____________________________________________________________________________________________________
convolution2d_3 (Convolution2D)  (None, 56, 56, 192)   110784      batchnormalization_2[0][0]
____________________________________________________________________________________________________
batchnormalization_3 (BatchNormal(None, 56, 56, 192)   384         convolution2d_3[0][0]
____________________________________________________________________________________________________
maxpooling2d_2 (MaxPooling2D)    (None, 28, 28, 192)   0           batchnormalization_3[0][0]
____________________________________________________________________________________________________
convolution2d_5 (Convolution2D)  (None, 28, 28, 96)    18528       maxpooling2d_2[0][0]
____________________________________________________________________________________________________
convolution2d_7 (Convolution2D)  (None, 28, 28, 16)    3088        maxpooling2d_2[0][0]
____________________________________________________________________________________________________
maxpooling2d_3 (MaxPooling2D)    (None, 28, 28, 192)   0           maxpooling2d_2[0][0]
____________________________________________________________________________________________________
convolution2d_4 (Convolution2D)  (None, 28, 28, 64)    12352       maxpooling2d_2[0][0]
____________________________________________________________________________________________________
convolution2d_6 (Convolution2D)  (None, 28, 28, 128)   110720      convolution2d_5[0][0]
____________________________________________________________________________________________________
convolution2d_8 (Convolution2D)  (None, 28, 28, 32)    12832       convolution2d_7[0][0]
____________________________________________________________________________________________________
convolution2d_9 (Convolution2D)  (None, 28, 28, 32)    6176        maxpooling2d_3[0][0]
____________________________________________________________________________________________________
merge_1 (Merge)                  (None, 28, 28, 256)   0           convolution2d_4[0][0]
                                                                   convolution2d_6[0][0]
                                                                   convolution2d_8[0][0]
                                                                   convolution2d_9[0][0]
____________________________________________________________________________________________________
convolution2d_11 (Convolution2D) (None, 28, 28, 96)    24672       merge_1[0][0]
____________________________________________________________________________________________________
convolution2d_13 (Convolution2D) (None, 28, 28, 32)    8224        merge_1[0][0]
____________________________________________________________________________________________________
maxpooling2d_4 (MaxPooling2D)    (None, 28, 28, 256)   0           merge_1[0][0]
____________________________________________________________________________________________________
convolution2d_10 (Convolution2D) (None, 28, 28, 64)    16448       merge_1[0][0]
____________________________________________________________________________________________________
convolution2d_12 (Convolution2D) (None, 28, 28, 128)   110720      convolution2d_11[0][0]
____________________________________________________________________________________________________
convolution2d_14 (Convolution2D) (None, 28, 28, 64)    51264       convolution2d_13[0][0]
____________________________________________________________________________________________________
convolution2d_15 (Convolution2D) (None, 28, 28, 64)    16448       maxpooling2d_4[0][0]
____________________________________________________________________________________________________
merge_2 (Merge)                  (None, 28, 28, 320)   0           convolution2d_10[0][0]
                                                                   convolution2d_12[0][0]
                                                                   convolution2d_14[0][0]
                                                                   convolution2d_15[0][0]
____________________________________________________________________________________________________
convolution2d_16 (Convolution2D) (None, 28, 28, 128)   41088       merge_2[0][0]
____________________________________________________________________________________________________
convolution2d_18 (Convolution2D) (None, 28, 28, 32)    10272       merge_2[0][0]
____________________________________________________________________________________________________
convolution2d_17 (Convolution2D) (None, 14, 14, 256)   295168      convolution2d_16[0][0]
____________________________________________________________________________________________________
convolution2d_19 (Convolution2D) (None, 14, 14, 64)    51264       convolution2d_18[0][0]
____________________________________________________________________________________________________
maxpooling2d_5 (MaxPooling2D)    (None, 14, 14, 320)   0           merge_2[0][0]
____________________________________________________________________________________________________
merge_3 (Merge)                  (None, 14, 14, 640)   0           convolution2d_17[0][0]
                                                                   convolution2d_19[0][0]
                                                                   maxpooling2d_5[0][0]
____________________________________________________________________________________________________
convolution2d_21 (Convolution2D) (None, 14, 14, 96)    61536       merge_3[0][0]
____________________________________________________________________________________________________
convolution2d_23 (Convolution2D) (None, 14, 14, 32)    20512       merge_3[0][0]
____________________________________________________________________________________________________
maxpooling2d_6 (MaxPooling2D)    (None, 14, 14, 640)   0           merge_3[0][0]
____________________________________________________________________________________________________
convolution2d_20 (Convolution2D) (None, 14, 14, 256)   164096      merge_3[0][0]
____________________________________________________________________________________________________
convolution2d_22 (Convolution2D) (None, 14, 14, 192)   166080      convolution2d_21[0][0]
____________________________________________________________________________________________________
convolution2d_24 (Convolution2D) (None, 14, 14, 64)    51264       convolution2d_23[0][0]
____________________________________________________________________________________________________
convolution2d_25 (Convolution2D) (None, 14, 14, 128)   82048       maxpooling2d_6[0][0]
____________________________________________________________________________________________________
merge_4 (Merge)                  (None, 14, 14, 640)   0           convolution2d_20[0][0]
                                                                   convolution2d_22[0][0]
                                                                   convolution2d_24[0][0]
                                                                   convolution2d_25[0][0]
____________________________________________________________________________________________________
convolution2d_27 (Convolution2D) (None, 14, 14, 112)   71792       merge_4[0][0]
____________________________________________________________________________________________________
convolution2d_29 (Convolution2D) (None, 14, 14, 32)    20512       merge_4[0][0]
____________________________________________________________________________________________________
maxpooling2d_7 (MaxPooling2D)    (None, 14, 14, 640)   0           merge_4[0][0]
____________________________________________________________________________________________________
convolution2d_26 (Convolution2D) (None, 14, 14, 224)   143584      merge_4[0][0]
____________________________________________________________________________________________________
convolution2d_28 (Convolution2D) (None, 14, 14, 224)   226016      convolution2d_27[0][0]
____________________________________________________________________________________________________
convolution2d_30 (Convolution2D) (None, 14, 14, 64)    51264       convolution2d_29[0][0]
____________________________________________________________________________________________________
convolution2d_31 (Convolution2D) (None, 14, 14, 128)   82048       maxpooling2d_7[0][0]
____________________________________________________________________________________________________
merge_5 (Merge)                  (None, 14, 14, 640)   0           convolution2d_26[0][0]
                                                                   convolution2d_28[0][0]
                                                                   convolution2d_30[0][0]
                                                                   convolution2d_31[0][0]
____________________________________________________________________________________________________
convolution2d_33 (Convolution2D) (None, 14, 14, 128)   82048       merge_5[0][0]
____________________________________________________________________________________________________
convolution2d_35 (Convolution2D) (None, 14, 14, 32)    20512       merge_5[0][0]
____________________________________________________________________________________________________
maxpooling2d_8 (MaxPooling2D)    (None, 14, 14, 640)   0           merge_5[0][0]
____________________________________________________________________________________________________
convolution2d_32 (Convolution2D) (None, 14, 14, 192)   123072      merge_5[0][0]
____________________________________________________________________________________________________
convolution2d_34 (Convolution2D) (None, 14, 14, 256)   295168      convolution2d_33[0][0]
____________________________________________________________________________________________________
convolution2d_36 (Convolution2D) (None, 14, 14, 64)    51264       convolution2d_35[0][0]
____________________________________________________________________________________________________
convolution2d_37 (Convolution2D) (None, 14, 14, 128)   82048       maxpooling2d_8[0][0]
____________________________________________________________________________________________________
merge_6 (Merge)                  (None, 14, 14, 640)   0           convolution2d_32[0][0]
                                                                   convolution2d_34[0][0]
                                                                   convolution2d_36[0][0]
                                                                   convolution2d_37[0][0]
____________________________________________________________________________________________________
convolution2d_39 (Convolution2D) (None, 14, 14, 144)   92304       merge_6[0][0]
____________________________________________________________________________________________________
convolution2d_41 (Convolution2D) (None, 14, 14, 32)    20512       merge_6[0][0]
____________________________________________________________________________________________________
maxpooling2d_9 (MaxPooling2D)    (None, 14, 14, 640)   0           merge_6[0][0]
____________________________________________________________________________________________________
convolution2d_38 (Convolution2D) (None, 14, 14, 160)   102560      merge_6[0][0]
____________________________________________________________________________________________________
convolution2d_40 (Convolution2D) (None, 14, 14, 288)   373536      convolution2d_39[0][0]
____________________________________________________________________________________________________
convolution2d_42 (Convolution2D) (None, 14, 14, 64)    51264       convolution2d_41[0][0]
____________________________________________________________________________________________________
convolution2d_43 (Convolution2D) (None, 14, 14, 128)   82048       maxpooling2d_9[0][0]
____________________________________________________________________________________________________
merge_7 (Merge)                  (None, 14, 14, 640)   0           convolution2d_38[0][0]
                                                                   convolution2d_40[0][0]
                                                                   convolution2d_42[0][0]
                                                                   convolution2d_43[0][0]
____________________________________________________________________________________________________
convolution2d_44 (Convolution2D) (None, 14, 14, 160)   102560      merge_7[0][0]
____________________________________________________________________________________________________
convolution2d_46 (Convolution2D) (None, 14, 14, 64)    41024       merge_7[0][0]
____________________________________________________________________________________________________
convolution2d_45 (Convolution2D) (None, 7, 7, 256)     368896      convolution2d_44[0][0]
____________________________________________________________________________________________________
convolution2d_47 (Convolution2D) (None, 7, 7, 128)     204928      convolution2d_46[0][0]
____________________________________________________________________________________________________
maxpooling2d_10 (MaxPooling2D)   (None, 7, 7, 640)     0           merge_7[0][0]
____________________________________________________________________________________________________
merge_8 (Merge)                  (None, 7, 7, 1024)    0           convolution2d_45[0][0]
                                                                   convolution2d_47[0][0]
                                                                   maxpooling2d_10[0][0]
____________________________________________________________________________________________________
convolution2d_49 (Convolution2D) (None, 7, 7, 192)     196800      merge_8[0][0]
____________________________________________________________________________________________________
convolution2d_51 (Convolution2D) (None, 7, 7, 48)      49200       merge_8[0][0]
____________________________________________________________________________________________________
maxpooling2d_11 (MaxPooling2D)   (None, 7, 7, 1024)    0           merge_8[0][0]
____________________________________________________________________________________________________
convolution2d_48 (Convolution2D) (None, 7, 7, 384)     393600      merge_8[0][0]
____________________________________________________________________________________________________
convolution2d_50 (Convolution2D) (None, 7, 7, 384)     663936      convolution2d_49[0][0]
____________________________________________________________________________________________________
convolution2d_52 (Convolution2D) (None, 7, 7, 128)     153728      convolution2d_51[0][0]
____________________________________________________________________________________________________
convolution2d_53 (Convolution2D) (None, 7, 7, 128)     131200      maxpooling2d_11[0][0]
____________________________________________________________________________________________________
merge_9 (Merge)                  (None, 7, 7, 1024)    0           convolution2d_48[0][0]
                                                                   convolution2d_50[0][0]
                                                                   convolution2d_52[0][0]
                                                                   convolution2d_53[0][0]
____________________________________________________________________________________________________
convolution2d_55 (Convolution2D) (None, 7, 7, 192)     196800      merge_9[0][0]
____________________________________________________________________________________________________
convolution2d_57 (Convolution2D) (None, 7, 7, 48)      49200       merge_9[0][0]
____________________________________________________________________________________________________
maxpooling2d_12 (MaxPooling2D)   (None, 7, 7, 1024)    0           merge_9[0][0]
____________________________________________________________________________________________________
convolution2d_54 (Convolution2D) (None, 7, 7, 384)     393600      merge_9[0][0]
____________________________________________________________________________________________________
convolution2d_56 (Convolution2D) (None, 7, 7, 384)     663936      convolution2d_55[0][0]
____________________________________________________________________________________________________
convolution2d_58 (Convolution2D) (None, 7, 7, 128)     153728      convolution2d_57[0][0]
____________________________________________________________________________________________________
convolution2d_59 (Convolution2D) (None, 7, 7, 128)     131200      maxpooling2d_12[0][0]
____________________________________________________________________________________________________
merge_10 (Merge)                 (None, 7, 7, 1024)    0           convolution2d_54[0][0]
                                                                   convolution2d_56[0][0]
                                                                   convolution2d_58[0][0]
                                                                   convolution2d_59[0][0]
____________________________________________________________________________________________________
averagepooling2d_1 (AveragePoolin(None, 1, 1, 1024)    0           merge_10[0][0]
____________________________________________________________________________________________________
flatten_1 (Flatten)              (None, 1024)          0           averagepooling2d_1[0][0]
____________________________________________________________________________________________________
dense_1 (Dense)                  (None, 3)             3075        flatten_1[0][0]
____________________________________________________________________________________________________
lambda_1 (Lambda)                (None, 3)             0           dense_1[0][0]
====================================================================================================
Total params: 7328819

Body:
I think you could use a final layer like this one:

tf.keras.layers.Lambda(lambda x: tf.math.l2_normalize(x, axis=1))


问:
Template partial specialization issues "template parameters not deducible in partial specialization"
I am trying to understand why there is a "template parameters not deducible in partial specialization". I could not find an answer to this with current answers.

Pre:

```<code>template<std::size_t, class T, class F>
struct IF {
    using type = T;
};

template<class T, class F>
struct IF<0, T, F>
{
    using type = F;
};
</code>```

Actual Issue:

```<code>template <std::size_t x, std::size_t y, std::size_t z = x*y >
struct Selector
{
    using A = int; //simplified for questioning- uses x,y
    using B = float;

    using type = typename IF<z, A, B>::type;
};

template <std::size_t x, std::size_t y>
using MyType = typename Selector<x, y>::type;

//Everything is good until here.

template <typename T>
struct XTyp;
// struct XTyp : std::integral_constant<std::size_t, 0> {};

template <std::size_t x, std::size_t y>
struct XTyp<MyType<x, y> > : std::integral_constant<std::size_t, x>
{
};
</code>```

error: template parameters not deducible in partial specialization:
struct XTyp<MyType<x, y> > : std::integral_constant<std::size_t, x>
note:         ‘x’
note:         ‘y’

See: https://godbolt.org/z/673f9WM3G

答:
Inserting the type alias, your partial specialization reads

```<code>template <std::size_t x, std::size_t y>
struct XTyp< typename Selector<x, y>::type > : std::integral_constant<std::size_t, x>
{
};
</code>```

When the compiler needs to check whether this partial specialization should be chosen for a given specialization XTyp<Arg>, it has to check whether there are values x and y, such that Arg is the same as Selector<x, y>::type. But that is generally impossible, since each specialization of Selector<x, y> could have any type, including Arg, as type.

In terms of the language specification, everything left of a :: is a non-deduced context in which template argument deduction cannot deduce template arguments.
But the x and y template arguments of the partial specialization must be deducible from Arg as if XTyp<Arg> was given as argument in a call to a function template with function parameter XTyp< typename Selector<x, y>::type >.

Since the template arguments of the partial specialization are never deducible, the compiler will reject the specialization outright.

Body:
I am trying to understand why there is a "template parameters not deducible in partial specialization". I could not find an answer to this with current answers.

Pre:

template<std::size_t, class T, class F>
struct IF {
    using type = T;
};

template<class T, class F>
struct IF<0, T, F>
{
    using type = F;
};

Actual Issue:

template <std::size_t x, std::size_t y, std::size_t z = x*y >
struct Selector
{
    using A = int; //simplified for questioning- uses x,y
    using B = float;

    using type = typename IF<z, A, B>::type;
};

template <std::size_t x, std::size_t y>
using MyType = typename Selector<x, y>::type;

//Everything is good until here.

template <typename T>
struct XTyp;
// struct XTyp : std::integral_constant<std::size_t, 0> {};

template <std::size_t x, std::size_t y>
struct XTyp<MyType<x, y> > : std::integral_constant<std::size_t, x>
{
};

error: template parameters not deducible in partial specialization:
struct XTyp<MyType<x, y> > : std::integral_constant<std::size_t, x>
note:         ‘x’
note:         ‘y’

See: https://godbolt.org/z/673f9WM3G

Body:
Inserting the type alias, your partial specialization reads

template <std::size_t x, std::size_t y>
struct XTyp< typename Selector<x, y>::type > : std::integral_constant<std::size_t, x>
{
};

When the compiler needs to check whether this partial specialization should be chosen for a given specialization XTyp<Arg>, it has to check whether there are values x and y, such that Arg is the same as Selector<x, y>::type. But that is generally impossible, since each specialization of Selector<x, y> could have any type, including Arg, as type.

In terms of the language specification, everything left of a :: is a non-deduced context in which template argument deduction cannot deduce template arguments.
But the x and y template arguments of the partial specialization must be deducible from Arg as if XTyp<Arg> was given as argument in a call to a function template with function parameter XTyp< typename Selector<x, y>::type >.

Since the template arguments of the partial specialization are never deducible, the compiler will reject the specialization outright.


问:
CoinGeckoAPI - Format Output - Python
Hi guys i'm working with the Coingecko API to get values from the site.

This is the code

```<code>from pycoingecko import CoinGeckoAPI
cg = CoinGeckoAPI()
cg.get_price(ids=['bitcoin'], vs_currencies='brl')
</code>```

This is the output that's i receive

```<code>{'bitcoin': {'brl': 221934}}
</code>```

Is there a way to get just the value of the output?

Thanks for your help

答:
Yep you can access it like that

```<code>from pycoingecko import CoinGeckoAPI
cg = CoinGeckoAPI()
dict = cg.get_price(ids=['bitcoin'], vs_currencies='brl')
print(dict['bitcoin']['brl'])

</code>```

output

221934

Title: CoinGeckoAPI - Format Output - Python

Body:
Hi guys i'm working with the Coingecko API to get values from the site.

This is the code

from pycoingecko import CoinGeckoAPI
cg = CoinGeckoAPI()
cg.get_price(ids=['bitcoin'], vs_currencies='brl')

This is the output that's i receive

{'bitcoin': {'brl': 221934}}

Is there a way to get just the value of the output?

Thanks for your help

Body:
Yep you can access it like that

from pycoingecko import CoinGeckoAPI
cg = CoinGeckoAPI()
dict = cg.get_price(ids=['bitcoin'], vs_currencies='brl')
print(dict['bitcoin']['brl'])

output

221934


问:
Azure Functions, Event Grid and Event Redelivery
I have an Azure function app running under a Consumption plan, with functions that are triggered with the EventGridTrigger, and an Event Grid Topic that is triggering the functions. I'm relying on the retry functionality to increase reliability. If the function doesn't acknowledge the event (via a return from the function), I'm seeing that the event is re-delivered.  So far so good.

I'm using EF Core with SQL Server, with a timestamp/row version column for concurrency management. More on that in a moment.

The documentation outlines that the event grid has 'at-least-once' delivery.  This implies that the consumers of the events should be idempotent. We have a multi-step process, and we're making modifications for this process to be idempotent, so we're thinking about the various situations.  This question involves one specific situation.

I'm reading 'at-least-once' to mean that a function could be triggered twice by the same event, and that an event could be processed by two instances of the function at the same time; maybe one is taking a long time, or the grid just delivered it twice.

If this is the case, and two function instances are processing an event at the same time, it's possible that one of them will succeed, and one could fail - either with a concurrency exception, or the function could have some other exception generated by the code or the platform.  These platform exceptions are rare, but we HAVE seen indications of this (where the invocation just dies; we've seen this with single invocations, and have seen the event be re-delivered).

We've never seen any indications that an event is processed by two instances at the same time; my question assumes that this is possible, though.  In that case, I'm not sure what will happen with the re-delivery:

'Successful' instance finishes first, then the second instance doesn't acknowledge the event (through a timeout or unhandled exception).

'Failed' instance finishes first by throwing an exception, then the 'successful' instance finishes and acknowledges the event.

In both of these cases, one instance acknowledges the event, the other does not.  Does anyone know if the event will be redelivered in any of these cases?  Does the order in which these instances run change the answer?

The actual problem is more complex: we're doing a multi-step process, and saving to the database at the end of each step.  So the plan is to only allow each step to be processed once.  In the case where two instances run at the same time, we're leveraging the concurrency validation in EF Core to prevent the second instance from saving the data when moving to the next 'step'.  But we don't know whether to acknowledge the event - because the other instance could encounter a problem in a subsequent step. We're being 'optimistic' in that we think these problems will be rare, but we would like to get as much automatic recovery as possible.

Any insight would be helpful.  We really can't change how that multi-step process is done; for one thing, the multiple steps allow us to track the progress.

Thanks in advance.

答:
I couldn't find anything solid in the documentation. So I ran a few tests myself as I was intrigued by the question. I've also included a potential "solution" to your multistep issue, or rather, that it is not idempotent (yet?). Scroll through the wall of text, it's at the end.

First thoughts are that two instances could run the same event, if only and if the first invocation exceeds the default 30 seconds for response, which is why the "at-least-once" delivery is mentioned. Example:

Event is published

Instance A picks up the event

Instance A runs for more than 30 seconds

Event is added to retry queue as instance A hasn't replied yet

Instance A is finished, 35 seconds total elapsed

Event from retry queue is published after sitting in retry queue for 10 seconds

Instance B picks up the event

I really think it comes down to the execution duration of the two instances how EventGrid reacts.

According to the documentation for Retry schedule:

If the endpoint responds within 3 minutes, Event Grid will attempt to
remove the event from the retry queue on a best effort basis but
duplicates may still be received.

This could be interpreted as such that as soon as an instance replies with a successful response EventGrid will attempt to clean out the retry queue (from the example above, instance B should never pick up the event). However, I'm also interested in what happens when instance A fails.

I tried with the following code, which will throw an exception from instance A after a certain delay:

public static class Function1
{
    private static Dictionary<string, int> _Counter = new();

    [FunctionName("Function1")]
    public static async Task Run([EventGridTrigger] EventGridEvent eventGridEvent, ILogger log)
    {
        if (_Counter.ContainsKey(eventGridEvent.Id))
        {
            _Counter[eventGridEvent.Id]++;
            log.LogInformation($"{eventGridEvent.Id}: {_Counter[eventGridEvent.Id]}");
            return;
        }

        _Counter.Add(eventGridEvent.Id, 1);
        var delay = (long)eventGridEvent.Data;
        log.LogInformation($"Delay: {delay}");
        await Task.Delay(TimeSpan.FromSeconds(delay));
        log.LogInformation($"{eventGridEvent.Id}: {_Counter[eventGridEvent.Id]}");
        throw new Exception($"{eventGridEvent.Id} Throwing after {delay} seconds delay");
    }
}
```
<p><strong>Results from different delays</strong></p>
<p>Delay = 35</p>
```2022-02-06T00:34:10.798 [Information] Executing 'Function1' (Reason='EventGrid trigger fired at 2022-02-06T00:34:10.7899831+00:00', Id=9d1adfe9-21bd-454c-862e-a4d8d5b312e0)
2022-02-06T00:34:10.801 [Information] Delay: 35
2022-02-06T00:34:45.807 [Information] 6d3d141d-d0ee-4e81-a648-e2497e562b84: 1
2022-02-06T00:34:45.894 [Error] Executed 'Function1' (Failed, Id=9d1adfe9-21bd-454c-862e-a4d8d5b312e0, Duration=35096ms)6d3d141d-d0ee-4e81-a648-e2497e562b84 Throwing after 35 seconds delay
2022-02-06T00:34:55.949 [Information] Executing 'Function1' (Reason='EventGrid trigger fired at 2022-02-06T00:34:55.9486015+00:00', Id=58a7a6db-2f97-4bc7-b878-030b8be25711)
2022-02-06T00:34:55.949 [Information] 6d3d141d-d0ee-4e81-a648-e2497e562b84: 2
2022-02-06T00:34:55.949 [Information] Executed 'Function1' (Succeeded, Id=58a7a6db-2f97-4bc7-b878-030b8be25711, Duration=1ms)
```
<p>Seems that the retry that was most likely added to the queue after 30 seconds was either removed/replaced or its scheduled execution was "updated":</p>
<ul>
<li>58-13 = 45,</li>
<li>35 for execution duration of instance A</li>
<li>10 for retry delay after instance A failed</li>
</ul>
<p>Delay = 45</p>
```2022-02-06T00:37:29.526 [Information] Executing 'Function1' (Reason='EventGrid trigger fired at 2022-02-06T00:37:29.5262414+00:00', Id=c4596efa-7034-4efe-bcf9-85d502517711)
2022-02-06T00:37:29.526 [Information] Delay: 45
2022-02-06T00:38:14.524 [Information] 284fa140-1cdc-41e7-973f-d0ecd6f19692: 1
2022-02-06T00:38:14.530 [Error] Executed 'Function1' (Failed, Id=c4596efa-7034-4efe-bcf9-85d502517711, Duration=44999ms)284fa140-1cdc-41e7-973f-d0ecd6f19692 Throwing after 45 seconds delay
2022-02-06T00:38:24.590 [Information] Executing 'Function1' (Reason='EventGrid trigger fired at 2022-02-06T00:38:24.5901035+00:00', Id=43a1fafa-7773-44e5-9f3a-b4bf697865a9)
2022-02-06T00:38:24.590 [Information] 284fa140-1cdc-41e7-973f-d0ecd6f19692: 2
2022-02-06T00:38:24.590 [Information] Executed 'Function1' (Succeeded, Id=43a1fafa-7773-44e5-9f3a-b4bf697865a9, Duration=0ms)
```
<p>This is sorta unexpected behavior. We'd have expected to see a 2nd invocation finish before the 1st one, presumably finishing after 40 seconds after the 1st invocation's start. This could indicate that EventGrid actually knows that the 1st instance hasn't failed, and is still running, so it's actually not adding the retry attempt to the queue just yet. It does however add it after the 1st instance fails, and the retry attempt is, as expected, executed 10 seconds later.</p>
<p>I wanted to test the above, and thought the magic number could be 3 minutes (also mentioned in the documentation) and not 30 seconds.</p>
<p>Delay = 185</p>
```2022-02-06T00:40:20.381 [Information] Executing 'Function1' (Reason='EventGrid trigger fired at 2022-02-06T00:40:20.3809687+00:00', Id=454b815f-6ca6-4b75-9272-711c7b6bf42a)
2022-02-06T00:40:20.381 [Information] Delay: 185
2022-02-06T00:43:00.393 [Information] Executing 'Function1' (Reason='EventGrid trigger fired at 2022-02-06T00:43:00.3928958+00:00', Id=23910142-d903-4b9b-bec2-a5665e8e1db7)
2022-02-06T00:43:00.393 [Information] 97d828e6-d1f3-4523-b043-1f76465de6ea: 2
2022-02-06T00:43:00.393 [Information] Executed 'Function1' (Succeeded, Id=23910142-d903-4b9b-bec2-a5665e8e1db7, Duration=0ms)
2022-02-06T00:43:25.381 [Information] 97d828e6-d1f3-4523-b043-1f76465de6ea: 2
2022-02-06T00:43:25.387 [Error] Executed 'Function1' (Failed, Id=454b815f-6ca6-4b75-9272-711c7b6bf42a, Duration=185002ms)97d828e6-d1f3-4523-b043-1f76465de6ea Throwing after 185 seconds delay
```
<p>This is also sorta contradicting the documentation. The first instance executes at 40:20. At 43:00 (would've expected 43:20), it runs the 2nd instance, completes immediately. Then the 1st instance fails at 43:25 (as expected). Maybe it is 3 minutes and not 30 seconds. But EventGrid only looks at the minute-part of the timestamp. One thing we can take away from this is that the 1st instance's delayed failure doesn't trigger a 3rd invocation.</p>
<p>Let's flip when the exception is thrown; the 2nd invocation will throw an exception, like this:</p>
<pre class="lang-cs prettyprint-override"><code>public static class Function1
{
    private static Dictionary<string, int> _Counter = new();

    [FunctionName("Function1")]
    public static async Task Run([EventGridTrigger] EventGridEvent eventGridEvent, ILogger log)
    {
        if (_Counter.ContainsKey(eventGridEvent.Id))
        {
            _Counter[eventGridEvent.Id]++;
            throw new Exception($"{eventGridEvent.Id}: {_Counter[eventGridEvent.Id]}");
        }

        _Counter.Add(eventGridEvent.Id, 1);
        var delay = (long)eventGridEvent.Data;
        log.LogInformation($"Delay: {delay}");
        await Task.Delay(TimeSpan.FromSeconds(delay));
        log.LogInformation($"{eventGridEvent.Id} finished after {delay}: {_Counter[eventGridEvent.Id]}");
        return;
    }
}
</code>```

Delay=35

2022-02-06T00:57:00.777 [Information] Executing 'Function1' (Reason='EventGrid trigger fired at 2022-02-06T00:57:00.7684489+00:00', Id=16505ac4-0cb2-4b1a-8b7c-d4adf964fe14)
2022-02-06T00:57:00.780 [Information] Delay: 35
2022-02-06T00:57:35.794 [Information] 7fce3bc0-f5d3-4b3e-bd5d-4997299aa9b7 finished after 35: 1
2022-02-06T00:57:35.796 [Information] Executed 'Function1' (Succeeded, Id=16505ac4-0cb2-4b1a-8b7c-d4adf964fe14, Duration=35028ms)
```
<p>Still nothing after 30 seconds. I'm skipping 45, as I'm pretty sure it'll yield same result as 35.</p>
<p>Delay=185</p>
```2022-02-06T00:59:04.226 [Information] Executing 'Function1' (Reason='EventGrid trigger fired at 2022-02-06T00:59:04.2262900+00:00', Id=cac343e5-911b-4ba7-a0c7-69e883a61392)
2022-02-06T00:59:04.227 [Information] Delay: 185
2022-02-06T01:01:44.196 [Information] Executing 'Function1' (Reason='EventGrid trigger fired at 2022-02-06T01:01:44.1962398+00:00', Id=2c65d66b-57c8-4a7d-b9ec-d54959e84e3d)
2022-02-06T01:01:44.271 [Error] Executed 'Function1' (Failed, Id=2c65d66b-57c8-4a7d-b9ec-d54959e84e3d, Duration=68ms)e051565c-9900-4cef-9786-5795c9fc7f91: 2
2022-02-06T01:02:09.240 [Information] e051565c-9900-4cef-9786-5795c9fc7f91 finished after 185: 2
2022-02-06T01:02:09.240 [Information] Executed 'Function1' (Succeeded, Id=cac343e5-911b-4ba7-a0c7-69e883a61392, Duration=185014ms)
2022-02-06T01:02:14.293 [Information] Executing 'Function1' (Reason='EventGrid trigger fired at 2022-02-06T01:02:14.2930303+00:00', Id=729e8079-e33e-48f4-8c5a-48e102a6d9d1)
2022-02-06T01:02:14.300 [Error] Executed 'Function1' (Failed, Id=729e8079-e33e-48f4-8c5a-48e102a6d9d1, Duration=1ms)e051565c-9900-4cef-9786-5795c9fc7f91: 3
2022-02-06T01:03:14.395 [Information] Executing 'Function1' (Reason='EventGrid trigger fired at 2022-02-06T01:03:14.3956880+00:00', Id=5996df91-cecf-418f-a5b5-82d7680761f8)
2022-02-06T01:03:14.403 [Error] Executed 'Function1' (Failed, Id=5996df91-cecf-418f-a5b5-82d7680761f8, Duration=1ms)e051565c-9900-4cef-9786-5795c9fc7f91: 4
```

It kept failing after this 'till the retry policy's delay became longer than the Function instance's idle cool down (the static dictionary was obviously removed from memory as the instance was taken down).

This could indicate that EventGrid ignores any response from an invocation older than 3 minutes. That is, the 1st invocation's 185 second delayed "OK" response was ignored. All subsequent invocations failed, forcing the event to be queued for retry.

There might be some more to it than what these simple tests show. If you really must now I suggest opening an issues ticket in GitHub

Potential solution for your idempotency issue

I'm not sure I fully understand your "multipart step". But if you can wrap that part into a single session, you could chain your EventGridTrigger with a session-enabled ServiceBusTrigger.

If your events have unique identifiers (eventGridEvent.Id), then you could build a service bus message with a session id matching the event's identifier. The service bus trigger, with sessions enabled, will make sure that the event (or session, rather) is only invoked 1 at a time.

This works because the two identical events also share the same eventGridEvent.Id. You will however have to keep track of these identifiers. At the end of your service bus session you'd have to mark the ID as "processed". At the beginning of your session, check if that ID was previously processed; ignore the request if it was.

Read more about ServiceBusTrigger with "Message sessions" here and here (look at the isSessionsEnabled property) (you can search for "session" to find more on the page related to session, it's scattered around).

Body:
I couldn't find anything solid in the documentation. So I ran a few tests myself as I was intrigued by the question. I've also included a potential "solution" to your multistep issue, or rather, that it is not idempotent (yet?). Scroll through the wall of text, it's at the end.

First thoughts are that two instances could run the same event, if only and if the first invocation exceeds the default 30 seconds for response, which is why the "at-least-once" delivery is mentioned. Example:

Event is published

Instance A picks up the event

Instance A runs for more than 30 seconds

Event is added to retry queue as instance A hasn't replied yet

Instance A is finished, 35 seconds total elapsed

Event from retry queue is published after sitting in retry queue for 10 seconds

Instance B picks up the event

I really think it comes down to the execution duration of the two instances how EventGrid reacts.

According to the documentation for Retry schedule:

If the endpoint responds within 3 minutes, Event Grid will attempt to
remove the event from the retry queue on a best effort basis but
duplicates may still be received.

This could be interpreted as such that as soon as an instance replies with a successful response EventGrid will attempt to clean out the retry queue (from the example above, instance B should never pick up the event). However, I'm also interested in what happens when instance A fails.

I tried with the following code, which will throw an exception from instance A after a certain delay:

public static class Function1
{
    private static Dictionary<string, int> _Counter = new();

    [FunctionName("Function1")]
    public static async Task Run([EventGridTrigger] EventGridEvent eventGridEvent, ILogger log)
    {
        if (_Counter.ContainsKey(eventGridEvent.Id))
        {
            _Counter[eventGridEvent.Id]++;
            log.LogInformation($"{eventGridEvent.Id}: {_Counter[eventGridEvent.Id]}");
            return;
        }

        _Counter.Add(eventGridEvent.Id, 1);
        var delay = (long)eventGridEvent.Data;
        log.LogInformation($"Delay: {delay}");
        await Task.Delay(TimeSpan.FromSeconds(delay));
        log.LogInformation($"{eventGridEvent.Id}: {_Counter[eventGridEvent.Id]}");
        throw new Exception($"{eventGridEvent.Id} Throwing after {delay} seconds delay");
    }
}

Results from different delays

Delay = 35

2022-02-06T00:34:10.798 [Information] Executing 'Function1' (Reason='EventGrid trigger fired at 2022-02-06T00:34:10.7899831+00:00', Id=9d1adfe9-21bd-454c-862e-a4d8d5b312e0)
2022-02-06T00:34:10.801 [Information] Delay: 35
2022-02-06T00:34:45.807 [Information] 6d3d141d-d0ee-4e81-a648-e2497e562b84: 1
2022-02-06T00:34:45.894 [Error] Executed 'Function1' (Failed, Id=9d1adfe9-21bd-454c-862e-a4d8d5b312e0, Duration=35096ms)6d3d141d-d0ee-4e81-a648-e2497e562b84 Throwing after 35 seconds delay
2022-02-06T00:34:55.949 [Information] Executing 'Function1' (Reason='EventGrid trigger fired at 2022-02-06T00:34:55.9486015+00:00', Id=58a7a6db-2f97-4bc7-b878-030b8be25711)
2022-02-06T00:34:55.949 [Information] 6d3d141d-d0ee-4e81-a648-e2497e562b84: 2
2022-02-06T00:34:55.949 [Information] Executed 'Function1' (Succeeded, Id=58a7a6db-2f97-4bc7-b878-030b8be25711, Duration=1ms)

Seems that the retry that was most likely added to the queue after 30 seconds was either removed/replaced or its scheduled execution was "updated":

58-13 = 45,

35 for execution duration of instance A

10 for retry delay after instance A failed

Delay = 45

2022-02-06T00:37:29.526 [Information] Executing 'Function1' (Reason='EventGrid trigger fired at 2022-02-06T00:37:29.5262414+00:00', Id=c4596efa-7034-4efe-bcf9-85d502517711)
2022-02-06T00:37:29.526 [Information] Delay: 45
2022-02-06T00:38:14.524 [Information] 284fa140-1cdc-41e7-973f-d0ecd6f19692: 1
2022-02-06T00:38:14.530 [Error] Executed 'Function1' (Failed, Id=c4596efa-7034-4efe-bcf9-85d502517711, Duration=44999ms)284fa140-1cdc-41e7-973f-d0ecd6f19692 Throwing after 45 seconds delay
2022-02-06T00:38:24.590 [Information] Executing 'Function1' (Reason='EventGrid trigger fired at 2022-02-06T00:38:24.5901035+00:00', Id=43a1fafa-7773-44e5-9f3a-b4bf697865a9)
2022-02-06T00:38:24.590 [Information] 284fa140-1cdc-41e7-973f-d0ecd6f19692: 2
2022-02-06T00:38:24.590 [Information] Executed 'Function1' (Succeeded, Id=43a1fafa-7773-44e5-9f3a-b4bf697865a9, Duration=0ms)

This is sorta unexpected behavior. We'd have expected to see a 2nd invocation finish before the 1st one, presumably finishing after 40 seconds after the 1st invocation's start. This could indicate that EventGrid actually knows that the 1st instance hasn't failed, and is still running, so it's actually not adding the retry attempt to the queue just yet. It does however add it after the 1st instance fails, and the retry attempt is, as expected, executed 10 seconds later.

I wanted to test the above, and thought the magic number could be 3 minutes (also mentioned in the documentation) and not 30 seconds.

Delay = 185

2022-02-06T00:40:20.381 [Information] Executing 'Function1' (Reason='EventGrid trigger fired at 2022-02-06T00:40:20.3809687+00:00', Id=454b815f-6ca6-4b75-9272-711c7b6bf42a)
2022-02-06T00:40:20.381 [Information] Delay: 185
2022-02-06T00:43:00.393 [Information] Executing 'Function1' (Reason='EventGrid trigger fired at 2022-02-06T00:43:00.3928958+00:00', Id=23910142-d903-4b9b-bec2-a5665e8e1db7)
2022-02-06T00:43:00.393 [Information] 97d828e6-d1f3-4523-b043-1f76465de6ea: 2
2022-02-06T00:43:00.393 [Information] Executed 'Function1' (Succeeded, Id=23910142-d903-4b9b-bec2-a5665e8e1db7, Duration=0ms)
2022-02-06T00:43:25.381 [Information] 97d828e6-d1f3-4523-b043-1f76465de6ea: 2
2022-02-06T00:43:25.387 [Error] Executed 'Function1' (Failed, Id=454b815f-6ca6-4b75-9272-711c7b6bf42a, Duration=185002ms)97d828e6-d1f3-4523-b043-1f76465de6ea Throwing after 185 seconds delay

This is also sorta contradicting the documentation. The first instance executes at 40:20. At 43:00 (would've expected 43:20), it runs the 2nd instance, completes immediately. Then the 1st instance fails at 43:25 (as expected). Maybe it is 3 minutes and not 30 seconds. But EventGrid only looks at the minute-part of the timestamp. One thing we can take away from this is that the 1st instance's delayed failure doesn't trigger a 3rd invocation.

Let's flip when the exception is thrown; the 2nd invocation will throw an exception, like this:

public static class Function1
{
    private static Dictionary<string, int> _Counter = new();

    [FunctionName("Function1")]
    public static async Task Run([EventGridTrigger] EventGridEvent eventGridEvent, ILogger log)
    {
        if (_Counter.ContainsKey(eventGridEvent.Id))
        {
            _Counter[eventGridEvent.Id]++;
            throw new Exception($"{eventGridEvent.Id}: {_Counter[eventGridEvent.Id]}");
        }

        _Counter.Add(eventGridEvent.Id, 1);
        var delay = (long)eventGridEvent.Data;
        log.LogInformation($"Delay: {delay}");
        await Task.Delay(TimeSpan.FromSeconds(delay));
        log.LogInformation($"{eventGridEvent.Id} finished after {delay}: {_Counter[eventGridEvent.Id]}");
        return;
    }
}

Delay=35

2022-02-06T00:57:00.777 [Information] Executing 'Function1' (Reason='EventGrid trigger fired at 2022-02-06T00:57:00.7684489+00:00', Id=16505ac4-0cb2-4b1a-8b7c-d4adf964fe14)
2022-02-06T00:57:00.780 [Information] Delay: 35
2022-02-06T00:57:35.794 [Information] 7fce3bc0-f5d3-4b3e-bd5d-4997299aa9b7 finished after 35: 1
2022-02-06T00:57:35.796 [Information] Executed 'Function1' (Succeeded, Id=16505ac4-0cb2-4b1a-8b7c-d4adf964fe14, Duration=35028ms)

Still nothing after 30 seconds. I'm skipping 45, as I'm pretty sure it'll yield same result as 35.

Delay=185

2022-02-06T00:59:04.226 [Information] Executing 'Function1' (Reason='EventGrid trigger fired at 2022-02-06T00:59:04.2262900+00:00', Id=cac343e5-911b-4ba7-a0c7-69e883a61392)
2022-02-06T00:59:04.227 [Information] Delay: 185
2022-02-06T01:01:44.196 [Information] Executing 'Function1' (Reason='EventGrid trigger fired at 2022-02-06T01:01:44.1962398+00:00', Id=2c65d66b-57c8-4a7d-b9ec-d54959e84e3d)
2022-02-06T01:01:44.271 [Error] Executed 'Function1' (Failed, Id=2c65d66b-57c8-4a7d-b9ec-d54959e84e3d, Duration=68ms)e051565c-9900-4cef-9786-5795c9fc7f91: 2
2022-02-06T01:02:09.240 [Information] e051565c-9900-4cef-9786-5795c9fc7f91 finished after 185: 2
2022-02-06T01:02:09.240 [Information] Executed 'Function1' (Succeeded, Id=cac343e5-911b-4ba7-a0c7-69e883a61392, Duration=185014ms)
2022-02-06T01:02:14.293 [Information] Executing 'Function1' (Reason='EventGrid trigger fired at 2022-02-06T01:02:14.2930303+00:00', Id=729e8079-e33e-48f4-8c5a-48e102a6d9d1)
2022-02-06T01:02:14.300 [Error] Executed 'Function1' (Failed, Id=729e8079-e33e-48f4-8c5a-48e102a6d9d1, Duration=1ms)e051565c-9900-4cef-9786-5795c9fc7f91: 3
2022-02-06T01:03:14.395 [Information] Executing 'Function1' (Reason='EventGrid trigger fired at 2022-02-06T01:03:14.3956880+00:00', Id=5996df91-cecf-418f-a5b5-82d7680761f8)
2022-02-06T01:03:14.403 [Error] Executed 'Function1' (Failed, Id=5996df91-cecf-418f-a5b5-82d7680761f8, Duration=1ms)e051565c-9900-4cef-9786-5795c9fc7f91: 4

It kept failing after this 'till the retry policy's delay became longer than the Function instance's idle cool down (the static dictionary was obviously removed from memory as the instance was taken down).

This could indicate that EventGrid ignores any response from an invocation older than 3 minutes. That is, the 1st invocation's 185 second delayed "OK" response was ignored. All subsequent invocations failed, forcing the event to be queued for retry.

There might be some more to it than what these simple tests show. If you really must now I suggest opening an issues ticket in GitHub

Potential solution for your idempotency issue

I'm not sure I fully understand your "multipart step". But if you can wrap that part into a single session, you could chain your EventGridTrigger with a session-enabled ServiceBusTrigger.

If your events have unique identifiers (eventGridEvent.Id), then you could build a service bus message with a session id matching the event's identifier. The service bus trigger, with sessions enabled, will make sure that the event (or session, rather) is only invoked 1 at a time.

This works because the two identical events also share the same eventGridEvent.Id. You will however have to keep track of these identifiers. At the end of your service bus session you'd have to mark the ID as "processed". At the beginning of your session, check if that ID was previously processed; ignore the request if it was.

Read more about ServiceBusTrigger with "Message sessions" here and here (look at the isSessionsEnabled property) (you can search for "session" to find more on the page related to session, it's scattered around).


问:
How to check for ENTER key press in curses. curses.KEY_ENTER not working
I am trying to get user input in curses (python), and for some reason it cannot detect when I press the ENTER key.

```<code>while True:
        key = stdscr.getkey()
        if key == curses.KEY_ENTER:
            TASK += 1
            break
        elif key.lower() == 'q':
            quit(stdscr)
            break
</code>```

the if part is not working and the elif part is working fine.

答:
curses.KEY_ENTER would be the numeric-keypad Enter key

if curses keypad mode is enabled and

if the terminal description has the corresponding code and

if the terminal actually sends what the terminal description says. (Keypad coverage on some terminal emulators is an area for improvement).

It's not related to the Enter key on the main keyboard.

You'll get better results if you add a comparison for \n and \r (this is probably a duplicate).

Body:
I am trying to get user input in curses (python), and for some reason it cannot detect when I press the ENTER key.

while True:
        key = stdscr.getkey()
        if key == curses.KEY_ENTER:
            TASK += 1
            break
        elif key.lower() == 'q':
            quit(stdscr)
            break

the if part is not working and the elif part is working fine.


问:
Can't hide modal within Layout (wrapper) component
I'm trying to hide the shopping cart modal of an e-commerce store that I'm trying to build on React. When I try to follow the code in the tutorial, the cart modal window does not hide from the display and just remains there in front of all the other components. There's no error that displays btw.  I'm using a wrapper component with the name of Layout here.

Karte.js - the main cart component

```<code>import { useState, React } from "react";
import Modal from "./Modal";

export default function Karte(props) {
  const [cartIsOpen, setCartIsOpen] = useState(false);

  function functionName() {
    setCartIsOpen(true);
  }

  const cartItems = (
    <ul>
      {[{ id: "i1", name: "Ralph Lauren", amount: 3, price: 14.99 }].map(
        (item) => (
          <li key={item.id}>
            {item.name}
            {item.price}
          </li>
        )
      )}
    </ul>
  );

  return (
    <Modal>
      {cartItems}
      <div>
        <span>Total Amount</span>
        <span>35.54</span>
      </div>
      <div>
        <button onClick={functionName}>Close</button>
        <button>Checkout</button>
      </div>
    </Modal>
  );
}
</code>```

This is the Modal component code

```<code>const Modal = (props) => {
  return <div className="modal">{props.children}</div>;
};

export default Modal;
</code>```

Lastly, this is the Wrapper component (that the modal is a child component of)

```<code>import { useState, React } from "react";
import NavBar from "../NavBar";
import Modal from "../Modal";
import Backdrop from "../Backdrop";

export default function Layout(props) {
  const [cartIsOpen, setCartIsOpen] = useState(false);

  function functionName() {
    setCartIsOpen(true);
  }
  return (
    <div>
      <NavBar />
      <main>{props.children}</main>
      {cartIsOpen && <Modal />}
      <Backdrop />
    </div>
  );
}
</code>```

If it means anything, this is the App component too

```<code>function App() {
  return (
    <Layout>
      <Karte />
      <Routes>
        <Route path="/" element={<HomePage />} exact />
        <Route path="/checkout" element={<CheckoutPage />} />
        <Route path="/cart" element={<CartPage />} />
        <Route path="/login" element={<LoginPage />} />
        <Route path="/sale" element={<SalePage />} />
        <Route path="/faqs" element={<FaqsPage />} />
      </Routes>
    </Layout>
  );
}

export default App;
</code>```

答:
check if functionName is running and setting state to true
current =  Close.
If so change code to this <button onClick={()=>{functionName}}></p>

Body:
I'm trying to hide the shopping cart modal of an e-commerce store that I'm trying to build on React. When I try to follow the code in the tutorial, the cart modal window does not hide from the display and just remains there in front of all the other components. There's no error that displays btw.  I'm using a wrapper component with the name of Layout here.

Karte.js - the main cart component

import { useState, React } from "react";
import Modal from "./Modal";

export default function Karte(props) {
  const [cartIsOpen, setCartIsOpen] = useState(false);

  function functionName() {
    setCartIsOpen(true);
  }

  const cartItems = (

      {[{ id: "i1", name: "Ralph Lauren", amount: 3, price: 14.99 }].map(
        (item) => (

            {item.name}
            {item.price}

        )
      )}

  );

  return (
    <Modal>
      {cartItems}

        Total Amount
        35.54

        <button onClick={functionName}>Close</button>
        <button>Checkout</button>

    </Modal>
  );
}

This is the Modal component code

const Modal = (props) => {
  return
{props.children}
;
};

export default Modal;

Lastly, this is the Wrapper component (that the modal is a child component of)

import { useState, React } from "react";
import NavBar from "../NavBar";
import Modal from "../Modal";
import Backdrop from "../Backdrop";

export default function Layout(props) {
  const [cartIsOpen, setCartIsOpen] = useState(false);

  function functionName() {
    setCartIsOpen(true);
  }
  return (

      <NavBar />
      {props.children}
      {cartIsOpen && <Modal />}
      <Backdrop />

  );
}

If it means anything, this is the App component too

function App() {
  return (
    <Layout>
      <Karte />
      <Routes>
        <Route path="/" element={<HomePage />} exact />
        <Route path="/checkout" element={<CheckoutPage />} />
        <Route path="/cart" element={<CartPage />} />
        <Route path="/login" element={<LoginPage />} />
        <Route path="/sale" element={<SalePage />} />
        <Route path="/faqs" element={<FaqsPage />} />
      </Routes>
    </Layout>
  );
}

export default App;


问:
Implementing pacman in c, ghost movement
I am creating a pacman in c and currently I am usisng a single thread for each ghost and each ghost represents a '#' but when I run it all the screen gets full of ghosts and not all the ghosts move just one or two.

Im using this logic

create a struct of 5 ghost, each ghost contains the x,y position.
create an array of 5 threads and each thread implements one ghost
each ghost moves randomly on the screen, for each space that it moves I print
a space in the old position and then I print a '#' in the new position.

Could you provide me please an example of how to implement the movement of the ghost,
or the implementation Im doing is the correct way?

Thank you

答: Trying to update the screen simultaneously from several threads requires a mutex around the screen update code.</p>


问:
Bot Mentions Discord.py
```<code>  if client.user.mentioned_in(message):
    await ctx.send("Hi!")
</code>```

So I want my bot to respond to anyone who @mentions it. It does work as it should, but the only problem it'll respond to @everyone and @here pings. It's probably simple and I am overthinking it but I just want to know if there is any way to make the bot respond to messages it's actually mentioned in, not @everyone or @here pings?

答:
You can use the

```<code>@client.event
async def on_message(message):
</code>```

Then detect if the message has mentioned the bot:

```<code>if client.user.mentioned_in(message):
    await message.channel.send("Hi!")
</code>```

Documentation: https://docs.pycord.dev/en/master/api.html?highlight=mentioned#discord.ClientUser.mentioned_in

Title: Bot Mentions Discord.py

Body:
  if client.user.mentioned_in(message):
    await ctx.send("Hi!")

So I want my bot to respond to anyone who @mentions it. It does work as it should, but the only problem it'll respond to @everyone and @here pings. It's probably simple and I am overthinking it but I just want to know if there is any way to make the bot respond to messages it's actually mentioned in, not @everyone or @here pings?

Body:
You can use the

@client.event
async def on_message(message):

Then detect if the message has mentioned the bot:

if client.user.mentioned_in(message):
    await message.channel.send("Hi!")

Documentation: https://docs.pycord.dev/en/master/api.html?highlight=mentioned#discord.ClientUser.mentioned_in


问:
b=b++ assignment unexpected result
I wrote this text code

```<code>int b=5;
int main()
{
    b=b++;
    printf("b = %d\n",b);
    return 0;
}
</code>```

and I expected it to print "b = 6"; however, the result is "b = 5", i.e. b is not incremented.
I know b=b++ is not a good practice but just to understand it, can anyone explain why it is not incrementing b please? What am I missing?

答:
b++ means incrementing the value after it is used
so for your case it should be ++b.
When b is incrementing to 6 by b++ it is overwritten by assignment of b when it is 5.

Just write it

```<code>int b=5;
int main()
{
    // b=b++;
    b++;
    // or ++b;
    printf("b = %d\n",b);
    return 0;
}
</code>```

Title: b=b++ assignment unexpected result

Body:
I wrote this text code

int b=5;
int main()
{
    b=b++;
    printf("b = %d\n",b);
    return 0;
}

and I expected it to print "b = 6"; however, the result is "b = 5", i.e. b is not incremented.
I know b=b++ is not a good practice but just to understand it, can anyone explain why it is not incrementing b please? What am I missing?

Body:
b++ means incrementing the value after it is used
so for your case it should be ++b.
When b is incrementing to 6 by b++ it is overwritten by assignment of b when it is 5.

Just write it

int b=5;
int main()
{
    // b=b++;
    b++;
    // or ++b;
    printf("b = %d\n",b);
    return 0;
}


问:
In React app, iframe is showing up in developer tools, elements
Its First time im asking a question, so not much idea how to describe/write it.

I am working in a react project (making clons for learning purpose). Watching video tutorials and first time use firebase and redux. After making much progress, I counter the problem, in which when I save my work, local host 3000 doesn't refresh. I know there are lot of answers, I tried all but they didn't work for me.

But the main issue is, In my developer tool i see

Within this, there is #document and inside of it,  then  and .

I didn't know what is this and the reason why it's showing up. Then i search, what is iframe, but i never use such thing i my project. And after a lot of research how to remove it. I didn't find the answer and way to do it Screen shot of my developer tool.

I can see all my components but they don't respond to me E.g can't take inputs, no hover effects etc. But when i manually delete  from dev tool, it works fine.

答:
The iframe is used by react to inject changes to the dom during hotreload. Sometimes it fails and doesn't remove the iframe, thus the behavior.

A fix would be to add:

```<code>  "resolutions": {
    "react-error-overlay": "6.0.9"
  },
</code>```

To your package.json immediately after the scripts, delete package.lock or yarn.lock files, install packages again.

Body:
The iframe is used by react to inject changes to the dom during hotreload. Sometimes it fails and doesn't remove the iframe, thus the behavior.

A fix would be to add:

  "resolutions": {
    "react-error-overlay": "6.0.9"
  },

To your package.json immediately after the scripts, delete package.lock or yarn.lock files, install packages again.


问:
Why does csvWriter require a StreamWriter object, why can't it make it for me?
In the following example, why do I need to make a SEPERATE StreamWriter class and then pass it to the CsvWriter?

It just feels repetitive and redundant. What if I never need to use the StreamWriter again? And secondly, if I need a StreamWriterevery time I want to use CsvWriter, wouldn't it be better for the CsvWriter to handle that for me?

var writer = new StreamWriter("./Output.csv"))
var csvWriter = new CsvWriter(writer, CultureInfo.InvariantCulture)
{
    csvWriter.WriteRecords(songQueryResults);
}
Console.WriteLine("Done");
```

Lately I've been learning OOP and this seems to go against the idea of encapsulation which is why I'm asking this question

答:
It doesn't.  It can be any TextWriter.  That means, sure, StreamWriter.  And also HttpWriter or anything else you might think of for an odd use case in the future where you need to write a CSV and might write your own class to handle.  (Maybe TcpWriter?  DBWriter?)

CsvWriter's one job is to format CSV output.  It doesn't care where it's going, so it depends on a TextWriter to persist it somewhere.  That's proper encapsulation.

Body:
In the following example, why do I need to make a SEPERATE StreamWriter class and then pass it to the CsvWriter?

It just feels repetitive and redundant. What if I never need to use the StreamWriter again? And secondly, if I need a StreamWriterevery time I want to use CsvWriter, wouldn't it be better for the CsvWriter to handle that for me?

var writer = new StreamWriter("./Output.csv"))
var csvWriter = new CsvWriter(writer, CultureInfo.InvariantCulture)
{
    csvWriter.WriteRecords(songQueryResults);
}
Console.WriteLine("Done");

Lately I've been learning OOP and this seems to go against the idea of encapsulation which is why I'm asking this question


问:
Can’t find all page tables when web scraping using r
I am trying to scrape a table of tide data collected at 6 minute interval from a NOAA site using r.
I have tried a few different approaches but none seem to be able to find the table I am looking for:

```<code>page_adress<-"https://tidesandcurrents.noaa.gov/noaatidepredictions.html?id=1612480&units=standard&bdate=20220204&edate=20220205&timezone=LST&clock=12hour&datum=MLLW&interval=6&action=data"

library(htmltab)
htmltab(doc = page_adress, which=1, header=0)

library(rvest)
html <- read_html(page_adress)

html %>%
  html_nodes("table") %>%
  .[[1]] %>%
  html_table()
</code>```

Both approaches can only find the short summary table on top of the page, but not the larger table requested.

```<code>> 1  5:18 AM high 1.89 ft.
2 12:11 PM  low 0.28 ft.
3  6:03 PM high 1.19 ft.
4 11:11 PM  low 0.67 ft.
</code>```

If I inspect the code, I can see the long table data in the html document.

I am proficient to r but new to scraping, so I may be missing something obvious… any help or guidance would be highly appreciated!

答:
Following MrFlick's answer the following obtains and formats the data for the larger table:</p>
```<code>library(tidyverse)
library(httr)
library(rvest)
library(lubridate)

url <- "https://api.tidesandcurrents.noaa.gov/api/prod/datagetter?product=predictions&begin_date=20220203&end_date=20220206&datum=MLLW&station=1612480&time_zone=LST&units=english&interval=6&format=json&application=NOS.COOPS.TAC.TidePred"

headers <- c(
  'authority' = "tidesandcurrents.noaa.gov",
  'method' = "GET",
  'path' = "/api/prod/datagetter?product=predictions&begin_date=20220203&end_date=20220206&datum=MLLW&station=1612480&time_zone=LST&units=english&interval=6&format=json&application=NOS.COOPS.TAC.TidePred",
  'scheme' = "https",
  'accept' = "*/*",
  'Accept-Encoding' = "gzip, deflate",
  'referer' = "https://tidesandcurrents.noaa.gov/",
  'User-Agent' = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.17 Safari/537.36",
  'x-requested-with' = "XMLHttpRequest"
)

h1 <- httr::handle('')

table <- url %>%
  httr::GET(.,
            httr::add_headers(.headers=headers),
            handle = h1
  ) %>%
  content() %>%
  map_dfr(., pluck, .id = NULL) %>%
  set_names("Date", "Prediction") %>%
  mutate(Time = format(as.POSIXct(Date,format="%Y-%m-%d %H:%M"),"%H:%M")) %>%
  mutate(Date = format(as.POSIXct(Date,format="%Y-%m-%d %H:%M"),"%Y-%m-%d")) %>%
  mutate(`Day of the Week` = wday(strptime(Date, "%Y-%m-%d"), label = TRUE)) %>%
  select(Date, `Day of the Week`, Time, Prediction)
</code>```

Body:
I am trying to scrape a table of tide data collected at 6 minute interval from a NOAA site using r.
I have tried a few different approaches but none seem to be able to find the table I am looking for:

page_adress<-"https://tidesandcurrents.noaa.gov/noaatidepredictions.html?id=1612480&units=standard&bdate=20220204&edate=20220205&timezone=LST&clock=12hour&datum=MLLW&interval=6&action=data"

library(htmltab)
htmltab(doc = page_adress, which=1, header=0)

library(rvest)
html <- read_html(page_adress)

html %>%
  html_nodes("table") %>%
  .[[1]] %>%
  html_table()

Both approaches can only find the short summary table on top of the page, but not the larger table requested.

> 1  5:18 AM high 1.89 ft.
2 12:11 PM  low 0.28 ft.
3  6:03 PM high 1.19 ft.
4 11:11 PM  low 0.67 ft.

If I inspect the code, I can see the long table data in the html document.

I am proficient to r but new to scraping, so I may be missing something obvious… any help or guidance would be highly appreciated!

Body:
Following MrFlick's answer the following obtains and formats the data for the larger table:

library(tidyverse)
library(httr)
library(rvest)
library(lubridate)

url <- "https://api.tidesandcurrents.noaa.gov/api/prod/datagetter?product=predictions&begin_date=20220203&end_date=20220206&datum=MLLW&station=1612480&time_zone=LST&units=english&interval=6&format=json&application=NOS.COOPS.TAC.TidePred"

headers <- c(
  'authority' = "tidesandcurrents.noaa.gov",
  'method' = "GET",
  'path' = "/api/prod/datagetter?product=predictions&begin_date=20220203&end_date=20220206&datum=MLLW&station=1612480&time_zone=LST&units=english&interval=6&format=json&application=NOS.COOPS.TAC.TidePred",
  'scheme' = "https",
  'accept' = "*/*",
  'Accept-Encoding' = "gzip, deflate",
  'referer' = "https://tidesandcurrents.noaa.gov/",
  'User-Agent' = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.17 Safari/537.36",
  'x-requested-with' = "XMLHttpRequest"
)

h1 <- httr::handle('')

table <- url %>%
  httr::GET(.,
            httr::add_headers(.headers=headers),
            handle = h1
  ) %>%
  content() %>%
  map_dfr(., pluck, .id = NULL) %>%
  set_names("Date", "Prediction") %>%
  mutate(Time = format(as.POSIXct(Date,format="%Y-%m-%d %H:%M"),"%H:%M")) %>%
  mutate(Date = format(as.POSIXct(Date,format="%Y-%m-%d %H:%M"),"%Y-%m-%d")) %>%
  mutate(`Day of the Week` = wday(strptime(Date, "%Y-%m-%d"), label = TRUE)) %>%
  select(Date, `Day of the Week`, Time, Prediction)


问:
cant seem to Deserialize to strongly typed list object from array
I'm trying to deserialize use the following Json and classes:

```<code>List<Root> OBJTEST = (List<Root>)Newtonsoft.Json.JsonConvert.DeserializeObject(response, typeof(List<Root>));
</code>```

Classes:

```<code>[DataContract]
public class Root
{
    [DataMember]
    [JsonProperty("Meta Data")]
    public MetaData MetaData { get; set; }

    [DataMember]
    [JsonProperty("Time Series (Daily)")]
    public TimeSeriesDaily TimeSeriesDaily { get; set; }
}

[DataContract]
public class MetaData
{
    [DataMember]
    [JsonProperty("1. Information")]
    public string _1Information { get; set; }

    [DataMember]
    [JsonProperty("2. Symbol")]
    public string _2Symbol { get; set; }

    [DataMember]
    [JsonProperty("3. Last Refreshed")]
    public string _3LastRefreshed { get; set; }

    [DataMember]
    [JsonProperty("4. Output Size")]
    public string _4OutputSize { get; set; }

    [DataMember]
    [JsonProperty("5. Time Zone")]
    public string _5TimeZone { get; set; }
}

[DataContract]
public class _20220203
{
    [DataMember]
    [JsonProperty("1. open")]
    public string _1Open { get; set; }

    [DataMember]
    [JsonProperty("2. high")]
    public string _2High { get; set; }

    [DataMember]
    [JsonProperty("3. low")]
    public string _3Low { get; set; }

    [DataMember]
    [JsonProperty("4. close")]
    public string _4Close { get; set; }

    [DataMember]
    [JsonProperty("5. volume")]
    public string _5Volume { get; set; }
}

public class _20220202
{
    [JsonProperty("1. open")]
    public string _1Open { get; set; }

    [JsonProperty("2. high")]
    public string _2High { get; set; }

    [JsonProperty("3. low")]
    public string _3Low { get; set; }

    [JsonProperty("4. close")]
    public string _4Close { get; set; }

    [JsonProperty("5. volume")]
    public string _5Volume { get; set; }
}
</code>```

JSON:

```<code>{
"Meta Data": {
    "1. Information": "Daily Prices (open, high, low, close) and Volumes",
    "2. Symbol": "IBM",
    "3. Last Refreshed": "2022-02-04",
    "4. Output Size": "Compact",
    "5. Time Zone": "US/Eastern"
},
"Time Series (Daily)": {
    "2022-02-04": {
        "1. open": "137.8600",
        "2. high": "138.8200",
        "3. low": "136.2150",
        "4. close": "137.1500",
        "5. volume": "4142045"
    },
    "2022-02-03": {
        "1. open": "137.0000",
        "2. high": "138.7600",
        "3. low": "135.8310",
        "4. close": "137.7800",
        "5. volume": "6100777"
    }
  }
}
</code>```

I could not get above to work
sourcing : "https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=IBM&apikey=demo"

The objective is to return a List<Root> of strongly typed objects.

答:
You don't have an array value there. You should deserialize to object Root obj = Newtonsoft.Json.JsonConvert.DeserializeObject<Root>(response).

```<code>{
"Meta Data": {
    "1. Information": "Daily Prices (open, high, low, close) and Volumes",
    "2. Symbol": "IBM",
    "3. Last Refreshed": "2022-02-04",
    "4. Output Size": "Compact",
    "5. Time Zone": "US/Eastern"
},
"Time Series (Daily)": {
    "2022-02-04": {
        "1. open": "137.8600",
        "2. high": "138.8200",
        "3. low": "136.2150",
        "4. close": "137.1500",
        "5. volume": "4142045"
    },
    "2022-02-03": {
        "1. open": "137.0000",
        "2. high": "138.7600",
        "3. low": "135.8310",
        "4. close": "137.7800",
        "5. volume": "6100777"
    }
  }
}
</code>```

Try to parse Time Series (Daily) as Dictionary<string, object>

```<code>  {
"Meta Data": {
    "Information": "Daily Prices (open, high, low, close) and Volumes",
    "Symbol": "IBM",
    "Last Refreshed": "2022-02-04",
    "Output Size": "Compact",
    "Time Zone": "US/Eastern"
},
"Time Series (Daily)": {
    "2022-02-04": {
        "open": "137.8600",
        "high": "138.8200",
        "low": "136.2150",
        "close": "137.1500",
        "volume": "4142045"
    },
    "2022-02-03": {
        "open": "137.0000",
        "high": "138.7600",
        "low": "135.8310",
        "close": "137.7800",
        "volume": "6100777"
    }
  }
}
</code>```

If you want enumerate object then you can use JsonDocument:

```<code>        var jDoc = JsonDocument.Parse(content, new JsonDocumentOptions() { CommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true });
        var root = jDoc.RootElement.EnumerateObject();
</code>```

From the discussion in the comment, I believe it will help:

```<code>[DataContract]
public class Root
{
    [DataMember]
    [JsonProperty("Meta Data")]
    public MetaData MetaData { get; set; }

    [DataMember]
    [JsonProperty("Time Series (Daily)")]
    public Dictionary<string, DataItem> TimeSeriesDaily { get; set; }
}

[DataContract]
public class MetaData
{
    [DataMember]
    [JsonProperty("1. Information")]
    public string _1Information { get; set; }

    [DataMember]
    [JsonProperty("2. Symbol")]
    public string _2Symbol { get; set; }

    [DataMember]
    [JsonProperty("3. Last Refreshed")]
    public string _3LastRefreshed { get; set; }

    [DataMember]
    [JsonProperty("4. Output Size")]
    public string _4OutputSize { get; set; }

    [DataMember]
    [JsonProperty("5. Time Zone")]
    public string _5TimeZone { get; set; }
}

[DataContract]
public class DataItem
{
    [DataMember]
    [JsonProperty("1. open")]
    public string _1Open { get; set; }

    [DataMember]
    [JsonProperty("2. high")]
    public string _2High { get; set; }

    [DataMember]
    [JsonProperty("3. low")]
    public string _3Low { get; set; }

    [DataMember]
    [JsonProperty("4. close")]
    public string _4Close { get; set; }

    [DataMember]
    [JsonProperty("5. volume")]
    public string _5Volume { get; set; }
}
</code>```

And then to parse your JSON and return the list you should do like this:

```<code>public List<Root> ParseJson(string json)
{
    Root obj = Newtonsoft.Json.JsonConvert.Deserialize<Root>(json);
    return new List<Root> { obj };
}
</code>```

Body:
I'm trying to deserialize use the following Json and classes:

List<Root> OBJTEST = (List<Root>)Newtonsoft.Json.JsonConvert.DeserializeObject(response, typeof(List<Root>));

Classes:

[DataContract]
public class Root
{
    [DataMember]
    [JsonProperty("Meta Data")]
    public MetaData MetaData { get; set; }

    [DataMember]
    [JsonProperty("Time Series (Daily)")]
    public TimeSeriesDaily TimeSeriesDaily { get; set; }
}

[DataContract]
public class MetaData
{
    [DataMember]
    [JsonProperty("1. Information")]
    public string _1Information { get; set; }

    [DataMember]
    [JsonProperty("2. Symbol")]
    public string _2Symbol { get; set; }

    [DataMember]
    [JsonProperty("3. Last Refreshed")]
    public string _3LastRefreshed { get; set; }

    [DataMember]
    [JsonProperty("4. Output Size")]
    public string _4OutputSize { get; set; }

    [DataMember]
    [JsonProperty("5. Time Zone")]
    public string _5TimeZone { get; set; }
}

[DataContract]
public class _20220203
{
    [DataMember]
    [JsonProperty("1. open")]
    public string _1Open { get; set; }

    [DataMember]
    [JsonProperty("2. high")]
    public string _2High { get; set; }

    [DataMember]
    [JsonProperty("3. low")]
    public string _3Low { get; set; }

    [DataMember]
    [JsonProperty("4. close")]
    public string _4Close { get; set; }

    [DataMember]
    [JsonProperty("5. volume")]
    public string _5Volume { get; set; }
}

public class _20220202
{
    [JsonProperty("1. open")]
    public string _1Open { get; set; }

    [JsonProperty("2. high")]
    public string _2High { get; set; }

    [JsonProperty("3. low")]
    public string _3Low { get; set; }

    [JsonProperty("4. close")]
    public string _4Close { get; set; }

    [JsonProperty("5. volume")]
    public string _5Volume { get; set; }
}

JSON:

{
"Meta Data": {
    "1. Information": "Daily Prices (open, high, low, close) and Volumes",
    "2. Symbol": "IBM",
    "3. Last Refreshed": "2022-02-04",
    "4. Output Size": "Compact",
    "5. Time Zone": "US/Eastern"
},
"Time Series (Daily)": {
    "2022-02-04": {
        "1. open": "137.8600",
        "2. high": "138.8200",
        "3. low": "136.2150",
        "4. close": "137.1500",
        "5. volume": "4142045"
    },
    "2022-02-03": {
        "1. open": "137.0000",
        "2. high": "138.7600",
        "3. low": "135.8310",
        "4. close": "137.7800",
        "5. volume": "6100777"
    }
  }
}

I could not get above to work
sourcing : "https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=IBM&apikey=demo"

The objective is to return a List<Root> of strongly typed objects.

Body:
You don't have an array value there. You should deserialize to object Root obj = Newtonsoft.Json.JsonConvert.DeserializeObject<Root>(response).

{
"Meta Data": {
    "1. Information": "Daily Prices (open, high, low, close) and Volumes",
    "2. Symbol": "IBM",
    "3. Last Refreshed": "2022-02-04",
    "4. Output Size": "Compact",
    "5. Time Zone": "US/Eastern"
},
"Time Series (Daily)": {
    "2022-02-04": {
        "1. open": "137.8600",
        "2. high": "138.8200",
        "3. low": "136.2150",
        "4. close": "137.1500",
        "5. volume": "4142045"
    },
    "2022-02-03": {
        "1. open": "137.0000",
        "2. high": "138.7600",
        "3. low": "135.8310",
        "4. close": "137.7800",
        "5. volume": "6100777"
    }
  }
}

Try to parse Time Series (Daily) as Dictionary<string, object>

  {
"Meta Data": {
    "Information": "Daily Prices (open, high, low, close) and Volumes",
    "Symbol": "IBM",
    "Last Refreshed": "2022-02-04",
    "Output Size": "Compact",
    "Time Zone": "US/Eastern"
},
"Time Series (Daily)": {
    "2022-02-04": {
        "open": "137.8600",
        "high": "138.8200",
        "low": "136.2150",
        "close": "137.1500",
        "volume": "4142045"
    },
    "2022-02-03": {
        "open": "137.0000",
        "high": "138.7600",
        "low": "135.8310",
        "close": "137.7800",
        "volume": "6100777"
    }
  }
}

If you want enumerate object then you can use JsonDocument:

        var jDoc = JsonDocument.Parse(content, new JsonDocumentOptions() { CommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true });
        var root = jDoc.RootElement.EnumerateObject();

From the discussion in the comment, I believe it will help:

[DataContract]
public class Root
{
    [DataMember]
    [JsonProperty("Meta Data")]
    public MetaData MetaData { get; set; }

    [DataMember]
    [JsonProperty("Time Series (Daily)")]
    public Dictionary<string, DataItem> TimeSeriesDaily { get; set; }
}

[DataContract]
public class MetaData
{
    [DataMember]
    [JsonProperty("1. Information")]
    public string _1Information { get; set; }

    [DataMember]
    [JsonProperty("2. Symbol")]
    public string _2Symbol { get; set; }

    [DataMember]
    [JsonProperty("3. Last Refreshed")]
    public string _3LastRefreshed { get; set; }

    [DataMember]
    [JsonProperty("4. Output Size")]
    public string _4OutputSize { get; set; }

    [DataMember]
    [JsonProperty("5. Time Zone")]
    public string _5TimeZone { get; set; }
}

[DataContract]
public class DataItem
{
    [DataMember]
    [JsonProperty("1. open")]
    public string _1Open { get; set; }

    [DataMember]
    [JsonProperty("2. high")]
    public string _2High { get; set; }

    [DataMember]
    [JsonProperty("3. low")]
    public string _3Low { get; set; }

    [DataMember]
    [JsonProperty("4. close")]
    public string _4Close { get; set; }

    [DataMember]
    [JsonProperty("5. volume")]
    public string _5Volume { get; set; }
}

And then to parse your JSON and return the list you should do like this:

public List<Root> ParseJson(string json)
{
    Root obj = Newtonsoft.Json.JsonConvert.Deserialize<Root>(json);
    return new List<Root> { obj };
}


问:
Styling Accordion dash bootstrap component
I would like to customize the tabs in the accordion bootstrap component.

This is the code:

```<code>import dash_bootstrap_components as dbc
from dash import html

accordion = html.Div(
    dbc.Accordion(
        [
            dbc.AccordionItem(
                "This is the content of the first section", title="Item 1"
            ),
            dbc.AccordionItem(
                "This is the content of the second section", title="Item 2"
            ),
            dbc.AccordionItem(
                "This is the content of the third section", title="Item 3"
            ),
        ],
        start_collapsed=True,
    ),
)
</code>```

rendering this:

I hev two ajdustments I want to make:

Set the title (eg. Item 1) to  H1, or something else.

When accordion is activated (open) the default color of the tab is light blue (see screenshot). I want to change this color. How?

I have tried different variations of css styling, like what is suggested here, but with no luck.

答:
To adjust the Item styling, you need to change the styling for .accordion-button. To adjust the styling when opening an accordion item, you need to change the styling for .accordion-button:not(.collapsed).

Here is an example of making the "Item" text larger, and changing the color of the item on opening to red:

```<code>.accordion-button {
    font-size: xx-large;
}

.accordion-button:not(.collapsed) {
    background-color: red;
}
</code>```

Body:
I would like to customize the tabs in the accordion bootstrap component.

This is the code:

import dash_bootstrap_components as dbc
from dash import html

accordion = html.Div(
    dbc.Accordion(
        [
            dbc.AccordionItem(
                "This is the content of the first section", title="Item 1"
            ),
            dbc.AccordionItem(
                "This is the content of the second section", title="Item 2"
            ),
            dbc.AccordionItem(
                "This is the content of the third section", title="Item 3"
            ),
        ],
        start_collapsed=True,
    ),
)

rendering this:

I hev two ajdustments I want to make:

Set the title (eg. Item 1) to  H1, or something else.

When accordion is activated (open) the default color of the tab is light blue (see screenshot). I want to change this color. How?

I have tried different variations of css styling, like what is suggested here, but with no luck.

Body:
To adjust the Item styling, you need to change the styling for .accordion-button. To adjust the styling when opening an accordion item, you need to change the styling for .accordion-button:not(.collapsed).

Here is an example of making the "Item" text larger, and changing the color of the item on opening to red:

.accordion-button {
    font-size: xx-large;
}

.accordion-button:not(.collapsed) {
    background-color: red;
}