text:
Q: How to replace providers in flutter with firestore for search functionality? I had implemented a simple search functionality using the list in my provider and it worked. Now I have transferred my list over to firebase firestore and I don't know how to make the search functionality work on the list in the firebase instead of the list in my provider. :") I can display the list from the firebase. I am now trying to filter the list. Any help or guidance will be greatly appreciate :") I am new to this.
This is how my page currently looks like, I am able to display the list from the firebase.
Screen Image Recipe in firestore
healthy_food_screen.dart
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:my_plate/models/calories.dart';
import 'package:my_plate/models/recipes.dart';
import 'package:my_plate/services/auth_service.dart';

class FirestoreService {
  AuthService authService = AuthService();
  addCalories(mealType, mealName, numCalories, weight, consumptionDate) {
    return FirebaseFirestore.instance.collection('calories').add({
      'email': authService.getCurrentUser()!.email,
      'mealType': mealType,
      'mealName': mealName,
      'numCalories': numCalories,
      'weight': weight,
      'consumptionDate': consumptionDate
    });
  }

  removeCalories(id) {
    return FirebaseFirestore.instance.collection('calories').doc(id).delete();
  }

  Stream<List<Calories>> getCalories() {
    return FirebaseFirestore.instance
        .collection('calories')
        .where('email', isEqualTo: authService.getCurrentUser()!.email)
        .snapshots()
        .map((snapshot) => snapshot.docs
            .map<Calories>((doc) => Calories.fromMap(doc.data(), doc.id))
            .toList());
  }

  Stream<List<Recipe>> getRecipes() {
    return FirebaseFirestore.instance
        .collection('recipes')
        // .where('email', isEqualTo: authService.getCurrentUser()!.email)
        .snapshots()
        .map((snapshot) => snapshot.docs
            .map<Recipe>((doc) => Recipe.fromMap(doc.data(), doc.id))
            .toList());
  }
//   editExpense(id, purpose, mode, cost, travelDate) {
//     return FirebaseFirestore.instance
//         .collection('expenses')
//         .doc(id)
//         .set({'purpose': purpose, 'mode': mode, 'cost': cost, 'travelDate':
//     travelDate});
//   }
}

all_recipes.dart (provider)
import 'package:flutter/material.dart';
import 'package:my_plate/models/recipes.dart';

class AllRecipes with ChangeNotifier {
  List<Recipe> myRecipe = [
    Recipe(
        title: 'Meatballs with noodles',
        ingredients:
            '400g lean beef steak mince, 2 tsp dried oregano, 1 large egg, 8 garlic cloves, 1 finely grated, the other sliced, 1-2 tbsp olive oil, 1 fennel bulb, finely chopped, fronds reserved, 2 carrots, finely chopped, 500g carton passata, 4 tbsp balsamic vinegar, 600ml reduced-salt vegetable bouillon, For the courgette noodles, 1 tsp rapeseed oil, 1-2 large courgettes , cut into noodles with a julienne peeler or spiralizer, 50g frozen soya beans , thawed.',
        recipe:
            'Put the mince, oregano, egg and grated garlic in a bowl and grind in some black pepper. Mix together thoroughly and roll into 16 balls. Heat the oil in a large sauté pan over a medium-high heat, add the meatballs and fry, moving them around the pan so that they brown all over – be careful as they're quite delicate and you don't want them to break up. Once brown, remove them from the pan. Reduce the heat slightly and add the fennel, carrots and sliced garlic to the pan and fry, stirring until they soften, about 5 mins. Tip in the passata, balsamic vinegar and bouillon, stir well, then return the meatballs to the pan, cover and cook gently for 20-25 mins. Meanwhile, heat the 1 tsp of oil in a non-stick pan and stir-fry the courgette with the beans to heat through and soften. Serve with the meatballs and scatter with any fennel fronds.',
        calories: 380,
        imageUrl:
            'https://images.immediate.co.uk/production/volatile/sites/30/2020/08/meatballs-with-fennel-balsamic-beans-courgette-noodles-6bc9a37.jpg?quality=90&webp=true&resize=300,272?raw=true',
        fav: 0,
        id: ''),
    Recipe(
        title: 'Greek salad salsa',
        ingredients:
            '400g can butter beans , drained, 1 lemon , ½ juiced, ½ cut into 4 wedges, 2 tbsp ricotta or bio yogurt, 85g feta , crumbled, 1 garlic clove, 12 oatcakes, For the salsa, 4 tomatoes , chopped, 1 medium cucumber , finely diced, 1 small red onion , finely chopped, 12 pitted Kalamata olives , chopped, a few chopped mint leaves (optional).',
        recipe:
            'Tip the beans, lemon juice, ricotta, 50g feta and the garlic into a bowl and blitz with a hand blender or in a food processor to make a paste. Stir in the remaining feta and spoon the mixture into four small pots. To make the salsa, stir all the ingredients together with the mint (if using) and divide into four more pots, topping with a lemon wedge. These will keep, chilled in an airtight container, for two-three days. To eat, spread the oatcakes with the bean mixture, squeeze the lemon wedges over the salads and pile generously onto the oatcakes.',
        calories: 382,
        imageUrl:
            'https://images.immediate.co.uk/production/volatile/sites/30/2020/08/bean-feta-spread-with-greesk-salad-salsa-oatcakes-d329436.jpg?quality=90&webp=true&resize=300,272?raw=true',
        fav: 0,
        id: ''),
    Recipe(
        title: 'Mexican bean soup',
        ingredients:
            '2 tsp rapeseed oil, 1 large onion, finely chopped,  1 red pepper, cut into chunks, 2 garlic cloves, chopped, 2 tsp mild chilli powder, 1 tsp ground coriander, 1 tsp ground cumin, 400g can chopped tomatoes, 400g can black beans, 1 tsp vegetable bouillon powder, 1 small avocado, handful chopped coriander, 1 lime, juiced, ½ red chilli, deseeded and finely chopped (optional).',
        recipe:
            'Heat the oil in a medium pan, add the onion (reserving 1 tbsp to make the guacamole later) and pepper and fry, stirring frequently, for 10 mins. Stir in the garlic and spices, then tip in the tomatoes and beans with their liquid, half a can of water and the bouillon powder. Simmer, covered, for 15 mins. Meanwhile, peel and de-stone the avocado and tip into a bowl, add the remaining onion, coriander and lime juice with a little chilli (if using) and mash well. Ladle the soup into two bowls, top with the guacamole and serve.',
        calories: 391,
        imageUrl:
            'https://images.immediate.co.uk/production/volatile/sites/30/2020/08/wdp-lunch-mexicanguacamolesoup_02051-d1c462c.jpg?quality=90&webp=true&resize=300,272?raw=true',
        fav: 0,
        id: ''),
    Recipe(
      title: 'Poached eggs',
      ingredients:
          '2 tomatoes, halved, ½ tsp rapeseed oil, 2 eggs, 1 small ripe avocado, 2 slices seeded wholemeal soda bread (see goes well with), 2 handfuls rocket.',
      recipe:
          'Heat a non-stick frying pan, very lightly brush the cut surface of the tomatoes with a little oil, then cook them, cut-side down, in the pan until they have softened and slightly caramelised. Meanwhile, heat a pan of water, carefully break in the eggs and leave to poach for 1-2 mins until the whites are firm but the yolks are still runny. Halve and stone the avocado, then scoop out the flesh and smash onto the bread. Add the eggs, grind over black pepper and add a handful of rocket to each portion. Serve the tomatoes on the side.',
      fav: 0,
      calories: 385,
      imageUrl:
          'https://images.immediate.co.uk/production/volatile/sites/30/2020/08/avocado-6b1cf76.jpg?quality=90&webp=true&resize=300,272',
      id: '',
    ),
    Recipe(
        title: 'Egg Niçoise salad',
        ingredients:
            'For the dressing, 2 tbsp rapeseed oil, juice 1 lemon, 1 tsp balsamic vinegar, 1 garlic clove , grated, ⅓ small pack basil , leaves chopped, 3 pitted black Kalamata olive , rinsed and chopped, For the salad, 2 eggs, 250g new potatoes , thickly sliced, 200g fine green beans, ½ red onion , very finely chopped, 14 cherry tomatoes , halved, 6 romaine lettuces leaves, torn into bite-sized pieces, 6 pitted black Kalamata olive , rinsed and halved.',
        recipe:
            'Mix the dressing ingredients together in a small bowl with 1 tbsp water. Meanwhile boil the potatoes for 7 mins, add the beans and boil 5 mins more or until both are just tender, then drain. Boil 2 eggs for 8 minutes then shell and halve.Toss the beans, potatoes and remaining salad ingredients, except the eggs, together in a large bowl with half the dressing. Arrange the eggs on top and drizzle over the remaining dressing. ',
        calories: 333,
        imageUrl:
            'https://images.immediate.co.uk/production/volatile/sites/30/2020/08/nicoise-egg-salad-8b5171c.jpg?quality=90&webp=true&resize=300,272?raw=true',
        fav: 0,
        id: ''),
    Recipe(
        title: 'Chicken casserole',
        ingredients:
            '1 leek, roughly chopped, 1 carrot, roughly chopped, 1 onion, roughly chopped, 350g new potatoes, roughly chopped, 6 skinless, boneless chicken thighs, chopped, 500ml chicken stock, 4 tbsp vegetable gravy granules.',
        recipe:
            'Put the veg and chicken in a slow cooker. Pour the stock over and around the chicken thighs, then mix in the gravy granules to thicken it up (the sauce will be quite thick – use less gravy if you prefer a runnier casserole). Switch the slow cooker to low and leave to cook for at least 4 hrs, or up to 8 hrs – try putting it on before you go to work, so that it's ready when you get home. Season well, then serve.',
        calories: 268,
        imageUrl:
            'https://images.immediate.co.uk/production/volatile/sites/30/2020/08/slow-cooker-chicken-casserole-1172edc.jpg?quality=90&webp=true&resize=300,272?raw=true',
        fav: 0,
        id: ''),
    Recipe(
        title: 'Wild salmon veggie bowl',
        ingredients:
            '2 carrots, 1large courgette, 2 cooked beetroot , diced, 2 tbsp balsamic vinegar, ⅓ small pack dill , chopped, plus some extra fronts (optional), 1small red onion , finely chopped, 280g poached or canned wild salmon, 2 tbsp capers in vinegar, rinsed.',
        recipe:
            'Shred the carrots and courgette into long spaghetti strips with a julienne peeler or spiralizer, and pile onto two plates. Stir the beetroot, balsamic vinegar, chopped dill and red onion together in a small bowl, then spoon on top of the veg. Flake over chunks of the salmon and scatter with the capers and extra dill, if you like.',
        calories: 395,
        fav: 0,
        imageUrl:
            'https://images.immediate.co.uk/production/volatile/sites/30/2020/08/wild-salmon-veggie-bowl-c5cc341.jpg?quality=90&webp=true&resize=300,272?raw=true',
        id: ''),
    Recipe(
      title: 'Banana overnight oats',
      ingredients:
          '2 bananas, peeled, 100g porridge oats, ¼ tsp ground cinnamon, plus a pinch to serve, 1 tbsp maple syrup, 300ml milk of your choice, plus a splash, 2 tbsp peanut or almond butter, plus extra to serve, 2 tbsp flaked or chopped almonds, 2-4 tbsp natural yogurt, to serve (optional).',
      recipe:
          'Mash 1 banana in a bowl with a fork until smooth. Stir in the oats, cinnamon, maple syrup, milk and peanut butter. Mix well, then cover and chill overnight. The next morning, stir the porridge, adding another splash of milk if the mixture is quite stiff. Divide between two bowls. Slice the remaining banana and scatter this over the porridge, drizzle with more nut butter and sprinkle over the almonds. Top with spoonfuls of yogurt, if using, and sprinkle with a pinch more cinnamon before serving.',
      calories: 557,
      imageUrl:
          'https://images.immediate.co.uk/production/volatile/sites/30/2022/01/Banana-Overnight-Oats-16f2208.jpg?quality=90&webp=true&resize=300,272?raw=true',
      fav: 0,
      id: '',
    ),
    Recipe(
        title: 'Miso & butternut soup',
        ingredients:
            '2 tsp rapeseed oil, 1 large onion, chopped, 400g butternut squash, skin-on, cut into chunks, 2 garlic cloves, chopped, 210g can butter beans, drained, 2 tsp vegetable bouillon, 80g shredded kale, finely chopped, 2 tsp sesame oil, 2 tsp toasted sesame seeds, 2 tsp finely grated ginger, 1 tbsp brown rice miso.',
        recipe:
            'Heat the oil in a large pan and fry the onion for 5 mins to soften. Add the squash and garlic, and stir for a minute. Add the beans and bouillon along with a litre of water, then cover and simmer for 20 mins until the squash is tender. Meanwhile, steam the kale for 10 mins, then toss together with the sesame oil, seeds and ginger. Add the miso to the soup, then blitz until smooth using a hand blender. Pour into bowls and top with the sesame kale mix to serve.',
        calories: 287,
        fav: 0,
        imageUrl:
            'https://images.immediate.co.uk/production/volatile/sites/30/2021/09/Miso-and-butternut-soup-efe9277.jpg?quality=90&webp=true&resize=300,272?raw=true',
        id: ''),
    Recipe(
        title: 'Pesto egg muffin bites',
        ingredients:
            'low-cal cooking spray, for the tin, 18 cherry tomatoes, quartered, 80g feta or goat's cheese, crumbled, 6 medium eggs, 30ml milk, 2 tbsp pesto (check the label if you're vegetarian).',
        recipe:
            'Heat the oven to 180C/160C fan/gas 4. Spray a 12-hole muffin tin with the oil spray. Evenly divide the tomatoes among the holes, and top each one with around 2 tsp of the feta or goat's cheese. Crack the eggs into a large bowl, then add the milk, pesto and seasoning and whisk to combine. Pour the mixture evenly into each hole. Bake for 20 mins or until the egg is set. Cool for 2-3 mins in the tin, then remove and leave to cool on a wire rack.',
        calories: 74,
        fav: 0,
        imageUrl:
            'https://images.immediate.co.uk/production/volatile/sites/30/2021/08/Pesto-egg-muffins-5d37964.jpg?quality=90&webp=true&resize=300,272?raw=true',
        id: '')
  ];

  void removeRecipe(i) {
    myRecipe.removeAt(i);
    notifyListeners();
    //remove from favorites list
  }

  List<Recipe> getMyRecipe() {
    return myRecipe;
  }
  // void addRecipe(i) {
  //   myRecipe.removeAt(i);
  //   notifyListeners();
  // }

  void addRecipe(i) {
    //add recipe to favorites

    if (myRecipe[i].fav > 0) {
      myRecipe[i].fav = 0;
    } else
      (myRecipe[i].fav++);
  }

  notifyListeners();
}

firestore_service.dart
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:my_plate/models/calories.dart';
import 'package:my_plate/models/recipes.dart';
import 'package:my_plate/services/auth_service.dart';

class FirestoreService {
  AuthService authService = AuthService();
  addCalories(mealType, mealName, numCalories, weight, consumptionDate) {
    return FirebaseFirestore.instance.collection('calories').add({
      'email': authService.getCurrentUser()!.email,
      'mealType': mealType,
      'mealName': mealName,
      'numCalories': numCalories,
      'weight': weight,
      'consumptionDate': consumptionDate
    });
  }

  removeCalories(id) {
    return FirebaseFirestore.instance.collection('calories').doc(id).delete();
  }

  Stream<List<Calories>> getCalories() {
    return FirebaseFirestore.instance
        .collection('calories')
        .where('email', isEqualTo: authService.getCurrentUser()!.email)
        .snapshots()
        .map((snapshot) => snapshot.docs
            .map<Calories>((doc) => Calories.fromMap(doc.data(), doc.id))
            .toList());
  }

  Stream<List<Recipe>> getRecipes() {
    return FirebaseFirestore.instance
        .collection('recipes')
        // .where('email', isEqualTo: authService.getCurrentUser()!.email)
        .snapshots()
        .map((snapshot) => snapshot.docs
            .map<Recipe>((doc) => Recipe.fromMap(doc.data(), doc.id))
            .toList());
  }
//   editExpense(id, purpose, mode, cost, travelDate) {
//     return FirebaseFirestore.instance
//         .collection('expenses')
//         .doc(id)
//         .set({'purpose': purpose, 'mode': mode, 'cost': cost, 'travelDate':
//     travelDate});
//   }
}

A: You need to listen to changes in your TextField and then return filtered documents according to the text in the search text field. Also, try using a StreamBuilder
You can have your search TextField as follows:
List<DocumentSnapshot> documents = [];
final collection = FirebaseFirestore.instance
    .collection('recipes')
    // .where('email', isEqualTo: authService.getCurrentUser()!.email)
    .snapshots()
    .map((snapshot) => snapshot.docs
        .map<Recipe>((doc) => Recipe.fromMap(doc.data(), doc.id))
        .toList());

final TextEditingController _searchController = TextEditingController();
String searchText = '';
**// Texfield Widget**
TextField(
 controller: _searchController,
 onChnaged: (value) {
   setState(()=> searchText = value);
 }
)

Then go a head and populate your Listview inside a StreamBuilder:
StreamBuilder buildCategoriesList(BuildContext context) {
return StreamBuilder<QuerySnapshot>(
    stream: collection.snapshots(),
    builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot)
     {
      if (snapshot.hasError) {
        return Center(child: Text('Error: ${snapshot.error}'));
      }
      switch (snapshot.connectionState) {
        case ConnectionState.waiting:
          return Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: const [
              CircularProgressIndicator(
              ),
              Text('Fetching recipes, please wait...'),
            ],
          );
        default:
          documents = snapshot.data!.docs;
          **// Search Logic**
          if (searchText.isNotEmpty) {
            documents = documents.where((element) {
              return element
                  .get('title')**// Field You want to search**
                  .toString()
                  .toLowerCase()
                  .contains(searchText.toLowerCase());
            }).toList();
          }
          //
          return ListView.builder(
          itemCount: documents.length,
          itemBuilder: (context, index) => Row(
           **// list item logic**
          );
     );
    }
   });
 }

A: The link is now completely blank and I cannot populate or filter the list from the collection.
[1]: https://i.stack.imgur.com/Ef3iV.png

A: Code with error, healthy_food_screen.dart. The index gets highlighted red
enter image description here
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:my_plate/models/recipes.dart';
import 'package:my_plate/providers/all_recipes.dart';
import 'package:my_plate/screens/bookmark_screen.dart';
import 'package:my_plate/screens/recipe_details_screen.dart';
import 'package:my_plate/widgets/app_drawer.dart';
import 'package:provider/provider.dart';

import '../services/firestore_service.dart';

class HealthyFoodScreen extends StatefulWidget {
  static String routeName = '/food';

  @override
  State<HealthyFoodScreen> createState() => _HealthyFoodScreenState();
}

class _HealthyFoodScreenState extends State<HealthyFoodScreen> {
  List<Recipe>? tempRecipeList;
  FirestoreService fsService = FirestoreService();
  addCount(recipe, AllRecipes myRecipe) {
    // tempRecipeList!.fav++
    setState(() {
      myRecipe.addRecipe(recipe);
    });
  }

  @override
  Widget build(BuildContext context) {
    List<DocumentSnapshot> documents = [];
    final collection = FirebaseFirestore.instance
        .collection('recipes')
    // .where('email', isEqualTo: authService.getCurrentUser()!.email)
        .snapshots()
        .map((snapshot) => snapshot.docs
        .map<Recipe>((doc) => Recipe.fromMap(doc.data(), doc.id))
        .toList());

    final TextEditingController _searchController = TextEditingController();
    String searchText = '';

    // final controller = TextEditingController();
    // FirestoreService fsService = FirestoreService();
    AllRecipes recipesList = Provider.of<AllRecipes>(context);
    // AllRecipes recipesList = Provider.of<AllRecipes>(context);
// created a new list so that when search query is empty it will be able to retrieve back the original list
    if (tempRecipeList == null) tempRecipeList = recipesList.getMyRecipe();
    print(tempRecipeList!.length);
    // if (tempRecipeList == null) tempRecipeList = recipesList.getMyRecipe();
    // print(tempRecipeList!.length);
    // var bookmark = Provider.of<Bookmark>(context);
    return Scaffold(
        drawer: AppDrawer(),
        backgroundColor: Colors.white,
        appBar: AppBar(
          // automaticallyImplyLeading: false,
            title: Text('Healthy Food Recipes'),
            backgroundColor: Color(0xff588157),
            actions: [
              IconButton(
                icon: Icon(Icons.book),
                onPressed: () {
                  Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) => BookmarksPage(),
                      ));
                },
              ),
            ]),
        body: Container(
          padding: EdgeInsets.all(10),
          child: Column(
            children: [

              // Texfield Widget**
              TextField(
                  controller: _searchController,
                  onChanged: (value) {
                    setState(()=> searchText = value);
                  }),
              // TextField(
              //   decoration: InputDecoration(
              //       enabledBorder: UnderlineInputBorder(
              //         borderSide: BorderSide(color: Color(0xff588157)),
              //       ),
              //       focusedBorder: UnderlineInputBorder(
              //         borderSide: BorderSide(color: Color(0xff588157)),
              //       ),
              //       hintText: 'Enter a search term',
              //       suffixIcon: Icon(Icons.search)),
              //   onChanged: (value) {
              //     searchRecipe(value, recipesList);
              //   },
              // ),
              Expanded(
                child: StreamBuilder<QuerySnapshot>(
                    stream: FirebaseFirestore.instance.collection('recipes').snapshots(),
                    builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot)
                    {
                      if (snapshot.hasError) {
                        return Center(child: Text('Error: ${snapshot.error}'));
                      }
                      switch (snapshot.connectionState) {
                        case ConnectionState.waiting:
                          return Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: const [
                              CircularProgressIndicator(
                              ),
                              Text('Fetching recipes, please wait...'),
                            ],
                          );
                        default:
                          documents = snapshot.data!.docs;
                          // Search Logic**
                          if (searchText.isNotEmpty) {
                            documents = documents.where((element) {
                              return element
                                  .get('title')// Field You want to search**
                                  .toString()
                                  .toLowerCase()
                                  .contains(searchText.toLowerCase());
                            }).toList();
                          }
                          //
                          return ListView.builder(
                            itemCount: documents.length,
                            itemBuilder: (context, index)
                              {// error lies here
                              //   Recipe recipe = snapshot.data![index];
                              //   return Card(
                              //       child: ListTile(
                              //       title: Text(snapshot.data![index].title,
                              //       style: TextStyle(
                              //           fontSize: 15,
                              //           fontWeight: FontWeight.bold)),
                              // subtitle: Text(
                              // snapshot.data![index].calories
                              //     .toString() +
                              // ' KCAL',
                              // style: TextStyle(
                              // fontStyle: FontStyle.italic),
                              // ),
                              // leading: Image.network(
                              // snapshot.data![index].imageUrl),
                              // onTap: () {
                              // Navigator.push(
                              // context,
                              // MaterialPageRoute(
                              // builder: (context) =>
                              // RecipeDetailsScreen(recipe)));
                              // },
                              // // This is useful as the snack bar shows exactly which recipe is being added to fav
                              // trailing: IconButton(
                              // icon: Icon(
                              // Icons.bookmark_add,
                              // ),
                              // onPressed: () {
                              // addCount(index, recipesList);
                              // ScaffoldMessenger.of(context)
                              //     .showSnackBar(SnackBar(
                              // content: Text(
                              // snapshot.data![index].title +
                              // ' has been saved!'),
                              // ));
                              // }),
                              //   ));
                            }
                          );
                      }
                    }),
              ),
            ],
          ),
        )
      // ,drawer: AppDrawer(),

    );
  }

  void searchRecipe(String query, AllRecipes recipesList) {
    tempRecipeList = recipesList.getMyRecipe();
// search query function
    //tries to filter and match recipes in list below according to alphabets entered in text field
    final suggestions = tempRecipeList!.where((recipe) {
      String recipeTitle = recipe.title.toLowerCase();
      String input = query.toLowerCase();
      print(input + "...");

      return recipeTitle.contains(input);
    }).toList();

    print(suggestions.length);

    setState(() => tempRecipeList = suggestions);
  }
}


text:
Q: Where have I used the assumption that $X\in L_2$? Let $X\in L_2$ be a random variable and $g$ a positive real function. Let $I$ be an interval and $b>0$, and suppose that $\forall x\in I\ g(x)>b$. I have to show that:
$$\operatorname E(g(X))\geq \operatorname P(X\in I) b$$
Well,
$$\operatorname E(g(X))=\int_\Omega g(X)\ d\operatorname P\geq \int_\Omega g(X)\chi_{X^{-1}(I)}d\operatorname P$$
Where $\chi_{X^{-1}(I)}$ is the characteristic function of $X^{-1}(I)$.
$$\geq b\int_\Omega\chi_{X^{-1}(I)}d\operatorname P=b\operatorname P(X^{-1}(I))=b\operatorname P(X\in I)$$
If this is correct, then where did I use $X\in L_2$?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why is $\int \cos(n\arccos(\sin(x)) = \int \cos(nx)$ on $[-1, 1]$? I would like to evaluate

$$\int \cos(n\arccos(\sin(x)) dx$$

with $x \in [-1, 1],$ and I used a calculator do to so. At the very beginning, the calculator simplifies
$$\int \cos(n\arccos(\sin(x)) dx = \int \cos(nx) dx.$$
This looks like $\arccos(\sin(x)) = x$, but I don't see where this comes from.

A: Not a full answer, but couldn't fit it in a comment.
As I wrote above, recalling that $\sin(x)=\cos(\pi/2-x)$ we obtain that
\begin{align*}\cos(n\cdot \arccos(\sin(x)))& =\cos(n\cdot\arccos(\cos(\pi/2-x)))=\cos(n\pi/2-nx )\\& =\cos(n\pi/2)\cos(nx)+\sin(n\pi/2)\sin(nx)\end{align*}
which is equal to $n\cos(x)$ iff $n=0\mod 4$.
Are we sure that the substitution is correct?


text:
Q: How do I include css from npm in Angular2 This has been surprisingly hard to find an answer to, please point out if I'm not searching right and this is a duplicate question.
I have an Angular2 (2.0.0-beta.14) app and am having issues including a 3rd party css file. I've downloaded materialize-css via npm and I can see the file is at node_modules/materialize-css/bin/materialize.css.
I would like this css file to be visible to my entire application.
At the highest level, I've tried including it in my index.html head section <link rel="stylesheet" href="./node_modules/materialize-css/bin/materialize.css" media="screen">, but can't figure out where it's being served or even if it's being served.
At a lower level, I've tried defining it in the styleUrls token of the app initiation.
@Component({
  selector: 'myApp',
  providers: [],
  pipes: [],
  directives: [ROUTER_DIRECTIVES],
  templateUrl: 'app/henna.html',
  styleUrls: ['materialize.css']
})

I've tried various different styleUrls trying to find the file, but it seems the problem might be that the file is not accessible.
Please let me know any more info that is needed to help, this is my first application that I've used Angular2.

A: This was an issue with webpack not bundling my files how I was expecting (I had never used webpack before). I needed to install the correct webpack loaders for css and font files, import materialize, and then the files were being included.
After installing the correct loaders (npm install css-loader npm install file-loader), in webpack.config.js I needed to modify the module object.
module: {
    loaders: [
      { test: /\.ts$/, loader: 'awesome-typescript-loader' },
      { test: /\.css$/, loader: "style-loader!css-loader" },
      { test: /\.(ttf|eot|svg|woff(2)?)(\?[a-z0-9]+)?$/, loader : 'file-loader'},
    ]
  }

in the vendor.js file, I needed to import the materialize js and css
import 'materialize-css/bin/materialize.css'
import 'materialize-css/bin/materialize.js'


text:
Q: when i use const { myCardStyle } = this.myStyles; at the class below it shows error I'm learning react native. in my application, for one of the components, when i use this. at const { myCardStyle } = this.myStyles; at the class below it shows error: Possible unhandled Promise Rejection ..., but when i put it without this it works.
const Card = (myProps) => {

const { myCardStyle } = myStyles;
console.log(8 + myProps.children);
  return(
    <View style={myCardStyle}>
      {myProps.children}
    </View>
  );

};

const myStyles = {
  myCardStyle: {
     blabla
  }
};

A: const can be accessed without the help of this keyword. Look at the example below. styles can be accessed globally by the class without using this keyword.
this keyword is used when we want to access state or prop objects that are binded to the class. Normally u can bind the finctions using bind keyword
/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */
import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View
} from 'react-native';

export default class VideoExample extends Component {
 __click(){
    //if u want to access this keyword here
    //u have to bind this function
  }

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          Welcome to React Native!
        </Text>
        <Text onPresss={this._click.bind(this)}/>

      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
});

AppRegistry.registerComponent('VideoExample', () => VideoExample);

A: Try to move const myStyle inside Card method and before
const { myCardStyle } = myStyles
const Card = (myProps) => {
  const myStyles = {
    myCardStyle: {
       blabla
    }
  };

  const { myCardStyle } = myStyles;
  console.log(8 + myProps.children);
  return(
    <View style={myCardStyle}>
      {myProps.children}
    </View>
  );

};

A: styles are defined outside the class VideoExample so you can't access it using the this.myStyles.
You can directly refer the variable by it's name and if you want to access it in another class you can access it by VideoExample.myStyles.


text:
Q: how to create an html href with added php variable How can I attach a php variable to an href link?
Been trying but not working

    <a href="login.php?lang='<?php echo $lang; ?>'"><?php echo $lang['sign_in'];?>

The problem is in this part --> ... <?php echo $lang; ?>
Anyone know what to do?
Thank you for your help

A: No need single quotes enclosed for $lang variable

<a href="login.php?lang='<?php echo $lang; ?>'"><?php echo $lang['sign_in'];?>

Change To

<a href="login.php?lang=<?php echo $lang; ?>"><?php echo $lang['sign_in']; ?>

A: $lang is a array variable.to assign declare variable with key value with $lang. and No need single quotes enclosed for $lang variable.
Try this:

<a href="login.php?lang=<?php echo $lang['sign_in'] ?>"><?php echo $lang['sign_in'];?>

A: This is a array value not possible to pass in anchor tag. If you need all array values into another page use following code
index.php
<?php
   $lang = array("php","c","c++");
$Text = json_encode($lang);
$RequestText = urlencode($Text);
?>
<a href="second.php?id=<?php echo $RequestText; ?>">Click
?>

second.php
$Text = urldecode($_REQUEST['id']);
$Mixed = json_decode($Text);
print_r( $Mixed);
?>


text:
Q: How to wait three seconds then turn to another webpage I'm new to web development, and I'm currently using ASP.net. I wonder what would I need to do to let the browser wait for 3 seconds so my users can read the text "Customer Successfully Added" before turning to another page? I have attached my code as follows.
Protected Sub btnAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAdd.Click
    Dim db As New DatabaseClass
    db.addProfile(txtLN.Text, txtFN.Text, txtUsername.Text, txtPassword.Text, txtAddress.Text, txtZip.Text, txtPhone.Text, txtEmail.Text)
    lblMessage.Text = "Customer Successfully Added"
End Sub

In addition, I'm not sure how to utilize MSDN. For me, its information overload, I'm wondering how to go about finding the solution on MSDN so i would be able to solve my problems in the future. Thank you!

A: You can't do it in the code behind of the page because of how asp.net works - the label text would not update until after the timeout occurred if you did it in the code-behind.
The server-side processing spits all the html back to the browser only after it has completely processed any server-side code unless you're using Ajax.  Since you're new, I won't even bother going into how to do it with Ajax as there is a MUCH simpler option for accomplishing what you want.
A simple method to accomplish what you're looking for would be to have a simple HTML page that just has a message that says "Customer successfully added" and use javascript (client-side code) to pause and then redirect using the Javascript "SetTimeout" function.
There's an example here: http://www.bloggingdeveloper.com/post/JavaScript-Url-Redirect-with-Delay.aspx
The logic flow wshould work like this:
The original page should add the record (in code-behind) then redirect to this simple html page (in code-behind).  The html page should have the "Customer Added" message and use the SetTimeout and Redirect to go to whatever page you want the user to see after viewing the message.

A: For stuff like this you need the code to run client side rather than on the server.  The easiest way to do this is to return some javascript with your page (in the .aspx part rather than the code behind)
Take a look here for an idea of what to do :)
The page is displayed for a few seconds and then the javascript triggers a redirect to a url of your choosing. Just add something like this into your html.

A: You can emit javascript to redirect to the other page, using the setTimeout function.
This is best accomplished using the ScriptManager to register any javascript on the page.


text:
Q: What does `class =` inside template mean? I found this construct in C-code:
template<typename T, class = decltype(std::declval<T>() < std::declval<T>())>
struct check : std::true_type {};

Now I understand what it does but I don't understand how it works. It throws a compile error if type T doesn't support the <-operator. But, apparently, when changing class to something else, the whole thing won't compile and throws a Syntax Error.
What does class = sometypename mean?

A: class is the same as typename here.  You could also do this:
template<typename T, typename = decltype(std::declval<T>() < std::declval<T>())>
struct check : std::true_type {};

You can specify default values for template arguments. For example
template<typename X = int> struct test { };

You can also leave off the name of the template arguments if you don't use them:
template<typename = int> struct test { };

So in your example, the second template parameter is just an unnamed parameter with a default argument.

A: The concept that makes this work is known as SFINAE (substitution failure is not an error) and is used to implement std::enable_if<> etc.  http://en.cppreference.com/w/cpp/language/sfinae


text:
Q: Writing a perpetual program with Python to check validity of integers I am a beginner in Python and I was trying to write a small program that asks the user to enter an integer that is greater than 0. The function should keep on asking the user for the number until it is valid.
I tried something like below, however I am getting the wrong results. Can you please help me understand my error?
num = input('please enter a number: ' )
n = int(num)
while n < 0:
    num = input('please enter a number: ' )
    if n >= 0:
       print('Valid number')
    else:
       print('Invalid number')

Is it possible to start the code without an input function? (like to start with num = int())
Thank You for Your Time

A: If your problem is the code not terminating, writing Invalid number all the time it's because you are not updating the value of n. You assigned it just once. The solution to your problem is as follows:
n = -1
while n < 0:
    n = int(input('please enter a number: '))
    if n >= 0:
        print('Valid number')
    else:
        print('Invalid number')

By the way you get rid of starting the code without an input function.
Edit:
As you just said - you want to keep the input reading despite passing an negative integer into the command line. This should help you accomplish this:
while True:
    n = int(input('please enter a number: '))
    if n >= 0:
        print('Valid number')
    else:
        print('Invalid number')

This loop will go forever until you exit the program lets say with ctrl + C. while True: is as you see an forever ongoing loop, because the True argument will never be false.

A: There's an error with the logic behind your code.

*

*You firstly ask the user for a number and if he inputs a number which is greater than or equal to 0, the while-loop will never start (in your script: while n < 0:), which, I assume is fine, because the goal of your program is, as you said, to make "the user to enter an integer that is greater than 0".

*If the user inputs a number that is smaller than or equal to 0, the while-loop will start, but will never break because inside of it, the value of variable n never changes, only does the value of num.
This is an appropriate script considering that you want to make the user input a number greater than 0, and that you want to give feedback regarding their input.
n = None

while n <= 0:

    n = int(input('please enter a number: '))

    if n <= 0:
        print('Invalid number')

    else:
        pass # the loop will break at this point
             # because n <= 0 is False

print('Valid number')

The code has the user stuck in a loop until they write a number that's greater than 0.
Another solution would be to, inside the loop, check whether int(num) is greater than 0 and if it is, print 'Valid number' and do break to stop the loop; if it's not, print 'Invalid number' (though then the loop doesn't need to be defined by while n < 0:; rather by while True:.
Also, what do you mean by this:

Is it possible to start the code without an input function? (like to start with num = int())

Please clarify this part.


text:
Q: What will be the 49th derivative? Let be the function $f=(x^3+3x) \cdot sin(x)$
$f'(x)=\left(3x^2+3\right)\sin\left(x\right)+\left(x^3+3x\right)\cos\left(x\right)$
$f''(x)=\left(3x-x^3\right)\sin\left(x\right)+\left(6x^2+6\right)\cos\left(x\right)$
$f'''(x)=\left(-9x^2-3\right)\sin\left(x\right)+\left(15x-x^3\right)\cos\left(x\right)$
$f''''(x)=\left(x^3-33x\right)\sin\left(x\right)+\left(12-12x^2\right)\cos\left(x\right)$
I still can't the exact pattern in the results, I would appreciate any help.

A: Going off A.Riesen's comment, the General Leibniz Rule states that
$$(uv)^{(n)} = \sum_{k=0}^n {n \choose k} u^{(k)} v^{(n-k)} %seriously, did nobody notice that I had written down the formula incorrectly the first time?$$
where $u,v$ are functions of $x$ and $f^{(n)}$ is the $n^{th}$ derivative of $f$ with respect to $x$. Plugging in $u = x^3 + 3x$, $v = \sin x$ and $n = 49$, we get
$$((x^3+3x)(\sin x))^{(49)} = \sum_{k=0}^{49} {n \choose k} (x^3+3x)^{(k)}(\sin x)^{(49-k)}$$
Fortunately, since $(x^3+3x)^{(n)} = 0$ for all $n \ge 4$, we can reduce this to
$$\sum_{k=0}^{3} {n \choose k} (x^3+3x)^{(k)}(\sin x)^{(49-k)}$$
$$= {49 \choose 0} (x^3+3x)^{(0)} (\sin x)^{(49)} + {49 \choose 1} (x^3+3x)^{(1)} (\sin x)^{(48)} + {49 \choose 2} (x^3+3x)^{(2)} (\sin x)^{(47)} + {49 \choose 3} (x^3+3x)^{(3)} (\sin x)^{(46)}$$
Using the derivatives of sines and cosines, this comes down to
$$= {49 \choose 0} (x^3+3x) \cos x + {49 \choose 1} (3x^2+3) \sin x + {49 \choose 2} (6x) (-\cos x) + {49 \choose 3} 6 (-\sin x)$$
I'll leave the number crunching and simplification for you.

A: So the general Leibniz rule somewhat is similar to the binomial theorem. Let $u,v$ be n-th differentiable functions then $(uv)^{(n)}=\sum_{k=0}^{n}{n \choose k}u^{(k)}v^{(n-k)}$ where the exponents denote the $kth$ derivative.
When now note that the fourth derivative and higher of $x^3+3x$ will be zero so we only need to consider the cases where the derivative taken is less than fourth one of $x^3+3x$ . For the $sin(x)$ we use the general formula that $(sin(x))^{(n)}=sin(\frac{n\pi}{2}+x)$.
Thus the forty-nith derivative will be.
$((x^3+3x)sin(x))^{(49)}={49 \choose 46}6sin(23\pi+x)+{49 \choose 47}6xsin(\frac{47\pi}{2}+x)+{49 \choose 48}(3x^2+3)sin(24\pi+x)+(x^3+3x)sin(\frac{49\pi}{2}+x)$
Which wil simplfy to
$(x^3 + 3 x) cos(x) + 49 (3 x^2 + 3) sin(x) - 110544 sin(x) - 7056 x cos(x)$


text:
Q: Change value of select option from Python Selenium When I inspect a page, I will get these HTML element:
<select name="limit">
    <option value="20">20</option>
    <option value="50">50</option>
    <option value="100">100</option>
</select>
<input type="submit" value="Fetch"/>

I have a Python Selenium script, which selects the third option, here is the code:
driver.find_element(By.XPATH,'//*[@id="news_info-filter"]/label[5]/select').send_keys('100')
driver.find_element(By.XPATH,'//*[@id="news_info-filter"]/input[1]').click()

But, I wanted to change the value of the third option before clicking the Fetch button like this:
....
    <option value="2000">100</option>
....

What can I try to get to a solution?

A: You can change the attribute value like this :
element =  driver.find_element_by_css_selector("option[value = '100']");
driver.execute_script("arguments[0].setAttribute('value', 'new value here')", element);

and then you can fire up the click on Fetch button.


text:
Q: Loading data fast I have a data (ex. 200 posts) and would like to load it fast so the user doesn't see a progress/preloader every time he enters on this screen. This is what I am doing:

*

*If the user is opening the screen for the first time, get first 8 posts, store them (I am storing the JSON as a string into SharedPreferences) and when the user starts scrolling and reaches the 7-th post I am using a pagination (fetching new 8 posts and append them) and so on. This case is working fine.

*If the user already have been on this scree, I load the first 8 posts from SharedPreferences so he can see immediately some results without start fetching new results. When he reaches the bottom - again pagination. The problem is that when clicking between bottom tab bar's items there is a 1s delay opening the tab with the stored data. And when you do it several times it's really annoying. Here's what I am doing:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    if (isFirstTime) {
        getFirstEight();
        progress.show();
    } else {
        JSONObject data = getStoredJSONFromShared();
        if (data != null) {
            Post[] posts = gson.fromJson(data.getJSONObject("response").get("posts").toString(), Post[].class);
        }
    }
}

I create this inside onCreateView because when the user is not seeing the screen for the first time, the data from SharedPreferences is loaded before RecycleView init. Maybe the parsing is slow or I should not create this inside onCreateView.

A: What you can do is show a preloader when the screen is shown to the user even while you are fetching the data from SharedPrefrences.
Load the data in the onResume method, once the data is loaded, you can hide the preloader. This way, at least, the user will be provided with a visual feedback and there won't be that 1 sec lag as you are not loading anything in onCreateView.


text:
Q: find value in complex object javascript Basically I have a complex object that retrieves the GPT API (google publisher tag) with this function:
googletag.pubads().getSlots();

The object value is something like this:

I need to know if there is a way to compare the value of each property with an X value without getting a problem of recursivity (because the object is huge and i need to to that validation several times)
Also, I tried to convert that object into a JSON with JSON.stringify(), and then tried to get the value with a regex, faster, but with this option, I have the problem with Cyclic Object Value.
Any suggestions ?

A: it's more simple. try it to convert it into an array and later use a filter for comparative with your value.
var objGoogle = {};
var arrayObjectGoogle = [objGoogle];
var filter = arrayObjectGoogle.filter(function(obj){
  obj.yourAttr == yourValue;  });

this will give you a second array with the values found it. later, index the array for pick up the value do you need.


text:
Q: How to choose primary key for data that has been changed to contain unique values only Man, was I having trouble with how to word the title.

*

*Summary: For a database project in uni, we have to import 1 million rows of data into a database, where each row represents an article scraped from the internet. One of the columns in this data, is the author of the article. As many articles were written by the same author, I wanted to create a table separate from the articles, that linked each unique author to a primary key and then I wanted to replace the author string in the article table, with the key for that author in the other table. How is this done in the most efficient way and is it possible to do it in a way that ensures a deterministic output, in that a specific author string would ALWAYS map to a certain pkey, no matter the order the article rows "come in" when this method creates that table.

*What I've done: The way I did it, was to (in Python using Pandas), go through all 1 million article rows and make a unique list of all the authors I found. Then I created a dictionary based on this list (sorted). Then I used this dictionary to replace the author string in the articles tables with a key corresponding to a specific author, and then used the dict to create my authors table. However, as I see it, if a row was inserted into my data with an author not found the first time around, it could mess with the alphabetical order my method adds the authors to the dict in, thus making it not-so-deterministic. So, what do people normally do in these instances? Can SQL on the 1mio articles directly make a new authors table with unique authors and keys, and replace the author string in the articles table? Could it be an idea to use hashing with a specific hash key to ensure a certain string always maps to a certain key, or?

*Show some code:
def get_authors_dict():

    authors_lists = []

    df = pd.read_csv("1mio-raw.csv", usecols=['authors'], low_memory=True)

    unique_authors_list = df['authors'].unique()

    num_of_authors = len(unique_authors_list)

    authors_dict = {}
    i = 0
    prog = 0
    for author in unique_authors_list:
        try:
            authors_dict[author]
            i += 1
        except KeyError:
            authors_dict[author] = i
            i += 1

        print(prog / num_of_authors * 100, "%")
        prog += 1

    return authors_dict

authors_dict = get_authors_dict()

col1_author_id = list(authors_dict.values())
col2_author_name = list(authors_dict.keys())

data_dict = {'col1': col1_author_id,
             'col2': col2_author_name}

df = pd.DataFrame(data=data_dict, columns=['col1', 'col2'])

df.to_csv('author.csv', index=False, header=False, sep="~")

f = open('author.csv', encoding="utf8")

conn = psycopg2.connect(--------)
cur = conn.cursor()
cur.copy_from(f, 'author', sep='~')
conn.commit()
cur.close()

# Processing all the 1mio rows again in seperate file
# and making changes to the dataframe using the dict:
sample_data['authors'] = sample_data['authors'].map(authors_dict)

A: So if i understand you correctly, you want to create a SQL table which connects authors to articles. Your problem is, that you do not know what primary key you should use in such a table, since an author might have written more than one article.
In this cases, instead of trying to do something clever, i would just use a composite primary key for your table. This means you define the author row in connection with the title/publishing date/identfier of the article as the primary key for the table. Thus, each row of your table has a unique identifier (if no author has written two identical articles). This is independent of your python code, as this needs to be defined in the database.
This question might help you to define a composite primary key.


text:
Q: Foreach loop, only show first element result in php? I see some answers on this site but none apply for my particular problem.
When i trying to loop through array it shows only one array element. i have to get the loop results. i have tried many possible condition but nothing worked. please help me to resolve this. how to get the 1st and 2nd element result
output example
print_r($items[$i]['svg']);

foreach loop results showing only one result
Items array:

print_r($items);

  Array
(
    [0] => Array
        (
            [type] => text
            [remove] => 1
            [rotate] => 0
            [text] => Hello
            [fontFamily] => Twine
            [color] => #000000
            [colors] => Array
                (
                    [0] => #000000
                )

            [stroke] => none
            [strokew] => 0
            [width] => 219px
            [height] => 109px
            [file] =>
            [confirmColor] =>
            [svg] =>
Hello

            [id] => 0
            [lockedProportion] => 1
            [align] => center
            [outlineC] => none
            [outlineW] => 0
            [top] => 22px
            [left] => 175px
            [zIndex] => 1
        )

    [1] => Array
        (
            [type] => text
            [remove] => 1
            [rotate] => 0
            [text] => Tetst
            [fontFamily] => Twine
            [color] => #000000
            [colors] => Array
                (
                    [0] => #000000
                )

            [stroke] => none
            [strokew] => 0
            [width] => 207px
            [height] => 109px
            [file] =>
            [confirmColor] =>
            [svg] =>
Tetst

            [id] => 1
            [lockedProportion] => 1
            [align] => center
            [outlineC] => none
            [outlineW] => 0
            [top] => 195px
            [left] => 116px
            [zIndex] => 6
        )

when i try to print inside foreach it show only one result
$i = 0;

foreach($items as $item){
echo '<pre>';
    print_r($items[$i]);
$i++
}
exit;

A: Try this :
foreach($items as $i => $item){
    echo '<pre>';

    // either use this
    print_r($items[$i]); // it's actually not recomended

    // or use this
    print_r($item);

    echo '</pre>';
}

A: Can you write your array but I think use this
foreach($items as $item){
   echo '<pre>';
   print_r($item);
}
exit;

A: You are iterating through $items while increment $i at the same time. It's not the same structure.
You are mingling foreach() and for().
Do one or the others, but you have to choose :
$cnt = count($items);
for ($i = 0; $i < $cnt; ++$i) {
    print_r($items[$i]);
}

or
foreach ($items as $item) {
    print_r($item);
}

A: Since foreach() take care of numeric indexes itself, so no need of $i there.You have do this only:-
foreach($items as $item){
   echo '<pre/>';print_r($item); // print each sub-array of  original array
}

Output:- https://eval.in/851758


text:
Q: MySQL values get added to absurd decimal places randomly I'm using the node.js mysql module, and I have a line that does this:
await connection.query("UPDATE users SET balance=balance+? WHERE userid=?", [amount.toFixed(2), user.id])

The balance row is updated without problem, and balance goes up to 2 decimal places. However, sometimes randomly the row inside the MySQL table will get set with weird decimals.
WHAT HAPPENS:
amount is 10.5 and the user's balance is 25. The balances are updated, but sometimes it goes and makes the value inside of the MySQL to go to 30.500000000004 or numbers with really absurd decimal places, even though I never put them in.


text:
Q: SML-NJ, how to compile standalone executable I start to learn Standard ML, and now I try to use Standard ML of New Jersey compiler.
Now I can use interactive loop, but how I can compile source file to standalone executable?
In C, for example, one can just write
$ gcc hello_world.c -o helloworld
and then run helloworld binary.
I read documentation for SML NJ Compilation Manager, but it don`t have any clear examples.
Also, is there another SML compiler (which allow standalone binary creating) available?

A: Both MosML and MLton also have the posibility to create standalone binary files. MosML through mosmlc command and MLton through the mlton command.
Note that MLton doesn't have an interactive loop but is a whole-program optimising compiler. Which in basic means that it takes quite some time to compile but in turn it generates incredibly fast SML programs.
For SML/NJ you can use the CM.mk_standalone function, but this is not advised in the CM User Manual page 45. Instead they recommend that you use the ml-build command. This will generate a SML/NJ heap image. The heap image must be run with the @SMLload parameter, or you can use the heap2exec program, granted that you have a supported system. If you don't then I would suggest that you use MLton instead.
The following can be used to generate a valid SML/NJ heap image:
test.cm:
Group is
        test.sml

        $/basis.cm

test.sml:
structure Test =
struct

fun main (prog_name, args) =
    let
      val _ = print ("Program name: " ^ prog_name ^ "\n")
      val _ = print "Arguments:\n"
      val _ = map (fn s => print ("\t" ^ s ^ "\n")) args
    in
      1
    end
end

And to generate the heap image you can use: ml-build test.cm Test.main test-image and then run it by sml @SMLload test-image.XXXXX arg1 arg2 "this is one argument" where XXXXX is your architecture.
If you decide to MLton at some point, then you don't need to have any main function. It evaluates everything at toplevel, so you can create a main function and have it called by something like this:
fun main () = print "this is the main function\n"

val foo = 4

val _ = print ((Int.toString 4) ^ "\n")

val _ = main ()

Then you can compile it by mlton foo.sml which will produce an executable named "foo". When you run it, it will produce this as result:
./foo
4
this is the main function

Note that this is only one file, when you have multiple files you will either need to use MLB (ML  Basis files) which is MLtons project files or you can use cm files and then compile it by mlton projectr.mlb


text:
Q: "Can't bind to 'ngForOf' since it isn't a known property of 'ng-container' I have the following code in my html modal component:
<ng-container *ngFor="let school of schools">
   {{school.name}}
<ng-container>

However I'm getting the following error:
"Can't bind to 'ngForOf' since it isn't a known property of 'ng-container'

I've looked at other people's solutions online who suggest importing forms module, reactive forms module and common module, but I already have these imported in the modal module
import { FormsModule, ReactiveFormsModule } from "@angular/forms";
import { CommonModule } from "@angular/common";

Does anyone have any other suggestions on how I can get rid of this error?

A: The ngFor directive is exported from the CommonModule, try importing the corresponding module to your app module imports or to the corresponding module in use.

A: Add BrowserModule in your app.module.ts. Stackblitz
import { BrowserModule } from '@angular/platform-browser';

@NgModule({
  imports:[ BrowserModule],

So, you should import BrowserModule in app.module whereas CommonModule in feature modules Here is a good read on this topic


text:
Q: Modeling phase delay in high frequency resonantly coupled inductors I am interested in simulating resonant wireless power transfer circuits similar to the ones developed by MIT and others. So far, I have been able to successfully create a basic simulation model of a set of resonantly coupled inductors with a k of 0.1 or less. However, I'm interested in exploring the behavior of the system at high frequencies where the distance between coils becomes a significant fraction of the transmission wavelength.
When I say significant, I mean within a quarter wavelength, as I am still interested in near-field coupling. However, even within this regime, I am interested in exploring the effects that the propagation/phase delay of the field from the receiver has on the transmitter.
Is there any way to model the effects of delayed phase of two resonantly coupled inductors in LTSpice? I imagine it would be something like a wireless transmission line but I have no idea how I would even start to model this. Again, the phase delay range I'm interested in is only 10-20 degrees max from the source. Any pointers in the right direction greatly appreciated!
Also, as a reference, here's a paper I've been reviewing that discusses the subject a bit more.
http://www.physics.princeton.edu/~mcdonald/examples/wireless.pdf
Thank you,
Jason O


text:
Q: Read an XML file uploaded with app I am using Java, GWT and Eclipse.  I have a static XML file I want to parse to get certain data that will fill in list boxes and other info. How can I read the static XML file in both the server and client side of the code?  Where do I put the XML file?  Also, where can I put it if I only want the server to have access to it (since it contains sensitive data)?

A: If you need it on a server side only, put it in the /war/WEB-INF directory, and you can read it directly in your server code.
You can use a DataResource if you need a file on the client side:
https://developers.google.com/web-toolkit/doc/latest/DevGuideClientBundle#DataResource
If you want this file accessible on the client side, put it in the /war directory.

A: I would suggest that you parse the file server-side using any good XML parser (for an example see this tutorial) and put the resulting data in POJOs. For the data that you need client-side, you can make an RPC call to the server to retrieve the POJOs previously populated. A good place to put the XML file to prevent it from being directly accessible is under the WEB-INF directory of your webapp.


text:
Q: How get values from object in js? I have object in JS:
File
accepted: true
dataURL: "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAASABIAAD/4Qh8RXhpZgAATU0AKgAAAAgADAEPAAIAAAAGAAAAngEQAAIAAAAOAAAApAESAAMAAAABAAYAAAEaAAUAAAABAAAAsgEbAAUAAAABAAAAugEoAAMAAAABAAIAAAExAAIAAAAFAAAAwgEyAAIAAAAUAAAAyAFCAAQAAAABAAACAAFDAAQAAAABAAACAIdpAAQAAAABAAAA3IglAAQAAAABAAAHPgAAAABBcHBsZQBpUGhvbmUgOCBQbHVzAAAAAEgAAAABAAAASAAAAAExMi4wAAAyMDE4OjA5OjIxIDE0OjI3OjU1AAAfgpoABQAAAAEAAAJWgp0ABQAAAAEAAAJeiCIAAwAAAAEAAgAAiCcAAwAAAAEAUAAAkAAABwAAAAQwMjIxkAMAAgAAABQAAAJmkAQAAgAAABQAAAJ6kQEABwAAAAQBAgMAkgEACgAAAAEAAAKOkgIABQAAAAEAAAKWkgMACgAAAAEAAAKekgQACgAAAAEAAAKmkgcAAwAAAAEABQAAkgkAAwAAAAEAEAAAkgoABQAAAAEAAAKukhQAAwAAAAQAAAK2knwABwAABC4AAAK+kpEAAgAAAAQ4NDIAkpIAAgAAAAQ4NDIAoAAABwAAAAQwMTAwoAIABAAAAAEAAA/AoAMABAAAAAEAAAvQohcAAwAAAAEAAgAAowEABwAAAAEBAAAApAIAAwAAAAEAAAAApAMAAwAAAAEAAAAApAUAAwAAAAEAHAAApAYAAwAAAAEAAAAApDIABQAAAAQAAAbspDMAAgAAAAYAAAcMpDQAAgAAACwAAAcSAAAAAAAAAAEAAAAPAAAACQAAAAUyMDE4OjA5OjIxIDE0OjI3OjU1ADIwMTg6MDk6MjEgMTQ6Mjc6NTUAAAASbAAABLcAAAhvAAAE+QAAEhsAAAq6AAAAAAAAAAEAAAGPAAAAZAffBecIqQUyQ…"
height: 3024
lastModified: 1537604334019
name: "%6qdJvzqS1OTnJATyo8lZQ.jpg"
previewElement:

previewTemplate:

processing: true
size: 1636910
status: "success"
type: "image/jpeg"
upload: Object { uuid: "af40c7d8-7d46-49f3-8770-1d6998a8485f", progress: 100, total: 1637145, … }
webkitRelativePath: ""width: 4032xhr: XMLHttpRequest { readyState: 4, timeout: 30000, withCredentials: false, … }
<prototype>: FilePrototype { name: Getter, lastModified: Getter, webkitRelativePath: Getter, … }
SystemConfiguration:642:17

How can I get accepted (true or false) and name?

A: Suppose the name of the object is obj.
Then you refer to the attribute as
let val = obj.accepted;

A: var myFile = new File([""], "filename");
Now you can access any properties of myFile in the following way.
myFile.name;
myFile.accepted;


text:
Q: How accurate is the iPhone X location data? First of all, I understand there are similar posts, however, they are to do with previous generation iPhones. This is specifically about the iPhone X.
How accurate is the GPS information that developers can get when using the iPhone X?
I am thinking about making a Raspberry Pi project where I need to get precise location data to create a map and calculate speed for some telemetry system I am making.
To check that it is do able first, I will test it with my iPhone X as I already have all the hardware. If the GPS is not accurate enough, I will go straight to the Pi setup. For example the GPS module I will be using updates location 10 times a second. What does the iPhone X do?

A:
How accurate is the GPS information that developers can get when using the iPhone X?

It's a subjective question and the perceived accuracy of location data may differ based on usage, location and signal availability. While the real answer can only be obtained by actually capturing the data, I'll try to share some information which can help you with your query.
iPhone X along with its contemporaries iPhone 8 and iPhone 8 Plus, are the first iPhones to include support for not one but four geolocation services:

A brief description of each one of them:

*

*GPS: Global Positioning System (GPS), originally Navstar GPS, is a satellite-based radionavigation system owned by the United States government and operated by the United States Air Force.

*GLONASS: Globalnaya navigatsionnaya sputnikovaya sistema, or Global Navigation Satellite System, is a space-based satellite navigation system operating in the radionavigation-satellite service. It provides an alternative to GPS and is the second navigational system in operation with global coverage and of comparable precision.

*Galileo: Galileo is the global navigation satellite system (GNSS) that is being created by the European Union (EU) through the European GNSS Agency (GSA). One of the aims of Galileo is to provide an independent high-precision positioning system so European nations do not have to rely on the Russian GLONASS, Chinese BeiDou or US GPS systems, which could be disabled or degraded by their operators at any time. The use of basic (lower-precision) Galileo services will be free and open to everyone. The higher-precision capabilities will be available for paying commercial users. Galileo is intended to provide horizontal and vertical position measurements within 1-metre precision, and better positioning services at higher latitudes than other positioning systems.

*QZSS: The Quasi-Zenith Satellite System (QZSS) is a project of the Japanese government for the development of a four-satellite regional time transfer system and a satellite-based augmentation system for the United States operated Global Positioning System (GPS) to be receivable in the Asia-Oceania regions, with a focus on Japan. The goal of QZSS is to provide highly precise and stable positioning services in the Asia-Oceania region, compatible with GPS.
While GPS support has been available since iPhone 3G, GLONASS was added starting with iPhone 4S (ref: List of iOS devices).
Some references from the Web which back the claim that availability of multiple service support will lead to more accurate positioning data:

*

*iPhone 8, 8 Plus, and X Support the Galileo Satellite System for Better GPS:

According to the European Global Navigation Satellite Systems Agency, Galileo support in the new iPhones will allow users to benefit from more precise positioning that's able to combine GPS, GLONASS, and Galileo signals. Galileo, says the agency, has a modern signal structure that's able to help users better maintain their position fix when navigating through cities worldwide.
Multi-satellite support also increases signal availability in urban areas where buildings can obstruct the sky and limit the number of visible satellites. Galileo has 15 operational satellites in orbit and three that are in testing, compared to 31 GPS satellites and 24 GLONASS satellites. By 2020, Galileo is expected to have 30 satellites operational.

*

*The latest iPhone 8, iPhone 8 Plus, and iPhone X are Galileo-enabled:

Among the new features of the latest Apple offerings is the fact that the newest versions of the iPhone are Galileo-enabled. The resulting 'multi-constellation' capability means that users of the new iPhones will be able to benefit from more precise positioning that combines GPS, Glonass and Galileo signals. The use of multi-constellation increases signal availability, especially in urban environments, where buildings obstruct the sky and limit the number of satellites visible. In terms of accuracy, Galileo's modern signal structure has better resistance to multipath, which helps users maintain their position fix when navigating in cities.

*

*New iPhones better serve you in different parts of the world with support for Galileo and QZSS satellites

Combining GPS, GLONASS and Galileo signals lets new iPhones increase signal availability in urban environments where buildings obstruct the sky and limit the number of satellites visible.
In terms of accuracy, Galileo's signal structure is said to provide better resistance to multipath, which helps iPhone users maintain their position fix when navigating in cities.

A: iPhone X GPS accuracy is the same as iPhone 8, 7, 6S, 6, 5S and all recent galaxy phones. That is because none of the smartphones come with a GPS chip in them.
Phones do not have GPS, they have GPS capability. This capability stems from the modem chip that's used to make phone calls and stems as a byproduct designed to receive GPS signals originally intended for clock maintenance needed for high speed internet to maintain internal phone clock.
They quickly realized it can also be used as low quality GPS, this is why current phones have such horrible accuracy of a radius that's about 15 meters (45 feet) in diameter in some less optimal conditions, where real GPS with a GPS chip, update rate of 10 times per second, and SBAS, you will get below 1 meter precision without breaking sweat.
Phone GPS capability is okay for walking around a city, due to having more GNSS ability makes it very good for getting signal in places with tall buildings, but having Glonass, Compass etc in addition to GPS itself, does not increase accuracy, a dedicated GPS chip would be the only thing Apple could add, those chips are insanely small and insanely good at what they do, there's plenty of space inside the iPhone, like for example that piece of plastic where headphone jack used to be.


text:
Q: Finding coefficients of a function, given a list of points on the function Given $f(x) = ax^n + bx^{n-1} + ... + cx + d$, a list of points, and a specification of a tangent line (point $p_t$ and equation) find  $a, b, ..., c, d$ s.t.

*

*$f(x)$ passes through each point

*the tangent line to $f(x)$ at $p_t$ satisfies the given equation

Now I know how to find a tangent line at a point on a function. What I'm less sure of is how to find the coefficients (and this is definitely not a linear regression problem).
This is a calculus I test question for which I don't have a specific example, and don't seem to know the magic google words to find one... In the actual case, I doubt this will be more than cubic in $x$, since this is a no-calculator test situation, but I'd still like to know the approach for arbitrary $n$
For the sake of argument, lets say the example polynomial is $ax^3 + bx^2 + cx + d$

A: The big trick in polynomial interpolation problems uses the function:
$$g(x)=(x-x_1)(x-x_2)\dots(x-x_n)$$
Note that this function is zero at each $x_n$ (and nowhere else). Also, $g'(x)=\sum_{i=1}^n \frac{g(x)}{x-x_i}$ (where the division is intended to cancel out the extra factor, so that it is defined even at each $x_i$).
If I divide $g(x)$ by $g(x^*)$ for some $x^*$ which is not equal to any $x_n$, I get a function that is $1$ at $x^*$ and $0$ at $x_i$. Adding functions of this form multiplied by scalars allows us to solve the problem of finding a polynomial which goes through $x_i,y_i$ (just take $\sum_{i=1}^ny_ig_i(x)$ where $g_i$ is zero for $x_j,j\ne i$ and one at $x_i$).
To get the derivative right at some specified $x^*$, just add to this expression $a\frac{g^*(x)}{{g^*}'(x^*)}$ where $g^*(x)$ is zero at each $x_i$ and at $x^*$; since $g^*(x)$ has a single root at $x^*$ its derivative there is nonzero, so the derivative of this part of the function is $a$, and we can set $a$ to be the desired derivative minus the derivative of the point-interpolation part of the function.

To give an example, let's find a polynomial such that $f(-2)=1$, $f(-1)=0$, $f'(0)=4$, $f(2)=2$. (I just made these numbers up.) First let's ignore the derivative part and construct functions that are zero at two of the points and one at the remaining point:
$$g_1(x)=\frac{(x+1)(x-2)}{(-2+1)(-2-2)}=\frac{x^2-x-2}{4}$$
$$g_2(x)=\frac{(x+2)(x-2)}{(-1+2)(-1-2)}=\frac{-x^2+4}{3}$$
$$g_3(x)=\frac{(x+2)(x+1)}{(2+2)(2+1)}=\frac{x^2+3x+1}{12}$$
Then $h(x)=g_1(x)+0g_2(x)+2g_3(x)=\frac{5x^2+3x-2}{12}$ satisfies $h(-2)=1$, $h(-1)=0$, $h(2)=2$. But it probably has the wrong derivative: $h'(x)=\frac{10x+3}{12}$, so $h'(0)=\frac14$ is not what we want. So let's construct a function which won't affect our other values, but has a nonzero derivative at $0$:
$$g^*(x)=(x+2)(x+1)(x-2)=x^3+x^2-4x-4\implies {g^*}'(x)=3x^2+2x-4$$
So ${g^*}'(0)=-4$. (It is possible for this to come out zero, in which case you can multiply the formula by $x-x^*$ to guarantee nonzero derivative at the expense of a higher degree.) Now the $h$ function is off from what we want by $4-\frac14=\frac{15}4$, while the adjustment function has derivative $-4$, so $-\frac{15}{16}{g^*}(x)$ has derivative $4-\frac14$ at $0$ and $f(x)=h(x)-\frac{15}{16}{g^*}(x)=-\frac{15}{16}x^3-\frac{25}{48}x^2+4x+\frac{43}{12}$ should do the trick.


text:
Q: How to download Docker for Windows without creating account at docker.com and logging in? I do not want to register and login to docker.com, docker is open source, right? How can just download it without creating a docker account?

A: I also found that this direct link works without logging in: https://download.docker.com/win/stable/Docker%20Desktop%20Installer.exe

A: You can use docker CE (community edition)
It is published here:
https://download.docker.com/win/static/stable/x86_64/


text:
Q: i am getting this error when i use npx command Error: EPERM: operation not permitted, I am trying to install create-guten-block package using this command npx create-guten-block my-block but i couldn't install it.
my node version: 10.15.1
npm version: 6.4.1
i am getting following error.  what i am doing wrong i am following documentation.

A: Use this command and try again:
npm cache clean --force


text:
Q: What subjects did you do in year 12 or what subjects did you do for year 12? is it
What subjects did you do in year 12 or
what subjects did you do for year 12?
Thanks!

A: Both are acceptable. I'd use the first example (in year 12) for preference. Using "for" suggests purpose (I take these subjects so that I can go to school.)
Some commentators have suggested using "senior year". That would apply only to the American School system, in which "year 12" is the last year of High School. Each school system has different ways of describing the years. In England, year 12 is the first year in the sixth form, and not usually the last year at school.

A: In US usage, I would not expect to see any year described as "year 12" but rather as "12th grade" or "senior year in high school". "Senior year" alone could be confused with "senior year in college" unless the context makes the choice clear.
Also, in US usage, it would be unusual to speak of "doing" a subject. The most common verb would be "take", followed i think by "study", and perhaps then by "have". So, in US usage:

*

*What subjects did you take in 12th grade?

*I took history during my senior year in high school.

*I studied chemistry in the 12th grade.

*I had baseball as my Gym unit.

*I had a term paper mini-course for English last spring.

This is for anyone wating to compare US usage with that of other countries listed in other answers.


text:
Q: de Rahm Laplace operator on forms bounded Let $M$ be a closed differentiable manifold. Let $E^{p}(M)$ be the vector space of $p$-forms on $M$ equipped with the $L^{2}$-inner product $(\alpha, \beta) = \int_{M}\alpha \wedge \star \beta$. The Laplace de Rahm operator is then defined by $\Delta = d^{*}d + dd^{*} : E^{p}(M) \rightarrow E^{p}(M)$. All these definitions are as in the ordinary Hodge theory. Is the operator $\Delta : E^{p}(M) \rightarrow E^{p}(M)$ bounded with respect to the $L^{2}$-inner product? I have not found any literature which treats these kind of questions. Is there any reference concerning functional analytical properties of this operator (spectrum etc....)?
Luigi

A: Differential operators are never bounded unless they are of order zero.
Standard references are Berline, Getzler, Vergne, "Heat Kernels and Dirac Operators" and Gilkey, "Invariance Theory, The Heat Equation and the Atiyah-Singer Index Theorem".
Your operator is an example of a general Laplace-type operator, which is a differential operator $L$ acting on a vector bundle $\mathcal{V}$ whose principal symbol is given by
$$ \sigma(L, \xi) = - |\xi|^2 \cdot \mathrm{id},$$
where $\mathrm{id}$ denotes the identity endomorphism of your bundle.
All these operators (if they are symmetric on smooth sections with respect to the $L^2$ inner product) have in common that they are unbounded on $L^2(M, \mathcal{V})$ and self-adjoint on the domain $H^2(M, \mathcal{V})$ (the Sobolev space of order $2$), given that your manifold is compact. Furthermore, they have a compact resolvent.
If the manifold is non-compact, the resolvent will usually not be compact, but in good cases (there are curvature assumption to be made, if I am not mistaken, and assumptions on the potential if you have one), the operator is still self-adjoint on $H^2(M, \mathcal{V})$ and has spectrum bounded from below.


text:
Q: Forward a thread of messages in Mail In Mail on Mac OS X Lion, is there a way to select an entire thread of messages and forward them to someone in a single e-mail?
Ideally I'm looking for a simple command in Mail (press ⌘ while selecting, or something like that), but I'm open to a more complex (AppleScript?) solution.

A: One thing you could do is start a new mail message to your recipient, then select the messages that you want to forward and drag them over to the new mail. They will be sent as attachments to your desired recipient.

A: It sounds like things have changed in Lion - I'm running 10.6.8 - but with threading enabled in Mail.app it's easy.  Select the thread header (which shows the subjects listed in the viewer window below) and press Shift + ⌘ + F. The messages and contents, attachments, etc. are compiled into one new email, ready to be forwarded to a new recipient or group.


text:
Q: using mod and equality to on right hand side of equation I am having trouble understanding this piece of code where it is setting the value for vals[i].
for(int i = 0; i < 100; i++)
    vals[i] = (i%4==1)*255;

Any help into understanding this would be greatly appreciated!

A: Thank you to the the ones who left comments.
I concluded that this code
(i % 4 == 1) * 255

is pretty much an inline if without using the keyword.
Here are my testing notes in case it might help someone else.
int main()
{
    int size = 50;
    for (int i = 0; i < size; i++)
    {
        int val = i % 4 == 1 * 255;
        printf("%d) %d\n", i, val);
        // Output: Zero for every index
    }
    printf("\n--------------------\n");     // just for some spacing for readability
    for (int i = 0; i < size; i++)
    {
        int val = (i % 4 == 1) * 255;
        printf("%d) %d\n", i, val);
        // Output...
        // 1) 255
        // 5) 255
        // 9) 255
        //...
    }
    printf("\n--------------------\n");     // just for some spacing for readability
    // This is a bit easier for me to understand, and it gives the same results as above
    for (int i = 0; i < size; i++)
    {
        int val = 0;
        if (i % 4 == 1)
            val = 255;
        printf("%d) %d\n", i, val);
        // Output...
        // 1) 255
        // 5) 255
        // 9) 255
        //...
    }
    return 0;
}


text:
Q: Powershell - Comparing and overriding a folder I am trying to create a powershell script to compare 1 folder to another, say Folder A to Folder B. I want my script to make folder B look exactly like Folder A every time this script runs. Overriding anything in there, and deleting anything in Folder B that is not in Folder A. I have no code for it yet, and everything ive tried does not work. I made a script that copies from Folder A to Folder B and it works but wont delete anything different and wont override a file. So if its already in there, it doesn't care that the item in Folder A is newer, it will keep Folder B old file:
Test-Path "C:\Users\Shawn\Desktop\Scripts\New Folder"
if((Test-Path True))
{
    Copy-Item -Path "C:\Users\Shawn\Pictures\" -Destination "C:\Users\Shawn\Desktop\Scripts\New Folder" -recurse
}

else

{
    New-Item -Path "C:\Users\Shawn\Desktop\Scripts\New Folder" -ItemType directory
    Copy-Item -Path "C:\Users\Shawn\Pictures\" -Destination "C:\Users\Shawn\Desktop\Scripts\New Folder" -recurse
}


text:
Q: How to use Azure databricks to read and write excel data with multiple sheets from ADLS gen 2 I want to implement the below logic in Azure databricks using pyspark.
I have a below file which has multiple sheets in it. the file is present on adls gen 2.
I want to read the data of all sheets into a different file and write the file to some location in adls gen 2 itself.
Note: All sheet has same schema ( Id, Name)
My final output file should have data from all the sheets. Also I need to create an additional column which stores the sheetName info

A: You can use the following logic

*

*Using Pandas to  read multiple worksheets of the same workbook link

*concat the multiple dataframes in Pandas and make it single data frame link

*Convert the Panda dataframe into pyspark dataframe .link

*Apply Business logic which you want to implement.


text:
Q: Best way to store SQL scripts and Power BI files in Azure Repos I would like to know what would be the best way to keep and transfer my SQL Server database scripts (views, trigger, ...)  and my files (dataset and reports) from Power BI in Azure Devops/Repo using GIT.
With the .NET environment, I'm used to building an solution (.sln) in Visual Studio 2019 but I'm less familiar with SQL scripts and Power BI files.
I did try to create a Visual Studio solution for my SQL Scripts and put them directly into Azure Repos directly by uploading them in the service. However, when I click back on my files SQL in Visual Studio, I can't see the scripts? It looks like they are not in the right solution/projet format. It doesn't load as usual and visual studio closes. The scripts are in a directory called 'Miscellaneous' in my Visual studio solution.
Maybe I didn't choose the right solution? And if so, which one should I choose and how can I go back in breaking my histories in Azure Repos.
Thank you

A: for your database objects (views/procs etc) you really need to add the whole database to your visual studio solution.
Right click on the solution in VS

*

*Add new project

*SQL Server | SQL Server Database Project (Choose a name and location to save it)

*OK

Then Right click on the project

*

*Import

*Import database

*Connect to your DB

*Start

Side note: to make the database project as close as you can to what you see in SSMS, before import,

*

*go to properties of database project

*check box Include schema name in filename

*When you import make sure Folder Structure: is set to Object type

PowerBI files, PBIX still sucks to add to source control as they are binary (zip)  and contain the data.  I'm not sure if there is a "useful" way to add pbix to source control


text:
Q: JQuery Autocomplete - Different color text based on value I'm trying to look through the jquery-ui.js file at the autocomplete function. I have autocomplete working just as I would like, however I would like to add a feature. I would like the color of the results to change for that single line item based on the value.
For example if the text value contains the substring test, the color of the text should be red instead of what is defined using the css color.

A: Found the answer. I had to edit this part of the code in the auto complete section of the file. I added a check that looked at the item.label value, if the value called for a color change I added the red style to the anchor tag (style="color:red;").
_renderItem: function( ul, item ) {
        return $( "<li>" )
        .append( $( "<a>" ).text( item.label ) )
        .appendTo( ul );
},


text:
Q: Reducing Second-Order Partial Differential Equation to Canonical Form I want to reduce the following equation to canonical form and to find general solution.
$$u_{xx} + 2u_{xy} +u_{yy} = 0$$
I found canonical form as $4u_{\eta\eta}+3u_{\xi\eta}=0.$ Is it right?
But I can' t find general solution from the canonical form.
Please help.
Thanks.

A: The Characteristic equation $$\big(\frac{d y}{d x}\big)^2-2\frac{d y}{d x}+1=0$$ gives only one characteristic curve, $$y-x=constant.$$ So, taking $\xi=y-x$ and $\eta=y$, the given equation reduces to $$u_{\eta \eta}=0.$$


text:
Q: How to figure out lambdas that are contributing to my invocation counts/costs I have 2 dozen lambdas. I noticed my bill was high this month and I see have 700k invocations. Is there an easy way to view all the stats for all my lambdas in one view, and 'sort by invocations within period'? This kind of dashboard would be very valuable.

A: You can go to Cloudwatch Metrics to get a list of invocations across all your lambdas. This will not give you a count but rather stats over your desired period and should help you arrive at the what lambda has greater invocations.
Just hit up this url.
You should see a list all of all the lambdas that you have in your account in us-east-1.
If your region is something else change the region.
And then select all the lambdas. On the top you should see a way to specify the time, limit that to say a few weeks or even a month. I have set it to the last 4 weeks in the URL.
In the graphed metrics make sure you set the Statistics Field to "Sum" to ensure you see a sum of invocations.
This should give you an idea of what Lambdas are invoking the most.
However this is part of the story.
The duration that a lambda executes for also matters you can use this url to figure out the duration of lambda executions over time.
These two metrics should help you get to the bottom of what lambda is the most invocations or is being executed with the longest duration.
If you want to automate this, you can also get actual stats in scripts  by using the list metrics and get metric statistics clis.

A: You can use a serverless monitoring service like Dashbird to get the exact cost of any AWS Lambda function and also the insights to optimise those costs.


text:
Q: I want to integrate spherical bessel function but it is not coverging L = (1/.197)10;
p = Table[i, {i, 1, 50}];
Roots of spherical bessel function
ap = Table[N[BesselJZero[3/2, i]], {i, Length[p]}];
Integration of spherical bessel function
NP = Table[ Integrate[SphericalBesselJ[1, (ap[[i]] x)/L]^2x^2, {x, 0, L}], {i, Length[p]}];

A: I am using
"12.0.0 for Linux x86 (64-bit) (April 7, 2019)"

We have:
L = (1/.197) 10;
p = Table[i, {i, 1, 50}];
ap = Table[N[BesselJZero[3/2, i]], {i, Length[p]}]

First we do the numerical integration
NP = Table[
   NIntegrate[
    SphericalBesselJ[1, (ap[[i]] x)/L]^2 x^2, {x, 0, L}], {i,
    Length[p]}];

Now we integrate analytically
analytics =
  Table[Integrate[SphericalBesselJ[1, (ap[[i]] x)/L]^2 x^2, {x, 0, L},
     PrincipalValue -> True], {i, Length[p]}];

Finally we compare the results
NP - analytics // Chop

and we get

{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0}


text:
Q: Data table and any function I have 3 variabes (world, place and group). There are 3 groups: 1,2 and 3. If any of the group observations has an observation with place==1, then I want to mark all the observations of that group as TRUE. I have been trying to use the function any and the inside data table join J but it has not worked. Can anyone explain why and how to do it?
Intended output: group 2 has no observation with place == 1, so place1_group should be FALSE. The other groups should have place1_group as TRUE.
df2 <-structure(list(world = structure(c(1L, 2L, 3L, 3L, 3L, 5L, 1L,
                                         4L, 2L, 4L), .Label = c("AB", "AC", "AD", "AE", "AF"), class = "factor"),
                     place = c(1, 1, 2, 2, 3, 3, 1, 2, 3, 1),
                     group = c(1,1, 1, 2, 2, 2, 3, 3, 3, 3)), .Names = c("world", "place","group"), row.names = c(NA, -10L), class = "data.frame")

df2 <- data.table(df2)
setDT(df2)
setkey(df2, group)

# Two step approach
df2[,place1:=FALSE][place==1,place1:= TRUE]
df2[,place1_group := FALSE][any(place1), place1_group := TRUE, by = group] # Not working, place1_group TRUE for all but it should be FALSE for group==2

# Inside join approach
df2[,test := "No place 1"][J(any(place1),by=group),test:="Yes Place 1", by=group] # Why it does not work for group 3?

A: I would use dplyr for this:
df.new <- df2 %>%
          group_by(group) %>%
          mutate(tf = any(place == 1))

This should mark the entire group as either TRUE or FALSE.
You may also have to
df.new <- data.table(df.new)

A: df2[,place1_group:=any(place==1),group][]
#     world place group place1_group
#  1:    AB     1     1         TRUE
#  2:    AC     1     1         TRUE
#  3:    AD     2     1         TRUE
#  4:    AD     2     2        FALSE
#  5:    AD     3     2        FALSE
#  6:    AF     3     2        FALSE
#  7:    AB     1     3         TRUE
#  8:    AE     2     3         TRUE
#  9:    AC     3     3         TRUE
# 10:    AE     1     3         TRUE


text:
Q: How to insert literal identifier from input pattern as symbol in syntax-rules macro I have code like this:
(define-syntax macron
  (syntax-rules ()
    ((_ name)
     (lambda (x)
       (eval (cons 'name x) (interaction-environment))))))

(define x (map (macron lambda)
               '(((x) (display x)) ((a b) (+ a b)))))

(let ((square (car x))
      (sum (cadr x)))
  (display (square 10))
  (newline)
  (display (sum 1 2 3))
  (newline))

the code is working it use macro as value by wrapping it with lambda. My question is how can I put inside syntax-rule macro literal symbol 'name instead of (cons 'lambda ...) so the output code is:
(lambda (x)
  (eval (cons 'name x) (interaction-environment)))

so it work with code like this:
(define (name x)
  (display x)
  (newline))

(for-each (macron lambda) ;; lambda can be anything
          '((1) (2) (3)))

and it print all the numbers.
I know that I can change the name in pattern into something else, but I want to know more about syntax-rules and it's edge cases. So is it possible to have name if I use it as input pattern?
I'm looking for answers with R7RS, that have more of this type of edge cases covered.

A: All macros happens in compile time so runtime stuff might not exist. That means that you should think of it as syntax sugar and use it as susch. eg.
(for-each (macron something) '((1) (2) (3)))

Should then have an expansion based on that. Your current expansion is that it turns into this:
(for-each (lambda (x)
            (eval (cons 'someting x) (interaction-environment))
          '((1) (2) (3)))

For something being a macro this will apply the macro in runtime. It is bad. It also removes the need for the macro in the first place. You could do this instead:
(define (macron-proc name)
  (lambda (x)
    (eval (cons name x) (interaction-environment))))

(for-each (macron-proc 'something) '((1) (2) (3)))

I made a programming language that had passable macros:
(define xor (flambda (a b) `(if ,a (not ,b) ,b)))
(define (fold comb init lst)
  (if (null? lst)
      init
      (fold comb (comb (car lst) init) (cdr lst))))
(fold xor #f '(#t #t)) ; ==> #f

It's not a very good approach if you are targeting an efficient compiled end product. The first macros were indeed like this and they removed it in LISP 1.5 before Common Lisp. Scheme avoided macros for many years and opted for syntax-rules in R4RS as an optional feature. R6RS is the only version that has full power macros.
With a procedure instead of macros this is actually the same as the following code with the bad eval removed:
(for-each (lambda (x)
            (apply something x))
          '((1) (2) (3)))

Which means you can implement macron much easier:
(define-syntax macron
  (syntax-rules ()
    ((_ name)
     (lambda (x)
       (apply name x)))))

But from looking at this now you don't need a macro at all. This is partial application.
(define (partial proc arg)
  (lambda (lst)
    (apply proc arh lst)))

(map (partial + 3) '((1 2) (3 4) (4 5)))
; ==> (6 10 12)

There is actually a SRFI-26 called cut/cute which allows us to do something similar where it wraps it in a lambda:
(map (cut apply + 3 <>) '((1 2) (3 4) (4 5)))

The syntax-rules are the macros with the least power. You cannot do anything unhygienic and you cannot make new identifiers based on other ones. Eg. it' impossible to implement a racket style struct where you can do (struct complex [real imag]) and have the macro create complex?, complex-real, and complex-imag as procedures.  You need to do as SRFI-57 does and require th euser to specify all the names such that you don't need to concatenate to new identifiers.
Right now R7RS-small only has syntax-rules. I think it was a mistake not to have a more powerful macro as an alternative since now the R7RS-large cannot be implemented with R7RS-small.


text:
Q: Fail to sent mail PHP recaptcha I have an issue with recaptcha, Its not sending the mail, even when if I have enter the code correctly, I have try so many times and I have even got someone else to try it and another person and secondly in my contact.php

A: Your variable is $response, but you're checking to see if $resp is not valid. Change this:
    if (!($resp->is_valid)) {
        $captchaErrorMsg = true;
    }

To
    if (!($response->is_valid)) {
        $captchaErrorMsg = true;
    }

A: The problem might be the way you're checking value of $captchaerrorMsg.
<?php if ($captchaErrorMsg){ ?>

Please enter correct verification code.

<?php } ?>

PHP does evaluate what it think you're checking when you don't clearly specify what it is. Therefore does the above code also run when $captchaErrorMsg is 1, when it is true or even when the variable just contains a character, like 'x'.
You only want to run the above code when error message is true, therefore you could do like this:
<?php if ($captchaErrorMsg === true){ ?>

Please enter correct verification code.

<?php } ?>

If it still doesn't work, you will have to figure out the actual value you're getting. Just do a var_dump of the variable like this:
var_dump($captchaErrorMsg);

If this doesn't work, look at this workaround at weird reCaptcha error in PHP


text:
Q: Cannot Increment Product count stored in a nested Dictionary - Pyhton OOP So, I am working on my OOP concepts and knowledge by creating dummy projects. Right now I am creating like an online shopping system where admins can upload different products and users can purchase products.
I am having problems with this specific feature where I want to increment product count.
Product Class:
class Product:
  def __init__(self, product_name, description, price, company, product_count):
   self.product_name = product_name
   self.description = description
   self.price = price
   self.company = company
   self.product_count = product_count

and that is how you create a product:
#CREATE PRODUCT
laptop = Product('Dell Inspiron', 'Dell Inspiron with 8GB ram', 1500, 'DELL', 100)
tv = Product('Sony TV', 'Best Sony TV Ever', 2000, 'Sony', 100)
smartwatch = Product('Fossil 6 Gen Smartwatch', 'Fossil watch with wear OS', 300, 'Fossil',100)
shoes = Product('Running shoes', 'Medium size running shoes', 100, 'Nike',100)
gloves = Product('Rock CLimbing gloves', 'Medium gloves for rock clmbing', 250, 'Timberland',100)

Only Admin can upload products and I am storing them in a dictionary:
Admin Class:
class Admin:
  def __init__(self, name):
    self.name = name
    self.products = {}
    self.order = {}
    self.total_products = 0
    self.orders_recieved = {}
    self.order_status = 'Order Recieved'

Logic to add_products:
def add_products(self, product):
    if product not in self.products:
      self.products[product.product_name] = {
        'name':product.product_name,
        'description':product.description,
        'price': product.price,
        'company':product.company,
        'count':product.product_count
      }
      if product not in s.site_products:  #I am also storing all products in different dict() ignore this
        s.site_products[product.product_name] = {
          'name':product.product_name,
          'description':product.description,
          'price': product.price,
          'company':product.company,
          'count':product.product_count
        }
      s.product_total += 1
      self.total_products += 1
    else:
      product.product_count += product.product_count

      print('Product already exists')

#This is how you add products:
admin1.add_products(laptop)
admin1.add_products(laptop)

admin1.add_products(tv)
admin1.add_products(smartwatch)

admin2.add_products(shoes)
admin2.add_products(gloves)

Admin has to pass in the product created using Product class in add_Product function(). What I want to do is when an Admin tries to upload the same product twice, only its count changes by adding the previous count and the new one.
But for some reason I am unable to do that I have tried multiple ways but still stuck on it. It is probably something very simple that I am missing out.
Thanks in advance!

A: Your check for whether a product is already in the dictionary uses the product object rather than its product_name attribute, which is the key you use to add items to the dictionary.
If you change that line, it should work.
Test code:
class Product:
    def __init__(self, product_name, description, price, company, product_count):
        self.product_name = product_name
        self.description = description
        self.price = price
        self.company = company
        self.product_count = product_count
class Admin:
    def __init__(self, name):
        self.name = name
        self.products = {}
        self.total_products = 0
    def add_products(self, product):
        if product.product_name not in self.products:
            self.products[product.product_name] = {
                'name':product.product_name,
                'description':product.description,
                'price': product.price,
                'company':product.company,
                'count':product.product_count
             }
            self.total_products += 1
        else:
            self.products[product.product_name]['count'] += product.product_count
            print('Product already exists')
a = Admin("foo")
print('try a product')
a.add_products(Product('Dell Inspiron', 'Dell Inspiron with 8GB ram', 1500, 'DELL', 100))
print('try it again')
a.add_products(Product('Dell Inspiron', 'Dell Inspiron with 8GB ram', 1500, 'DELL', 100))

Output:
try a product
try it again
Product already exists


text:
Q: How do I kill a process and ensure that port bindings are cleaned up? I have a situation where I kill a process, but when restarting it, I get the Address already in use error.
I am running sudo netstat -lntp to get the process ID, which returns, for example:
tcp        0      0 0.0.0.0:8002            0.0.0.0:*               LISTEN       475/valhalla_servic

I then run  sudo kill -9 475
After running this, netstat no longer shows the process, but when I try to restart I receive the Address already in use error and I'm not sure what I'm doing wrong?

A:
I'm not sure what I'm doing wrong?

Good news: nothing.
The TCP state machine has timeout conditions. For that reason, ports linger a while, by default.
As a user of some software, there's not much you can do about that - not letting arbitrary software instantly rebind a port is, in the end, also a security feature.
As a developer of the software, you can set SO_LINGER to 0. It is, in most cases, not the right thing to do – especially not when you do actually kill the owning process.