text:
Q: Using riverpod for simple state management is not reading state changes at UI I'm moving to Riverpod and starting with what should be a very simple boolean state management to switch the app theme.  I've read many "how to" to do this exact thing, but none focus on the basics itself, are using outdated API, use different notifiers and providers, and add more features than needed.  So now I'm lost.
versions:

*

*shared_preferences: ^2.0.13

*flutter_riverpod: ^1.0.3

Simple story:

*

*A model class that extends StateNotifier and has accessor and mutators in it for 1 single boolean value

*Very basic app + stateful widget

Problem: I can see, via prints, the state is being altered, but the UI is not changing to when the state is changed.  Am I not using StateNotifier and StateProvider properly for a simple boolean state?
Thank you for any insight and guidance!   Code follows:
===
model class with accessors / mutators

class RiverThemeDarkModel  extends StateNotifier<bool> {

  RiverThemeDarkModel() : super(false) {}

  bool get isDark  {
    print("model asked for dark status: ${state}");
    return state;
  }

  toggleDark() {
    print("toggler has listeners: ${hasListeners}");
    state = !state;
    print("toggled to: ${state}");
  }

  set isDark(bool value) {
    state = value;
  }

}

Very basic app + stateful widget

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

void main() {

  runApp(ProviderScope(child: MyApp()));
}

final themeProvider = StateProvider((ref) =>  RiverThemeDarkModel());

class MyApp extends ConsumerWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) {

    final darkValueModel = ref.watch(themeProvider);

     print("consumer widget: dark value is ${darkValueModel.state} and listeners: ${darkValueModel.hasListeners}");
          return MaterialApp(
            title: 'Flutter Demo',
            debugShowCheckedModeBanner: false,
            theme: darkValueModel.isDark? ThemeData.dark() : ThemeData.light(),
            home: const MyHomePage(title: 'Flutter Demo Home Page'),
          );
        }

}

class MyHomePage extends ConsumerStatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  ConsumerState<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends ConsumerState<MyHomePage> {

  @override
  Widget build(BuildContext context) {
    final darkValueModel = ref.watch(themeProvider);
print("build of state");
      return Scaffold(
        appBar: AppBar(
          title: Text(darkValueModel.isDark ? "Dark Mode" : "Light Mode"),
          actions: [
            IconButton(
                icon: Icon(darkValueModel.isDark
                    ? Icons.nightlight_round
                    : Icons.wb_sunny),
                onPressed: () {
                  ref.read(themeProvider).toggleDark();
                  print("Got pressed button, after setting is ${ref.read(themeProvider).isDark} \n\n");
                })
          ],
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              const Text(
                'Something',
              ),
            ],
          ),
        ),
      );
    }
}

A: From your code snippet, what you did here
final themeProvider = StateProvider((ref) =>  RiverThemeDarkModel());

was to provide to your UI access to the default state of your class which is false. thus if you change it to true and rerun the app it changes the theme. now what you want to do is expose access to the stateNotifier of your class which listens to the state changes of the class and notifies its listeners. To achieve this you need to use a StateNotifierProvider this way...
final themeProvider = StateNotifierProvider<RiverThemeDarkModel, bool>(
        (ref) =>  RiverThemeDarkModel());

Now the rest of the code to help your implementation is as follows
For your Model.
class RiverThemeDarkModel  extends StateNotifier<bool> {

  RiverThemeDarkModel() : super(false) {}

//u don't need this 'getter' piece of code
  bool get isDark  {
    print("model asked for dark status: ${state}");
    return state;
  }

  toggleDark() {
    print("toggler has listeners: ${hasListeners}");
    state = !state;
    print("toggled to: ${state}");
  }

//neither do you need this
  set isDark(bool value) {
    state = value;
  }

}

For your UI...
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

void main() {

  runApp(ProviderScope(child: MyApp()));
}

final themeProvider = StateNotifierProvider<RiverThemeDarkModel, bool>(
        (ref) =>  RiverThemeDarkModel());

class MyApp extends ConsumerWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) {

    final darkValueModel = ref.watch(themeProvider);

     print("consumer widget: dark value is ${darkValueModel.state} and listeners: ${darkValueModel.hasListeners}");
          return MaterialApp(
            title: 'Flutter Demo',
            debugShowCheckedModeBanner: false,
            theme: darkValueModel? ThemeData.dark() : ThemeData.light(),
            home: const MyHomePage(title: 'Flutter Demo Home Page'),
          );
        }

}

class MyHomePage extends ConsumerStatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  ConsumerState<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends ConsumerState<MyHomePage> {

  @override
  Widget build(BuildContext context) {
    final darkValueModel = ref.watch(themeProvider);
print("build of state");
      return Scaffold(
        appBar: AppBar(
          title: Text(darkValueModel ? "Dark Mode" : "Light Mode"),
          actions: [
            IconButton(
                icon: Icon(darkValueModel
                    ? Icons.nightlight_round
                    : Icons.wb_sunny),
                onPressed: () {
                  ref.read(themeProvider.notifier).toggleDark();
                  print("Got pressed button, after setting is ${ref.read(themeProvider)} \n\n");
                })
          ],
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              const Text(
                'Something',
              ),
            ],
          ),
        ),
      );
    }
}

Check out the documentation too. It clarifies some things you won't get from most tutorials. https://riverpod.dev/docs/concepts/reading

A:
use this
final themeProvider = StateNotifierProvider<RiverThemeDarkModel, bool>(
    (ref) => RiverThemeDarkModel());

Instead of this
final themeProvider = StateProvider(
(ref) => RiverThemeDarkModel());
Small Change on your code
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

void main() {
  runApp(ProviderScope(child: MyApp()));
}

final themeProvider = StateNotifierProvider<RiverThemeDarkModel, bool>(
    (ref) => RiverThemeDarkModel());

class MyApp extends ConsumerWidget {
   MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final darkValueModel = ref.watch(themeProvider);

    print(
        "consumer widget: dark value is ${ref.read(themeProvider.notifier).state} and listeners: ${ref.read(themeProvider.notifier).hasListeners}");
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme:darkValueModel
          ? ThemeData.dark()
          : ThemeData.light(),
      home:  MyHomePage(title: 'Flutter Demo Home Page${ref.read(themeProvider.notifier).isDark}'),
    );
  }
}

class MyHomePage extends ConsumerStatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  ConsumerState<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends ConsumerState<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    final darkValueModel = ref.watch(themeProvider);
    print("build of state");
    return Scaffold(

      appBar: AppBar(
        title: Text(ref.read(themeProvider.notifier).isDark
            ? "Dark Mode${widget.title}"
            : "Light Mode"),
        actions: [
          IconButton(
              icon: Icon(ref.read(themeProvider.notifier).isDark
                  ? Icons.nightlight_round
                  : Icons.wb_sunny),
              onPressed: () {
                ref.read(themeProvider.notifier).toggleDark();
                print(
                    "Got pressed button, after setting is ${ref.read(themeProvider.notifier).isDark} \n\n");
              })
        ],
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              "Something ${ref.read(themeProvider.notifier).isDark} ",
            ),
          ],
        ),
      ),
    );
  }
}

class RiverThemeDarkModel extends StateNotifier<bool> {
  RiverThemeDarkModel() : super(false) {}

  bool get isDark {
    print("model asked for dark status: ${state}");
    return state;
  }

  toggleDark() {
    print("toggler has listeners: ${hasListeners}");
    state = !state;
    print("toggled to: ${state}");
  }

  set isDark(bool value) {
    state = value;
  }
}


text:
Q: Select item from PowerShell hashtable without using Foreach I have this list of PSObjects, each of which contains a Hashtable. Currently I can get it out like this:
foreach ($item in $myListOfItems) { $item.Metadata["Title"] }

However, I am wondering if I can do it somehow with piping and Select. Is this possible?  For example:
$myListOfItems | Select $_.Metadata["Title"]

...which only outputs a whole bunch of blank lines :(
Any ideas? Thanks so much in advance!

A: What about
$myListOfItems | select @{ Label="Title";Expression={$_.Metadata["Title"]}}

A: The original idea was close but just got the syntax wrong. To use $_, the expression must be within a script-block parameter (Powershell V3+):
 $myListOfItems | select { $_.Metadata["title"] }

Without the enclosing script-block, $_ is evaluated in the context of the whole pipeline instead of the pipeline element (Select-Object in this case). At this level, $_ is not defined so evaluates to $null. PowerShell is somewhat forgiving about using $null inappropriately. In particular, attempting to retrieve a property of $null is not an error, it just returns $null. So $null.Metadata["title"] → $null["title"] → $null. Select-Object $null just outputs an empty selection object for each input object thus resulting in the blank lines.
It should be noted that, strictly speaking, neither the originally suggested Select-Object (as fixed) nor the hash table version in the answer provide the same output as the ForEach loop. The loop produces a sequence of values from the .Metadata["Title"] members while Select-Object produces a sequence of selection objects [Selected.System.Collections.Hashtable] each containing a member (named $_.Metadata["Title"] and Title respectively) which holds the value. Whether this causes a problem depends on the usage.
For a really short version, try:
$myListOfItems.Metadata.Title

Since PowerShell V3, specifying a non-existent member of a collection causes Powershell to perform a member enumeration† whereby it would enumerate the collection and return a sequence of values of the specified member of each element of the collection (assuming there is one). If we assume left to right evaluation then the expression would be evaluated as:
($myListOfItems.Metadata).Title

Firstly enumerating the collection of items, as it has no Metadata member. Each item does have a Metadata member thus resulting in an Array of the Metadata members. Then this collection of Metadata hashtables, having no Title member, is enumerated to produce an Array of the Title elements of the hashtables.
† I think the term member enumeration is somewhat misleading. It is not the members which are being enumerated but the objects in the collection and an Array of the specified member of each object is then created. Indeed, even though the manual about_Hash_Tables states that the hash table has properties named after the keys with corresponding values, this is actually just Powershell shorthand for invoking the indexer [] (which actually appears to override member access so beware of hash tables with keys "Count", "Keys", "Values", ... if you want to access the actual hash table members of these names). So, strictly speaking, there is no 'Title' member. The term "enumerated collection member access" (ECMA ;) would better describe what is happening but after all "A rose by any other name".

redpajama_set_name: RedPajamaStackExchange


text:
Q: Terraform: Move entire resource group to new Azure subscription A historically grown project with it's associated infrastructure on Azure must be split up. Luckily, it is well structured and as a result it is pretty clear that we need to move two resource groups and it's affiliated resources to a new Azure subscription.

*

*I have checked, most of the resource can be moved, thus don't have to be created anew and data can be preserved.

*For those resources that cannot be moved, luckily we are using terraform, which can be run to re-create those resources.

*The resources that need to be moved is an entire terraform-project, so there is no need to remove resources from the current configuration files. All of it needs to go to a new subscription.
So far so good, but now I need to understand how to practically proceed, so that terraform is aware of the moved resources. The only option I currently see is to manually move the resources on the Azure portal, change subscription on the CLI/for terraform and then run an terraform state rm; terraform import or a terraform mv for each of the resources.
Isn't there an easier way to achieve this? It seems overly cumbersome and basically would make it easier to just delete the entire infrastructure in the current subscription and recreate it via terraform in the new subscription (not an option!)

A: It is NOT possible to move resources from one resource group to another simply via changing resource_group_name parameter in *tf file. Terraform 1.0.2 will attempt to destroy such a resource, therefore trying to setup a multi-subscription terraform workspace is futile. Also as docs say:

resource_group_name - (Required) The name of the Resource Group in
which the Linux Virtual Machine should be exist. Changing this forces
a new resource to be created.

TL;DR - there is no native mechanism for migrating Azure resources between resource groups or subscriptions via terraform
As you point out, moving resources manually and retaining them in Terraform would require some state file manipulation. Fortunately Azure resource IDs are pretty straightforward, so a simple string processing in bash can do the trick.
Quick and dirty bash script could just replace old subscription UUID with new and be similar to this (WARNING - Correct implementation depends on your setup - do some testing before running all the statements):
# Extract the identifying URLs using terraform plan
terraform  plan | grep "Refreshing state" > terraform-current-states.txt
# Extract the states we know from the configuration
terraform state list > terraform-state-list.txt

# Subscription strings
OLD_SUBSCRIPTION=11111111-1111-1111-1111-111111111111
NEW_SUBSCRIPTION=00000000-0000-0000-0000-000000000000
# Resource group strings (other name)
OLD_RG='SOME_NAME'
NEW_RG='ANOTHER_NAME'

# Iterate over state list
cat terraform-state-list.txt | while read RESOURCE; do
  AZURE_ID=$(grep "${RESOURCE}"  terraform-current-states.txt | cut -d"=" -f2 | tr -d ']')

  # null resources etc can be filtered out - no AZURE_ID
  if [ -z "$AZURE_ID" ]; then
    continue
  fi

  # print out the current resource and azure id mapping as a comment
  echo "# ${RESOURCE} ${AZURE_ID}"

  # replace the subscription and resource group strings (and remove weird characters from terraform
  NEW_AZURE_ID=$(echo ${AZURE_ID} | sed "s/${OLD_SUBSCRIPTION}/${NEW_SUBSCRIPTION}/" | sed "s/${OLD_RG}/${NEW_RG}/g" | sed "s/\x1b\[[0-9;]*m//g")

  # replace the current terraform state with a "state rm" and then "import" command
  echo "terraform state rm ${RESOURCE}; terraform import ${RESOURCE} ${NEW_AZURE_ID}
  "
done > terraform-migration-generated-script.sh

The above produces a ready-to-use terraform-migration-generated-script.sh script with terraform rm and terraform import commands.
Don`t forget about state backup or even terraform state pull and push to different location before you start.

A: This been a massive problem for me, but there's official way to do this and it's totally possible. You have to remove the resource from state, and import it again.
Short examples:
Get resource id
$ echo azurerm_autoscale_setting.example.id | terraform console
/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group1/providers/microsoft.insights/autoscalesettings/setting1

Than remove the resource from state:
$ terraform state rm azurerm_autoscale_setting.example
Removed azurerm_autoscale_setting.example
Successfully removed 1 resource instance(s).

Now go to azure portal and move the resource, when you'll be moving, it will be determined if it can be moved. Actually I'd do this first, only then start touching terraform state.
$ terraform import [resourcename].[identifier] [resourceid]

Example:
$ terraform import azurerm_monitor_autoscale_setting.test /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group1/providers/microsoft.insights/autoscalesettings/setting1
azurerm_monitor_autoscale_setting.test: Importing from ID "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group1/providers/microsoft.insights/autoscalesettings/setting1"...
azurerm_monitor_autoscale_setting.test: Import prepared!
  Prepared azurerm_monitor_autoscale_setting for import
azurerm_monitor_autoscale_setting.test: Refreshing state... [id=/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group1/providers/microsoft.insights/autoscalesettings/setting1]

Import successful!

The resources that were imported are shown above. These resources are now in
your Terraform state and will henceforth be managed by Terraform.

And now your terraform plan should not show any changes. Enjoy!
Official manual for azurerm provider how to migrate resources:
https://registry.terraform.io/providers/hashicorp/azurerm/2.35.0/docs/guides/migrating-between-renamed-resources


text:
Q: Multiple Selects With Influxdb I am trying to figure out if it's possible to run multiple select statements on influxdb data. I've looked at continuous queries, but am not sure if it's what I need, or if it even makes sense to use them.
I would like to run:
select * from series group by work_id limit 1;

Then take that data, and run
select * from new_series_from_prior_query where state = 'error'

First question, is this even possible? Second, if not, is there another way to get the desired result using influxdb. Basically I need to filter all work items by their work_id and most recent state. Then, depending on what filters are passed in, check if they match and return that data.
Any help is greatly appreciated. If I cannot get it to work, I will most likely have to switch out the database, would love to stick with influxdb though.

A: Influx just released 1.2 today, which has sub queries, that solve this issue.
SELECT * FROM  (select  * from workflows GROUP BY work_id limit 1) WHERE state = 'processed'.

This is what I was looking for.


text:
Q: How to get sentence after chunking in NLTK? I have a sentence as follow:
txt =  "i am living in the West Bengal and my brother live in New York. My name is John Smith"

What I need is:

*

*Get the Chunks With GPE/location as labels and combine these chunks using "_"

*Get the Chunks With PERSON label and remove those chunks.

Output I needed:
preprocessed_txt =  "i am living in the West_Bengal and my brother live in New_York. My name is "

I use code from NLTK Named Entity recognition to a Python list to get the labels of the chunks.
import nltk
for sent in nltk.sent_tokenize(sentence):
   for chunk in nltk.ne_chunk(nltk.pos_tag(nltk.word_tokenize(sent))):
      if hasattr(chunk, 'label'):
         print(chunk.label(), '_'.join(c[0] for c in chunk))

This returned me the output as:
LOCATION West_Bengal
GPE New_York
PERSON John_Smith

What to do next?

A: This should be all you need:
new = list()
for chunk in nltk.ne_chunk(nltk.pos_tag(tokens)):
  try:
    if chunk.label().lower() == 'person':
      continue
    else:
      new.append('_'.join(c[0] for c in chunk))

  except AttributeError:
    new.append(chunk[0])

print(' '.join(new))


text:
Q: Contar el numero de A de una palabra JavaScript estoy empezando en programación y tengo el siguiente ejercicio:
Función que solicite una frase y diga en un alert cuantas "A" tiene usando un for.
He estado mirando por Internet y veo distintos códigos que no logro entender ni hacer que funcionen.
function contar () {
    var palabra = prompt ("Pon una palabra")
    for(var i=0; i<texto.length; i++){
        if (texto[i] == caracter){
            cont = cont + 1;
            console.log(cont);
        }
    }
}

A: Puedes usar un "match" como este ejemplo
var contar = palabra.match(/a/g).length;
alert(contar);

Y saldrá una alerta indicando el numero de veces que aparece la letra "a".

A: *

*Puedes hacer uso de Array.from para que se transforme el string en un vector cuyos elementos se pueden recorrer

*Una vez que la cadena de texto se transforma en vector recorres cada posición y verificas con === si el elemento en cada vuelta es igual a A

*Hacemos uso de === para verificar que el elemento sea igual en tipo y valor

*Ya para que se haga dinámico, solo basta que a la variable palabra la iguales con la función prompt() para leer y trabajar con el string que ingrese el usuario

Código

    function contar() {
      let palabra = "AnacondaAltaA"
      let palabraFragmentada = Array.from(palabra)
      let contador = 0
      console.log(palabraFragmentada)
      for(i=0; i<palabraFragmentada.length; i++) {
        if(palabraFragmentada[i] === "A") {
          contador++
        }else{
        }
      }
      return contador
    }

    console.log(contar())

O bien puedes trabajar tu solución con el método reduce() el cual reduce un vector de valores y retorna un único valor:

    let palabra = "AnacondaAnaA"

    let convertida = Array.from(palabra)
    let resultado = convertida.reduce((total = 0, elemento) => {
      if(elemento === "A") {
        total = total + 1
      }
      return total
    }, 0)
    console.log(resultado)

Y obtenemos como salida:

3

A: Hay varias formas de hacerlo.. la mas sencilla que se me ocurre es tomar el string y utilizar la funcion match() que te regresa la cantidad de 'a' en forma de arreglo... luego solo tienes que tomar la longitud del arreglo y tienes la cantidad de 'a'... como la respuesta anterior... pero si debes hacerlo con un for.. deberias cambiar lo siguiente en tu funcion..

     function contar () {
        let caracter='a', cont =0;
        var palabra = prompt("Pon una palabra")
        for(var i=0; i<palabra.length; i++){
        if (palabra[i] == caracter){
            cont++
        }
        }
        alert('la cantidad de a es: '+cont)
    }

    contar()

palabra es la variable donde se guarda lo que te insertan en el prompt caracter es la letra que deseas contar.. (vale decir que se diferenciaran mayusculas de minusculas.. si quieres contar las mayusculas debes hacer un toLowerString() de palabra[i])

A: Basándome en lo que tienes hecho, y que dices claramente que debes usar un bucle for, te propongo la siguiente solución comentada y genérica (te valdría para cualquier letra).
He asumido que no necesitas diferenciar mayúsculas de minúsculas, si no es así, con quitar los .toLowerCase() sería suficiente.

function contarLetra(letra) {

  // Pedimos al usuario una palabra. La pasamos a lowercase para no diferenciar mayúsculas de minúsculas
  const palabra = prompt ("Pon una palabra").toLowerCase();

  // Sacamos el comparador como el valor de letra en lowercase para no diferenciar mayúsculas de minúsculas
  const comparador = letra.toLowerCase();

  // inicializamos el valor del conteo a cero.
  let cont = 0;

  // Iteramos sobre los caracteres de la palabra introducida
  // let i=0; es el valor inicial del iterador
  // i < palabra.length; el valor del iterador no debe llegar a la longitud de la palabra
  // i += 1; añade al iterador 1 despues de cada iteración
  for(let i=0; i < palabra.length; i+=1) {

    // Si la letra que estamos evaluando es igual que comparador, añadimos 1 a cont.
    if( palabra[i] === comparador ) cont += 1;
  }

  // Devolvemos el valor de conteo
  return cont;
}

console.log(contarLetra('a'));


text:
Q: window.scrollTo not working in phonegap - alternative solution or workaround? I've written a rather basic js function that programatically and automatically aligns the iPhone keyboard perfectly underneath each and every input field that gets focused (feel free to use it if you like it!). The alignment's primarily handled by window.scroll - a standard method that works in any browser view, except in UIWebView hence phonegap/cordova (2.1). So I need a workaround.
My working code:
function setKeyboardPos(tarId) {

//programmatically: set scroll pos so keyboard aligns perfectly underneath textfield
var elVerticalDistance = $("#"+tarId).offset()["top"]; //i.e. 287
var keyboardHeight = 158;
var heightOfView = document.height; // i.e. 444
var inputHeight = $("#"+tarId).outerHeight();

var viewPortSpace = heightOfView-keyboardHeight; //i.e. 180
var verticalNewSroll = (elVerticalDistance+inputHeight)-viewPortSpace;
if(verticalNewSroll<0) { verticalNewSroll = 0; }
////

    //OK, all done lets go ahead with some actions
    $("#footer").hide(); //hide footer so that the keyboard doesn't push it on top of textfield
    $("#containingDiv").css("bottom","0px"); //remove bottom space for footer
    window.scrollTo(0,verticalNewSroll); //scroll! where the problem starts

}

Working in everything but UIWebView, that is. As I mentioned above, everything works except the window.scrollTo (N.B. some minor changes have been made for the sake of clarity). So does anyone know of an alternative solution or even a good workaround?
Similar questions
window.scrollTo doesn't work in phonegap for IOS
PhoneGap / Cordova scrollTo Ignored
How to add vertical scroll in Phonegap
Above are furthermore three similar questions that somewhat points one in the right direction. One of the answerers mentions the use of css to accomplish this. Can anyone come up with a more concrete example? Another guy suggests anchors but that's not a very pretty solution and doesn't go very well with the rest of my code.

A: After doing some research, I realized window.scrollTo() does actually work in iOS6 with phonegap 2.1, there was something else that failed; for some reason, document.height didn't yield a property of equal proportion within UIwebView so I had to write a small workaround. I'll post the solution and the entire code below for future reference.
function setKeyboardPos(tarId) {

//programmatically: set scroll pos so keyboard aligns perfectly underneath textfield
var elVerticalDistance = $("#"+tarId).offset()["top"];
var keyboardHeight = 157;

if(isNativeApp()) { keyboardHeight = 261; } //I choose to change the keyboard height for the sake of simplicity. Obviously, this value does not correnspond to the actual height of the keyboard but it does the trick
var keyboardTextfieldPadding = 2;
var heightOfView = document.height;
var inputHeight = $("#"+tarId).outerHeight();

var viewPortSpace = heightOfView-keyboardHeight-keyboardTextfieldPadding; //180
var verticalNewSroll = (elVerticalDistance+inputHeight)-viewPortSpace;
if(verticalNewSroll<0) { verticalNewSroll = 0; }
////

//OK, all done lets go ahead with some actions
$("#footer").hide(); //hide footer so that the keyboard doesn't push it on top of textfield
$("#containingDiv").css("bottom","0px"); //remove bottom space for footer
window.scrollTo(0,verticalNewSroll); // perform scroll!

}

function isNativeApp() {

var app = (document.URL.indexOf('http://') === -1) && (document.URL.indexOf('https://') === -1);
if (app) {
    return true; // PhoneGap native application
} else {
    return false; // Web app / safari
}

}

A: you can try and use the animate and scrollTop property to scroll It looks something like this:
$("html, body").animate({ scrollTop: "The value to scroll to" });

Hope this helps.

A: You just need to use this:
$(window).scrollTop(0);


text:
Q: How to find vscode installed path in ubuntu I am trying to change the FileZilla filetype association and set vscode as default for any filetype. I couldn't find installed application path or executable file to give a path. How do I make vscode the default executable for all filetypes?

A: By default, the executable is /usr/bin/code
If for some reason it was installed in a different directory, from a terminal type:
which code

And it will tell you the path to the executable.

A: I wasn't able to find it using
which code

I was able to find it using
whereis code

This is running PopOS 20.04

A: If you used snap to install it, then it will be at /snap/bin/code, but if you didn't use snap or did not find it there, then just execute this command:-
which code


text:
Q: how can i make an html list in jquery or javascript? I want to make a list in HTML and then the user selects the list and then do something with the selections.
For example. List of fruits. Apple bannana, grapes.
User selects grapes and if grapes is selected asked how many grapes?
I would like to know how i can do this in Javascript or Jquery

A: Use this code block. As simple as that,

//generates the list
var items = 'Apple, bannana, grapes';
var nHtml = '';
items = items.split(',');
items.forEach(function(v){
   //trim() will remove the blank spaces
   nHtml+='
'+ v.trim() +'
';
});
$('#itemList').append('
'+ nHtml +'
');

//detect click on the list item
$('li').click(function(){
   var name = $(this).text();
   var question = 'How many '+name+' ?';
   $('#question').html(''+ question +'<input type="text" id="answer" />')
});

//get the number feed into the text box
function getCount(){
  var answer = $('#answer').val();
  console.log(answer);
}

<button onclick='getCount()'>Get Count</button>


text:
Q: Linux/compiler-gcc5.h: No such file or directory I run into problem compiling a kernel scheduler for testing
the compiling error
 linux-2.6.32-rc3/include/linux/compiler-gcc.h:86:30: fatal error: linux/compiler-gcc5.h: No such file or directory

Do I get this error because the kernel is too old?
kernel
uname -r

4.1.0-3-generic

gcc
gcc --version

gcc-5.real (Ubuntu 5.2.1-22ubuntu2) 5.2.1 20151010

So if this is the reason for the compilation error - what solutions are available? Should I for instance update the kernel - how do I do that? Or regress to an earlier version of gcc? Other sugestions?

A: Any kernel older than 3.18 will not compile using gcc 5. Use an older compiler.

A: it's possible to install gcc-4.9 to be able to compile 3.xx kernels.
but then, next question would be: "how to switch for gcc-4.9 for kernel compilation?"
instead, the simpler answer would be here - just download missing file into include/linux folder
unfortunately gcc5 dislike "extern inline" construction at all, so you'll have to proceed with grep -sRl "extern inline" .|xargs sed -i -e "s/extern inline/inline/g" for all your kernel source code before moving forward with any compilation

A: You do not have the kernel sources. The compiler is looking for that header file.
This link will get you a version of the kernel source tree that should be mostly similar to what you are looking for.
https://cdn.kernel.org/pub/linux/kernel/v2.6/longterm/v2.6.32/linux-2.6.32.71.tar.xz

A: Simply:
Get an older version of GCC and do make CC=gcc-4.9 in your kernel directory to compile using the 4.9 gcc version.


text:
Q: Getting a data class from a given value of that class in Haskell I have two definitions that
data Person = Person Name Surname [Projects]
data Employees = Employees [Person] Salary

And I want to get the corresponding person from a given name by using the person list in employee and make some changes in the corresponding person. For example, I want to add a project to the list of project of the person that I want to do the project. How can I do this in Haskell?
The function signature should be like
myfunction :: Employees -> Name -> Employees

A: We can write this most directly by just pattern matching and using map.
In this case we might start by writing a small helper function to perform the local modification a single Person value and use something like map to apply our transformation to a whole bunch of other data. So we might have
 updatePerson :: Name -> Person -> Person
 updatePerson targetName (Person name sur projects)
   | targetName == name = Person name sur (NewProject : project)
   | otherwise = Person name sur projects

and then we can write a little more code to uniformly  apply this transformation to our Employee data
myFunction :: Person -> Person
myFunction name (Employee ps salary) =
  Employee (map (updatePerson name) ps) salaray

In your scenario this is the right thing to do. However, presumably we're going to be accessing parts of these data structures a lot so it makes sense to optimize for it a bit! By writing a few helper functions to manipulate our data types we might see how to get a more general approach:
personName :: Person -> Name
personName (Person name sur projects) = name

modifyProjects :: ([Project] -> [Project]) -> Person -> Person
modifyProjects f (Person name sur p) = Person name sur (f p)

and then writing something like
 myFunction name (Employee people salary) = Employee (map go people) salary
   where go p | personName p == name = modifyProject ... p
              | otherwise = p

Now I wrote this with helper functions rather than pattern matching directly because it suggests we use Haskell's built in feature for generating these functions, records.
data Person = Person { _name :: Name
                     , _surname :: Surname
                     , _projects :: [Projects]
data Employees = Employees {_people :: [Person], _salary :: Salary}

And then we can do something like
myFunction name e = e {_people = map go (_people e}}
  where go p | _name p == name = p {_projects = New :: _projects p}
             | otherwise = p

but now this is still clunky, Haskell's record system is a little tough to work with. This is actually the impetus for a whole lot of crazy powerful libraries implementing "lenses" which give us the ability to implement these record like transformations using a kit of generic combinators. I provide the corresponding lens code for an example of Haskell scaling up to do something cool, but either of the 3 alternatives I mentioned above are perfectly fine and much less complex
import Control.Lens
data Person = Person { _name :: Name
                     , _surname :: Surname
                     , _projects :: [Projects] }
data Employees = Employees {_people :: [Person], _salary :: Salary}

makeLenses ''Person
makeLenses ''Employees

myFunction n e =
  e & people.traverse.filtered pred.projects %~ (:) "New Project"
  where pred person = person^.name.to (== n)


text:
Q: Is there any way to change background color of comments in VScode? I would like to change the color of the comments so that it can be highlighted. I prefer to change background-color most of the time. I found the color setting in setting.json. it looks like this.
"editor.tokenColorCustomizations": {
    "textMateRules": [
        {
            "scope": "comment",
            "settings": {
                "fontStyle": "bold",
                "foreground": "#FFD83B"
            }
        }
    ]
}

It does change but it seems like there is no "background" option in "settings". it says "Token background colors are currently not supported."
so I only can change the text color, not the background. is there any way I can set background color of comments in VSCode?

A: There isn't any way to do that built-in.  You could look through the extensions - search for comment - to see if any of them do that.
Alternatively, one way to do it would be to use an extension like highlight.  You can style anything you can capture with a regex.  In settings.json:
"highlight.regexes": {

 "(//\\s*)(\\sTODO\\s)(\\s*?:?)(.*)": [
   {},
   {
    "overviewRulerColor": "#ffcc00", // does this work?
    // "backgroundColor": "#aaa",
    "color": "#fff",
    "fontWeight": "bold",
    "letterSpacing": "2.5px",
    "outline": "1px solid #aaa",
    // "border": "1px solid #fff",
    // "before": {
    //   "backgroundColor": "#fff",
    //   "contentText": " *** ",
    //   "fontWeight": "bold",
    //   "margin": "10px"
    //   // "width": "20px"
    // }
   },
   {},
   {
    "color": "#999",
    "fontStyle": "italic",
    "letterSpacing": "1px"
   }
 ],

 "(//\\s*)(-+\\s+//)": [
   {
    "color": "#000",
    "backgroundColor": "#aaa",
    "outline": "2px solid #aaa",
    "fontWeight": "bold",
   },
   {
    "overviewRulerColor": "#ffcc00",
    "backgroundColor": "#aaa",
    "color": "#000",
    "fontWeight": "bold",
    // "letterSpacing": "2.5px",
    "outline": "2px solid #aaa",
    // "border": "1px solid #fff",
    // "before": {
    //   "backgroundColor": "#fff",
    //   "contentText": " *** ",
    //   "fontWeight": "bold",
    //   "margin": "10px"
    //   // "width": "20px"
    // }
   },
 ]
},

yields:

For styling options, see https://code.visualstudio.com/api/references/vscode-api#DecorationRenderOptions


text:
Q: How to Run C# as background in Winjs ,Windows store App I have an Windows store app that's on HTML5 I listen somewhere that we will also able to apply C# as in other project and can easily pass function and variable to each other ?
So it is Possible to Add C# in HTML5 App ?

A: Check the link to get How it will be done :
Windows Runtime Components ,
Creating a simple component


text:
Q: MySQL 5.7 - Calling procedure with dynamic name I'm trying to write a MySQL (5.7) procedure that dynamically calls another procedure based on the one of its inputs.
The code I came up with so far is this (procedure_exists works for checking whether or not the function is available):
CREATE PROCEDURE process_event (IN event_type VARCHAR(32), IN aggregate_id CHAR(36), IN payload JSON)
BEGIN
    DECLARE handler_name VARCHAR(38) DEFAULT CONCAT('handle', event_type);

    IF procedure_exists(handler_name) THEN
        SET @handler_sql = CONCAT('CALL ', handler_name, '(?,?)');

        PREPARE prepared_statement FROM @handler_sql;

        SET @aggregate_id = aggregate_id;
        SET @payload = payload;

        EXECUTE prepared_statement USING @aggregate_id, @payload;
    END IF;
END;

The procedure is called from this trigger:
CREATE TRIGGER events_before_insert BEFORE INSERT ON events FOR EACH ROW
BEGIN
    DECLARE next_sequence BIGINT DEFAULT 0;

    SELECT COALESCE(new.sequence, COALESCE(MAX(sequence), 0) + 1) FROM events INTO next_sequence;

    SET new.sequence = next_sequence;
    SET new.recorded_at = COALESCE(new.recorded_at, NOW());

    CALL process_event(new.event_type, new.aggregate_id, new.payload);
END //

This doesn't work however, because I keep getting
[0A000][1336] Dynamic SQL is not allowed in stored function or trigger
From what I understand, disallowing that by default makes perfect sense, but from what I've gathered there seems to be no way of opting in to theoretically less secure behavior, by allowing certain types of statements or disabling the check altogether.
Do you have any suggestions for getting this to work?
In short the question boils down to this:

Can I somehow have a procedure to which I pass event_type (VARCHAR(32)), aggregate_id (CHAR(36)) and payload (JSON) which will then automatically call handle{event_type}(aggregate_id, payload) if it exists?


text:
Q: how to run angular application in IntelliJ I am following steps in IntelliJ to support Angular.
https://www.jetbrains.com/help/idea/2017.1/using-angular.html#install_angular_cli
I have created the project successfully but do not know how to run it. I guess I have to mention some configuration in Edit Configuration option.
What is the way to run Angular2 application in IntelliJ?

A: To run Angular application created with angular-cli in IDEA, you have to run npm start from NPM Tool Window to start the application, create JavaScript Debug run configuration for http://localhost:4200/ URL and hit Debug.
See https://blog.jetbrains.com/webstorm/2017/01/debugging-angular-apps/, https://www.youtube.com/watch?v=upgjCMHGpwo for more info.
See also https://blog.jetbrains.com/webstorm/2016/04/angular-2-workflow-in-webstorm/

A: Officially only the Ultimate version of IntelliJ has support for web applications enabled. The Community version does not support that (See here).
If you have the Ultimate version do as described on the IntelliJ website:

*

*Choose File | New | Project on the main menu or click the New Project
  button on the Welcome screen.

*In the Project Category and Options dialog, which is the first page of
  the New Project wizard, choose Static Web in the left-hand pane.

*In the right-hand pane, choose AngularCLI and click Next.

*On the second page of the wizard, specify the project name and the
  folder to create it in. In the Node Interpreter field, specify the
  Node.js interpreter to use. Choose a configured interpreter from the
  drop-down list or choose Add to configure a new one In the Angular CLI
  field, specify the path to the @angular/cli package. Optionally, in
  the Additional parameters field, specify the extra ng new options to
  pass to Angular CLI. Code completion is available in this field: as
  you start typing the name of an option or press Ctrl+Space, IntelliJ
  IDEA shows you the available options and their description.
When you click Finish, IntelliJ IDEA generates an Angular-specific
  project with all the required configuration files.

A: To run Angular2 application in IntelliJ go through following steps:

*

*First you should be in angular-cli project

*run npm install (It will add all dependencies)

*Wait for Indexing to be done (otherwise your changes will not reflect)

*run npm serve (It will start server on http://localhost:4200)


text:
Q: How to get rid of progress-indicator? I am trying to launch a mini-popups via JS for a specific control. Ok, I admit that sort of defeats the purpose of intro, but on that page there is really one control only that would "deserve" this treatment. So the navigation-controls, numbers and progess-indicator for a standard intro don't make sense there.
I followed the doc and managed to eliminate numbers using
     showStepNumbers: false,
however,
 showProgress: false,

as does not seem to work as documented. Am I missing anything or is it a bug?
Fiddle.

A: Maybe you miss showBullets option!
There is a little way to play with some options:

function showHelp()
{
var intro = introJs();
        intro.setOptions ( {
 showStepNumbers: document.getElementById('showStepNumbers').checked,
 showProgress: document.getElementById('showProgress').checked,
 showBullets: document.getElementById('showBullets').checked,
 steps: [
           {
 intro: "I really mean it!",
 element: document.querySelector ( '#bla' )
           }
           ]
        } );
        intro.start();
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/intro.js/2.7.0/introjs.min.css" rel="stylesheet"/>

Hello World!

<button onclick="showHelp()">
Help!
</button>

showStepNumbers:<input type="checkbox" id="showStepNumbers" />
showProgress:<input type="checkbox" id="showProgress" />
showBullets:<input type="checkbox" id="showBullets" />


text:
Q: IndexedDB module breaks functionality I had decided to build a PWA for experience in JavaScript and decided to use IndexedDB to store data as the project houses stats for players that have been looked up.
I decided to make an IndexedDB wrapper with promises for other projects as I thought that would be useful. I built and tested it without proper module syntax and as just a collection of functions to test. When I added export to abide by proper module requirements, some things stopped working.
Besides obvious code refactoring that needs to be done, I can't see why it is not function when actually put into a module, at least why some functions don't work while others do still.
I have one record in my object store currently:
1:"{"stats":{"skill":{"Overall":{"Rank":420475,"Level":1703,"Experience":41536951},"Attack":{"Rank":365100,"Level":90,"Experience":5348211},"Defence":{"Rank":387640,"Level":86,"Experience":3643081},"Strength":{"Rank":681596,"Level":86,"Experience":3619845},"Hitpoints":{"Rank":568026,"Level":89,"Experience":5338699},"Ranged":{"Rank":615697,"Level":86,"Experience":3872192},"Prayer":{"Rank":543130,"Level":70,"Experience":765936},"Magic":{"Rank":858588,"Level":77,"Experience":1586816},"Cooking":{"Rank":533540,"Level":75,"Experience":1265604},"Woodcutting":{"Rank":128685,"Level":90,"Experience":5396564},"Fletching":{"Rank":534221,"Level":75,"Experience":1210429},"Fishing":{"Rank":325821,"Level":80,"Experience":2088438},"Firemaking":{"Rank":802393,"Level":65,"Experience":454386},"Crafting":{"Rank":526605,"Level":70,"Experience":771273},"Smithing":{"Rank":508338,"Level":70,"Experience":763913},"Mining":{"Rank":527787,"Level":70,"Experience":761613},"Herblore":{"Rank":400792,"Level":70,"Experience":750904},"Agility":{"Rank":715721,"Level":65,"Experience":466967},"Thieving":{"Rank":516257,"Level":61,"Experience":310438},"Slayer":{"Rank":597053,"Level":72,"Experience":989731},"Farming":{"Rank":396681,"Level":74,"Experience":1102421},"Runecrafting":{"Rank":238233,"Level":66,"Experience":526072},"Hunter":{"Rank":634376,"Level":61,"Experience":321529},"Construction":{"Rank":602088,"Level":55,"Experience":181889}},"boss":{"Abyssal Sire":{"Rank":0,"Participation":0},"Alchemical Hydra":{"Rank":0,"Participation":0},"Barrows Chests":{"Rank":0,"Participation":0},"Bryophyta":{"Rank":0,"Participation":0},"Callisto":{"Rank":0,"Participation":0},"Cerberus":{"Rank":0,"Participation":0},"Chambers of Xeric":{"Rank":0,"Participation":0},"Chambers of Xeric: Challenge Mode":{"Rank":0,"Participation":0},"Chaos Elemental":{"Rank":0,"Participation":0},"Chaos Fanatic":{"Rank":0,"Participation":0},"Commander Zilyana":{"Rank":0,"Participation":0},"Corporeal Beast":{"Rank":0,"Participation":0},"Crazy Archaeologist":{"Rank":0,"Participation":0},"Dagannoth Prime":{"Rank":0,"Participation":0},"Dagannoth Rex":{"Rank":0,"Participation":0},"Dagannoth Supreme":{"Rank":0,"Participation":0},"Deranged Archaeologist":{"Rank":0,"Participation":0},"General Graardor":{"Rank":0,"Participation":0},"Giant Mole":{"Rank":0,"Participation":0},"Grotesque Guardians":{"Rank":0,"Participation":0},"Hespori":{"Rank":0,"Participation":0},"Kalphite Queen":{"Rank":0,"Participation":0},"King Black Dragon":{"Rank":0,"Participation":0},"Kraken":{"Rank":0,"Participation":0},"Kree'Arra":{"Rank":0,"Participation":0},"K'ril Tsutsaroth":{"Rank":0,"Participation":0},"Mimic":{"Rank":0,"Participation":0},"Nightmare":{"Rank":0,"Participation":0},"Obor":{"Rank":0,"Participation":0},"Sarachnis":{"Rank":0,"Participation":0},"Scorpia":{"Rank":0,"Participation":0},"Skotizo":{"Rank":0,"Participation":0},"The Gauntlet":{"Rank":0,"Participation":0},"The Corrupted Gauntlet":{"Rank":0,"Participation":0},"Theatre of Blood":{"Rank":0,"Participation":0},"Thermonuclear Smoke Devil":{"Rank":0,"Participation":0},"TzKal-Zuk":{"Rank":0,"Participation":0},"TzTok-Jad":{"Rank":0,"Participation":0},"Venenatis":{"Rank":0,"Participation":0},"Vet'ion":{"Rank":0,"Participation":0},"Vorkath":{"Rank":0,"Participation":0},"Wintertodt":{"Rank":0,"Participation":0},"Zalcano":{"Rank":0,"Participation":0},"Zulrah":{"Rank":0,"Participation":0}},"activity":{"League Points":{"Rank":0,"Participation":0},"Bounty Hunter - Hunter":{"Rank":0,"Participation":0},"Bounty Hunter - Rogue":{"Rank":0,"Participation":0},"Clue Scrolls (all)":{"Rank":1306445,"Participation":2},"Clue Scrolls (beginner)":{"Rank":798671,"Participation":1},"Clue Scrolls (easy)":{"Rank":0,"Participation":0},"Clue Scrolls (medium)":{"Rank":961590,"Participation":1},"Clue Scrolls (hard)":{"Rank":0,"Participation":0},"Clue Scrolls (elite)":{"Rank":0,"Participation":0},"Clue Scrolls (master)":{"Rank":0,"Participation":0},"LMS - Rank":{"Rank":0,"Participation":0}}},"username":"limerain","type":"Standard","timestamp":1606315205012,"id":1}"

Module -
/**
 * Opens a connection to an indexedDB database
 * @param {string} database_name Name of indexedDB to be opened
 * @param {number} database_version Version of database to be opened
 * @param {function} upgrade_function Function to be executed if database needs to be upgraded
 * @returns {Promise} Resolve => IDBDatabase | Reject => Error
 */
function openDB(database_name, database_version, upgrade_function) {
    return new Promise(function (resolve, reject) {
        let request = indexedDB.open(database_name, database_version);

        request.onsuccess = function () {
            console.log("Database opened successfully")
            resolve(request.result);
        }

        request.onerror = function (event) {
            reject(`Error: openDB - Request Failed - Supplied Data {${database_name},${database_version},${upgrade_function}} Code: ${event.target.errorCode} Error: ${request.error}`)
        };

        request.onupgradeneeded = function (event) {
            console.log('OnUpgradeNeeded - Called')
            upgrade_function(event.target.result)
                .then(console.log("Database Upgrade Successful"))
                .catch((reason) => {
                    reject(`Error: openDB - Database Upgrade Failed - Reason: ${reason}, Supplied Data {${database_name},${database_version},${upgrade_function}} Code: ${event.target.errorCode} Error: ${request.error}`)
                })
        };
    });
}

/**
 * Adds record objects to the specificed objectStore
 * @param {IDBDatabase} database Initiliazed database
 * @param {string} storeName Name of objectStore where transactions will be occurring
 * @param {[object]} data Object to be inserted into the objectStore
 * @returns {Promise} Resolve => String | Reject => Error
 */
function addRecords(database, storeName, data) {
    return new Promise(function (resolve, reject) {
        let transaction = database.transaction(storeName, "readwrite");

        transaction.oncomplete = function () {
            console.log("Add Transaction Successful.");
            resolve("Add Transaction Succesful")
        };

        transaction.onabort = function (event) {
            reject(`Error: addRecord - Transaction Aborted - Supplied Data: {${database},${storeName},${data}} Code: ${event.target.errorCode} Error: ${event.target.error}`)
        }

        transaction.onerror = function (event) {
            reject(`Error: addRecord - Transaction Failed - Supplied Data: {${database},${storeName},${data}} Code: ${event.target.errorCode} Error: ${event.target.error}`)
        };

        let objectStore = transaction.objectStore(storeName);

        data.forEach(record => {
            let request = objectStore.add(record);

            request.onsuccess = function () {
                console.log("Add Request Succesful");
            };

            request.onerror = function (event) {
                reject(`Error: addRecord - Request Failed: Supplied Data: {${database_name},${database_version},${upgrade_function}} Code: ${event.target.errorCode} Error: ${request.error} Record: ${record}`)
            };

        })

    });
}

/**
 * Deletes records on a given Index and key from the specified objectStore
 * @param {IDBDatabase} database Initialized database
 * @param {string} storeName Name of ObjectStore where transactions will be occurring
 * @param {string} indexName An Index from a provided ObjectStore
 * @param {any} key Key being looked for
 */
function deleteRecords(database, storeName, indexName, key) {
    return new Promise(function (resolve, reject) {
        let transaction = database.transaction(storeName, "readwrite");

        transaction.oncomplete = function () {
            console.log("Delete Transaction Successful.");
            resolve("Records Deletion Successful")
        };

        transaction.onabort = function (event) {
            reject(`Error: deleteRecords - Transaction Aborted - Supplied Data: {${database},${storeName},${indexName},${key} Code: ${event.target.errorCode} Error: ${event.target.error}`)
        }

        transaction.onerror = function (event) {
            reject(`Error: deleteRecords - Transaction Failed - Supplied Data: {${database},${storeName},${indexName},${key} Code: ${event.target.errorCode} Error: ${event.target.error}`)
        };

        let objectStoreCursor = transaction.objectStore(storeName).index(indexName).openCursor();

        objectStoreCursor.onsuccess = function (event) {
            let cursor = event.target.result;
            if (cursor) {
                if (cursor.value[indexName] === key) {
                    let request = cursor.delete();
                    request.onsuccess = function () {
                        console.log('Record Deleted:', cursor.value);
                    }
                    request.onerror = function (event) {
                        reject(`Error: deleteRecords - Request Failed - Cursor: ${cursor} Supplied Data: {${database},${storeName},${indexName},${key} Code: ${event.target.errorCode} Error: ${event.target.error}`)
                    }
                }
                cursor.continue();
            }
            console.log("Delete Request(s) Successful")
        }

        objectStoreCursor.onerror = function (event) {
            resolve(`Error: deleteRecords - Cursor Failed - Supplied Data: {${database},${storeName},${indexName},${key} Code: ${event.target.errorCode} Error: ${event.target.error}`)
        }
    });
}

/**
 * Returns all records from the provided ObjectStore searching on the provided Index
 * @param {IDBDatabase} database Initialized database
 * @param {string} storeName Name of ObjectStore where transactions will be occurring
 * @param {string} indexName An Index from a provided ObjectStore
 * @param {IDBKeyRange | any} key Key being looked for
 * @returns {Promise} Resolve => Array of Objects | Reject => Reason
 */
function getRecordsOnIndex(database, storeName, indexName, key) {
    return new Promise(function (resolve, reject) {
        let transaction = database.transaction(storeName, "readonly");

        transaction.oncomplete = function () {
            console.log("Get Transaction Successful.");
        };

        transaction.onabort = function (event) {
            reject(`Error: getRecordsOnIndex - Transaction Aborted - Supplied Data: {${database},${storeName},${indexName},${key}} Code: ${event.target.errorCode} Error: ${event.target.error}`)
        }

        transaction.onerror = function (event) {
            reject(`Error: getRecordsOnIndex - Transaction Failed - Supplied Data: {${database},${storeName},${indexName},${key}} Code: ${event.target.errorCode} Error: ${event.target.error}`)
        };

        let request = transaction.objectStore(storeName).index(indexName).getAll(key);

        request.onsuccess = function (event) {
            console.log("Get All Request Succesful");
            resolve(event.target.result)
        };

        request.onerror = function (event) {
            reject(`Error: getRecordsOnIndex - Request Failed - Supplied Data: {${database},${storeName},${indexName},${key}} Code: ${event.target.errorCode} Error: ${event.target.error}`)
        };

    });
}

/**
 * Returns all records from the provided ObjectStore
 * @param database Initialized database
 * @param storeName  Name of ObjectStore where transactions will be occurring
 * @returns {Promise} Resolve => Array of Object | Reject => Reason
 */
function getRecordsOnObjectStore(database, storeName) {
    return new Promise(function (resolve, reject) {
        let transaction = database.transaction(storeName, "readonly");

        transaction.oncomplete = function () {
            console.log("Get All Transaction Successful.");
        };

        transaction.onabort = function (event) {
            reject(`Error: getRecordsOnObjectStore - Transaction Aborted - Supplied Data: {${database},${storeName}} Code: ${event.target.errorCode} Error: ${event.target.error}`)
        }

        transaction.onerror = function (event) {
            reject(`Error: getRecordsOnObjectStore - Transaction Failed - Supplied Data: {${database},${storeName}} Code: ${event.target.errorCode} Error: ${event.target.error}`)
        };

        let request = transaction.objectStore(storeName).getAll();

        request.onsuccess = function (event) {
            console.log("Get All Request Succesful");
            resolve(event.target.result)
        };

        request.onerror = function (event) {
            reject(`Error: getRecordsOnObjectStore - Request Failed - Supplied Data: {${database},${storeName}} Code: ${event.target.errorCode} Error: ${event.target.error}`)
        };

    })
}

export {
    openDB,
    addRecords,
    deleteRecords,
    getRecordsOnIndex,
    getRecordsOnObjectStore
}

My utilities module that houses shared data or functionality
function upgradeDB(database) {
    return new Promise(function (resolve, reject) {
        //Create Table
        if (!database.objectStoreNames.contains('records')) {
            let records_table = database.createObjectStore('records', { keyPath: "id", autoIncrement: true })
            records_table.createIndex('username', 'username', { unique: false });
            records_table.createIndex('type', 'type', { unique: false });
            records_table.createIndex('id', 'id', { unique: true });
            resolve("Upgrade Successful.");
        } else {
            reject("ObjectStore already exists?")
        }
    });
}

function parseDate(UTC) {
  let date = new Date(UTC);
  return `${date.toLocaleDateString()} ${date.toLocaleTimeString()}`;
}

const HISCORE_PROFILE = [
    "Overall",
    "Attack",
    "Defence",
    "Strength",
    "Hitpoints",
    "Ranged",
    "Prayer",
    "Magic",
    "Cooking",
    "Woodcutting",
    "Fletching",
    "Fishing",
    "Firemaking",
    "Crafting",
    "Smithing",
    "Mining",
    "Herblore",
    "Agility",
    "Thieving",
    "Slayer",
    "Farming",
    "Runecrafting",
    "Hunter",
    "Construction",
    "League Points",
    "Bounty Hunter - Hunter",
    "Bounty Hunter - Rogue",
    "Clue Scrolls (all)",
    "Clue Scrolls (beginner)",
    "Clue Scrolls (easy)",
    "Clue Scrolls (medium)",
    "Clue Scrolls (hard)",
    "Clue Scrolls (elite)",
    "Clue Scrolls (master)",
    "LMS - Rank",
    "Abyssal Sire",
    "Alchemical Hydra",
    "Barrows Chests",
    "Bryophyta",
    "Callisto",
    "Cerberus",
    "Chambers of Xeric",
    "Chambers of Xeric: Challenge Mode",
    "Chaos Elemental",
    "Chaos Fanatic",
    "Commander Zilyana",
    "Corporeal Beast",
    "Crazy Archaeologist",
    "Dagannoth Prime",
    "Dagannoth Rex",
    "Dagannoth Supreme",
    "Deranged Archaeologist",
    "General Graardor",
    "Giant Mole",
    "Grotesque Guardians",
    "Hespori",
    "Kalphite Queen",
    "King Black Dragon",
    "Kraken",
    "Kree'Arra",
    "K'ril Tsutsaroth",
    "Mimic",
    "Nightmare",
    "Obor",
    "Sarachnis",
    "Scorpia",
    "Skotizo",
    "The Gauntlet",
    "The Corrupted Gauntlet",
    "Theatre of Blood",
    "Thermonuclear Smoke Devil",
    "TzKal-Zuk",
    "TzTok-Jad",
    "Venenatis",
    "Vet'ion",
    "Vorkath",
    "Wintertodt",
    "Zalcano",
    "Zulrah",
  ];

  const SKILLS = [
    "Overall",
    "Attack",
    "Defence",
    "Strength",
    "Hitpoints",
    "Ranged",
    "Prayer",
    "Magic",
    "Cooking",
    "Woodcutting",
    "Fletching",
    "Fishing",
    "Firemaking",
    "Crafting",
    "Smithing",
    "Mining",
    "Herblore",
    "Agility",
    "Thieving",
    "Slayer",
    "Farming",
    "Runecrafting",
    "Hunter",
    "Construction",
  ];

  const BOSS_KILLS = [
    "Abyssal Sire",
    "Alchemical Hydra",
    "Barrows Chests",
    "Bryophyta",
    "Callisto",
    "Cerberus",
    "Chambers of Xeric",
    "Chambers of Xeric: Challenge Mode",
    "Chaos Elemental",
    "Chaos Fanatic",
    "Commander Zilyana",
    "Corporeal Beast",
    "Crazy Archaeologist",
    "Dagannoth Prime",
    "Dagannoth Rex",
    "Dagannoth Supreme",
    "Deranged Archaeologist",
    "General Graardor",
    "Giant Mole",
    "Grotesque Guardians",
    "Hespori",
    "Kalphite Queen",
    "King Black Dragon",
    "Kraken",
    "Kree'Arra",
    "K'ril Tsutsaroth",
    "Mimic",
    "Nightmare",
    "Obor",
    "Sarachnis",
    "Scorpia",
    "Skotizo",
    "The Gauntlet",
    "The Corrupted Gauntlet",
    "Theatre of Blood",
    "Thermonuclear Smoke Devil",
    "TzKal-Zuk",
    "TzTok-Jad",
    "Venenatis",
    "Vet'ion",
    "Vorkath",
    "Wintertodt",
    "Zalcano",
    "Zulrah",
  ];

  const ACTIVITIES = [
    "League Points",
    "Bounty Hunter - Hunter",
    "Bounty Hunter - Rogue",
    "Clue Scrolls (all)",
    "Clue Scrolls (beginner)",
    "Clue Scrolls (easy)",
    "Clue Scrolls (medium)",
    "Clue Scrolls (hard)",
    "Clue Scrolls (elite)",
    "Clue Scrolls (master)",
    "LMS - Rank",
  ];

  const DATABASE_NAME = "runescape_tracker_pwa";

export {upgradeDB, parseDate, HISCORE_PROFILE, SKILLS, BOSS_KILLS, ACTIVITIES, DATABASE_NAME}

My module on the page to delete/view a record
import { openDB, deleteRecords, getRecordsOnObjectStore } from "./libraries/IndexedDB_Wrapper_Promises/database.js"
import { DATABASE_NAME, upgradeDB, parseDate } from "./utilities.js"

const OBJECTSTORE = "records";

function createRecordEntry(value) {

    let div = "";
    Object.entries(value).forEach(([key, value]) => {
        div += `

                <button data-id=${value.id} class="btnView">View</button>
                <button data-id=${value.id} class="btnDelete">Delete</button>

${parseDate(parseInt(key))}

        `
    });

    return div;
}

function createTypeEntry(value) {

    let div = "";

    Object.entries(value).forEach(([key, value]) => {
        div += `

${key}

        ${createRecordEntry(value)}

    `
    })

    return div;
}

function createElement(username, value) {
    let div = document.createElement("div");
    div.className = "collection"
    div.innerHTML = `

${username}

            ${createTypeEntry(value)}
`
    return div;
}

function buildResultSet(data) {

    let list = {};

    data.forEach(row => {
        if (list.hasOwnProperty(row.username)) {
            list[row.username][row.type] = { ...list[row.username][row.type], [row.timestamp]: { 'stats': row.stats, 'id': row.id } };
        } else {
            list = { ...list, [row.username]: { [row.type]: { [row.timestamp]: { 'stats': row.stats, 'id': row.id } } } };
        }
    });

    return list;
}

function deleteRecord(event) {
    openDB(DATABASE_NAME, 1, upgradeDB)
        .then(database => {
            console.log(database)
            deleteRecords(database, "records", "id",1)
                .then(result => { console.log(result) })
                .catch(result => { throw result });
        })
        .catch(result => { throw result })

}

function viewRecord(event) {
    window.location.assign(`view.html?id=${parseInt(event.target.dataset.id)}`)
}

window.onload = function () {
    openDB(DATABASE_NAME, 1, upgradeDB)
        .then((database) => {
            getRecordsOnObjectStore(database, OBJECTSTORE)
                .then((results) => {
                    let resultSet = buildResultSet(results)
                    Object.entries(resultSet).forEach(([key, value]) => {
                        document.getElementById("container").appendChild(createElement(key, value));
                    });

                    let deleteButtons = document.getElementsByClassName("btnDelete");

                    Array.from(deleteButtons).forEach(button => {
                        button.addEventListener("click", deleteRecord)
                    });

                    let viewButtons = document.getElementsByClassName("btnView");

                    Array.from(viewButtons).forEach(button => {
                        button.addEventListener("click", viewRecord)
                    });

                })
                .catch((result) => {
                    throw result;
                });
        })
        .catch((result) => {
            throw result;
        });
};

*

*DeleteRecords - should delete one record as it's on a unique index, however the cursor is returned as null

Calling function -
function deleteRecord(event) {
    openDB(DATABASE_NAME, 1, upgradeDB)
        .then(database => {
            deleteRecords(database, 'records', 'id', parseInt(event.target.dataset.id))
                .then(result => { console.log(result) })
                .catch(result => { throw result });
        })
        .catch(result => { throw result })
}

My module that builds a page for a specific record
import {openDB, getRecordsOnIndex} from "./libraries/IndexedDB_Wrapper_Promises/database.js"
import {DATABASE_NAME,upgradeDB,parseDate} from "./utilities.js"

window.onload = function () {
    let skillsTable = document.getElementById("skillTable"), otherTable = document.getElementById("otherTable"), usernameHeader = document.getElementById("usernameHeader"), recordTimestamp = document.getElementById("recordTimestamp"), recordID = document.getElementById("recordID");

    const params = new URLSearchParams(window.location.search)
    console.log(params.get('id'))

    openDB(DATABASE_NAME, 1, upgradeDB)
        .then((database) => {
            getRecordsOnIndex(database, 'records', 'id', parseInt(params.get('id')))
                .then((results) => {
                    console.log(results)
                    if(results.length == 1){
                        usernameHeader.innerHTML = results[0].username
                        recordTimestamp.innerHTML = `Date: ${parseDate(results[0].timestamp)}`
                        recordID.innerHTML = `ID: ${results[0].id}`
                        buildTable(results[0].stats)
                    }else{
                        console.error("No results returned for the provided ID")
                    }
                })
                .catch((result) => {
                    throw result;
                });
        })
        .catch((result) => {
            throw result;
        });

    function buildTable(data) {
        //skill,boss,game
        Object.entries(data).forEach(([key, values]) => {
            //skill/activity
            Object.entries(values).forEach(([entry, values2]) => {
                //determine which table it falls under
                Object.keys(values2).length == 3
                    ? (newRow = skillsTable.insertRow(-1))
                    : Object.keys(values2).length == 2
                        ? (newRow = otherTable.insertRow(-1))
                        : _throw(
                            `Error: Unknown Data Structure In buildTable: \n Key: ${key} \n Value: ${values2}`
                        );
                newRow.className = entry;
                newRow.insertCell(-1).outerHTML = `<th scope="row">${entry}</th>`;

                //newRow.insertCell(-1).appendChild(document.createTextNode(entry));
                //rank:x,level/participation/experience
                Object.entries(values2).forEach(([col, value]) => {
                    newRow.insertCell(-1).appendChild(document.createTextNode(value));
                });
            });
        });
    }
};

*getRecordsOnIndex - returns an empty array instead of an array with a singular object in the current usage (index is primary keys)

Calling function -
openDB(DATABASE_NAME, 1, upgradeDB)
        .then((database) => {
            getRecordsOnIndex(database, 'records', 'id', parseInt(params.get('id')))
                .then((results) => {
                    console.log(results)
                    if(results.length == 1){
                        usernameHeader.innerHTML = results[0].username
                        recordTimestamp.innerHTML = `Date: ${parseDate(results[0].timestamp)}`
                        recordID.innerHTML = `ID: ${results[0].id}`
                        buildTable(results[0].stats)
                    }else{
                        console.error("No results returned for the provided ID")
                    }
                })
                .catch((result) => {
                    throw result;
                });
        })
        .catch((result) => {
            throw result;
        });


text:
Q: How do assembly instruction differentiate between register, memory address, immediate value or offset parameter? I've been wondering, are there some invisible op-codes or flags or anything that tells the assembly instruction how to treat its parameters? Am a little confused, since apparently the same instruction can operate with different type operands - registers, memory addresses, offsets and immediate values are supported.
There doesn't seem to be any extra specifics in the "textual representation" of the assembly program, but maybe there is difference in the binary, e.g. some bits are toggled so that the CPU knows which type of operand is used?

A: The instructions are encoded in the hardware. How this is exaclty done is CPU specific. On the x86 architecture, you have some bits which define what the operand adressing modes are. For more detail you should refer to the Intel programmers reference manual, where this is explained in detail.
Sometimes there are instructions with different opcodes and the same effect, in such a case, the assembler can choose one.
http://www.sandpile.org/x86/opc_rm.htm


text:
Q: Artefacts using osm2vectortiles world map with OpenLayers 3 in mbtiles Using the information in this question, I managed to unpack a random small mbtiles vector tile map from osm2vectortiles.org and load it locally in a browser using npm http-server, based on this OpenLayers example.
This leaves me with this question, when I download the world map for zoom level 0-5 from osm2vectortiles.org, I seem strange triangles tiles appearing in the sea at level 2,3,4 and 5. Please see the screenshot. Land looks perfect.
How can I resolve this?

A: This appears to be caused by a bug in openlayers
https://github.com/openlayers/openlayers/issues/6341
either get a version of openlayers with that fixed or make sure your water polygon has a stroke when you set it's style. I used this to fix this issue.
function createMyStyle() {
    var strokedPolygon = new ol.style.Style({fill: fill, stroke: stroke});
    var styles = [];
    return function(feature, resolution) {
        var length = 0;
        var layer = feature.get('layer');
        if (layer == 'water') {
            fill.setColor('#a0c8f0');
            stroke.setColor('#a0c8f0');
            stroke.setWidth(1);
            styles[length++] = strokedPolygon;
        } .....all the other styles
        }
        styles.length = length;
        return styles;
   };
}


text:
Q: sed + how to remove the word if one of the characters in word contain "m" or "M" How to remove the word if one of the characters in the word contains "m" or "M"?
I tried this, but it doesn't work:
 echo 6.5G 66.5m | sed -e 's/[m][M]//g'

A: Your sed command is
s/[m][M]//g

This will remove only the string mM from its input, because you've asked to match

*

*anything in the set m, followed by

*anything in the set M.

You probably meant to write [Mm] instead.  You can get the same effect by adding the /i option to the s command, though:
s/m//ig

Now this will remove all upper- or lower-case ms:
$ echo 6.5G 66.5m | sed -e s/m//ig
6.5G 66.5

Your question asks how to remove entire words containing this letter.  For that, we need to match any non-space characters before or after.  [^ ] matches a non-space character, and [^ ]* matches zero or more non-space characters, so we want
s/[^ ]*m[^ ]*//ig

Testing this:
$ echo 6.5G 66.5m | sed -e 's/[^ ]*m[^ ]*//ig'
6.5G

and
$ echo Five Merry Women went fishing | sed -e 's/[^ ]*m[^ ]*//ig'
Five   went fishing

A: $ echo 6.5G 66.5m | sed -e 's/[[:space:]].*[mM]//g'
6.5G

Note that the "m" and "M" form one pattern - your (non-working) version looks for an "m" followed by an "M".

A: Try This it will Delete The line containg 'm' or 'M'
echo 6.5G 66.5m | sed "/[mM]/d"

A: If you want to remove you can try this
[root@connect ~]# echo 6.5M 66.5m | sed -e 's/m//g' | sed -e 's/M//g'
6.5 66.5


text:
Q: How to create sequence number based on a condition of another table? I am trying to add a column in a table but i'm stuck trying to figure out a way to assign sequence number to this column.

*

*Column ID and C_Seq_No are from one table (A)

*D_Seq_No and Type are from another table (B).

I'm trying to join the 2 tables together where anytime C_Seq_No shows up with the number "1" three times for one ID, then D_Seq_No would create a sequence number of 1, 2, and 3 for that ID.
Here is what I have when I run the query to join the 2 table since I haven't assigned anything to the D_Seq_No column yet:
      TABLE A                          TABLE B
ID           C_Seq_No    |    D_Seq_No         Type
123              1       |      NULL            02
123              1       |      NULL            04
123              1       |      NULL            06
123              2       |      NULL            03
123              2       |      NULL            05
123              2       |      NULL            07

This is what I want in my query resultset to look like when joining those 2 tables:
ID           C_Seq_No        D_Seq_No         Type
123              1             1               02
123              1             2               04
123              1             3               06
123              2             1               03
123              2             2               05
123              2             3               07

A: You are looking for row_number.  The call would look like this:
select . . .,
       row_number() over (partition by id, c_seq_no order by type) as d_seq_no,
       type
from . . .


text:
Q: How can i take snapshot of command prompt window in full screen mode I need to take snapshot if command prompt window running in full screen mode.
I had tried it using PrintScreen,Ctrl+PrintScreen, Ctrl+Alt+PrintScreen button(s) but nothing seems to work
Also are there any reasons that the print screen button does not work in full screen commandprompt mode?  After all, it does for all windows under normal conditions.
Abdul Khaliq

A: In full screen mode all you have is text. There is no graphical `rendering' as such. If you can capture the text, it is enough ... though you can always reconstruct a png image later from the text (if you really have to get an image out of it).

A: Why don't you just use an external screen shot software?
There's many, e.g. greenshot, which is free (is in speech and beer :-)).

A: did you try alt + print screen?

A: Click any window except the command window and then hit PrtScrn.

A: First off all open cmd in full screen mode then click on print screen button after that open paint brush and press ctrl+v (past) you can save it in any where, where ever you want (file type should be .png).

A: I wasn't able to find any of these replies that work, and I can't install unapproved software do to IT policies. Here is what I did:
Right click inside command window. Hit select all. Right click outside of window (on top bar close to the maximize minimize controls. Select edit; select copy. Open a notepad window and paste. The advantage here is you have text that can be copied and pasted back into a command window later. I hope this helps.

A: *

*press ctrl+a     //select all

*press ctrl+c      // copy all text

*write   notepad mytext.txt + press entet    // open notepad

*press ctrl+v       //paste in text in notepad

*press ctrl+s         // Save file

*press ctrl+w          // Close notepad.


text:
Q: Collapsing Toolbar & NestedScrollView invalid behavior I have the following layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v4.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="fill_vertical"
        android:paddingBottom="?attr/actionBarSize"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <!-- Rest of the code there -->

        </FrameLayout>
    </android.support.v4.widget.NestedScrollView>

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fitsSystemWindows="true"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            app:contentScrim="?attr/colorPrimary"
            app:expandedTitleMarginEnd="64dp"
            app:expandedTitleMarginStart="48dp"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <ImageView
                android:id="@+id/image_iv"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:adjustViewBounds="true"
                android:scaleType="fitXY"
                app:layout_collapseMode="parallax"
                app:layout_collapseParallaxMultiplier="0.7"
                tools:ignore="ContentDescription" />

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

        </android.support.design.widget.CollapsingToolbarLayout>
    </android.support.design.widget.AppBarLayout>

    <!-- FAB -->
    <android.support.design.widget.FloatingActionButton
        android:id="@+id/favorite_fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/fab_margin"
        android:clickable="true"
        android:src="@drawable/ic_star_rate"
        app:layout_anchor="@id/container"
        app:layout_anchorGravity="bottom|right" />

</android.support.design.widget.CoordinatorLayout>

Take a look on the following video: http://www.youtube.com/watch?v=kkWuh4UU6qM (Sorry for wrong orientation).
On Nexus 4 (5.1.1) CollapsingToolbarLayout works fine, on Galaxy S3 (4.4) it does not.
On Galaxy S3 scrolling of the NestedScrollView's contents works fine (card scrolls to the top under the toolbar), // on Nexus 4 scrolls the content of the card instead of card. — fixed by swapping NestedScrollView and AppBarLayout positions.
I use build tools 23.0.1.
How to fix it?

A: The solution is to add this attribute to the CoordinatorLayout:
android:fitsSystemWindows="true"


text:
Q: How to implement Continuous Integration with Puppet and multiple services We're trying to implement a Continuous Integration pipeline in our environment. We have a lot of different services, each with its own Git repository. Deployment is done via Puppet, using an external node classifier that determines what classes to deploy to each host type. And the Puppet files are sitting in their own Git repo, as depicted here:

Only, it's not just 3 services, it's more like 100. So the Puppet project is this monstrous monolith of multiple manifests, and of course it's in its own independent Git repo.
Now, along comes lil' ol' me, tasked with setting up a pattern for CI, so that when someone requests to merge a branch from, say, Service A, into master, we should be able to kick off a CI build that will spin up a virtual environment, deploy Service A to some VMs, and ensure that the new branch passes all automated tests. Of course, the problem is that to deploy a new build of Service A, I not only have to build it, but I also have to update the Puppet manifest to refer to the new build version...and the Puppet files are sitting in a completely independent repo, not on my branch. So I don't have any easy way to tell the Puppet Master that for this branch, we need to use the CI build, not the master version.
I can't be the first person ever to want to set up CI for an environment like this, but I've searched the web for solutions and come up empty. Perhaps I'm using the wrong search terms.
Can anyone suggest a suitable design pattern that will enable me to implement CI for all my service repos?
(Please pardon the cross-posting. I originally posted this on ServerFault, but it got almost no attention there, even with a bounty. Maybe this is more of a programming question than a SysEng question.)


text:
Q: How to show only 'Open in source Panel' option when right click from Developers Tools using javascript In a Browser when we open websites and open Developrs toos and right click on .Css
or .Js file then there is four option will be shown. example like below.
enter image description here
But i want to show only 'Open in source Panel' option when right click from Developers Tools, want to disable other option, example like below.
enter image description here
So, May i know how it will be possible by javascirpt, jquery ??


text:
Q: How to use python split? I have some data like that:

I use split function process data into list.I want to make some data mining in this training set,but I don't know how to separate data as futures like this in python:

By the way,some data are float.Firstly,I want to fill all the data into a list,coding like that:
key_zi = []
for i in range(len(train_set['zi_id'])):
    key_zi = key_zi + train_set['zi_id'][i].split('/')

but the result call:

AttributeError: 'float' object has no attribute 'split'.

Could you please help me ?

A: You said that the documentation says
str.split(str="", num=string.count(str))

What you're missing is that the the first instance of str in this definition is the delimiter for splitting.
Your error is that in this:
  train_set['zi_id'][i].split('/')

You are trying to call the split method of train_set['zi_id'][i].   But that thing is a float, not a delimiter string.


text:
Q: The type or namespace name 'builtInShaderGraphSaveContext' could not be found unity problem Can anyone help me , I was learning from https://youtu.be/FbM4CkqtOuA?t=126 this codemonkey youtube channel . The extension is here : https://unitycodemonkey.com/download.php?dt=videoProjectFiles&yid=FbM4CkqtOuA .
this is the image

A: You can try to move the script that reports the error to the Editor folder. The location of this folder is very arbitrary, and it can be placed under the initial directory of the Asset. Of course other English should also work. If there is no Editor folder, just create a new Editor folder.


text:
Q: IDLE shows up empty when running a code with tkinter dropdown When I run a code with tkinter dropdown in pycharm, the IDLE interface comes up empty on my macOS. but the code works fine on a windows. I use python 3.9.8 and I can't figure out what's wrong.
 from tkinter import *
root=Tk()
def fun1():
    print("Clicked")
mymenu=Menu(root)
root.config(menu=mymenu)
submenu=Menu(mymenu)
mymenu.add_cascade(label="File",menu=submenu)
submenu.add_command(label="Save")
submenu.add_command(label="Save as")
submenu.add_separator()
submenu.add_command(label="Open")
submenu.add_command(label="Send")
newmenu=Menu(mymenu)
mymenu.add_cascade(label="Edit",menu=newmenu)
newmenu.add_command(label="Undo",command=fun1)
root.mainloop()


text:
Q: Where can I find google analytics ga id for report apis For Google Analytics Real Time Data: get where can I find google analytics ga id for report APIs

A: It is the View ID, you can find it in View Settings of the Administration panel in Google Analytics.


text:
Q: Form submission to Mailchimp using Vue.js and Axios results in CORS error I have a component in my Vue.js app that submits email from a form to Mailchimp using Axios.
I've read that to get around CORS in Mailchimp's post URL, I need to use the post-json version and add &c=? to the end of the URL. I've also updated my request method from POST to GET and serialized my form input.
Component.vue
<mailchimp-subscribe action="https://example.us15.list-manage.com/subscribe/
post-json?u=xxx&id=xxx&c=?"></mailchimp-subscribe>

MailchimpSubscribe.vue
<template>
  <form @submit.prevent="subscribe">
    <input v-model="email" type="email" name="EMAIL" value="" placeholder="Email Address" required>
    <input class="button" type="submit" value="Subscribe">
  </form>
</template>

<script>
  import axios from 'axios'

  export default {
    name: 'MailchimpSubscribe',
    props: {
      action: {}
    },
    data: () => ({
      email: '',
      response: {}
    }),
    methods: {
      subscribe: function (event) {
        axios({
          method: 'get',
          url: this.action,
          data: JSON.stringify(this.email),
          cache: false,
          dataType: 'json',
          contentType: 'application/json; charset=utf-8'
        })
        .then(response => {
          console.log(response)
        })
        .catch(error => {
          console.log(error)
        })
      }
    }
  }
</script>

Using the code above, I still get the following error:

Failed to load https://example.us15.list-manage.com/subscribe/post-json?u=xxx&id=xxx&c=?: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.

Is there a step I'm missing?

A: Your server (backend) must respond with exactly the same header.
Namely: https://developer.mozilla.org/ru/docs/Web/HTTP/Headers/Access-Control-Allow-Origin
For example Axios get/post (never mind):

const configAxios = {
  headers: {
    'Content-Type': 'application/json',
  },
};
axios.post('api/categories', configAxios)
  .then((res) => {
    this.categories = res.data;
    console.log(res);
  })
  .catch((err) => {
    console.warn('error during http call', err);
  });

For example server-side. I like Symfony4 and it is used NelmioCorsBundle, look at the allow_origin: ['*']. It's pretty simple, if you use Symfony.

nelmio_cors:
    defaults:
        allow_credentials: false
        allow_origin: ['*']
        allow_headers: ['Content-Type']
        allow_methods: []
        expose_headers: []
        max_age: 0
        hosts: []
        origin_regex: false
        forced_allow_origin_value: ~
    paths:
        '^/api/':
            allow_origin: ['*']
            allow_headers: ['X-Custom-Auth', 'Content-Type', 'Authorization']
            allow_methods: ['POST', 'PUT', 'GET', 'DELETE']
            max_age: 3600
        '^/':
            origin_regex: true
            allow_origin: ['^http://localhost:[0-9]+']
            allow_headers: ['X-Custom-Auth', 'Content-Type']
            allow_methods: ['POST', 'PUT', 'GET', 'DELETE']
            max_age: 3600
            hosts: ['^api\.']

If you are not directly working with the server, then check with your supplier for this nuance.
This header can also be transmitted for example through Nginx, which is not the best idea.
For example, look at the:
add_header Access-Control-Allow-Origin *;

server {
    listen 8080;
    server_name site.local;
    root /var/www/site/public;

    location / {
       add_header Access-Control-Allow-Origin *;

        # try to serve file directly, fallback to index.php
        try_files $uri /index.php$is_args$args;
    }

    location ~ ^/index\.php(/|$) {
        fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
        fastcgi_split_path_info ^(.+\.php)(/.*)$;
        include fastcgi_params;
        # When you are using symlinks to link the document root to the
        # current version of your application, you should pass the real
        # application path instead of the path to the symlink to PHP
        # FPM.
        # Otherwise, PHP's OPcache may not properly detect changes to
        # your PHP files (see https://github.com/zendtech/ZendOptimizerPlus/issues/126
        # for more information).
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        fastcgi_param DOCUMENT_ROOT $realpath_root;
        # Prevents URIs that include the front controller. This will 404:
        # http://domain.tld/index.php/some-path
        # Remove the internal directive to allow URIs like this
        internal;
    }

    # return 404 for all other php files not matching the front controller
    # this prevents access to other php files you don't want to be accessible.
    location ~ \.php$ {
        return 404;
    }

    error_log /var/log/nginx/project_error.log;
    access_log /var/log/nginx/project_access.log;
}

It is worth paying attention if there is no data passed it removes the Content-Type. The data must always be transmitted or be null. This is strange and it is misleading.


text:
Q: If $a_n \uparrow a$, then $\lim_{N\to \infty} \sum_{n=0}^{N-1} (a_N - a_n) = \sum_{n=0}^{\infty}(a -a_n)$ Suppose that $a_n$ is a sequence increasing to $a > 0$. Apparently, the following is true:
$$\lim_{N\to \infty} \sum_{n=0}^{N-1} (a_N - a_n) = \sum_{n=0}^{\infty}(a -a_n)$$
I am solving a problem and everything boiled down to proving the above equality. Can someone help me see this? (by hints or otherwise)
Thanks in advance

A: If you can readily use Lebesgue integration: Let $\zeta$ be the counting measure on $\mathbb{N}$, and for $N \in \mathbb{N}$ define $f_N(n) = (a_N - a_n)^+ = \max \{ a_N - a_n, 0\}$, and $f(n) = a-a_n$. Then $0 \leqslant f_N \uparrow f$, so by the monotone convergence theorem
$$\sum_{n = 0}^{N-1} (a_N - a_n) = \int_{\mathbb{N}} f_N\,d\zeta \uparrow \int_{\mathbb{N}} f\,d\zeta = \sum_{n = 0}^\infty (a - a_n).$$
Without Lebesgue integration: It's clear that
$$\sum_{n = 0}^{N-1} (a_N - a_n)\leqslant \sum_{n = 0}^\infty (a - a_n),$$
and that the sequence of finite sums is monotonically increasing. So the limit of the finite sums exists, and is not larger than the infinite sum (which may be $+\infty$ or $< +\infty$, that doesn't matter). For every $K < \sum_{n = 0}^\infty (a - a_n)$, choose an $M$ such that
$$\sum_{n = 0}^M (a - a_n) > K.$$
Since $a_N \uparrow a$, we have
$$K < \sum_{n = 0}^M (a_N - a_n) \leqslant \sum_{n = 0}^{N-1} (a_N - a_n)$$
for all large enough $N$, so
$$\lim_{N\to\infty} \sum_{n = 0}^{N-1} (a_N - a_n) > K.$$


text:
Q: Возможно ли изменить иконку Snapengage-чата для мобильных устройств? В настройках чата внутри crm snapengage можно изменить вид кнопки, единая кнопка под все экраны, возможно ли изменить её для мобильных девайсов?
*заменить саму иконку. изначально она загружается в  crm.

A:

if($(window).width() <= 600) {
 $("#img").attr("src","https://www.flaticon.com/premium-icon/icons/svg/69/69075.svg");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="https://image.flaticon.com/icons/svg/281/281769.svg" id="img" width="50px">


text:
Q: How can I use refresh token in react I have a get refresh token url like this client.com/api//auth/refresh-token. but I have a hard time using this. I think it should save a refresh token in the local storage after the login. but how can I use it?
login.tsx
export const useLogin = () => {

    const LoginAuth = async (data: AuthenticationProps) => {
        await axios.post(baseURL + `client/auth/login`,
        {
            email: data.email,
            password: data.password,
        },
        {
            headers: {
                "Content-Type": "application/json",
                Accept: "application/json",
            }
        }
        )
        .then((res) => {
            if(res.status === 200) {
                console.log("success")
            }
        }, (err) => {
            console.log(err);
        })

    }
    return {
        LoginAuth,
    }
}

A: You should not set the refresh token in local storage, it would cause a security vulnerability, since local storage is accessible by javascript, and since refresh token is long term token (live longer than access token), what you would do is, to store access token in local storage, since access token is short termed token, storing in local storage or cookies is totally fine, and then you should make an useEffect() call in react, that check whenever the token is expired and then make the call, a small example:
import Cookies from 'js-cookie';
axios.get("ur_url_here/",data,{withCredentials:true}).then((res)=>{
                Cookies.set(res.data.access) // assuming the response has the access token

}))

// now we check the expiration of access token

useEffect(()=>{
   if(!(Cookies.get("access"))){
      axios.get("refresh_url_here/",{withCredentials:true}).then((res)=>{
        Cookies.set(res.data.access)
})
/*what you do here, is try to have a
resource/view in your backend that has
the refresh token and make request to it
so that it gives you a new access token,
because refresh token should be in cookies tagged with `httponly',
then you can send the access token to client side
as a response and set it somewhere.
*/
}
   else{
      //do something else
}
},[])

this is a simplified code, but should explain well the idea of refreshing a token safely.
also note, i stored access in cookies, but you can do the same and store it in local storage.

A: Save it in local storage
export const storeToken = async (token: string) => {
  await AsyncStorage.setItem('@token', token);
};

And fetch from storage when needed
export const getToken = async () => {
  return await AsyncStorage.getItem('@token');
};

You should probably fetch the token from storage when application starts or when fetching from the API and store it in state or such while using the application.

A: Save in web storage
Only strings can be stored in web storage
LocalStorage
Persists even when the browser is closed and reopened.
Get
const token = localStorage.getItem('token');

Set
localStorage.setItem('token', 'value')

SessionStorage
Data removed when browser closed
Get
sessionStorage.getItem('token', 'value')

Set
sessionStorage.setItem('token', 'value')

A: You can use LocalStorage, or SessionStorage.
export const useLogin = () => {

    const LoginAuth = async (data: AuthenticationProps) => {
        await axios.post(baseURL + `client/auth/login`,
        {
            email: data.email,
            password: data.password,
        },
        {
            headers: {
                "Content-Type": "application/json",
                Accept: "application/json",
            }
        }
        )
        .then((res) => {
            if(res.status === 200) {
                console.log("success")
                window.localstorage.setItem('authToken', res.data.token);
                // Same as session storage
                // window.localstorage.setItem('authToken', res.data.token);
            }
        }, (err) => {
            console.log(err);
        })

    }

    return {
        LoginAuth,
    }
}

You can check here for the difference

A: The best way to store the refresh token is in localstorage.
Setting token in localstorage,
localStorage.setItem("token", token);

Getting token from localstorage
let token = localStorage.getItem("token");

You can also view the stored token in browser like below,

A: All the measures of security of web application logic process conclude by giving you access token and refresh token, then and its your responsibility to keep them safe. As long as these tokens are valid, they are only artifacts required to make an access. In fact if you look at OIDC flows the access token is not even handed to browsers in most of them because of so many known weaknesses of browsers in terms in security.
The best way to keep or store either of these tokens is to deal with them in back channel and if not then in browsers encrypt them with custom logic and store in local storage so that only your app knows how to use these tokens.
Better even to have the backend code does this part for you as you know javascript is always exposed and retrievable.
Hope this helps.


text:
Q: How to avoid that Facebook fetches some images of my website? I´m having problems with my cutenews and Facebook "share" buttons, but I´m working with "og:" metas to solve it.
In the mean time, another problem that I have (and I won´t solve it with Open Graph Protocol) it´s that some images are always fetched by Facebook and the most important images (the articles images) too but there isn´t the first choices.
So, if Facebook fetches 7 images, the first 3 options to people are always the banners images and not the articles images.
Is there any way to mark the images that I don´t want to be fetched by Google?
Sorry my bad english.

A: If you've already implemented the proper Open Graph tags (og:image, etc), then the next step is to determine if your implementation of those tags is valid.
Facebook provides an Open Graph debugger for exactly this purpose. Provide it with the URL in question, and it will tell you what to do next.