text:
Q: Windows Azure AD User Registration through custom UI I want to use Windows Azure AD for users management for my new Web App. For any new users who want to sing up to my web app they have to register themselves, for this scenario i want to add this new user to Azure AD through Azure providing Create User REST Web service call.
But here i need to pass the Authorization with Bearer Token as a request header for Create User call. I want to know how to obtain Bearer Token from Azure AD for performing user addition.
Since this case is at Home page of the application there are no authentications performed & there will be no Access Token/Bearer Token available.

A: I believe that this guide and code sample fully covers your scenario.

A: I have found out answer for my question:- below code snippet is written in Node JS

*

*ensure Your Application has got privilege to read/write access on Azure AD Graph

*Authorize the Client by sending following parameter
var data={
  grant_type: 'client_credentials',
  client_id: "********************************",
  client_secret: "***************************",
  resource: '00000002-0000-0000-c000-000000000000/graph.windows.net@<app_name>.onmicrosoft.com'};

   request.post('https://login.windows.net/<app_name>.onmicrosoft.com/oauth2/token?api-version=1.0', {form: data}, function(e, resp, body) {if (e) console.log(e);
    if (resp.statusCode == 200) {
       var appAccessToken = JSON.parse(body).access_token;
    }});

*Once we get the access token for the Application, we can use the same access token to perform all the Azure AD Graph operations.


text:
Q: indexing a numpy array containing functions I have a Numpy array, "nFuncs" containing function objects as blow:
array([ [<bound method ncNN.sigmoid of <__main__.ncNN object at 0x11c01f510>>,
         <bound method ncNN.sigmoid of <__main__.ncNN object at 0x11c01f510>>,
         <bound method ncNN.sigmoid of <__main__.ncNN object at 0x11c01f510>>],
        [<bound method ncNN.sigmoid of <__main__.ncNN object at 0x11c01f510>>,
         <bound method ncNN.sigmoid of <__main__.ncNN object at 0x11c01f510>>]], dtype=object)

What's the legitimate way to index this array?
when I tried nFuncs[1,1], I have IndexError: too many indices for array. However, nFuncs[1][1] works. Can you explain why I cannot use nFuncs[1,1]?

A: The array has shape (2,): It is 1-dimensional. This is because the first and the second sub-lists in the constructor have different lengths. So this is interpreted as a 1-d array of 2 lists. To get an array of functions insert a function into the second list (or remove one from the first).

A: Make a nested list:
In [8]: alist=[[1,2,3],[4,5]]
In [9]: len(alist)
Out[9]: 2

It's a list of 2 items; the items happen to be lists.  In some sort meta view it is 2d, but nothing about the list itself is 2d.
Make an array from it:
In [10]: arr = np.array(alist)
In [11]: arr.shape
Out[11]: (2,)
In [12]: arr.dtype
Out[12]: dtype('O')
In [13]: arr
Out[13]: array([[1, 2, 3], [4, 5]], dtype=object)
In [14]: arr[0]
Out[14]: [1, 2, 3]
In [15]: type(arr[0])
Out[15]: list

It too has 2 elements, in fact the same 2 sublists as alist (same id)
In [16]: id(alist[0])
Out[16]: 2992863468
In [17]: id(arr[0])
Out[17]: 2992863468

If I change an element of one of those sublists, the change appears in the other structure
In [18]: arr[0][1]=3
In [19]: arr
Out[19]: array([[1, 3, 3], [4, 5]], dtype=object)
In [20]: alist
Out[20]: [[1, 3, 3], [4, 5]]

For most purposes an object array like this is just like a list.  You can reshape it, eg. `arr.reshape(2,1)', but you can't append to it.  And to perform most actions you (or numpy) has to iterate through the elements just as if it were a list.
Contrast that with a 2d array of integers
In [21]: A=np.array([[1,2,3],[4,5,6]])
In [22]: A
Out[22]:
array([[1, 2, 3],
       [4, 5, 6]])
In [23]: A.shape
Out[23]: (2, 3)
In [24]: A.dtype
Out[24]: dtype('int32')

May be it will to visualize the object barrier if I change the elements of arr into arrays:
In [26]: arr[0]=np.array(arr[0])
In [27]: arr[1]=np.array(arr[1])
In [28]: arr
Out[28]: array([array([1, 3, 3]), array([4, 5])], dtype=object)

It is now an array of arrays; but that still not the same as a 2d array.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get the devanagari sign candrabindu with velthuis mapping? I am typesetting the following document and, to my dismay, I hit this issue in its title!

*

*See the example doc below. For now, I must use Velthuis mapping for typesetting in devanaagarii (as dictated by my current workflow which I am trying to improve, but that's for later).

*I need the title of the doc below to be गॅलरी. I do not know how to map in Velthuis the devanaagarii sign candrabindu (unicode code-point 0901 hex (e.g. as in गॅ)). According to the Velthuis encoding scheme (as documented in Devanaagarii for TEX package Version 2.17), the encoding for candrabindu is ~a. But this does not work as ~ is rendered verbatim in the PDF (via xelatex).

*I tried the workaround suggested in a similar question, but that does not seem to work. The title is rendered as .

I need it to render as
Can you suggest any workaround?
Minimum Example Source File
\documentclass[a4paper]{article}
\usepackage{polyglossia}
\usepackage[margin=10mm]{geometry}
\setdefaultlanguage{marathi}
\setotherlanguages{english}
\setmainfont[Mapping=velthuis-sanskrit,Script=Devanagari,Language=Sanskrit]{Shobhika}
\newfontfamily\englishfont{Lato}
% make sure ~ as non-breaking space doesn't interfere with velthuis-sanskrit mapping
\edef~{\string~}
\pagenumbering{gobble}
\begin{document}

\title{g~alarii}
\maketitle
\end{document}

A: \documentclass{article}
\usepackage{fontspec}
\setmainfont[Script=Devanagari]{Siddhanta}  %% use any other font in your OS.
\begin{document}
गॅलरी
\end{document}
You may use the online helpful editor
https://www.lexilogos.com/keyboard/devanagari.htm to key in गॅ.
This file processes coprrectly using XeLaTeX.


text:
Q: Consulta de packages en Python Estoy haciendo mis primeras pruebas para crear packages en python y no estaría lográndolo.
Tengo una carpeta llamada funciones, la que contiene n archivos de código python pero para la consulta va 1:
folder/func.py:
#!/usr/bin/python3
def function():
    print("soy una función")
    return

folder/__init__.py:
#!/usr/bin/python3
from func import function

Y por último en el directorio raiz del proyecto...
programa.py:
#!/usr/bin/python3
import folder
folder.function

Yo esperaba que al correr programa.py mostrara en consola "soy una función" pero recibo el siguiente error:

File "/.../prueba/programa.py", line 3, in  import folder
File "/.../prueba/folder/init.py", line 1, in  from func import function
ModuleNotFoundError: No module named 'func'

Alguna idea de dónde estoy metiendo la pata?

A: En el archivo __ init__.py
te falto el punto antes del func
es decir:
from .func import function

solo eso, el resto esta bien


text:
Q: Adding to regex, dont allow certain characters I have a regex that does not allow an url to start with http, and foreces it to start with www. Now I would like to add to it so it does not allow any special characters.
Current regex: ^(?!https?)www\..*$
Characters I do not want to allow: !"@#£¤$%&/{([)]=}?+`´*'
I'm using ASP.NET.
I've tried using negated characters for ex: [^%!] to not allow % and !, but can't get it to work, it just checks the first character of the word.

A: Use a negative lookahead assertion at the start which includes the list of characters you want to exclude.
^(?!.*?[!"@#£¤$%&\/{(\[)\]=}?+\\`´*'])(?!https?)www\..*$


text:
Q: Is {∅} ⊆ ∅? Set theory Is {∅} ⊆  ∅? I'm guessing no, as {∅} is a subset of {∅} but not of ∅. But I'm having doubts as ∅ is the only element in {∅} and ∅  is ∅.

A: Indeed $\{ \emptyset \} \neq \emptyset$ since it has one element : $\emptyset$

A: From the definition it follows that the only subset of the empty set is itself. By definition $\{ \phi \} \neq \phi$. So $\{ \phi \}$ is not a subset of $\phi$.

A: The set $\{\varnothing\}$ has one element i.e. $\varnothing$ while the set $\varnothing=\{ \}$ has no element. So the set inclusion doesn't hold.

A: It is indeed false.  For a nifty application of this investigate von Neumann ordinals.  The naturals are defined as $\emptyset,\{\emptyset\},\{\emptyset,\{\emptyset\}\},\dots$


text:
Q: Exporting MS Access Charts to Word/Excel I am amazed and dumbfounded to find out that a report generated in Microsoft Access will not include the charts I generated when exporting to Excel, Word or any other technology.
Has anyone found a work-around for this?  My user base needs to be able to copy/paste the generated reports (including graphics) into different status reports.  Copying/pasting does not seem to be possible directly from the Access report.

A: I would really need more info to help you (which version of Access, How are you generating the graph, etc.).
Have you tried the "Publish It to Microsoft Word" or "Analyze it with Microsoft Excel" options from Print Preview?
One option your users have is to Alt-PrintScreen and paste it.
What I typically do is have users install CutePDF Writer (it's free), and it lets them print to a PDF, which they then can send to whomever they want.

A: There is also something called snapshot, that can be further viewed by users and/or inserted in documents.

A: install CutePDF Writer (it's free), and it lets them print to a PDF

A: I'm not sure about Access 2003 but in Access 2007 you go to the chart properties and set Enabled to Yes. Afterwards you can copy and paste the chart in Excel and/or Word.

A: As a workaround I use a free screen capture utility for graphs generated in Access: get the graph on the screen, capture it, Paste or Paste Special into Word. Works well and fast, the only downside is losing resolution if you want the graph to be big (e.g. full page) in the Word document.


text:
Q: Quarkus Elytron LDAP security not finding UID I have added the Quarkus quarkus-elytron-security-ldap dependency to my project to enable basic auth on my REST services. I have configured it in my properties file as below. I know that it is connecting successfully to the LDAP repository, but it never finds the UID when doing a search:
quarkus.security.ldap.dir-context.principal=uid=serviceLdapAccount,ou=Systems,ou=Users,DC=COMPANY
quarkus.security.ldap.dir-context.url=ldap://some.server.com
quarkus.security.ldap.dir-context.password=*****

quarkus.security.ldap.identity-mapping.rdn-identifier=uid
quarkus.security.ldap.identity-mapping.search-base-dn=DC=COMPANY

I have confirmed that the user definitely exists in the repository and is included in the search base. But I always get this response:
[io.qua.ver.htt.run.sec.BasicAuthenticationMechanism] Found basic auth header requestAccountName:***** (decoded using charset UTF-8)
[org.wil.security] Obtaining lock for identity [requestAccountName]...
[org.wil.security] Obtained lock for identity [requestAccountName].
[org.wil.security] Trying to create identity for principal [requestAccountName].
[org.wil.security] Executing search [(uid={0})] in context [DC=COMPANY] with arguments [requestAccountName]. Returning attributes are []. Binary attributes are [].
[org.wil.security] Identity for principal [requestAccountName] not found.

Why can't it find the identity?

A: The seach-base-dn needed to be more specific:
quarkus.security.ldap.identity-mapping.search-base-dn=ou=Systems,ou=Users,DC=COMPANY

What I had before should work though, imo.


text:
Q: Implementing array bound canaries in C I would like to scatter some canaries in strategic positions in the data layout of a C program (with GCC, for embedded), to serve for checking whether some pointer ran into the wild.
Something like the following:
const volatile uint32_t canary_0 = CANARY_DEF;
static uint32_t some_global_array_0[SOME_SIZE_0] = {0};
const volatile uint32_t canary_1 = CANARY_DEF;
static uint32_t some_global_array_1[SOME_SIZE_1] = {0};
...

Of course I know that sample above is not functional, just for the idea. I would like to use something alike in safety-critical embedded software as an additional point for fallback, when all else (such as the usual array index bounds assertions etc.) fail to operate correctly.
I read this post on the GCC mailing list (I am scared to think that "craft" is to be interpreted as in "aircraft"...), suggesting to use structures. The problem is that in larger scale it feels like it would severely mess up program structure, losing more for this (developer pulling out hair & making bugs because of it) than winning by implementing such a failsafe mechanism.
For now my best bet would be using linker scripts (like necessary anyway to implement stack canaries) to split the RAM up in various segments, scattering canaries inbetween. This is however feels somewhat fragile, needing maintenance. (Or maybe not so? For now I know little of LD's linker scripts, only sufficient for the basics like adding a code flash CRC, stack canaries, and the like to the default script used for the micro. Right now I even lack the knowledge of how to make a flexible layout which would adapt to the amount of data allocated in sections)
For my purposes considering threads and messing up some operating system's structures are not of concern (for the point of actually being able to fall back when the situation arise), as here we design single threaded software architectures with no third-party components. If the main thread can't go around eventually reaching the fallback code, the watchdog kills it. It is OK to involve those in an answer, but please don't just post an answer stating something like this won't work because of an RTOS goofing up.

A: Indeed, the only reliable way to ensure that two data pieces are (nearly, up to alignment and padding) contiguous is to put them in a single aggregate (e.g. array or struct). Otherwise the compiler is permitted to optimize.
You might consider
volatile struct {
  uint32_t my1_canary_0 = CANARY_DEF;
  uint32_t my1_array_0[SOME_SIZE_0] = {0};
} my1;
#define canary0 my1.my1_canary_0
#define array0 my1.my1_array_0

So we are using structures, but the two macros above are "hiding" them!
However, I am not sure that declaring this entire struct to be volatile is a good idea
(maybe it might be enough to have only the canary be volatile). It might slow down significantly your code.
The main point is where and how do you check for the canary? You could do that manually (but it is tedious), adding a lot of
assert (canary0 == CANARY_DEF);

at many places (or your own assert-like checking). You could also consider customizing GCC with MELT for such purposes
(e.g. adding an optimization pass which would add the equvalent of above code inside every block accessing array0). Of course that requires a few weeks of work.
As I commented, the -fsanitize= options of recent GCC should also be helpful.


text:
Q: How can I remove border circle in TabPageSelector? I want to create something like this

But when I try to use such code:
TabPageSelector(
  controller: _tabController,
  color: Color(0x21000000),
  selectedColor: Colors.white,
),

I get in result:

What I can change for getting the exact result, which I showed in the first picture?

A: It's not supported by the TabPageSelector widget, but you can create your own Widget, I create one for you, check the code and add the file to your project:
https://gist.github.com/diegoveloper/9de80d0e22cac8a2ef4357a620b375a9
Usage:
        MyTabPageSelector(
                    controller: _controller,
                    color: Color(0x21000000),
                    //borderColor: Colors.blue     you can set your own color if you want
                    selectedColor: Colors.white,
                  )

A: I have understand what you want; to do this , actually ctrl and click on TabPageSelector ,then go to bottom search for TabPageSelectorIndicator (it's in the bottom) , then replace it with what's below with this :
class TabPageSelectorIndicator extends StatelessWidget {
  /// Creates an indicator used by [TabPageSelector].
  ///
  /// The [backgroundColor], [borderColor], and [size] parameters must not be null.
  const TabPageSelectorIndicator({
    Key key,
    @required this.backgroundColor,
    @required this.size,
  }) : assert(backgroundColor != null),
       assert(size != null),
       super(key: key);

  /// The indicator circle's background color.
  final Color backgroundColor;

  /// The indicator circle's diameter.
  final double size;

  @override
  Widget build(BuildContext context) {
    return Container(
      width: size,
      height: size,
      margin: const EdgeInsets.all(4.0),
      decoration: BoxDecoration(
        color: backgroundColor,
        shape: BoxShape.circle,
      ),
    );
  }
}

/// Displays a row of small circular indicators, one per tab. The selected
/// tab's indicator is highlighted. Often used in conjunction with a [TabBarView].
///
/// If a [TabController] is not provided, then there must be a [DefaultTabController]
/// ancestor.
class TabPageSelector extends StatelessWidget {
  /// Creates a compact widget that indicates which tab has been selected.
  const TabPageSelector({
    Key key,
    this.controller,
    this.indicatorSize = 12.0,
    this.color,
    this.selectedColor,
  }) : assert(indicatorSize != null && indicatorSize > 0.0),
       super(key: key);

  /// This widget's selection and animation state.
  ///
  /// If [TabController] is not provided, then the value of [DefaultTabController.of]
  /// will be used.
  final TabController controller;

  /// The indicator circle's diameter (the default value is 12.0).
  final double indicatorSize;

  /// The indicator circle's fill color for unselected pages.
  ///
  /// If this parameter is null then the indicator is filled with [Colors.transparent].
  final Color color;

  /// The indicator circle's fill color for selected pages and border color
  /// for all indicator circles.
  ///
  /// If this parameter is null then the indicator is filled with the theme's
  /// accent color, [ThemeData.accentColor].
  final Color selectedColor;

  Widget _buildTabIndicator(
    int tabIndex,
    TabController tabController,
    ColorTween selectedColorTween,
    ColorTween previousColorTween,
  ) {
    Color background;
    if (tabController.indexIsChanging) {
      // The selection's animation is animating from previousValue to value.
      final double t = 1.0 - _indexChangeProgress(tabController);
      if (tabController.index == tabIndex)
        background = selectedColorTween.lerp(t);
      else if (tabController.previousIndex == tabIndex)
        background = previousColorTween.lerp(t);
      else
        background = selectedColorTween.begin;
    } else {
      // The selection's offset reflects how far the TabBarView has / been dragged
      // to the previous page (-1.0 to 0.0) or the next page (0.0 to 1.0).
      final double offset = tabController.offset;
      if (tabController.index == tabIndex) {
        background = selectedColorTween.lerp(1.0 - offset.abs());
      } else if (tabController.index == tabIndex - 1 && offset > 0.0) {
        background = selectedColorTween.lerp(offset);
      } else if (tabController.index == tabIndex + 1 && offset < 0.0) {
        background = selectedColorTween.lerp(-offset);
      } else {
        background = selectedColorTween.begin;
      }
    }
    return TabPageSelectorIndicator(
      backgroundColor: background,
      size: indicatorSize,
    );
  }

  @override
  Widget build(BuildContext context) {
    final Color fixColor = color ?? Colors.transparent;
    final Color fixSelectedColor = selectedColor ?? Theme.of(context).accentColor;
    final ColorTween selectedColorTween = ColorTween(begin: fixColor, end: fixSelectedColor);
    final ColorTween previousColorTween = ColorTween(begin: fixSelectedColor, end: fixColor);
    final TabController tabController = controller ?? DefaultTabController.of(context);
    assert(() {
      if (tabController == null) {
        throw FlutterError(
          'No TabController for $runtimeType.\n'
          'When creating a $runtimeType, you must either provide an explicit TabController '
          'using the "controller" property, or you must ensure that there is a '
          'DefaultTabController above the $runtimeType.\n'
          'In this case, there was neither an explicit controller nor a default controller.'
        );
      }
      return true;
    }());
    final Animation<double> animation = CurvedAnimation(
      parent: tabController.animation,
      curve: Curves.fastOutSlowIn,
    );
    return AnimatedBuilder(
      animation: animation,
      builder: (BuildContext context, Widget child) {
        return Semantics(
          label: 'Page ${tabController.index + 1} of ${tabController.length}',
          child: Row(
            mainAxisSize: MainAxisSize.min,
            children: List<Widget>.generate(tabController.length, (int tabIndex) {
              return _buildTabIndicator(tabIndex, tabController, selectedColorTween, previousColorTween);
            }).toList(),
          ),
        );
      }
    );
  }
}

A: Just set the borderStyle
 TabPageSelector(
     controller: _tabController,
     color: Color(0x21000000),
     selectedColor: Colors.white,
     borderStyle: BorderStyle.none,
),


text:
Q: Im getting a Quota exceeded response from the YouTube API but my quota limits are not reached yet At least I think thats what this error message means:
HttpError: <HttpError 429 when requesting https://youtube.googleapis.com/youtube/v3/playlists?part=snippet%2Cstatus&alt=json returned "Resource has been exhausted (e.g. check quota).". Details: "Resource has been exhausted (e.g. check quota).">

But my YouTube Data API v3 quotas have not been fully used up:

I have used 31k from my 112k limit and as I understand it the Queries per minute quota is higher than my daily limit, so that should also be no problem.
Am I understanding it right that this error happened because of Quota Limits or is this from another source?
My request basically was creating a new playlist.


text:
Q: 'phing' is not recognized as an internal or external command, i am a laravel developer and i have integrated aimeos in laravel.There is a command specific to aimeos
phing -f phing.xml i18n which i try to run this command in the command line inside my laravel project
directory it gives me error
'phing' is not recognized as an internal or external command,
operable program or batch file.
please note that i have installed phing package through composer and it successfully installed because
i can see it in my composer.json file

{
    "name": "laravel/laravel",
    "type": "project",
    "description": "The Laravel Framework.",
    "keywords": [
        "framework",
        "laravel"
    ],
    "license": "MIT",
    "require": {
        "php": "^7.3|^8.0",
        "aimeos/ai-client-html": "2020.10.x-dev",
        "aimeos/aimeos-laravel": "~2020.10",
        "fideloper/proxy": "^4.4",
        "fruitcake/laravel-cors": "^2.0",
        "gettext/gettext": "^5.5",
        "guzzlehttp/guzzle": "^7.0.1",
        "laravel/framework": "^8.12",
        "laravel/jetstream": "^2.1",
        "laravel/sanctum": "^2.6",
        "laravel/tinker": "^2.5",
        "livewire/livewire": "^2.0",
        "phing/phing": "^2.16"
    },
    "require-dev": {
        "facade/ignition": "^2.5",
        "fakerphp/faker": "^1.9.1",
        "laravel/sail": "^1.0.1",
        "mockery/mockery": "^1.4.2",
        "nunomaduro/collision": "^5.0",
        "phpunit/phpunit": "^9.3.3"
    },
    "config": {
        "optimize-autoloader": true,
        "preferred-install": "dist",
        "sort-packages": true
    },
    "extra": {
        "laravel": {
            "dont-discover": []
        }
    },
    "autoload": {
        "psr-4": {
            "App\\": "app/",
            "Database\\Factories\\": "database/factories/",
            "Database\\Seeders\\": "database/seeders/"
        },
        "classmap": [
            "ext/moudhah/lib/custom/src",
            "ext/moudhah/controller/common/src",
            "ext/moudhah/controller/frontend/src",
            "ext/moudhah/controller/jobs/src",
            "ext/moudhah/client/html/src",
            "ext/moudhah/client/jsonapi/src",
            "ext/moudhah/admin/jqadm/src",
            "ext/moudhah/admin/jsonadm/src"
        ]
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\\": "tests/"
        }
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "scripts": {
        "post-update-cmd": [
            "@php artisan migrate",
            "@php artisan vendor:publish --tag=public --force",
            "\\Aimeos\\Shop\\Composer::join"
        ],
        "post-autoload-dump": [
            "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
            "@php artisan package:discover --ansi"
        ],
        "post-root-package-install": [
            "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "@php artisan key:generate --ansi"
        ]
    }
}

the reason why i posted that question here instead of aimeos forum because i think it is some kind of
composer issue

A: If you didn't add it to your path it won't be found. Most (all?) packages installed via composer have their exec's in the vendor/bin folder. phing is no exception to this.
Assuming you're on Linux you need to run
./vendor/bin/phing

from inside your project folder.


text:
Q: How to copy a map in golang? I can offer decomposition of map to 2 slices example:
func decomposeMap(m map[string]int) ([]string, []int) {
  var i uint
  l := len(m)
  keys, values := make([]string, l), make([]int, l)
  for keys[i], values[i] = range m {
    i++
  }
  return keys, values
}

but I am failing to write map copying:
func copyMap(m map[string]int) map[string]int {
  m2 := make(map[string]int, len(m))
  for id, m2[id] = range m {} // error - id is not declared
  for id, m2[id] := range m {} // error with m2[id] already declared
  // id should not be accessible here, it should exist only inside loop
  return m2
}

I can declare id as a var, but I dont want it to be available outside for loop. How can i mix assigment and declaration, eg: for id:=, m[id]= range m {} ?
So it will declare index just inside for loop, and will be not accessible outside?

A: The id variable must be declared before for, because you can't use short variable declaration with m2[id].
func copyMap(m map[string]int) map[string]int {
    m2 := make(map[string]int, len(m))
    var id string
    for id, m2[id] = range m {
    }
    return m2
}

But! This won't duplicate the map! The key is only assigned to id after m2[id] is already evaluated, so this loop will assign values to keys of the previous iteration, this is not duplicating, this is "shuffling"!
This is basically a tuple assignment (key and value are assigned to id, m2[id]). Spec: Assignments:

The assignment proceeds in two phases. First, the operands of index expressions and pointer indirections (including implicit pointer indirections in selectors) on the left and the expressions on the right are all evaluated in the usual order. Second, the assignments are carried out in left-to-right order.

So first id and m2[id] are evaluated (including the index expression), so id is not "yet" changed, so the value from the previous iteration is used, and only after this are the new key and values assigned.
To demonstrate, see:
m := map[string]int{
    "one":   1,
    "two":   2,
    "three": 3,
}
m2 := copyMap(m)
fmt.Println(m2)

Output (try it on the Go Playground):
map[:1 one:2 two:3]

The values are assigned to different keys (different than in the source map), and one value is assigned to the empty string key in the first iteration (the default, zero value of id).
To duplicate the map, simply use:
for id, v := range m {
    m2[id] = v
}

Or if you want to avoid the temporary assignment:
for id := range m {
    m2[id] = m[id]
}


text:
Q: RabbitMQ with Python: Acknowledging and rejecting messages individually while using executemany() I plan on receiving over 5 million messages a day with rabbitmq and I only have control over the consumer side. I wanted to use executemany to store the messages in batches but sometimes a message may be caught in an exception and I want just those individual messages to be rejected and simply acknowledge the rest. How can I selectively reject and acknowledge after an executemany()?
insert_sql = '''MERGE INTO table1
                        USING (
                        SELECT :col1 COL1, TO_TIMESTAMP(:col2, 'YYYY-MM-DD HH24:MI:SS,FF9') COL2,
                        :col3 COL3, :col4 COL4
                        FROM DUAL
                        ) source_table
                        ON (table1.COL1 = source_table.COL1 AND table1.COL2 = source_table.COL2
                        AND table1.COL3 = source_table.COL3 AND table1.COL4 = source_table.COL4)
                        WHEN NOT MATCHED THEN
                        INSERT (COL1, COL2, COL3, COL4, COL5, COL6, COL8)
                        VALUES (:col1, TO_TIMESTAMP(:col2, 'YYYY-MM-DD HH24:MI:SS,FF9'), :col3,
                        :col4, :col5, xmltype(:col6), xmltype(:col7))'''

def callback(ch, method, properties, body):
    # some code to clean up the body, snipping it off
    # ...
    if decompressed_j == None:
        _reject(delivery_tag=method.delivery_tag, requeue=False)
    elif isinstance(decompressed_j, dict):
        ch.basic_ack(delivery_tag=method.delivery_tag)
        global acx_list
        acx = ACX_Obj(decompressed_j, raw_jsonArray)
        if acx.response.startswith('<someignorabletag>'):
            ch.basic_reject(delivery_tag=method.delivery_tag, requeue=False)
        else:
            acx_list.append(acx.transactionValues)
        if len(acx_list) % 20 == 0:
            try:
                ora_exe(acx_list, ch, method)
            except AttributeError as att_e:
                print(att_e)
                ch.basic_reject(
                    delivery_tag=method.delivery_tag, requeue=False)
                raise att_e
            acx_list = []
    else:
        ch.basic_reject(delivery_tag=method.delivery_tag, requeue=False)

def ora_exe(acx_list, ch, method):
    conn = cx_Oracle.connect('dummy1/dummyenv', threaded=True)
    c = conn.cursor()
    try:
        c.executemany(insert_sql, acx_list)
    except cx_Oracle.IntegrityError as integrity_err:
        print('integrity err')
        conn.rollback()
    except cx_Oracle.DatabaseError as db_err:
        print(db_err)
        conn.rollback()
    else:
        conn.commit()
    finally:
        c.close()
        conn.close()


text:
Q: Opening a Chrome tab in a new window, the new window is transparent and also flickers When opening a Chrome tab in a new window, the new window becomes transparent and nothing is visible, as you can see in the following screenshot:

I have a GTX 1050 Ti (tried with driver version 470 and latest driver version 495 ).
I tried reinstalling Chrome and also tried previous versions of it, but still it is was not working properly and the issue remained.
See the video:
https://drive.google.com/file/d/1nwUhJOL4UQfd2_anQU9cvXKngZinp_Bb/view?usp=sharing


text:
Q: Cross-browser Text-indenting Is the a uniform cross-browser text-indenting technique ?
I use text-indenting to hide text and replace with images quite alot. I do something like the following: text-indent: -30000px;
But, on Chrone, IE, and Oprah the text is indented out so it's not visible but the width of the element is still as wide at the text.
Ordinarily, this would not be a problem except tah it looks one way on FF and entirely different on other browsers.

A: You most likely need to specify the width of the element as well.
If you're doing that and it's still not working, could you provide some sample code for us to take a look at?

A: I also use this technique at times to show images, but in all cases I'm also setting the width on the element to match the image swap. If you set the width you'll get consistent sizing of the block across most browsers * cough IE cough *.
If you're hiding the text but also need to rely on the width of the rendered text for spacing I'd question if you're using the right technique for that particular situation.


text:
Q: Cannot find symbol 'DirImp1' Corba client file:
import DirApp.*;
import org.omg.CosNaming.*;
import org.omg.CosNaming.NamingContextPackage.*;
import org.omg.CORBA.*;
import java.util.Scanner;
import java.lang.*;

public class DirClient
{
 static DirInterface DirImpl;

 public static void main(String args[])
 {  int ch=0;

 try{
             System.out.println("\n-----------------------------------  ");
    System.out.println("DirClient: Looking up DirServer...");

     // create and initialize the ORB
     ORB orb = ORB.init(args, null);

     // get the root naming context
     org.omg.CORBA.Object objRef =
     orb.resolve_initial_references("NameService");

     // Use NamingContextExt instead of NamingContext.
     // This is part of the Interoperable naming Service.
     NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef);

     // resolve the Object Reference in Naming
     String name = "DirOperations";
     DirImpl = DirInterfaceHelper.narrow(ncRef.resolve_str(name));

     System.out.print("DirClient: Obtained a handle on server object:\n\n");
     System.out.println(DirImpl);

     Scanner sc=new Scanner(System.in);
       do
       {

       System.out.println("1.add details 2. get details 3.Get phone number
       0.exit");
       ch=sc.nextInt();
       switch(ch){

                 case 1:
                 System.out.println("Input company name");
                 String namec=sc.nextLine();
                 System.out.println("Input company number");
                 String numbc=sc.next();
                 System.out.println("Input Details for company");
                 String detc=sc.nextLine();
                 DirImp1.adddetails(namec,numbc,detc);
                 break;

                 case 2:
                 System.out.println("Input company name to get itsdetails");
                 String name2=sc.next();
                 String det=DirImp1.getDetails(name2);
                 System.out.println(det);
                 System.out.println("Do you want to rate the company
                 (y/n)?");
                 String rate=sc.next();
                 DirImp1.Rate(rate,name2);
                 break;

                 case 3:
                 System.out.println("Enter name of the company to get
                 contact number");
                 String name1=sc.next();
                 String xx=DirImp1.getContact(name1);
                 System.out.println(xx);break;

                 case 0:System.exit(0);

                 }

        }while (ch!=0);

            DirImpl.shutdown();
    }
        catch (Exception e)
        {
             //System.err.println("ERROR: " + e);
             //e.printStackTrace(System.out);
             System.out.println("\n---------------------------------");
             System.out.println("DirClient: Some Error Has Occurred !");
             System.out.println("\n--------------------------------");
        }

        System.out.println("\nDirServer: Exiting...");
        System.out.println("\n----------------------");
    }
 }

A: You have declared your variable as DirImpl but you're using DirImp1, so change them to DirImpl or declare the variable as DirImp1.


text:
Q: Splitting an input signal into two separate opamps? I am designing a circuit that takes an incoming signal from a preamp and splits the signal into two shaping amplifiers to compare different amplifier settings (via the EL5163 opamps). I was wondering if some sort of buffer should be used to split the input signal. Or will splitting the signal how I have done in the schematic suffice?
EDIT: The input signal is 50 ohm impedance. I am testing RF signals. The signals being tail pulses with a 5 ns rise time.

A: what's your input signal's impedance?
That fully defines the answer to this: If it can drive two of your input circuits (R12, C6, L2, R11 || R1, C1, L1, R6) without appearing loaded, you're fine. Otherwise, you need to buffer.
Seeing that R11||R1 form a 500 Ω path to ground, for your source to be loaded less than 1% by that, you need a source impedance <= 5Ω for that alone, even if we ignore the two filters and the potentiometers after that.
Things that have a coax connector very rarely have impedances lower than 20Ω; so, maybe this wasn't a great design to start with!

A: It looks like you are testing RF signal. Matching the input impedance to the source wouldn't hurt. An RF splitter can help that.


text:
Q: How to generate convex polygon I really can't think of any method which would be efficient and faster. Does anyone has any clue?

A: make a circle around the centroid and inscribe the n-gon in that circle.


text:
Q: Can't restore a VM from a disk backup in Azure I can't get my VM disk restored in Azure: it is only "converted" to the Storage Account linked to my VM.
Does anyone know how to get a VM fully restored from a Recovery Service Vault backup in Azure please?
Edit :
For additional precision, I made a simple Linux VM hosting a test website in order to experience Azure's backup and restore feature.
So once the test website was online, I waited for a backup job to be done.
Then I deliberately broke the test website inside the VM, and launched a disk restore.
Unfortunately, the restore did nothing to the VM. I checked on the jobs and restore was marked as "Successful", and a VM restart did nothing.
Anyway, I can find the "vhd" in the Conainer tab of the Storage Account. But I can't find a way to attach it to the VM...
Is the disk restoration feature even supposed to work like intended ?

A: I tried to replicate a backed up restore of a virtual machine using Azure Site Recovery.
When you restore the virtual machine you have the option to select if you want to restore the disks or the virtual machine.

Selecting here to restore as a VM, will create the VM for you.
You can check that status of the restore by going to the jobs section of the machine in ASR.

For reference, see this page for more detailed instructions.

A: This likely flies in the face of what Azure thinks it can do, but have you tried to create the VM first and then just restore your data? Other possible options are:

*

*The user you are logged in as does have the correct permissions to create a VM in that space as well as restore the data, yes?

*And you did select Recovery Service vaults in the portal, correct?

*check if the original VM had any special conditions, such as multiple NICs or a load balancer. Any custom VM configurations, including HUB licensing, will not be duplicated with the Create Virtual Machine option as it uses Quick Create. You will need to use PowerShell to attach the restore disks to your chosen VM configuration. You can get additional information on PowerShell and Azure backups here.

*And in the link that kim provided above, scroll down to the "Create a new VM from a restore point" section and review the options and notes for creating a new VM. You can get more information on ASR at this page.


text:
Q: Why is the DOM incomplete after AJAX I have an AJAX function that populates a page using an on('click')... delegate function and creates 2 or more flex containers each of which has it's own unique id. The id and class is displayed in each flex div block. An outline of the code is shown below:
$('li.dicap_menu_action a').on("click",function(){
  var dicap_action =  $(this).attr("href");
  $.ajax({
    //call to php function that defines the blocks
  });
  return false; //prevent the browser from following the link
});

This works fine and output looks like this

Next I wanted to add content to each block based on the id value of the block and then the problems started. As a proof of concept, I created a function called populate_snapshot and added the function call to the code below the AJAX function:
$('li.dicap_menu_action a').on("click",function(){
    var dicap_action =  $(this).attr("href");
    $.ajax({
        //call to php function that defines the blocks
    });
    populate_snapshot();
    return false; //prevent the browser from following the link
});

so that it executes directly after the AJAX function to replace the content in each block. The populate_snapshot function looks like this
function populate_snapshot(){
    var $flx = $('div.dicap-flex-2');
    console.log($flx);
    $flx.each(function() {
        $(this).html('This block was found');
    });
}

However, the console log does not find the flex containers and the output does not change when this runs.
If I include an alert() into populate_snapshot as shown, then the function works fine after I dismiss the popup:
function populate_snapshot(){
    alert('Test');
    var $flx = $('div.dicap-flex-2');
    console.log($flx);
    $flx.each(function() {
        $(this).html('This block was found');
    });
}

the console log shows the 2 flex containers and output becomes

It is as though the DOM needs to be refreshed before the populate_snapshot function can run. Is there some way to do this or is there something more fundamental that I am missing. Is this an event-bubbling issue? and Is there some other way to delegate the populate_snapshot function so that it runs automatically after completion of the AJAX call?
I thought about using ajaxComplete() after the AJAX to trigger populate_snapshot, but this will not work because my populate_snapshot will later use another AJAX function and this will result in an endless loop.
Any help with this will be appreciated.

A: Thanks to @Andreas for his advice - this answer is totally to his credit.
Here is how I used this advice to solve my problem. The AJAX part of the code was changed as follows (notice the .then() function):
$('li.dicap_menu_action a').on("click",function(){
    var dicap_action =  $(this).attr("href");
    var aj = $.ajax({
        //call to php function that defines the blocks
    });
    aj.then(function(){
      populate_snapshot();
    })
    return false; //prevent the browser from following the link
});

The populate_snapshot function is:
function populate_snapshot(){
    var $flx = $('div.dicap-flex-2');
    console.log($flx);
    $flx.each(function() {
        $(this).html('This block was found');
    });
}

and the proof of concept output is as expected

Again, thanks and all quedos to @Andreas.


text:
Q: How can I create a dual boot, keeping in mind my pc boots to Ubuntu? So I got 2 new 500GB hard drives and I installed Windows 7 first on the first hard drive and on the second I installed 12.04 ubuntu.
Is there any software that I can use to make it easier to get a boot menu to choose the os that I want to boot into?

A: Try grub customizer via synaptic package manager. I use this for multi-boot systems.
A few years back I had a program on a cd called "super grub disk" that allowed one to boot-up any OS found on the pc. Try google as I cannot remember where I got it from. Hope this helps.


text:
Q: Bring index info to the groupby selection in PYthon Pandas Dataframe I have the following dataframe called 'grouped':

I am using the following code to bring the max/min for each column:
mm = grouped.agg(['max', 'min'])
mm

That brings me:

I know I can use '.T' to invert rows and columns but I still need to add which 'Day' this result happened.
The desired result I am looking for is:

can someone give me a hand?

A: Add DataFrame.idxmax, DataFrame.idxmin, then rename index and transpose:
mm = (grouped.agg(['max','idxmax', 'min', 'idxmin'])
             .rename({'idxmax': 'DateMax', 'idxmin': 'DateMin'})
             .T
             .astype({'DateMin':'int', 'DateMax':'int'}))


text:
Q: How to update string with Ecto I thought string concat was <> but I can't get it to work in the code below. I get an error

Only literal binaries and strings are allowed, dynamic values need to be explicitly interpolated in queries with ^

I've added ^ but it still does not work
  def delete(conn, %{"id" => id}) do
    card = Repo.get!(Card, id)

    # Look for any cards that have chosen one as master
    # Update name to deleted card + version name
    # remove master_id
    query =
        from(c in Card,
             where: c.master_id == ^id,
             update: [set: [ estimate_name: (^card.estimate_name <> ^c.estimate_name),
                             master_id: 0 ]])
        |> Repo.update_all([])

There is something strange about how the code is interpreted as my string fields are been read as functions I think:
<<^card.estimate_name()::binary, ^c.estimate_name()::binary>>

A: As one of the two parts you want to concatenate is a column from the table, you'll need the database to do the concatenation.
There is no function in Ecto to do this, so you'll have to use fragment. This should work on SQLite and PostgreSQL (I'm not sure about MySQL):
update: [set: [estimate_name: fragment("? || ?", ^card.estimate_name, c.estimate_name),
               master_id: 0]]


text:
Q: Deriving from PXGraph multiple time I'd like to have some common logic shared between two screens, so I want to have an abstract class inheriting from PXGraph, and then two different Graphs inheriting from this abstract class.
Like this :
namespace LE
{
    public abstract class ICarrySomeLogic : PXGraph<ICarrySomeLogic>
    {
        // common business logic
    }

    public class graph1 : ICarrySomeLogic
    {
        // specific business logic
    }

    public class graph2 : ICarrySomeLogic
    {
        // specific business logic
    }
}

Does it work correctly ? Is there a "best practice" or another proper way to do it ?
Thanks a lot,

A: I have done this before and works great. Here is my example simplified...
public abstract class MyGraphBase<TGraph, TPrimary, TWhere> : PXGraph<TGraph, TPrimary>
    where TGraph : PXGraph
    where TPrimary : class, IBqlTable, new()
    where TWhere : class, IBqlWhere, new()
{
    public PXSelect<TPrimary, TWhere> document;
}

public class GraphOneEntry : MyGraphBase<GraphOneEntry, MyDac, Where<MyDac.docType, Equal<DocType.typeOne>>>
{
}

public class GraphTwoEntry : MyGraphBase<GraphTwoEntry, MyDac, Where<MyDac.docType, Equal<DocType.typeTwo>>>
{
}

My events in the base abstract class will fire and I can override as needed in the other graphs.
I have been using this since version 5.3
Edit: starting in 2017R2 there is a new concept around Reusable Business Logic that can also be utilized for this same purpose.

A: The example you have given should do what you need. The inheritable traits and behavior of your abstract class will be inherited by your subclasses as expected.  This works for extension classes as well.  If you extend an existing Graph, you can then subclass your extension class to achieve inheritance.
Note: The "I" prefix for type naming is a standard in C# for interfaces, not classes. Even though abstract classes have some similarities to interfaces, they are not the same. If you want to follow Microsoft best practices, you might consider not using this prefix for class naming. If your I prefix is simply meant as the word "I" (as in you, yourself), then you can just ignore this note. :)


text:
Q: How to count the number of objects in a constructor javascript Im working with javascript and would like to know the number of objects inside of a constructor.
I have this:
var EventData = function(ID, Name, StartDate, StartTime, EndDate, EndTime, Location, Notes){
  this.type = "event";
  this.id = ID;
  this.name = Name;
  this.startDate = StartDate;
  this.startTime = StartTime;
  this.endDate = EndDate;
  this.endTime = EndTime;
  this.location = Location;
  this.notes = Notes;
};
EventData.prototype.count = function(){
  return //some code;
};

And i want to call something like this:
var Start = function(){
  var thisEventData = new EventData(1,"Bill", 1,1,1,1, "Home", "N/A");
  console.log(thisEventData.count());
};

Where thisEventData.count() would return 10.

A: The most natural way in this case would be to store parameters count in some property (maybe private). I'm not sure why you need this, but, yea, something like this:
var EventData = function (ID, Name, StartDate, StartTime, EndDate, EndTime, Location, Notes) {
    this._paramsCount = arguments.length;
    this.type = "event";
    this.id = ID;
    this.name = Name;
    this.startDate = StartDate;
    this.startTime = StartTime;
    this.endDate = EndDate;
    this.endTime = EndTime;
    this.location = Location;
    this.notes = Notes;
};
EventData.prototype.count = function () {
    return this._paramsCount;
};

UPD. Based on the edited question, look like you want to calculate number of own properties of the instance. In this case you would use convenient Object.keys method which returns an array of property names.
EventData.prototype.count = function () {
    return Object.keys(this).length;
};

A: Just get the properties of the EventData object as an array with Object.keys, and then the length of the array?
EventData.prototype.count = function(){
  return Object.keys(this).length;
};

A: If you want to know the number of canonical parameters, use the Function.length property, in your case:
EventData.length

or
thisEventData.constructor.length

Note that it won't count additional parameters (variable arguments) since it infers the count from the constructor object.
If you want to know the property count of the constructed object, use Object.keys:
Object.keys(thisEventData).length

This will give you the count of the own properties (excluding the prototype chain).
Or just write your own customizable logic if you need something else, for instance if you want non-falsey objects:
function getPropertyCount(obj, withPrototypeChain) {
    var prop;
    var count = 0;

    for (prop in obj) {
        if ((withPrototypeChain || obj.hasOwnProperty(prop)) && obj[prop])
            ++count;
    }

    return count;
}

A: To build a bit on the accepted answer:
export class Person {
      constructor (name, age) {
        if (arguments.length !== 2) {
          throw new Error('invalid Person argument count')
        }
        this.name = name
        this.age = age
      }
    }


text:
Q: Android Register Screen using Volley I tried to implement an Register Screen with Volley for android (School project). So far I finished the code but the register does not work. I tried to debug it and noticed the server gives me error 500 an internal server error. On my user interface it gives me a com.android.volley.server.
I double checked my url and code but everything seems to be fine. The url is fine because with the same url I can make requests via Postman. And code I could not find any mistakes as I am new to android and volley.. Maybe someone could give me a pointer. My school gave me a google.json file but I do not know if I am allowed to post it here.
This is my method where I make the request:
@Headers("Content-Type: application/json")
    public void registerData() {
        userName = Username.getText().toString();

        password = Password.getText().toString().trim();
        StringRequest request = new StringRequest(Request.Method.POST, BASE_URL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                    try{
                        JSONObject jsonobj = new JSONObject(response);
                        String MsgType = jsonobj.getString("MsgType");
                        if(MsgType.equals(1)){
                            Toast.makeText(registerActivity.this, "Geklappt",Toast.LENGTH_LONG).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        Toast.makeText(registerActivity.this, "Fail",Toast.LENGTH_LONG).show();

                    }
            }
        },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(registerActivity.this, "Fail: " + error.toString(),Toast.LENGTH_LONG).show();
                        error.printStackTrace();

                    }
                })
        {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> params = new HashMap<>();
                params.put("Username", userName);
                params.put("Password", password);
                return params;

            }
        };

        RequestQueue queue = Volley.newRequestQueue(this);
        queue.add(request);

    }

This is serverResposne which I can get (json)
    {
        "MsgType": 1,
        "Info": "Benutzer erfolgreich angelegt",
        "Data": null
    }

Parameters which the server accepts (tested postman)
        {"Username":"Fds",
        "Password":"Gdg"}

Here is the error as asked
  E/SpannableStringBuilder: SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
E/SpannableStringBuilder: SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
E/SpannableStringBuilder: SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
    SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
D/HwAutofillHelper: recordCurrentInfo:0
    inputType = 131073
D/mali_winsys: EGLint new_window_surface(egl_winsys_display *, void *, EGLSurface, EGLConfig, egl_winsys_surface **, EGLBoolean) returns 0x3000
W/libEGL: EGLNativeWindowType 0x7a31358250 disconnect failed
V/AudioManager: querySoundEffectsEnabled...
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
E/Volley: [38804] BasicNetwork.performRequest: Unexpected response code 500 for http://palaver.se.paluno.uni-due.de/api/user/register
D/: [ZeroHung]zrhung_send_event: wp = 257, ret = 0
D/: [ZeroHung]zrhung_send_event: wp = 258, ret = 0
D/: [ZeroHung]zrhung_send_event: wp = 260, ret = 0
Disconnected from the target VM, address: 'localhost:8600', transport: 'socket'


text:
Q: Getshopped (WP-e-commerce): show all protucts on one admin page for drag-and-drop ordering How I can show all my products on one page? I need drag-and-drop products from page 3 to page 1 but I can't do this over pages.
Or I can use another solution for manual product sorting?

A: Is that generic [enough] admin screen? Usually you should be able to set amount of posts per page via "Screen options" (upper right corner of admin on the page).


text:
Q: How to avoid duplicate notifications in iOS? My app shows up a local notification when the user disables the Wifi from iOS system settings. But it shows 'n' number of notifications if the user turns on and off the Wifi for 'n' number of times.
I would like to show the new notification only when the previous notification was cleared or user taps on the same to launch the app.
How can i achieve this?
Thanks in Advance.

A: You should call [[UIApplication sharedApplication] cancelLocalNotification:notification] before scheduling a new notification. It will cancel your notifications and user will receive only one notification.
For more check this.


text:
Q: Getting referential integrity constraint violation while trying to delete from OneToMany relation with cascadeType.ALL in hibernate This is the relevant code for the table I'm deleting from:
/**
     * Liste der Aufgaben der Abgabe
     */
    @Setter
    @OneToMany(fetch = FetchType.EAGER, cascade = {CascadeType.ALL})
    @JoinTable(
            name = "ABGABEAUFGABENZUORDNUNG",
            joinColumns = {@JoinColumn(name = "ABGABE")},
            inverseJoinColumns = {@JoinColumn(name = "AUFGABE")}
    )
    private List<Aufgabe> aufgaben = new ArrayList<>();

These are my hibernate functions for deleting and updating:
@Override
    public void update(Abgabe abgabe) throws NullPointerException {
        HibernateUtil.execute(s -> s.update(abgabe));
    }

    @Override
    public void delete(Abgabe abgabe) {
        HibernateUtil.execute(s -> s.delete(abgabe));
    }

These are my tables:
CREATE TABLE `Abgabe` (
                          `id` INT NOT NULL AUTO_INCREMENT,
                          `name` varchar(255) NOT NULL UNIQUE,
                          `gewicht` FLOAT NOT NULL,
                          `date` SMALLDATETIME NOT NULL UNIQUE,
                          `gruppenAbgabe` BOOLEAN,
                          `bewertet` BOOLEAN,
                          `kommentar` varchar(1000),
                          PRIMARY KEY (`id`)
);

CREATE TABLE `Aufgabe` (
                           `id` INT NOT NULL AUTO_INCREMENT,
                           `oberaufgabe_Id` INT,
                           `name` VARCHAR(255) NOT NULL,
                           `maxPunkte` FLOAT,
                           `maxPunkteMitGewicht` FLOAT,
                           `gewicht` FLOAT NOT NULL,
                           `bewertungskriterien` VARCHAR(255),
                           PRIMARY KEY (`id`)
);

CREATE TABLE `AbgabeAufgabenZuordnung` (
                                           `abgabe` INT NOT NULL,
                                           `aufgabe` INT NOT NULL
);

now when I try to delete a aufgabe from a abgabe I get this exception:
Caused by: org.hibernate.MappingException: Could not determine type for: de.unibremen.swp.model.benotung.Abgabe, at table: BEWERTETEABGABE, for columns: [org.hibernate.mapping.Column(ABGABE)]

I've seen other questions asked here where the answer was to use Cascade=CascadeType.ALl but this is not working for me.

A: This is not a runtime error "during delete" but a bootstrap error. Your model is not correctly mapped, but I can't help you unless you share your whole entity model.


text:
Q: uploadify + jQuery 1.4 response is empty after uploadComplete I'm using uploadify with jquery 1.4 to upload images. In the php script that uploads the files we print this:
$json_response['status'] = "true";
$json_response['file'] = $_FILES;
echo Zend_Json_Encoder::encode($json_response);

In javascript we do (in short):
$('#images_upload_file').uploadify({

    onComplete: function(event, queueID, fileObj, response, data) {

            console.log("upload complete");
            console.log(response);

the "response" is always empty, no matter what. Event, queueID, fileObj and data are all filled up correctly. Does anyone know how to fix this?
Let me know if you need more information. PS: our code uploads images just fine, just the response is empty all the time since we upgraded to jquery 1.4

A: I always use json2.js to process any json data. This library have safety mechanism in case the data is not in proper json format. You can get it from http://json.org, be sure to download the js file, not using it directly from their site.
My code always looks like this:
onComplete : function (event, queueID, fileObj, response, data) {
  //process response
  try {
    var r = JSON.parse(response);
    //process the JSON data, ex
    console.log(r.status);
  }
  catch(e) {
    //not json or bad format, do something about it
    alert("cannot parse data as json!");
  }
}

The reason I use json2.js is because my php script have session checking, and will redirect if the session is not accepted. It done before entering the page, using filter module, so I cannot check if it an AJAX request, or normal page access. If the required session is not satisfied the page's rule, it will redirect immediately, so it will return a full web page.
This will make the response is not in valid json format. Using json2.js I can handle it in catch block, then do another action, reloading current page for example. This is just something that I always use, and always working for me.
FYI, json2.js not require and not related with jQuery at all.

A: Is error_reporting turned on in the PHP script?
Could it be a fatal error (e.g. because it can't load the Zend_Json_Encoder class) that is not output because of the error_reporting setting?


text:
Q: Hide show error I have a dropdownlist and it is very simple. You click the button to go further you have error if you don't select nothing from DDL. But how i do to not appear the error when the user choose something from the DDL?
Here is the markup:
<asp:DropDownList ID="DropDownList1" runat="server" CssClass="jump">
     <asp:ListItem Text="" Value="0"></asp:ListItem>
     <asp:ListItem Text="Coupé" Value="Coupé" />
     <asp:ListItem Text="Cabriolet" Value="Cabriolet" />
     <asp:ListItem Text="Pickup" Value="Pickup" />
     <asp:ListItem Text="Kombi" Value="Kombi" />
     <asp:ListItem Text="Kombi-Coupé" Value="Kombi-Coupé" />
     <asp:ListItem Text="Minibuss" Value="Minibuss" />
     <asp:ListItem Text="Sedan" Value="Sedan" />
     <asp:ListItem Text="Skåpbil" Value="Skåpbil" />
     <asp:ListItem Text="SUV" Value="SUV" />
     <asp:ListItem Text="Övrig" Value="Övrig" />
</asp:DropDownList>

and code-behind:
if (DropDownList1.SelectedIndex == 0)
{
    err.InnerHtml = "Du måste välja Fordonstyp!";
    return;
}

Thank you so much in advance

A: As simple as this:
err.InnerHtml = "";
if (DropDownList1.SelectedIndex == 0)
    {
        err.InnerHtml = "Du måste välja Fordonstyp!";
        return;
    }

This will hide the error by default, then show it only if needed.
Edit: to support more than one drop down wrap it nicely with a function first:
private bool HandleDropDownError(DropDownList oDDL, HtmlGenericControl oErrorControl, string strErrorText)
{
    oErrorControl.InnerHtml = "";
    if (oDDL.SelectedIndex == 0)
    {
        oErrorControl.InnerHtml = "" + strErrorText + "";
        return false;
    }
    return true;
}

Now just use the same error label to show error for any drop down, and have such code in the Page_Load:
if (!HandleDropDownError(DropDownList1, err, "Du måste välja Fordonstyp!"))
    return;
if (!HandleDropDownError(DropDownList2, err, "Du måste välja matta!"))
    return;
if (!HandleDropDownError(DropDownList3, err, "Du måste välja byggnad!"))
    return;

A: You could also use a RequiredFieldValidator :
<asp:RequiredFieldValidator
        id="rfvFavoriteCar"
        Text="Du måste välja Fordonstyp!"
        ControlToValidate="DropDownList1"
        Runat="server" />

A: If you need to have a field selected, why not remove the empty selection line?
<asp:ListItem Text="" Value="0"></asp:ListItem>

A: if (DropDownList1.SelectedIndex == 0)
    {
        err.InnerHtml = "Du måste välja Fordonstyp!";
        err.visible = true;
        return;
    }
else
        err.visible = false;

A: I took your code modified it to work.  (at least what I think you are looking for)
   <asp:DropDownList ID="DropDownList1" runat="server" CssClass="jump" AutoPostBack="true">

and here
if (DropDownList1.SelectedIndex == 0)
{
    err.InnerHtml = "Du måste välja Fordonstyp!";
    return;
}else {err.InnerHtml = ""}


text:
Q: How does heapsort's big-O runtime relate to the number of comparisons made? I have read quite a bit on big-O notation and I have a basic understanding.  This is a specific question that I hope will help me understand it better.
If I have and array of 100 integers (no duplicates, and randomly generated) and I use heapsort to sort it, I know that big-O notation for heapsort is n lg n.  For n = 100, this works out to 100 × 6.64, which is roughly 664.
While I know this is the upper bound on the number of comparisons and my count can be less than 664, if I am trying to figure out the number of comparisons for a heap sorted array of 100 random numbers, it should always be less than or equal to 664?
I am trying to add counters to my heapsort to get the big-O comparison time and coming up with crazy numbers.  I will continue to work it out, but wanted to just verify that I was thinking of the upper bound properly.
Thanks!

A: Big-O notation does not give you an exact upper bound on a function's runtime - instead, it tells you asymptotically how the function's runtime grows.  If a function has runtime O(n log n), it means that the function grows at roughly the same rate as the function f(n) = n log n.  That means, for example, that the actual runtime could be 23 n log n + 17 n, or it could be 0.05 n log n.  Consequently, you can't use the fact that heapsort is O(n log n) to count the number of comparisons made.  You'd need a more precise analysis.
It just so happens that you can get a very precise analysis of heapsort, but it requires you to do a more meticulous analysis of the algorithm.  You can show, for example, that the number of comparisons required to call make-heap is at most 3n, and that the number of comparisons made during the repeated calls to extract-min is at most 2n log (n + 1) (the binary heap has log (n + 1) layers, and during each of the n extract-max's, at each layer at most two comparisons are made).  This gives an overall number of comparisons upper-bounded by 2n log (n + 1) + 3n.
The famous Ω(n log n) sorting barrier can be used to get a matching lower bound.  Any comparison-based sorting algorithm, of which heapsort is one, must make at least log n! = n log n - n + O(log n) (this is Stirling's approximation) comparisons on average, and so heapsort is required to make at least n log n - n comparisons in the worst-case.  (Note that this is actually n log n, not some constant multiple of n log n.  You can read over the proof of the Ω(n log n) barrier for why this is.)
Hope this helps!

A: Let's say that you know that your algorithm requires O( n log_2 n ) comparisons when sorting n elements.
This tells you the following, and only the following: there exists a constant number C such that, as n approaches infinity, the algorithm never requires more than C * n * log_2 n comparisons.
It does not tell you anything about the specific number of comparisons that might be required for any value of n -- it tells you about how the number of comparisons required grows in the limit as the number of elements grows.
You can not use the Big-O complexity of your sorting algorithm to prove anything about the behaviour of a particular finite n, such as 100 elements. Sorting 100 elements might require 64 comparisons, or 664, or 664 million. The latter is clearly not reasonable, but Big-O simply provides no information here.


text:
Q: Calling C# enum to React Component I am using enum in my .Net Core Web API to list types of cuisine in my project such as
public enum CuisineClass
{
    American = 1,
    British = 2,
    Chinese = 3
}

and so on.
At this point when I'm mapping my GetRestaurantDto and calling my endpoint from in my react SPA, I get the int instead of the string.
Is there a way to get the string instead?

A: You can use JsonStringEnumConverter. In .NET 5 use it this way:
`services.AddControllers()
.AddJsonOptions(o =>
 {
o.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
});`

A: Why return the full name? If you are using typescript you can setup the enum on your reactjs application too and handle it as such.
export enum CuisineClass
{
    American = 1,
    British = 2,
    Chinese = 3
}

You can then access the strings from TS if you want How to get names of enum entries?


text:
Q: How to read a 2-D array and write it into console as a matrix I wanted to read a 2-D array and write it as a matrix to the console.My code is shown below
To read the Array
int[][] arr = new int[3][];
for(int i=0;i<3;i++)
{
    arr[i] = Array.ConvertAll(Console.ReadLine().Split(' '),aTemp => Convert.ToInt32(aTemp));
}

To write the array as matrix to the console
for(int i=0;i<arr.GetLength(0);i++)
{
    for(int j=0;j<arr.GetLength(1);j++)
    {
         Console.WriteLine("\t" + arr[i][j]);
    }
}

However when I enter the input in the console and try to run, I am getting an Index out of bound exception in here
arr.GetLength(1);

I then tried initializing the column too like this with both row and column
"int[][] arr = new int[3][3];".
At that time another error comes saying

Invalid rank specifier:expected ','or ']'

Then I tried initializing the array as below
"int[,] arr = new int[3,3];"

The invalid rank specifier error gone this time but error comes in the line of reading array elements,
probably this error may be due to not using arr[i][j] and reading each elements.
I just want to know what was the mistake in my initial code,that I don't get the value of GetLength(1).
and What is the difference between int[,] arr = new int[3,3]; and int[][]arr = new int[3][3];
and also is there any optimized way to read a 2-d array like the statement, rather than using 2 for loops.
I hope the question is clear. It would be so nice if somebody helps me with this problem. Thanks in Advance!!!

A: int[,] is a multidimensional array
int[][] is a jagged array, which is an array of arrays. A jagged array as described like this doesn't have a rank, and calling GetLength(rank) will cause an error as it only has one technical dimension to the compiler. It's just a single array, with each element filled with another array.
To write a jagged 2d array into a matrix, you could take advantage of string.Join

Concatenates the elements of a specified array or the members of a
collection, using the specified separator between each element or
member.

var arr = new [] {new []{1,2,3},new []{4,5,6},new []{7,8,9}};

for(int i = 0; i< arr.Length; i++)
    Console.WriteLine(string.Join(", ",arr[i] ));

Output
1, 2, 3
4, 5, 6
7, 8, 9

Or another approach
for (var i = 0; i < arr.Length; i++)
{
   for (var j = 0; j < arr[i].Length; j++)
      Console.Write(arr[i][j] + " ");
   Console.WriteLine();
}

or
foreach (var t in arr)
{
   foreach (var t1 in t)
      Console.Write(t1 + " ");
    Console.WriteLine();
}

or
var result = string.Join(Environment.NewLine, arr.Select(x => string.Join(", ", x)));
Console.WriteLine(result);

For a multi dimensional 2d arrays, you can then call GetLength(rank) to get the length of that particular dimension
var arr = new [,] {{1,2,3},{4,5,6},{7,8,9}};

for (var i = 0; i < arr.GetLength(0); i++)
{
   for (var j = 0; j < arr.GetLength(1); j++)
      Console.Write(arr[i, j]);
   Console.WriteLine();
}

A: I agree with @TheGeneral that defining jagged arrays have many advantages. I personally like to show 2D array data with fixed-width columns.
For example
static void Main(string[] args)
{
    var data = new[] { new[] { 1, 2, 3 }, new[] { 4, 5, 6 }, new[] { 7, 8, 9 } };
    var matrix = new MatrixJagged(data);

    Console.WriteLine("Matrix =");
    Console.WriteLine(matrix.ToTableFormat(4));
    // Matrix =
    // | 1    2    3 |
    // | 4    5    6 |
    // | 7    8    9 |
}

Here is starting jagged array class to be able to store data, read data and format it into a table.
public class MatrixJagged
{
    readonly int[][] data;

    public MatrixJagged(int[][] data)
    {
        this.data = data;
        this.RowCount = data.Length;
        this.ColumnCount = data.Length > 0 ? data[0].Length : 0;
    }
    public MatrixJagged(int rowCount, int columnCount, int[] array)
    {
        RowCount = rowCount;
        ColumnCount = columnCount;
        this.data = new int[rowCount][];
        int index = 0;
        for (int i = 0; i < rowCount; i++)
        {
            var row = new int[columnCount];
            Array.Copy(array, index, row, 0, columnCount);
            this.data[i] = row;
            index += columnCount;
        }
    }
    public MatrixJagged(int rowCount, int columnCount)
    {
        RowCount = rowCount;
        ColumnCount = columnCount;
        this.data = new int[rowCount][];
        for (int i = 0; i < data.Length; i++)
        {
            data[i] = new int[columnCount];
        }
    }
    public ref int this[int row, int column] { get => ref data[row][column]; }
    public int[] GetRow(int row) => data[row];
    public int RowCount { get; }
    public int ColumnCount { get; }

    public static MatrixJagged ReadFrom(string path)
    {
        return ReadFrom(File.OpenText(path));
    }
    public static MatrixJagged ReadFrom(StreamReader reader)
    {
        var rows = new List<int[]>();
        while (!reader.EndOfStream)
        {
            var line = reader.ReadLine();
            var parts = line.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            var row = parts.Select((s) => int.Parse(s)).ToArray();
            rows.Add(row);
        }
        return new MatrixJagged(rows.ToArray());
    }

    public string ToTableFormat(int columnWidth, bool withBrackets=true)
    {
        var sb = new StringBuilder();
        for (int i = 0; i < RowCount; i++)
        {
            if (withBrackets) { sb.Append("| "); }
            sb.Append(string.Join(" ", data[i].Select(
                (x) => x.ToString().PadLeft(columnWidth))));
            if (withBrackets) { sb.Append(" |"); }
            sb.AppendLine();
        }
        return sb.ToString();
    }
}


text:
Q: Kusto ANY / ALL operators (larger than column) I have a query like the following (data taken from tutorial)
SELECT State, EventType, DamageProperty From StormEvents where DamageProperty >= ALL(select DamageProperty from StormEvents where State = 'NEW YORK') AND EventType = 'Wildfire'

I want to translate this query to KQL, but I'm having trouble with translating the ALL operator.
The following query would receive the same results:
StormEvents | where (DamageProperty >= toscalar( StormEvents | where State == "NEW YORK" | summarize max(DamageProperty) ) and EventType == "Wildfire") | distinct State, EventType, DamageProperty | limit 1000

But I don't want to use max(), I want for future use know how to use the any / all operators (and somehow I didn't find something related on Google).

A: I don't know Kusto.  But the following SQL is equivalent:
select se.State, se.EventType, se.DamageProperty
from StormEvents se
where se.DamageProperty >= (select max(se2.DamageProperty)
                            from StormEvents se2
                            where se2.State = 'NEW YORK'
                           ) and
      se.EventType = 'Wildfire';

I also find it odd that you are filtering on the event type only in the outer query.  I would expect the same filter in the subquery as well.
Note:  There is a difference between this version and your query, if there are no matching rows in the subquery.  You can handle this with a slight tweak:
where se.DamageProperty >= (select coalesce(max(se2.DamageProperty), se.DamageProperty)
                            from . . .

A: Turns out there isn't a direct translation to ANY / ALL.
The answer I received from Microsoft support:

We have looked upon your request and unfortunately we could not find a
  way to translate the ANY/ALL operators in a Kusto stream at this
  moment. We will keep searching for a workaround but we recommend you
  to try looking for alternatives.


text:
Q: Doctrine setparamers in wrong order It seems that doctrine sets parameters in a wrong order. I have the following parameter array:
$params = array(
        1 => array(1, 2, 3, 4, 5, 6),
        2 => array(150, 12, 130),
        3 => 'CALLED',
        4 => array('ND', 'PF', 'OS'),
        5 => '2015-07-02 00:00:00',
        6 => '2015-07-05 00:00:00'
    );

And i have the following query
$query = $this->getEntityManager()->createQuery('
        SELECT c FROM Customers\Entity\Customer c
        WHERE c.customer_categories_id IN(?1)
        AND c.countries_id IN(?2)
        AND c.state = ?3
        AND c.potential_diamonds IN(?4)
        AND c.last_call NOT BETWEEN ?5 AND ?6
        ');

$query->setParameters($params);
$result = $query->getResult();

And this is the final query:
SELECT c0_.id AS id_0, c0_.company AS company_1, c0_.vat_number AS vat_number_2, c0_.first_name AS first_name_3, c0_.last_name AS last_name_4, c0_.phone AS phone_5, c0_.phone2 AS phone2_6, c0_.mobile AS mobile_7, c0_.email AS email_8, c0_.email2 AS email2_9, c0_.fax AS fax_10, c0_.address AS address_11, c0_.address2 AS address2_12, c0_.postal_code AS postal_code_13, c0_.town AS town_14, c0_.province AS province_15, c0_.countries_id AS countries_id_16, c0_.customer_titles_id AS customer_titles_id_17, c0_.customer_categories_id AS customer_categories_id_18, c0_.present_list AS present_list_19, c0_.vip_list AS vip_list_20, c0_.previous_sold AS previous_sold_21, c0_.previous_bought AS previous_bought_22, c0_.opening_hours AS opening_hours_23, c0_.main_office AS main_office_24, c0_.newsletter AS newsletter_25, c0_.website AS website_26, c0_.`state` AS state_27, c0_.potential_diamonds AS potential_diamonds_28, c0_.remarks AS remarks_29, c0_.date_created AS date_created_30, c0_.date_changed AS date_changed_31, c0_.last_call AS last_call_32, c0_.customer_languages_id AS customer_languages_id_33, c0_.display_state AS display_state_34, c0_.longitude AS longitude_35, c0_.latitude AS latitude_36 FROM customers c0_ WHERE c0_.customer_categories_id IN ('ND', '2015-07-05 00:00:00', 'CALLED', 130, 130, 'CALLED') AND c0_.countries_id IN ('ND', '2015-07-05 00:00:00', '2015-07-02 00:00:00') AND c0_.`state` = 'PF' AND c0_.potential_diamonds IN ('2015-07-02 00:00:00', 'OS', 'PF') AND c0_.last_call NOT BETWEEN 'OS' AND 12

if we look in the WHERE part of the query than we see that the parameters are completely flipped. This is very strange. does anyone have an explanation for this or have the same problem? There is not much to find on google.
Thanks in advance


text:
Q: Подсказки типов. Как указать всех наследников абстрактного класса? class A(metaclass=ABCMeta):
    pass

class B(A):
    pass

class C(A):
    pass

def fun(a: "A"):
   pass

Хочу чтобы функция(метод) принимала аргументом экземпляр любого из подклассов абстрактного класса. Как такие вещи правильно указывать?

A:
Хочу чтобы функция(метод) принимала аргументом экземпляр любого из подклассов абстрактного класса

fun() уже принимает всех наследников A в примере:
#!/usr/bin/env python3
class A:
    pass

class B(A):
    pass

def isA(a: A):
    return isinstance(a, A)

print(isA(B()))
print(isA(1))

выводит ожидаемую ошибку при проверке с помощью mypy:
$ python3 . && mypy __main__.py
True
False
__main__.py:12: error: Argument 1 to "isA" has incompatible type "int"; expected "A"

Видно, что экземпляр B, не вызвал ошибку, так как B подкласс A.
Для обычных подклассов это работает с и без A(metaclass=abc.ABCMeta). Но виртуальные подклассы через A.register(klass) или через A.__subclasshook__ не работают с mypy==0.4.6.
Метаклассы вообще и abc.ABCMeta в частности пока не поддерживаются, см:
Unsupported Python Features.

A: from abc import ABCMeta

class A(metaclass=ABCMeta): pass
class B(A): pass
class D: pass

def fun(a: A):
    if issubclass(a.__class__, fun.__annotations__['a']):
        print(True, a)
    else:
        print(False, a)

b = B()
d = D()
fun(b)
fun(d)


text:
Q: How can I view html from the node console? I have a javascript code that dumps an object, downloaded it from https://github.com/johan/node-dump.
Unfortunately, it prints an HTML, which is not very helpful, since I am working from the node console. How can I send this html output to some HTML rendering engine to display it visually? This could be a browser or a node plugin capable to display HTML snippets in a window.
I am on Windows 7.
EDIT
Guys, I do not need to beautify html. I want to render it.

A: Have you considered just using console.log() or console.dir() to print your object in the console in a human-readable format?


text:
Q: In a 4 hour Powershell 101 class should I skip for/while/do and just teach ForEach-Object I'm making a syllabus to teach non-programmer co-workers PowerShell. The first non-pilot group I will run the course with will be a team that deploys and configures one of our software products. They are bright intelligent motivated IT workers, but not programmers.
I intend to cover the basics (variables, arrays, functions, and loops), and then move onto examples that are close to their problem domain. I'm not married to a 4 hour class, if necessary I can expand it to two four hour classes.
I'm toying with the idea of skipping for and while loops and simply teaching ForEach-Object. I've personally used traditional for and while loops in powershell scripts, but they can always be rewritten  as ForEach-Object loops with a bit of creativity. Part of me feels the good old for ($i=0 $i < foo; $i++) is a necessary fundamental before moving onto foreach, but the other part of me thinks that might be me clinging to my Model M and my K&R Bible.
To draw an analogy to SQL, I'd never teach a CURSORs or other loops in a 4 hour class there because you're supposed to be able to do everything in SQL as a SET operation. In theory you should stick to the pipeline in PowerShell. I use for and while loops in PowerShell more often than I do do cursors and while loops in SQL. However, PowerShell is a scripting language and conventions are less strictly enforced and I also push the boundaries of powershell with inline C# and excessive dependencies on calling native .NET APIs. My audience will not be ding this.
For those not adept at powershell, I'm pretty sure you don't actually need a for or while loop. I use them, but that's because I have experience with other languages. For example if you only want the first 10 members of an array of 20 members:
1..20 | Select-Object -First 10 | ForEach-Object { Write-Host $_ }

A: Why skip them? I appreciate you are time restricted, but include the syntax of each with a little example in the course notes at the very least. You don't have to spend more than 30 seconds describing them.
If they can't code a "display the first 10" easily I think you've missed a trick.

A: Touching on the basic loop constructs is very important -- if for nothing else than giving the students a fighting chance when they see the for/while constructs in the wild.

A: I think the key part of your post rather spells out that you shouldn't skip them:

I've personally used traditional for and while loops in powershell scripts, but they can always be rewritten as ForEach-Object loops with a bit of creativity.

I feel that it's good to know how to do the basic for/while/do loops so that you can take the next step to realize that creativity. It really doesn't take long to teach loops to people, and it would be a good lead in for the foreach loop.
So why not make it for/while/do/foreach, and walk though each one? You can even say right in the training that the foreach-object loop will be the one they use most, and you could spend more time on it.

A: I think this hinges on what kind of programming experience they have coming in --
If they are rank beginners and have never seen loops/control structures before they definitely need to see traditional for and while structure: They'll see it in the wild (in nearly every language they'll ever use), and it shouldn't be a surprise when they do.
ForEach-Object, much like Perl's foreach is a tasty shortcut dipped in syntactic sugar.  They should know it because it saves a lot of typing and is logical when you read it.
If they're already programmers (or have at least some limited experience) they'll grasp the concept quickly.  If not, contrive a for loop that is easier to do with ForEach-Object, and have them do it both ways (for loop first, ForEach-Object second) so they see a real and immediate benefit.

A: I find myself using the for and while loops a lot in powershell. When I have a boolean I just write while($bool). I think that it is important to atleast touch on these concepts, considering they are found in a lot of other programming languages.
A better example that you may not be able to do with a foreach loop (effeciently atleast) is take every other object out of an array:
for($i=0; $i -le $arr.length-1; $i=$i+2) {$newArr += $arr[$i]}

I find myself using this one alot after a -split

A: Traditional for and while loops I don't think add much value to a 4 hour course.  Ideally they are taking your course so they can write scripts and get stuff done.  A ForEach loop is easier and sufficient to get the job done most of the time.   If they need the traditional loop construct then they can always learn it when they need it.  Same thing with objects, they don't need a deep understanding, just enough to know how to use methods.


text:
Q: How to calculate the mean in R with several conditions I am trying to calculate the means of this data frame and group them in a tale! I know how to do that using averageifs in excel but because I want to eventually get the standard deviation and coefficient of variation (CV) I need to learn that in R.
For now I just need the mean. Here are my conditions:
I need a table where the "stim_ending_t" which is my time intervals are arranged from 1.0 to 3.5 in a rows. For time intervals I need these three conditions to be met while calculating the mean which is "key_resp_2.rt"
only image Visibility and soundvolume(V=1 & s=0)
Only Sound (V=0 & s=1)
Blank (V=0 & s=0)
The data frame
Expected out come

A: This will compute stim_ending_t (6) x modality (3) = 18 group means.
First I generate some data like your analysis_v or analysis_a data frames:
library(dplyr)
library(tidyr)

analysis_v <- data.frame(stim_ending_t = rep(seq(1, 3.5, 0.5), each = 30),
                         visbility = rep(c(1, 0, 0), 60),
                         soundvolume = rep(c(0, 1, 0), 60),
                         key_resp_2.rt = runif(180, 1, 5))

Then I pipe the object into the code block:
analysis_v %>%
  group_by(stim_ending_t, visbility, soundvolume) %>%
  summarize(average = mean(key_resp_2.rt)) %>%
  ungroup() %>%
  mutate(key = case_when(visbility == 0 & soundvolume == 0 ~ "blank",
                         visbility == 0 & soundvolume == 1 ~ "only_sound",
                         visbility == 1 & soundvolume == 0 ~ "only_images")) %>%
  select(-visbility, -soundvolume) %>%
  spread(key, average)

Which results in the requested output format:
# A tibble: 6 x 4
  stim_ending_t blank only_images only_sound
          <dbl> <dbl>       <dbl>      <dbl>
1           1    3.28        3.55       2.84
2           1.5  2.64        3.11       2.32
3           2    3.27        3.72       2.42
4           2.5  2.14        3.01       2.30
5           3    2.47        3.03       3.02
6           3.5  2.93        2.92       2.78

You would need to repeat the code block using analysis_a to get those means.

A: Thank you for your help @Matthew Schuelke, but with your code I was getting different results every time I run the code.
Here is how I solved the problem with this code:
name of the new data = (name of the data frame without the parentheses) %>%
  group_by(stim_ending_t, visbility, soundvolume, Opening_text) %>%
  summarize(m = mean(key_resp_2.rt),
            sd = sd(key_resp_2.rt),
            coefVar = cv(key_resp_2.rt))

The result as I wanted:
stim_ending_t visbility soundvolume Opening_text               m     sd coefVar
          <dbl>     <dbl>       <dbl> <chr>                  <dbl>  <dbl>   <dbl>
1             1         0           0 Now focus on the Image  1.70  1.14    0.670
2             1         0           0 Now focus on the Sound  1.57  0.794   0.504
3             1         0           1 Now focus on the Image  1.62  1.25    0.772
4             1         0           1 Now focus on the Sound  1.84  1.17    0.637
5             1         1           0 Now focus on the Image  3.19 17.2     5.38
6             1         1           0 Now focus on the Sound  1.59  0.706   0.444


text:
Q: Location counter not changing I have a linker script like the one below :
....
.MemSection :
{
    _MEM_SEC_BEGIN = . ;

    *(.bss .vbss.* .section.*)

    *(.common)

    _MEM_SEC_END = . ;

} > RAM

_MEM_SEC_END_OUTSIDE = . ;

ASSERT( (_MEM_SEC_END_OUTSIDE == _MEM_SEC_END) , "Warning message" )

ASSERT( (_MEM_SEC_END_OUTSIDE != _MEM_SEC_BEGIN) , "Warning message" )

....
All the names are fictive , but the structure is the same.
The problem is that asserts are failing , I don't know why my location counter is not changing . Please keep in mind that my .MemSection is not empty .
In which situation the location counter could remain the same after an output section definition ?
Thank you !


text:
Q: SQLite: full outer join with four tables with 30+ columns This question is an extension to this post
 I want to join four different tables with SQLite which have just two columns in common. However, assume that there are 30+ columns, i.e more than just columns a - h. Please take a look at following example
Table1:
a   b   lon lat
---------------
22  33  11  22

Table2:
c   d   lon lat
---------------
1   2   44  45

Table3
e       f       lon lat
-----------------------
NULL    NULL    100 101

Table4
g       h       lon lat
-----------------------
NULL    NULL    200 201

The current solution is the following
SELECT a,b,NULL AS c, NULL AS d,NULL AS e, NULL AS f, NULL AS g, NULL AS h,
lon,lat
FROM table1
UNION ALL
SELECT NULL, NULL,c,d,NULL AS e, NULL AS f, NULL AS g, NULL AS h, lon,lat
FROM table2
UNION ALL
SELECT NULL, NULL,NULL,NULL,e,f, NULL AS g, NULL AS h, lon,lat
FROM table3
UNION ALL
SELECT NULL, NULL,NULL,NULL,NULL,NULL,g,h, lon,lat
from table4

Result:
+------+------+------+------+------+------+------+------+-----+-----+
|  a   |  b   |  c   |  d   |  e   |  f   |  g   |  h   | lon | lat |
+------+------+------+------+------+------+------+------+-----+-----+
| 22   | 33   | NULL | NULL | NULL | NULL | NULL | NULL |  11 |  22 |
| NULL | NULL | 1    | 2    | NULL | NULL | NULL | NULL |  44 |  45 |
| NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | 100 | 101 |
| NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | 200 | 201 |
+------+------+------+------+------+------+------+------+-----+-----+

DEMO

*

* Problem: What if I have not just the columns a until h, but a until z, i.e many many columns in table1, table2, table3, and table4 -> It would be very time-consuming and the structure wouldn't be clear if I had to write everywhere NULL as [letter] in my sql statement

* @zarruq was a huge help and he suggested that In that case I can just use `UNION ALL` and then `PIVOT` to convert columns to rows

* However, I am not sure how to do that. And, I do not know 100% what he means by that.

* EDIT: SQLite does not support pivot: Any other suggestions?

A: I don't believe there's a particularly neat way of doing this when you have 30+ columns. The following is the best I could do, using nested CTEs to implement full outer joins, then using coalesce to choose the first non-null lat/lon.
It's still required to enumerate all 30+ fields in the top SELECT statement, but at least the massive lists of NULL AS ... aren't needed:
SELECT
  a, b, c, d, e, f, g, h,
  coalesce(lat1, lat2, lat3, lat4) AS lat,
  coalesce(lon1, lon2, lon3, lon4) AS lon
  FROM (
    WITH t1_x_t2 AS (
        SELECT t1.*, t2.*,
        t1.lat AS lat1, t2.lat AS lat2, t1.lon AS lon1, t2.lon AS lon2
        FROM table1 t1 LEFT OUTER JOIN table2 t2 ON 0
      UNION ALL
        SELECT t1.*, t2.*,
        t1.lat AS lat1, t2.lat AS lat2, t1.lon AS lon1, t2.lon AS lon2
        FROM table2 t2 LEFT OUTER JOIN table1 t1 ON 0
    ), t3_x_t4 AS (
        SELECT t3.*, t4.*,
        t3.lat AS lat3, t4.lat AS lat4, t3.lon AS lon3, t4.lon AS lon4
        FROM table3 t3 LEFT OUTER JOIN table4 t4 ON 0
      UNION ALL
        SELECT t3.*, t4.*,
        t3.lat AS lat3, t4.lat AS lat4, t3.lon AS lon3, t4.lon AS lon4
        FROM table4 t4 LEFT OUTER JOIN table3 t3 ON 0
    )
    SELECT t1_x_t2.*, t3_x_t4.* FROM t1_x_t2 LEFT OUTER JOIN t3_x_t4 ON 0
    UNION ALL
    SELECT t1_x_t2.*, t3_x_t4.* FROM t3_x_t4 LEFT OUTER JOIN t1_x_t2 ON 0
)

A: One way to derive the result using pivot()(if your dbms supports that) could be as below.
select a,b,c,d,e,f,g,h,lon,lat
from (
select 'a' as columnName1, a as val1,'b' as ColumnName2, b as val2, lon,lat
from table1
union all
select 'c',c,'d', d, lon,lat
from table2
union all
select 'e',e,'f', f, lon,lat
from table3
union all
select 'g',g,'h', h, lon,lat
from table4
) t1
PIVOT (MAX(val1)
      FOR columnName1 IN (a,c,e,g)) as Pivot1
PIVOT (MAX(val2)
      FOR columnName2 IN (b,d,f,h)) AS Pivot2;

Result:
+------+------+------+------+------+------+------+------+-----+-----+
|  a   |  b   |  c   |  d   |  e   |  f   |  g   |  h   | lon | lat |
+------+------+------+------+------+------+------+------+-----+-----+
| 22   | 33   | NULL | NULL | NULL | NULL | NULL | NULL |  11 |  22 |
| NULL | NULL | 1    | 2    | NULL | NULL | NULL | NULL |  44 |  45 |
| NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | 100 | 101 |
| NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | 200 | 201 |
+------+------+------+------+------+------+------+------+-----+-----+

DEMO
P.S. Kindly note that the above query is for sql-Server, so you probably need to tweek it for your dbms.


text:
Q: MySQL - easiest way to insert multiple table rows - doing a foreach Ok i have 2 tables,
users_table: id | firstname

messages_table : id | id_to | id_from | message

what i'm trying to do now is getting all users_table ID and insert for each one id a message in messages_table (so send messages to all users using one query)
i'm trying somenthing like this :
foreach $users_table.id do:

    INSERT INTO messages_table (id_to,id_from,message) VALUES ($users_table.id, 5, "Hey man!");

Can i do that without a server side script?

A: You can use a INSERT ... SELECT statement as long as the other parameters are constant (or can be derived from other tables):
INSERT INTO `message_table` ( `id_to`, `id_from`, `message`)
SELECT user.`id`, 5, "Hey man!"
  FROM `users_table` user