text:
Q: Why do we need to mention the loss function in Keras load_model function? I created a Keras model using a custom loss function and saved it. When I reload the trained model using Keras load_model() function to make the prediction, I had to pass the custom loss function to custom_objects argument:
new_model=load_model('yolo_1.model',custom_objects={'custom_loss':custom_loss})

My question is, why we have to mention the custom loss function in load_model()? I think loss function is not needed in prediction process.

A: That's because the include_optimizer argument of save method is by default set to True. Therefore, the optimizer as well as the loss function will be saved and as a result they will be loaded when you use load_model function.
However, if you only want to use your model for prediction then you would not need to save the optimizer and therefore set the include_optimizer to False when saving the model:
model.save('my_model.h5', include_optimizer=False)

This way the optimizer and the loss function used will not be saved and therefore you would not need to specify the custom loss function you have used when loading the model.


text:
Q: What is a better solution for a changed zigzag printing? Consider the following transformation on a string.  Given as an input a number of rows and a string, write that string in a zigzag back and forth across the rows.  For example, given input

Please convert me to a customized zigzag printing format

with three rows, we would write the string in a zigzag like this:
P   s   n   t   o   s   i   z   a   i   n   r
 l a e o v r m t a u t m z d i z g r n i g o m t
 e   c   e   e   c   o   e   g   p   t   f   a

(please dont edit this print out, this is required output, it is not a real zigzag, it is
a customized zigzag)
Finally, we concatenate the contests of each row together to get the resulting string
Psntosizainrlaeovrmtautmzdizgrnigomteceecoegptfa

I have a sketch of an algorithm for this problem that I've written out in pseudocode here:
it is asking about the relationship between {index} and {output row and  col}
Def:
  down = false;
  up = false;
  r=0;
  c=0;
  char[][] output;
there are three cases here:
case 1:
  index % 4 == 0, it is the beginning of a down printing
  r = 0;
  output[r][c] = in.charAt(index);
  c++;
  down = true; up = false;

case 2:
  index%4 != 0 && down = true;
  r = index % 4;
  output[r][c] = in.charAt(index);
  if( r == 2){ up = true; down = false; c++;}  // when come to the last row of a down formatting

case 3:
  index%4 != 0 && up == true;
  r = 4- index%4;
  output[r][c] = in.charAt(index);
  c++;

For a general solution, i can replace 4 as nRows+1;
While I think this works, I'm not too happy with it.  Does anyone have a clearer or faster algorithm for solving this problem?

A: One observation that might make this problem much easier to solve is this following: Suppose that you have a row count of 3 and want to keep zigzagging across the rows distributing the characters.  Then if you cycle over four characters, you would add them to rows 1, 2, 3, and 2 before repeating this pattern.  With a row count of five you'd visit rows 1, 2, 3, 4, 5, 4, 3, and 2 before repeating this pattern.  More generally, if you have a row count of k, then the set of rows to distribute the characters into follows the pattern 1, 2, 3, ..., k, k - 1, k - 2, ..., 2, which has length 2k - 2.
Given this observation, you might make the code much cleaner by precomputing a table containing this cycle along with the length of that cycle.  Once you have this table, you can then cycle across the characters, keep track of which character you are on.  When you're on the nth character, you would index into the table at position n mod k, then distribute the character into that row.
In pseudocode (using one-based indices):
rowTable = new array of ints length 2k - 2
for i = 1 up to k:
    rowTable[i] = i
for i = 2 up to k - 1:
    rowTable[(2k - 1) - (i - 2)] = i

resultRows = new array of strings of length k

for i = 1 up to the length of your string:
    Append the current character to resultRows[rowTable[i mod k]]

Concatenate all the entries of resultRows

This approach doesn't require you to hard-code in all of the different cases into a switch statement, which means that it can handle arbitrary k instead of just k = 3.  Moreover, it's very fast; the runtime is O(n + k), where n is the length of the string and k is the number of rows.
Hope this helps!

A: What do you think of this one. Original string is s
-copy chars from 0 to rows-1 in a string say str
str[rows]=some impossible to occur in d original string character , like -1

-copy reverse chars from s[r] to s[2r-3] into str
str[2r-2]=some impossible to occur in d original string character, -1

repeat until length is covered for these two steps, one by one.
In string str, take up every character at rows location, i.e. str[0],str[rows],str[2rows]... skipping over where str[rows] is -1.
Repeat this step until length of str.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Which CRC is used to change key in Desfire Card Which type of CRC is used to change key in Desfire Card?
Should the order of CRC bytes to reversed or not.
I cannot able to change the key of PICC applicaton.
Can anyone help please.

A: CRC16/32 and MAC/CMAC selection will depend on the Desfire card, CRC16 and MAC are for MF3ICD40 (backward compatibility). CRC16 is used if your DES key is 16 byte long but the first half and second half are the same. You can dig some info of whether resultant CRC should be reversed or not from this link.


text:
Q: Use matplotlib plot and PYsimpleGUI in pycharm I'm trying to add a plot to my GUI window.
the plot code is :
df.groupby(['zigzag', 'speed']).size().unstack().plot.bar()

and this is my GUI so far:
layout = [[sg.Text('Welcome', font='Thoma', size=(14, 1), justification='center')],
          [sg.Text('Please Upload Database:')],
          [sg.Text('File:', size=(8, 1)), sg.Input(key='file_input'), sg.FileBrowse(key="-IN-")],
          [sg.Submit(), sg.Cancel()]]

window = sg.Window('Welcome', layout)

while True:
    event, vals = window.read()
    if event in (sg.WINDOW_CLOSED, "Cancel"):
        break
    elif event == "Submit":
        file = vals["-IN-"]
        if file is not None:
            try:
                df = pd.read_csv(file)
                print(df)
                columns_list, unique_columns = column_list(df)
                window.close()
                layout2 = [
                    [sg.Text('Welcome', font='Thoma', size=(14, 1), justification='center')],
                    [sg.Text(' ')],
                    [sg.Button('OK'), sg.Cancel()]
                ]
                window2 = sg.Window('Choose', layout2, size=(500, 300), grab_anywhere=True)

                while True:
                    e, vals = window2.read()
                    if e == sg.WIN_CLOSED or e == 'Cancel':  # if user closes window or clicks cancel
                        break

                    elif e == 'OK':
                        df.groupby(['zigzag', 'speed']).size().unstack().plot()
                        window2.close()

the plot is supposed to be at the second window.
how can I show a plot on the GUI window?


text:
Q: How to make HTTP DELETE method using urllib2? Does urllib2 support DELETE or PUT method? If yes provide with any example please. I need to use piston API.

A: you can do it with httplib:
import httplib
conn = httplib.HTTPConnection('www.foo.com')
conn.request('PUT', '/myurl', body)
resp = conn.getresponse()
content = resp.read()

also, check out this question.  the accepted answer shows a way to add other methods to urllib2:
import urllib2
opener = urllib2.build_opener(urllib2.HTTPHandler)
request = urllib2.Request('http://example.org', data='your_put_data')
request.add_header('Content-Type', 'your/contenttype')
request.get_method = lambda: 'PUT'
url = opener.open(request)

A: You can subclass the urllib2.Request object and override the method when you instantiate the class.
import urllib2

class RequestWithMethod(urllib2.Request):
  def __init__(self, method, *args, **kwargs):
    self._method = method
    urllib2.Request.__init__(*args, **kwargs)

  def get_method(self):
    return self._method

Courtesy of Benjamin Smedberg

A: Correction for Raj's answer:
import urllib2
class RequestWithMethod(urllib2.Request):
  def __init__(self, *args, **kwargs):
    self._method = kwargs.pop('method', None)
    urllib2.Request.__init__(self, *args, **kwargs)

  def get_method(self):
    return self._method if self._method else super(RequestWithMethod, self).get_method()

A: Found following code from https://gist.github.com/kehr/0c282b14bfa35155deff34d3d27f8307 and it worked for me (Python 2.7.5):
import urllib2

request = urllib2.Request(uri, data=data)
request.get_method = lambda: 'DELETE'
response = urllib2.urlopen(request)

A: You can define a subclass of the Request object, and call it as follows:
import urllib2

class RequestWithMethod(urllib2.Request):
    def __init__(self, *args, **kwargs):
        self._method = kwargs.pop('method', None)
        urllib2.Request.__init__(self, *args, **kwargs)

    def get_method(self):
        return self._method if self._method else super(RequestWithMethod, self).get_method()

def put_request(url, data):
    opener = urllib2.build_opener(urllib2.HTTPHandler)
    request = RequestWithMethod(url, method='PUT', data=data)
    return opener.open(request)

def delete_request(url):
    opener = urllib2.build_opener(urllib2.HTTPHandler)
    request = RequestWithMethod(url, method='DELETE')
    return opener.open(request)

(This is similar to the above answers, but shows usage.)


text:
Q: Modify indexed object in numpy I want to update an np.array based on some indices.
a = np.array([[1,2,3],[4,5,6],[7,8,9]])
b = np.array([1,2])
a[b, :][:, b] += 1

Afterwards, a is unchanged, since just a copy got modified.
How can I modify the original object?

A: Create an open mesh grid with numpy.ix_ and use it for the index. Using ix_ takes advantage of broadcasting, it saves space because it doesn't need to create the full complement of indices.
>>> import numpy as np
>>> np.ix_(b,b)
(array([[1],
       [2]]), array([[1, 2]]))
>>>
>>> a[np.ix_(b,b)] += 10
>>> a
array([[ 0,  1,  2],
       [ 3, 14, 15],
       [ 6, 17, 18]])
>>>

Using ix_ is preferable for this use case but numpy.meshgrid could also be used.  It has the disadvantage of creating a larger set of indices.
>>> np.meshgrid(b,b)
[array([[1, 2],
       [1, 2]]), array([[1, 1],
       [2, 2]])]

>>> a[np.meshgrid(b,b)] *= -1
>>> a
array([[  0,   1,   2],
       [  3, -14, -15],
       [  6, -17, -18]])
>>>

Numpy's meshgrid is more typically used as descibed in What is purpose of meshgrid in Python? and Meshgrids and disambiguating rows and columns from Cartesian coordinates

A: First select rows using array b and restrict the columns from position 1 to extract the square on the lower right corner.
>>> a
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])

# select the square on the lower right corner and increment it
>>> a[b, 1:] += 1
>>> a
array([[ 1,  2,  3],
       [ 4,  6,  7],
       [ 7,  9, 10]])

Alternatively, you can also use this:
>>> a[b, b[0]:] += 1
>>> a
array([[ 1,  2,  3],
       [ 4,  6,  7],
       [ 7,  9, 10]])

A: You need to do the indexing in one step. For what you're trying to do, this will work:
a[b[:, np.newaxis], b] += 1
print(a)
# array([[ 1,  2,  3],
#        [ 4,  6,  7],
#        [ 7,  9, 10]])

When you index an array with multiple lists of indices, those lists are broadcast together to index into the array. So if you have a 2x1 index and a 1x2 index, the resulting array slice is 2x2, and in this case references the 2x2 section of the array you were hoping to modify.


text:
Q: connected components of open sets are open I would like to prove that the connected components of an open set are open.
Take $U$ an open set in a space $X$ and $U=\cup_\alpha C_\alpha$ where the $C_\alpha$ are the connected components.
Suppose that there exists a $C_\alpha$ which is closed. Then ${C_\alpha}^c$ is open and ${C_\alpha}^c\cap U$ is open. However $$U= U\cap X = U\cap(C_\alpha\cup{C_\alpha}^c) = C_\alpha\cup ({C_\alpha}^c\cap U)$$
which is neither open nor closed. So we have a contradiction.
Is this proof correct?

A: A space $X$ is locally connected iff a component of an open set is open. See here e.g.
So this proof is not correct. Consider the rationals $\mathbb{Q}$, then all components are singletons which are never open in $\mathbb{Q}$ (nor in any of its open sets).
Logical fallacies: "not open" does not imply "closed" (sets aren't doors). Components are always closed, so the complement of a component is a union of closed sets, namely all other components,but unions of closed sets need not be closed, only finite unions are. So the complement need not be closed, etc.

A: Connected components are open if X is locally connected.
Q is not locally connected, I = { x in Q : 0 < x < 1 } is
open subset and its connected components are the singletons
which are closed and not open.


text:
Q: WebSecurity in ASP .NET User Profile is not creating I am working with WebSecurity in my asp.net website and I write a code in _AppStart.cshtml is
@{
    WebSecurity.InitializeDatabaseConnection("Membership","UserProfile", "UserId", "UserName", true);
}

and I am creating my account through the following code
 if(!WebSecurity.UserExists(username))
            {
                WebSecurity.CreateUserAndAccount(username,password);

            }

But the User Profile is not creating. Plz help me.

A: Shouldn't you be using this override?  Because the third parameter takes a list of property values, which would be stored in the user profile feature.


text:
Q: How to pass Json data from one dart file to another? I am trying to pass JSON data from Scryfall from my results.dart to display on my wishlist.dart after clicking the shopping bag button. I have no clue how to go about it. I mainly just want to display the name of the card, and the price. If i could get some help in the next hour, that'd be great! Here is the code:
RESULTS.DART:
import 'dart:async';
import 'package:demo_1/model/constant.dart';
import 'package:demo_1/viewscreen/wishlist_screen.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:demo_1/model/scryfall_1.dart';
import 'package:demo_1/model/tokens.dart';
import 'package:flutter/material.dart';

class GetProjectScreen extends StatefulWidget {
  static const routeName = '/GetProjectScreen';
  const GetProjectScreen({required this.user, Key? key}) : super(key: key);
  final User user;

  @override
  State<StatefulWidget> createState() {
    return _GetProjectState();
  }
}
class _GetProjectState extends State<GetProjectScreen> {
  late _Controller con;
  @override
  void initState() {
    super.initState();
    con = _Controller(this);
  }
  void render(fn) => setState(fn);
  bool checked1 = true;
  @override
  Widget build(BuildContext context) {
    final searchCard = ModalRoute.of(context)!.settings.arguments as Future<Scryfall>;
    return MaterialApp(
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          leading: BackButton(
            color: Colors.white,
            onPressed: () {
              curToken = '';
              Navigator.of(context).pop();
            },
          ),
          title: const Text('Showing Results For...'),
        ),
        // body: Center(child: buildFutureBuilder(searchCard)),
        body: Center(
          child: FutureBuilder<Scryfall>(
            future: searchCard,
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                List<String> prices = [
                  '\$' + snapshot.data!.prices.usd.toString(),
                ];
                prices.removeWhere((item) => item.contains('null'));
                for (int index = 0; index < prices.length; index++) {
                  if (prices[index].contains('\$') && !checked1) {
                    prices.removeAt(index);
                  }
                }
                return ListView(
                  padding: const EdgeInsets.all(8),
                  children: <Widget>[
                    Container(
                      width: 1000,
                      height: 500,
                      color: Colors.white,
                      child: Center(
                        child: Image(
                          image: NetworkImage(snapshot.data!.imageUris.borderCrop!),
                        ),
                      ),
                    ),
                    ListView.builder(
                      scrollDirection: Axis.vertical,
                      shrinkWrap: true,
                      itemCount: prices.length,
                      itemBuilder: (BuildContext context, int index) {
                        return ListTile(
                          tileColor: Colors.white,
                          title: Text(prices[index]),
                          onTap: () {
                            launchURL(
                              (prices[index].contains('\$')
                                  ? snapshot.data!.purchaseUris.tcgplayer
                                  : (prices[index].contains('\€')
                                      ? snapshot.data!.purchaseUris.cardmarket
                                      : snapshot.data!.purchaseUris.cardhoarder)),
                            );
                          },
                          trailing: Wrap(spacing: 10, children: <Widget>[
                            new IconButton(
                              icon: Icon(Icons.shopping_bag_sharp),
                              onPressed: () {
                                con.goToWishlist();
                              },
                            ),
                          ]),
                        );
                      },
                    ),
                  ],
                );
                //return cardFutureBuilder();
              } else if (snapshot.hasError) {
                return const Text('Either card does not exist or search is too vague');
              }
              return const CircularProgressIndicator();
            },
          ),
        ),
        endDrawer: Drawer(
          child: ListView(
            padding: EdgeInsets.zero,
            children: <Widget>[
              const DrawerHeader(
                decoration: BoxDecoration(
                  color: Colors.blue,
                ),
                child: Text('Drawer Header'),
              ),
              CheckboxListTile(
                title: const Text("USD"),
                value: checked1,
                onChanged: (bool? value) {
                  setState(
                    () {
                      checked1 = value!;
                    },
                  );
                },
              ),
              ),
            ],
          ),
        ),
      ),
    );
  }
  void launchURL(String url) async {
    if (!await launch(url)) throw 'Could not launch $url';
  }
}
class _Controller {
  _GetProjectState state;
  _Controller(this.state) {
    user = state.widget.user;
  }
  late User _user;
  User get user => _user;
  set user(User user) {
    _user = user;
  }
  void goToWishlist() async {
    await Navigator.pushNamed(
      state.context,
      WishlistScreen.routeName,
      arguments: {
        ArgKey.user: user,
      },
    );
    state.render(() {});
  }
}

WISHLIST.DART
import 'package:demo_1/model/constant.dart';
import 'package:demo_1/model/scryfall_1.dart';
import 'package:demo_1/viewscreen/confirmation_screen.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'results.dart';
import 'home_screen.dart';
class WishlistScreen extends StatefulWidget {
  static const routeName = '/WishlistScreen';
  const WishlistScreen({required this.user, Key? key}) : super(key: key);
  final User user;
  @override
  State<StatefulWidget> createState() {
    return _WishlistState();
  }
}
class _WishlistState extends State<WishlistScreen> {
  late _Controller con;
  late String profilePicture;
  Future<Scryfall>? searchCard;
  final TextEditingController _controller = TextEditingController();
  @override
  void initState() {
    super.initState();
    con = _Controller(this);
    profilePicture = widget.user.photoURL ?? 'No profile picture';
  }
  void render(fn) => setState(fn);
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        floatingActionButton: FloatingActionButton(
          backgroundColor: Colors.cyan[400],
          onPressed: () => con.searchDialog(),
          child: const Icon(Icons.search),
        ),
        appBar: AppBar(
          title: const Text('Wish List'),
          centerTitle: true,
        ),
        body: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                const SizedBox(height: 18.0),
                const CartItem(),
                const CartItem(),
                const CartItem(),
                const SizedBox(height: 21.0),
                MaterialButton(
                  onPressed: () {
                    setState(
                      () {
                        /*Navigator.push(
                            context,
                            MaterialPageRoute(
                              builder: (context) => const ConfirmationScreen(),
                            ));*/
                        con.confirmationScreen();
                      },
                    );
                  },
                  color: Colors.cyan,
                  height: 30.0,
                  minWidth: double.infinity,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10.0),
                  ),
                  child: const Text(
                    "CHECKOUT",
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 14.0,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
                const SizedBox(height: 18.0),
              ],
            )));
  }
}

class CartItem extends StatelessWidget {
  const CartItem({
    Key? key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      color: const Color.fromARGB(255, 209, 206, 206),
      margin: const EdgeInsets.symmetric(vertical: 8.0),
      child: Row(
        children: <Widget>[
          Container(
              width: 80.0,
              height: 80.0,
              child: Center(
                  child: Container(
                      width: 60.0,
                      height: 60.0,
                      decoration: BoxDecoration(
                        image: const DecorationImage(
                          fit: BoxFit.scaleDown,
                          image: NetworkImage(
                            "https://c1.scryfall.com/file/scryfall-cards/large/front/b/e/be524227-8adc-4b01-808f-5ec4ab9dc09c.jpg?1568004322",
                          ),
                        ),
                        borderRadius: BorderRadius.circular(15.0),
                      )))),
          const SizedBox(width: 12.0),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Container(
                  width: 100.0,
                  child: const Text(
                    "Default Card Name",
                    style: TextStyle(
                      color: Colors.black,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
                const SizedBox(height: 8.0),
                Row(
                  children: <Widget>[
                    Container(
                      width: 20.0,
                      height: 20.0,
                      decoration: BoxDecoration(
                        color: const Color.fromARGB(255, 146, 143, 143),
                        borderRadius: BorderRadius.circular(4.0),
                      ),
                      child: const Icon(
                        Icons.add,
                        color: Colors.white,
                        size: 15.0,
                      ),
                    ),
                    const Padding(
                      padding: EdgeInsets.symmetric(horizontal: 8.0),
                      child: Text(
                        "1",
                        style: TextStyle(
                          color: Colors.black,
                          fontSize: 16.0,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                    Container(
                      width: 20.0,
                      height: 20.0,
                      decoration: BoxDecoration(
                        color: const Color.fromARGB(255, 37, 114, 177),
                        borderRadius: BorderRadius.circular(4.0),
                      ),
                      child: const Icon(
                        Icons.add,
                        color: Colors.white,
                        size: 15.0,
                      ),
                    ),
                    const Spacer(),
                    const Text(
                      "000.00",
                      style: TextStyle(
                        color: Colors.black,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

class _Controller {
  _WishlistState state;
  _Controller(this.state) {
    user = state.widget.user;
  }
  late User _user;
  User get user => _user;
  set user(User user) {
    _user = user;
  }
  void confirmationScreen() async {
    await Navigator.pushNamed(
      state.context,
      ConfirmationScreen.routeName,
      arguments: {
        ArgKey.user: user,
      },
    );
    state.render(() {});
  }
  Future? searchDialog() {
    return showDialog(
      context: state.context,
      builder: (BuildContext context) => AlertDialog(
        title: const Text('Search'),
        content: Container(
          height: 180,
          decoration: const BoxDecoration(
            borderRadius: BorderRadius.all(
              Radius.circular(10),
            ),
          ),
          padding: const EdgeInsets.all(10),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              const Text('Search for a card:'),
              TextField(
                controller: state._controller,
                decoration: const InputDecoration(hintText: 'Enter Title'),
              ),
              OutlinedButton(
                onPressed: () {
                  state.setState(
                    () {
                      state.searchCard =
                          scryfallGet(state._controller.text.replaceAll(' ', '+'));

                      Navigator.push(
                          context,
                          MaterialPageRoute(
                              builder: (context) =>
                                  GetProjectScreen(user: state.widget.user),
                              settings: RouteSettings(arguments: state.searchCard)));
                    },
                  );
                },
                child: const Text('Search'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

SCRYFALL_1.DART
/*
 * parsed with Nicol Bolas
 */

class Scryfall {
  Scryfall({
    required this.object,
    required this.id,
    required this.oracleId,
    required this.multiverseIds,
    required this.mtgoId,
    required this.mtgoFoilId,
    required this.tcgplayerId,
    required this.cardmarketId,
    required this.arenaId,
    required this.name,
    required this.lang,
    required this.releasedAt,
    required this.uri,
    required this.scryfallUri,
    required this.layout,
    required this.highresImage,
    required this.imageStatus,
    required this.imageUris,
    required this.manaCost,
    required this.cmc,
    required this.typeLine,
    required this.oracleText,
    required this.power,
    required this.toughness,
    required this.colors,
    required this.colorIdentity,
    required this.keywords,
    required this.producedMana,
    required this.legalities,
    required this.games,
    required this.reserved,
    required this.foil,
    required this.nonfoil,
    required this.finishes,
    required this.oversized,
    required this.promo,
    required this.reprint,
    required this.variation,
    required this.setId,
    required this.scryfallSet,
    required this.setName,
    required this.setType,
    required this.setUri,
    required this.setSearchUri,
    required this.scryfallSetUri,
    required this.rulingsUri,
    required this.printsSearchUri,
    required this.collectorNumber,
    required this.digital,
    required this.rarity,
    required this.watermark,
    required this.flavorText,
    required this.cardBackId,
    required this.artist,
    required this.artistIds,
    required this.illustrationId,
    required this.borderColor,
    required this.frame,
    required this.securityStamp,
    required this.fullArt,
    required this.textless,
    required this.booster,
    required this.storySpotlight,
    required this.edhrecRank,
    required this.prices,
    required this.relatedUris,
    required this.purchaseUris,
  });

  String object;
  String id;
  String? oracleId;
  List<num> multiverseIds;
  num? mtgoId;
  num? mtgoFoilId;
  num? tcgplayerId;
  num? cardmarketId;
  num? arenaId;
  String name;
  String lang;
  DateTime releasedAt;
  String uri;
  String scryfallUri;
  String? layout;
  bool highresImage;
  String imageStatus;
  ImageUris imageUris;
  String? manaCost;
  num? cmc;
  String? typeLine;
  String? oracleText;
  String? power;
  String? toughness;
  List<String> colors;
  List<String> colorIdentity;
  List<String> keywords;
  List<String> producedMana;
  Legalities legalities;
  List<String> games;
  bool reserved;
  bool foil;
  bool nonfoil;
  List<String> finishes;
  bool oversized;
  bool promo;
  bool reprint;
  bool variation;
  String setId;
  String? scryfallSet;
  String setName;
  String setType;
  String setUri;
  String setSearchUri;
  String scryfallSetUri;
  String rulingsUri;
  String printsSearchUri;
  String collectorNumber;
  bool digital;
  String rarity;
  String? watermark;
  String? flavorText;
  String cardBackId;
  String artist;
  List<String> artistIds;
  String? illustrationId;
  String borderColor;
  String frame;
  String? securityStamp;
  bool fullArt;
  bool textless;
  bool booster;
  bool storySpotlight;
  num? edhrecRank;
  Prices prices;
  RelatedUris relatedUris;
  PurchaseUris purchaseUris;

  factory Scryfall.fromJson(Map<String, dynamic> json) => Scryfall(
        object: json["object"],
        id: json["id"],
        oracleId: json["oracle_id"],
        multiverseIds: json["multiverse_ids"] != null
            ? List<int>.from(json["multiverse_ids"].map((x) => x))
            : [],
        arenaId: json["arena_id"],
        mtgoId: json["mtgo_id"],
        mtgoFoilId: json["mtgo_foil_id"],
        tcgplayerId: json["tcgplayer_id"],
        cardmarketId: json["cardmarket_id"],
        name: json["name"],
        lang: json["lang"],
        releasedAt: DateTime.parse(json["released_at"]),
        uri: json["uri"],
        scryfallUri: json["scryfall_uri"],
        layout: json["layout"],
        highresImage: json["highres_image"],
        imageStatus: json["image_status"],
        imageUris: ImageUris.fromJson(json["image_uris"]),
        manaCost: json["mana_cost"],
        cmc: json["cmc"],
        typeLine: json["type_line"],
        oracleText: json["oracle_text"],
        power: json["power"],
        toughness: json["toughness"],
        colors: json["colors"] != null
            ? List<String>.from(json["colors"].map((x) => x))
            : [],
        colorIdentity: List<String>.from(json["color_identity"].map((x) => x)),
        keywords: List<String>.from(json["keywords"].map((x) => x)),
        producedMana: json["produced_mana"] != null
            ? List<String>.from(json["produced_mana"].map((x) => x))
            : [],
        legalities: Legalities.fromJson(json["legalities"]),
        games: List<String>.from(json["games"].map((x) => x)),
        reserved: json["reserved"],
        foil: json["foil"],
        nonfoil: json["nonfoil"],
        finishes: List<String>.from(json["finishes"].map((x) => x)),
        oversized: json["oversized"],
        promo: json["promo"],
        reprint: json["reprint"],
        variation: json["variation"],
        setId: json["set_id"],
        scryfallSet: json["set"],
        setName: json["set_name"],
        setType: json["set_type"],
        setUri: json["set_uri"],
        setSearchUri: json["set_search_uri"],
        scryfallSetUri: json["scryfall_set_uri"],
        rulingsUri: json["rulings_uri"],
        printsSearchUri: json["prints_search_uri"],
        collectorNumber: json["collector_number"],
        digital: json["digital"],
        rarity: json["rarity"],
        watermark: json["watermark"],
        flavorText: json["flavor_text"],
        cardBackId: json["card_back_id"],
        artist: json["artist"],
        artistIds: List<String>.from(json["artist_ids"].map((x) => x)),
        illustrationId: json["illustration_id"],
        borderColor: json["border_color"],
        frame: json["frame"],
        securityStamp: json["security_stamp"],
        fullArt: json["full_art"],
        textless: json["textless"],
        booster: json["booster"],
        storySpotlight: json["story_spotlight"],
        edhrecRank: json["edhrec_rank"],
        prices: Prices.fromJson(json["prices"]),
        relatedUris: json["related_uris"] != null
            ? RelatedUris.fromJson(json["related_uris"])
            : RelatedUris(
                gatherer: "",
                tcgplayerInfiniteArticles: "",
                tcgplayerInfiniteDecks: "",
                edhrec: "",
                mtgtop8: ""),
        purchaseUris: json["purchase_uris"] != null
            ? PurchaseUris.fromJson(json["purchase_uris"])
            : PurchaseUris(tcgplayer: "", cardmarket: "", cardhoarder: ""),
      );

  Map<String, dynamic> toJson() => {
        "object": object,
        "id": id,
        "oracle_id": oracleId,
        "multiverse_ids": List<dynamic>.from(multiverseIds.map((x) => x)),
        "mtgo_id": mtgoId,
        "mtgo_foil_id": mtgoFoilId,
        "tcgplayer_id": tcgplayerId,
        "cardmarket_id": cardmarketId,
        "name": name,
        "lang": lang,
        "released_at":
            "${releasedAt.year.toString().padLeft(4, '0')}-${releasedAt.month.toString().padLeft(2, '0')}-${releasedAt.day.toString().padLeft(2, '0')}",
        "uri": uri,
        "scryfall_uri": scryfallUri,
        "layout": layout,
        "highres_image": highresImage,
        "image_status": imageStatus,
        "image_uris": imageUris.toJson(),
        "mana_cost": manaCost,
        "cmc": cmc,
        "type_line": typeLine,
        "oracle_text": oracleText,
        "power": power,
        "toughness": toughness,
        "colors": List<dynamic>.from(colors.map((x) => x)),
        "color_identity": List<dynamic>.from(colorIdentity.map((x) => x)),
        "keywords": List<dynamic>.from(keywords.map((x) => x)),
        "legalities": legalities.toJson(),
        "games": List<dynamic>.from(games.map((x) => x)),
        "reserved": reserved,
        "foil": foil,
        "nonfoil": nonfoil,
        "finishes": List<dynamic>.from(finishes.map((x) => x)),
        "oversized": oversized,
        "promo": promo,
        "reprint": reprint,
        "variation": variation,
        "set_id": setId,
        "set": scryfallSet,
        "set_name": setName,
        "set_type": setType,
        "set_uri": setUri,
        "set_search_uri": setSearchUri,
        "scryfall_set_uri": scryfallSetUri,
        "rulings_uri": rulingsUri,
        "prints_search_uri": printsSearchUri,
        "collector_number": collectorNumber,
        "digital": digital,
        "rarity": rarity,
        "watermark": watermark,
        "flavor_text": flavorText,
        "card_back_id": cardBackId,
        "artist": artist,
        "artist_ids": List<dynamic>.from(artistIds.map((x) => x)),
        "illustration_id": illustrationId,
        "border_color": borderColor,
        "frame": frame,
        "security_stamp": securityStamp,
        "full_art": fullArt,
        "textless": textless,
        "booster": booster,
        "story_spotlight": storySpotlight,
        "edhrec_rank": edhrecRank,
        "prices": prices.toJson(),
        "related_uris": relatedUris.toJson(),
        "purchase_uris": purchaseUris.toJson(),
      };
}

class ImageUris {
  ImageUris({
    required this.small,
    required this.normal,
    required this.large,
    required this.png,
    required this.artCrop,
    required this.borderCrop,
  });

  String? small;
  String? normal;
  String? large;
  String? png;
  String? artCrop;
  String? borderCrop;

  factory ImageUris.fromJson(Map<String, dynamic> json) => ImageUris(
        small: json["small"],
        normal: json["normal"],
        large: json["large"],
        png: json["png"],
        artCrop: json["art_crop"],
        borderCrop: json["border_crop"],
      );

  Map<String, dynamic> toJson() => {
        "small": small,
        "normal": normal,
        "large": large,
        "png": png,
        "art_crop": artCrop,
        "border_crop": borderCrop,
      };
}

class Legalities {
  Legalities({
    required this.standard,
    required this.future,
    required this.historic,
    required this.gladiator,
    required this.pioneer,
    required this.modern,
    required this.legacy,
    required this.pauper,
    required this.vintage,
    required this.penny,
    required this.commander,
    required this.brawl,
    required this.historicbrawl,
    required this.alchemy,
    required this.paupercommander,
    required this.duel,
    required this.oldschool,
    required this.premodern,
  });

  String? standard;
  String? future;
  String? historic;
  String? gladiator;
  String? pioneer;
  String? modern;
  String? legacy;
  String? pauper;
  String? vintage;
  String? penny;
  String? commander;
  String? brawl;
  String? historicbrawl;
  String? alchemy;
  String? paupercommander;
  String? duel;
  String? oldschool;
  String? premodern;

  factory Legalities.fromJson(Map<String, dynamic> json) => Legalities(
        standard: json["standard"],
        future: json["future"],
        historic: json["historic"],
        gladiator: json["gladiator"],
        pioneer: json["pioneer"],
        modern: json["modern"],
        legacy: json["legacy"],
        pauper: json["pauper"],
        vintage: json["vintage"],
        penny: json["penny"],
        commander: json["commander"],
        brawl: json["brawl"],
        historicbrawl: json["historicbrawl"],
        alchemy: json["alchemy"],
        paupercommander: json["paupercommander"],
        duel: json["duel"],
        oldschool: json["oldschool"],
        premodern: json["premodern"],
      );

  Map<String, dynamic> toJson() => {
        "standard": standard,
        "future": future,
        "historic": historic,
        "gladiator": gladiator,
        "pioneer": pioneer,
        "modern": modern,
        "legacy": legacy,
        "pauper": pauper,
        "vintage": vintage,
        "penny": penny,
        "commander": commander,
        "brawl": brawl,
        "historicbrawl": historicbrawl,
        "alchemy": alchemy,
        "paupercommander": paupercommander,
        "duel": duel,
        "oldschool": oldschool,
        "premodern": premodern,
      };
}

class Prices {
  Prices({
    required this.usd,
    required this.usdFoil,
    required this.usdEtched,
    required this.eur,
    required this.eurFoil,
    required this.tix,
  });

  String? usd;
  String? usdFoil;
  dynamic usdEtched;
  String? eur;
  String? eurFoil;
  String? tix;

  factory Prices.fromJson(Map<String, dynamic> json) => Prices(
        usd: json["usd"],
        usdFoil: json["usd_foil"],
        usdEtched: json["usd_etched"],
        eur: json["eur"],
        eurFoil: json["eur_foil"],
        tix: json["tix"],
      );

  Map<String, dynamic> toJson() => {
        "usd": usd,
        "usd_foil": usdFoil,
        "usd_etched": usdEtched,
        "eur": eur,
        "eur_foil": eurFoil,
        "tix": tix,
      };
}

class PurchaseUris {
  PurchaseUris({
    required this.tcgplayer,
    required this.cardmarket,
    required this.cardhoarder,
  });

  String tcgplayer;
  String cardmarket;
  String cardhoarder;

  factory PurchaseUris.fromJson(Map<String, dynamic> json) => PurchaseUris(
        tcgplayer: json["tcgplayer"],
        cardmarket: json["cardmarket"],
        cardhoarder: json["cardhoarder"],
      );

  Map<String, dynamic> toJson() => {
        "tcgplayer": tcgplayer,
        "cardmarket": cardmarket,
        "cardhoarder": cardhoarder,
      };
}
class RelatedUris {
  RelatedUris({
    required this.gatherer,
    required this.tcgplayerInfiniteArticles,
    required this.tcgplayerInfiniteDecks,
    required this.edhrec,
    required this.mtgtop8,
  });

  String gatherer;
  String tcgplayerInfiniteArticles;
  String tcgplayerInfiniteDecks;
  String edhrec;
  String mtgtop8;

  factory RelatedUris.fromJson(Map<String, dynamic> json) => RelatedUris(
        gatherer: json["gatherer"],
        tcgplayerInfiniteArticles: json["tcgplayer_infinite_articles"],
        tcgplayerInfiniteDecks: json["tcgplayer_infinite_decks"],
        edhrec: json["edhrec"],
        mtgtop8: json["mtgtop8"],
      );

  Map<String, dynamic> toJson() => {
        "gatherer": gatherer,
        "tcgplayer_infinite_articles": tcgplayerInfiniteArticles,
        "tcgplayer_infinite_decks": tcgplayerInfiniteDecks,
        "edhrec": edhrec,
        "mtgtop8": mtgtop8,
      };
}


text:
Q: Android notification every 15 minutes crashes if app is closed So i'm a complete newbie in Android Studio and I'm trying to make a simple app which does the following:
The app has a string array set on the /res/values folder called "frases".
The Main activity contains a button, when it's pressed, it increments a variable that represents the index of the array to be used (i've called it "iterador") and sets a textView to the value of frases[iterador].
Then on the onCreate method of the MainActivity, I have an alarnm with setRepeating that calls a class to receive a notification each 15 minutes. The purpose of this is to both have a textview in the MainActivity and a notification that can show the value of frases[iterador].
The problem here is whenever my app is closed (not stopped from the android settings menu, just closed) I get an error saying string array is null. And even worse, after the first notification, sometimes the second one won't appear even after 15 minutes if I don't open the app in my phone (even if it isn't closed).
I've tried to fix this by making both variables static so that I can access them from the notification class, but still doesn't work.
Is there a way to fix this and make the notificactions appear even whith the app closed?
My MainActivity vars and onCreate method:
public class MainActivity extends Activity implements View.OnClickListener {

//MY CODE
public static boolean primera; //APP OPENED FOR THE FIRST TIME

private Button b_corazon, b_carta;
private TextView t_frase;
public static final String PREFS_NAME = "MyPrefsFile";

//-------------------------STRING SHOW VARIABLES----------------------
public static String[] frases; //STRING ARRAY
public static int iterador; // INDEX FOR THE ARRAY
AlarmManager alarmManager; //ALARM MANAGER

@Override
protected void onCreate(Bundle savedInstanceState) {
    Resources res=getResources(); //GET THE RESOURCES
    frases=res.getStringArray(R.array.cartas); //ASIGN THE STRING ARRAY TO THE VARIABLE
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_main);
    //MI CODIGO

    Intent intent = new Intent(getApplicationContext(), RecibeNotif.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(),0,intent,0);
    alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

    Calendar firing = Calendar.getInstance();  //SCHEDULED TIME
    Calendar current = Calendar.getInstance(); //CURRENT TIME

    firing.set(Calendar.HOUR_OF_DAY,14);
    firing.set(Calendar.MINUTE,20);
    firing.set(Calendar.SECOND,0);

    long intendedTime=firing.getTimeInMillis(); //SCHEDULED TIME
    long currentTime=current.getTimeInMillis(); //CURRENT TIME

    if(intendedTime>=currentTime){ //IF IT ISN'T THE TIME YET
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, intendedTime,AlarmManager.INTERVAL_FIFTEEN_MINUTES,pendingIntent);
    }
    else{ //IF THE TIME HAS ALREADY PASSED
        firing.add(Calendar.MINUTE,15); //ADD 15 MINUTES FOR THE NEXT ALARM
        intendedTime=firing.getTimeInMillis();
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, intendedTime,AlarmManager.INTERVAL_FIFTEEN_MINUTES,pendingIntent);
    }

    //SAVE THE VALUE OF ITERADOR IN THE APPLICATION DATA
    SharedPreferences settings = getSharedPreferences(PREFS_NAME,0); //GUARDAR DATO DE ITERADOR
    primera=getSharedPreferences("PREFERENCE",MODE_PRIVATE).getBoolean("primera", true);
    iterador=settings.getInt("iterador",iterador);
    init();
}

My BroadcastReceiver notification class:
public class RecibeNotif extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        String[] frasesaux;
        int iteraux;

        iteraux=MainActivity.iterador;
        frasesaux=MainActivity.frases;
        if(iteraux==frasesaux.length){
            iteraux=0;
        }

        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        Intent redir = new Intent(context,direct.class);
        redir.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        PendingIntent pendingIntent = PendingIntent.getActivity(context, 100, redir, PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
                .setContentIntent(pendingIntent)
                .setSmallIcon(R.drawable.message)  //ICONO DE LA NOTIFICACION
                .setContentTitle(".////.")
                .setContentText(frasesaux[iteraux])
                .setAutoCancel(true);

        notificationManager.notify(100,builder.build());

    }
}

<-----------EDIT------------->
Okay, so it's fixed now, the notification works quite well. The only thing that still drives me crazy is how to update the value of iterador at the end of the notification class so it matches with iteraux.
So far, i've tried to edit the value of iterador using the SharedPreferences.editor but it doesn't seem to work.
Any ideas?
public void onReceive(Context context, Intent intent) {
    String[] finale;
    int iteraux;
    SharedPreferences settings = context.getSharedPreferences(PREFS_NAME,0); //GUARDAR DATO DE ITERADOR
    iteraux = settings.getInt("iterador",iterador);
    Resources res= context.getResources(); //GET THE RESOURCES
    finale=res.getStringArray(R.array.cartas); //ASIGN THE STRING ARRAY TO THE VARIABLE
    //iteraux=MainActivity.iterador;

    if(iteraux==finale.length){
        iteraux=0;
    }
    else{
        iteraux++;
    }

    //<-----------UPDATE ITERADOR VAR IN MAINACTIVITY
    SharedPreferences.Editor editor2 = settings.edit();
    editor2.putInt("iterador",iteraux);
    editor2.commit();

   // frasesaux=MainActivity.frases;

A: Your activity is not alive when you receive your notification so if you try to access the fields of Activity which is not alive , you get an exception
Solution
1.) use the context to get getStringArray(R.array.cartas)
2.) Use the same context to fetch data from SharedPreferences

public class RecibeNotif extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        String[] frasesaux;
        int iteraux;
        SharedPreferences settings = context.getSharedPreferences("MyPrefsFile",0);
        iteraux = settings.getInt("iterador",0);
        //                                   ^^ your default value

        //iteraux=MainActivity.iterador;
        frasesaux=context.getResources().getStringArray(R.array.cartas);
        // ^^ fetch the array
        if(iteraux==frasesaux.length){
            iteraux=0;
        }
        //...
   }
}

Note : static won't make any difference because your array will only be initialized when onCreate will get called by the android OS so since this is not the case so hence your static fields will stay un-initialized mean null and 0.


text:
Q: What Is Difference Between Json and Jsonp? I am trying to access cross origin site via script.
So I am getting an error, I have searched on internet that shows the solution is the JsonP.
Anyone Please help me to know what is jsonp  .
and what is the difference between json and jsonp.
Is JSONP cross browser compatible?
can i use jsonp in mobile applications or asp.net mvc?

A: JSONP is a simple way to overcome browser restrictions when sending JSON responses from different domains from the client.
But the practical implementation of the approach involves subtle differences that are often not explained clearly.
Here is a simple tutorial that shows JSON and JSONP side by side.
All the code is freely available at Github and a live version can be found at http://json-jsonp-tutorial.craic.com


text:
Q: batch script to copy lowercase file I have files being uploaded to a folder.  I need a batch script to redirect those files to separate folders based on filenames.  That's all fine except for two sets of files that have very similar names but only different by case.  Ie. log0000.txt and LOG0000.txt.
What I would like to do is search through the folder and check all files and if they have a lowercase "log", move them to one folder and if they have uppercase "LOG", move them to the other.
I know how to loop through the files in the folder, but I'm unsure how to match the comparision and match each file based on case.
Thanks.

A: Since you already know how to loop and move,
@echo off

for /f "usebackq delims=" %%f in (`dir /s /b log* ^| findstr "log"`) do (
    @rem code to copy all lower case files
)

for /f "usebackq delims=" %%f in (`dir /s /b log* ^| findstr "LOG"`) do (
    @rem code to copy all upper case files
)


text:
Q: ACRCloud song Recognize Hey all I have the following code from the ACRCloud c# demo:
static void Main(string[] args)
{
    var config = new Dictionary<string, object>();

    config.Add("host", "us-west-2.api.acrcloud.com");
    config.Add("access_key", "key here....");
    config.Add("access_secret", "secret here...");
    config.Add("timeout", 10); // seconds

    ACRCloudRecognizer re = new ACRCloudRecognizer(config);

    // It will skip 0 seconds from the beginning of test.mp3.
    string result = re.RecognizeByFile("C:\\temp\\acrcloud_sdk_csharp-master\\01Track01.mp3", 80);
    //string result2 = re.Recognize("C:\\temp\\acrcloud_sdk_csharp-master\\01Track01", 80);
    Console.WriteLine(result);

    using (FileStream fs = new FileStream(@"C:\temp\acrcloud_sdk_csharp-master\01Track01.mp3", FileMode.Open))
    {
        using (BinaryReader reader = new BinaryReader(fs))
        {
            byte[] datas = reader.ReadBytes((int)fs.Length);
            // It will skip 0 seconds from the beginning of datas.
            result = re.RecognizeByFileBuffer(datas, datas.Length, 80);
            Console.WriteLine(result);
        }
    }

    Console.ReadLine();
}

For both results I am getting the return of:
{"status":{
    "msg":"No result",
    "code":1001,
    "version":"1.0"
}}

Not sure what I am doing incorrect.... Any help would be great!

A: I checked the project you have created the problem is you attached your own bucket to this project but you didn't upload any files to this bucket, in other words: your database is empty, that's why you could not recognize anything. If you want to recognize music, please refer to this tutorial and attach "ACRCloud Music" bucket to your project then you should be able to recognize music.


text:
Q: Multi toggle switch using in Laravel is getting just first element
//IN PAGE

        @foreach ($permissionlist as $pl)

 @php if(true===$pl->roleisactive){ @endphp
 <input type="checkbox" name="onoffswitch" checked>
@php }else{ @endphp
  <input type="checkbox" name="onoffswitch">
 @php } @endphp

<input type="text" name="id" id="id" value="{{$pl->permissionid}}">
        @endforeach

//IN SCRİPT

I can write just first id element in script. But I want to get last or others data with script. How can i do that ?

A: Try this,
@foreach ($permissionlist as $pl)

 @php if(true===$pl->roleisactive){ @endphp
 <input type="checkbox" name="onoffswitch"  checked>
@php }else{ @endphp
  <input type="checkbox" name="onoffswitch">
 @php } @endphp

<input type="text" name="id" id="id-{{$pl->permissionid}}" data-switch="{{$pl->permissionid}}" value="{{$pl->permissionid}}">
        @endforeach

//IN SCRİPT


text:
Q: Override anti-forgery token errors on login page I have a site that receives a large amount of the following errors:

The provided anti-forgery token was meant for a different claims-based
user than the current user.
The anti-forgery cookie token and form field token do not match.

I would like to prevent the site from throwing an error if the anti-forgery token is meant for no user but contains a user on the login page, for example:

The provided anti-forgery token was meant for user "", but the current
user is "Garret".

I don't want this exception to apply to any other page other than the login page. So I don't want to add AntiForgeryConfig.SuppressIdentityHeuristicChecks = true; to the entire site. I also want to keep the site as secure as possible since it contains HIPAA data. What can I do to keep it as secure as possible but still try to prevent this error on the login page because it is making it difficult for users to use?
The site is hosted on load balancing servers but I don't think this is the issue. I think the error is mostly caused by using the browser's back button, having the login page opened for a while before logging in, already being logged in or pressing login more than once. Also some users access it through an application that may not be loading the page and just trying to post the login information.
So please let me know what the best option is to prevent this error on the login page while still being as secure as possible?

A: What I ended up doing, and it seems to be working while still providing the same security, is to manually check the antiforgery token after checking if the user is logged in.
    [HttpPost]
    [AllowAnonymous]
    //[ValidateAntiForgeryToken]
    [OutputCache(NoStore = true, Duration = 0, VaryByParam = "None")]
    public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
    {
        // Skip the login process if the user is already logged in
        if (User.Identity.IsAuthenticated)
        {
            return RedirectToAction("Index", "Home");
        }
        // Check the anti forgery token now
        System.Web.Helpers.AntiForgery.Validate();
        ...

A: There is an answer for concurrent login attempts originated from certain user:
How can I fix anti-forgery token was meant for user "", but the current user is "xxxx " error
If AntiForgeryToken exception comes when the user has too long time to fill in login page, simply redirect to that page and show a message explaining his/her session (i.e. security token) had expired.
[HttpPost]
[ValidateAntiForgeryToken]
[HandleError(View="Login", ExceptionType = typeof(HttpAntiForgeryException))]
public ActionResult Login(LoginModel model)
{
     // some login processing stuff
}

If the exception comes from user's clicking back button, provide JS function on client-side which prevent the back button action on login page only:
...

// or wrap it inside a function

...

For another case that certain user has already logged in, redirect to the index or somewhat page indicating their user name (with User.Identity.Name).
I hope this explanation useful.

A: Instead of checking User.Identity.IsAuthenticated I used a custom attribute to handle the exceptions and redirect the user to the home page if it is a HttpAntiForgeryToken
I believe this avoids any potential security concerns of using the other methods
public override void OnException(ExceptionContext filterContext)
    {
        var controllerName = (string)filterContext.RouteData.Values["controller"];
        var actionName = (string)filterContext.RouteData.Values["action"];
        var model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);
        if (filterContext.Exception is HttpAntiForgeryException)
        {
            filterContext.Result = new RedirectToRouteResult(
                new RouteValueDictionary
                {
                    { "action", "Index" },
                    { "controller", "Home" }
                });

            filterContext.ExceptionHandled = true;
        }
}

A: To answer @Michael_B's concern, how about you change this part of Garrett's solution:
    // Skip the login process if the user is already logged in
    if (User.Identity.IsAuthenticated)
    {
        return RedirectToAction("Index", "Home");
    }
    // Check the anti forgery token now
    System.Web.Helpers.AntiForgery.Validate();
    ...

to this:
    // if not authenticated, check anti forgery token now:
    if (!User.Identity.IsAuthenticated)
    {
        System.Web.Helpers.AntiForgery.Validate();
    }
    // run rest of login process normally

    ...


text:
Q: Interpretation of Theil's U2 Statistic - "Forecasting Methods and Applications" book I was reading "Forecasting Methods and Applications" book and came across Theil's U statistic formula. I am facing difficulty in understanding the interpretation of Theil's U statistic.
According to my understanding, when U = 0 the forecasts are perfect. That means if U>0 then forecasts are not perfect. As we keep increasing U, the forecasts will keep becoming more and more imperfect. When it reaches 1, it means Forecast is equivalent to Naive Method. Hence, a general pattern can be seen that as U increases forecast is wrong and at 1 forecast is same as naive and hence by extrapolating this we can say that if U>1 then the forecast is worse than naive method forecast, i.e. APE of the forecast is even bigger than naive method forecasts.
I am able to understand the above interpretation but when I dig deep into the formula, I am not able to understand the below lines from the book.

For simplicity, I am also attaching equation (2.18) -

I am not able to understand 2 things here -

*

*How do numerator and denominator represent the MAPE formulas for a general forecast and naive approach forecast? This is because MAPE of any forecast is represented by this formula: MAPE = Mean of (sum of (Forecast - Actual)/Actual). Hence, if we follow this formula of MAPE in the numerator, then Y(t) should be Y(t+1) i.e.
(F(t+1) - Y(t+1)) / (Y(t+1) (mentioned above). This is because if we are taking the forecast of (t+1) then every number in the formula should be of (t+1).
The same is for the denominator.

*Why are we taking t from 1 to n-1? Shouldn't it be t from 1 to n?
The reason I am asking this question is that I want to know the underlying premise or logic behind using this formula.

A: jbowman already gave some very useful pointers. To follow up on your question:

If you were to intuitively explain the numerator and denominator, how would you do it?

I would call them both "nonstandard mean squared percentage errors", each period's error being expressed as a percentage of the previous observation. The numerator does this for the focal forecast, the denominator for the naive random walk one-step ahead forecast. If the ratio is less than one, then the nonstandard mean squared percentage error of the focal forecast is lower than the one for the naive method.
As such, this version of Theil's U (see below for my choice of words) is a type of "scaled" or "relative" forecast accuracy measure. It is similar to the MASE, which scales the focal forecasts's MAE by the MAE achieved (in-sample) by the naive random walk one-step forecast. "Relative" measures of accuracy divide a focal forecast's error measure by the one achieved by a benchmark method, and values less than one indicate that the focal forecast is better than the benchmark one.
A few things to keep in mind:

*

*This is pertinent:

If you perform a Google search for Theil's U, you'll find an interesting assortment of different formulae, each purporting to be "Theil's U". According to Armstrong, the existence of multiple formulas "…has caused some confusion."

"This" Theil's U is a different thing than stuff I have seen elsewhere.

*Using the previous observation as the denominator in the percentage error is... strange.

*Theil's U only looks at one-step-ahead forecasts. That a method is worse than the naive method one step ahead does not necessarily mean it is worse multiple steps ahead. Compare Interpretation of mean absolute scaled error (MASE).

*The numerator and denominator are both means of (squared) percentage errors. As such, both are subject to What are the shortcomings of the Mean Absolute Percentage Error (MAPE)? Most importantly, the MAPE (and therefore also the numerator and denominator in "this" Theil's U) are minimized by biased forecasts, so a biased forecast will more easily achieve $U<1$ than an unbiased one. Be aware of this.


text:
Q: How to add URL links to the alerts? I'm trying to add a URL link to the string but for some reason I can't get it to display. Is there a way to add a anchor link to the alerts? I'm using antd to display the alerts.

class Settings extends PureComponent {
  state = {
    inValid:
      "This is a message because you haven't verified your email. If you haven't so, please click here to Verify Email`<a href=\"http://bing.com\">Bing</a>.`"
  };

  render() {
    const { inValid } = this.state;
    return (
      <AppLayout>
        <Container>
          <Row>
            <Alert
              message="Verify Email"
              description={inValid}
              type="warning"
              showIcon
            />

            <SettingsTabs />
          </Row>
        </Container>
      </AppLayout>
    );
  }
}

A: According to the documentation the description property accepts either a string or a ReactNode. Therefore you can try to define a ReactNode instead of a string that contains a Link component, e.g:
state = {
    inValid: (

This is a message because you haven't verified your email. If you haven't so, please click here to Verify Email <Link href="http://bing.com">Bing</Link>.

    )
};


text:
Q: inputFormatter should allow just decimal numbers and negative numbers I want to allow users to just adding numbers "12345" and decimal numbers like "21321.12312" and negative numbers like -23423.32432. Users shouldn't be able to add multiple "." like "12..32" and add "-" just in first of input like -324.34 not like 324-4323.
I used this regEx r'^(-?\d+\.\d+)(\s*,\s*-?\d+\.\d+)+$' but can't enter anything.
TextField code:
TextFormField(
          inputFormatters: [
            FilteringTextInputFormatter.allow(
                RegExp(r'^(-?\d+\.\d+)(\s*,\s*-?\d+\.\d+)+$')),
          ],
          controller: budget,
          keyboardType: TextInputType.number,
          decoration: InputDecoration(
            contentPadding:
                EdgeInsets.only(right: 20, left: 20, top: 10, bottom: 10),
            hintText: getTranslated(context, "budget_example"),
            hintStyle: TextStyle(fontSize: 13, fontFamily: "tahoma"),
            border: OutlineInputBorder(
              borderSide: BorderSide(width: 1, color: MyColors.secondary),
              borderRadius: BorderRadius.circular(100),
            ),
          ),
        ),

A: Allow only 1 .
Allow negative
Place negative sign on beginning
We should create our own input formatter
import 'package:flutter/services.dart';

class NumberTextInputFormatter extends TextInputFormatter {
  NumberTextInputFormatter({this.decimalRange}) : assert(decimalRange == null || decimalRange > 0);

  final int decimalRange;

  @override
  TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
    TextEditingValue _newValue = this.sanitize(newValue);
    String text = _newValue.text;

    if (decimalRange == null) {
      return _newValue;
    }

    if (text == '.') {
      return TextEditingValue(
        text: '0.',
        selection: _newValue.selection.copyWith(baseOffset: 2, extentOffset: 2),
        composing: TextRange.empty,
      );
    }

    return this.isValid(text) ? _newValue : oldValue;
  }

  bool isValid(String text) {
    int dots = '.'.allMatches(text).length;

    if (dots == 0) {
      return true;
    }

    if (dots > 1) {
      return false;
    }

    return text.substring(text.indexOf('.') + 1).length <= decimalRange;
  }

  TextEditingValue sanitize(TextEditingValue value) {
    if (false == value.text.contains('-')) {
      return value;
    }

    String text = '-' + value.text.replaceAll('-', '');

    return TextEditingValue(text: text, selection: value.selection, composing: TextRange.empty);
  }
}

and (don't forget to import the previous class)
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class NumberFormField extends StatelessWidget {
  final InputDecoration decoration;
  final TextEditingController controller;
  final int decimalRange;

  const NumberFormField({Key key, this.decoration, this.controller, this.decimalRange}) :super(key: key);

  @override
  Widget build(BuildContext context) {
    return TextFormField(
      decoration: this.decoration,
      controller: this.controller,
      keyboardType: TextInputType.numberWithOptions(decimal: true),
      inputFormatters: [
        WhitelistingTextInputFormatter(RegExp(r'[\d+\-\.]')),
        NumberTextInputFormatter(decimalRange: this.decimalRange),
      ],
    );
  }
}