text:
Q: Ansible: Get a value of first pair based on the value of a second pair's value I have this file and I know the value of LOC for example /oracle/19.0.0.
Would like to get the value of HOME NAME=, the corresponding value would be OraDB19Home1.
Looked at lookup but unable to get it fully working. Appreciate any help.
<?xml version = '1.0' encoding = 'UTF-8' standalone = 'yes'?>
<!-- Copyright (c) 1999, 2022, Oracle. All rights reserved. -->
<!-- Do not modify the contents of this file by hand. -->
<INVENTORY>
   <VERSION_INFO>
      <SAVED_WITH>13.9.4.0.0</SAVED_WITH>
      <MINIMUM_VER>2.1.0.6.0</MINIMUM_VER>
   </VERSION_INFO>
   <HOME_LIST>
      <HOME NAME="OraHome1" LOC="/oracle/agent/agent13.4" TYPE="O" IDX="3"/>
      <HOME NAME="OraDB19Home1" LOC="/oracle/19.0.0" TYPE="O" IDX="2"/>
   </HOME_LIST>
</INVENTORY>

A:
Given the XML
shell> cat inventory.xml
<?xml version = '1.0' encoding = 'UTF-8' standalone = 'yes'?>
<!-- Copyright (c) 1999, 2022, Oracle. All rights reserved. -->
<!-- Do not modify the contents of this file by hand. -->
<INVENTORY>
  <VERSION_INFO>
    <SAVED_WITH>13.9.4.0.0</SAVED_WITH>
    <MINIMUM_VER>2.1.0.6.0</MINIMUM_VER>
  </VERSION_INFO>
  <HOME_LIST>
    <HOME NAME="OraHome1" LOC="/oracle/agent/agent13.4" TYPE="O" IDX="3"/>
    <HOME NAME="OraDB19Home1" LOC="/oracle/19.0.0" TYPE="O" IDX="2"/>
  </HOME_LIST>
</INVENTORY>

Read the file and convert XML to YAML
  inv_xml: "{{ lookup('file', 'inventory.xml') }}"
  inv_yml: "{{ inv_xml|ansible.utils.from_xml }}"

gives
  inv_yml:
    INVENTORY:
      HOME_LIST:
        HOME:
        - '@IDX': '3'
          '@LOC': /oracle/agent/agent13.4
          '@NAME': OraHome1
          '@TYPE': O
        - '@IDX': '2'
          '@LOC': /oracle/19.0.0
          '@NAME': OraDB19Home1
          '@TYPE': O
      VERSION_INFO:
        MINIMUM_VER: 2.1.0.6.0
        SAVED_WITH: 13.9.4.0.0

Create a dictionary of LOC and NAME
  loc_name: "{{ inv_yml.INVENTORY.HOME_LIST.HOME|
                items2dict(key_name='@LOC',
                           value_name='@NAME') }}"

gives
  loc_name:
    /oracle/19.0.0: OraDB19Home1
    /oracle/agent/agent13.4: OraHome1

Then, searching is trivial
  loc: '/oracle/19.0.0'
  name_of_loc: "{{ loc_name[loc] }}"

gives
  name_of_loc: OraDB19Home1

, or in the loop
    - debug:
        msg: "The name of LOC {{ item }} is {{ loc_name[item] }}"
      loop:
        - '/oracle/19.0.0'
        - '/oracle/agent/agent13.4'

gives (abridged)
  msg: The name of LOC /oracle/19.0.0 is OraDB19Home1
  msg: The name of LOC /oracle/agent/agent13.4 is OraHome1

Example of a complete playbook for testing
shell> cat pb.yml
- hosts: localhost

  vars:

    inv_xml: "{{ lookup('file', 'inventory.xml') }}"
    inv_yml: "{{ inv_xml|ansible.utils.from_xml }}"
    loc_name: "{{ inv_yml.INVENTORY.HOME_LIST.HOME|
                  items2dict(key_name='@LOC',
                             value_name='@NAME') }}"
    loc: '/oracle/19.0.0'
    name_of_loc: "{{ loc_name[loc] }}"

  tasks:

    - debug:
        var: inv_xml
    - debug:
        var: inv_yml
    - debug:
        var: loc_name
    - debug:
        var: name_of_loc

    - debug:
        msg: "The name of LOC {{ item }} is {{ loc_name[item] }}"
      loop:
        - '/oracle/19.0.0'
        - '/oracle/agent/agent13.4'

Example of the project
shell> tree .
.
├── ansible.cfg
├── hosts
├── inventory.xml
└── pb.yml

0 directories, 4 files

shell> cat ansible.cfg
[defaults]
gathering = explicit
collections_path = $HOME/.local/lib/python3.9/site-packages/
inventory = $PWD/hosts
roles_path = $PWD/roles
remote_tmp = ~/.ansible/tmp
retry_files_enabled = false
stdout_callback = yaml

shell> cat hosts
localhost

Q: "Give an alternative to ansible.utils"
A: Install jc and use it in the pipe. The declaration below expands to the same YAML as before
  inv_yml: "{{ lookup('pipe', 'cat inventory.xml | jc --xml') }}"

Q: "Using possible regex?"
A: Select the line first
  inv_xml: "{{ lookup('file', 'inventory.xml') }}"

  loc: '/oracle/19.0.0'
  home_loc_regex: '^\s*<HOME .*? LOC="{{ loc }}" .*$'
  home: "{{ inv_xml.splitlines()|
            select('regex', home_loc_regex)|
            first|
            trim }}"

gives
  home: <HOME NAME="OraDB19Home1" LOC="/oracle/19.0.0" TYPE="O" IDX="2"/>

Parse the attributes
  home_dict: "{{ dict(home[6:-2]|
                      replace('\"', '')|
                      split(' ')|
                      map('split', '=')) }}"

gives
  home_dict:
    IDX: '2'
    LOC: /oracle/19.0.0
    NAME: OraDB19Home1
    TYPE: O

Q: "No filter named 'split'"
A: The filter split is available since 2.11. For the lower versions, only the '.split' method is available. In this case, use Jinja and create the YAML structure. The declarations below give the same dictionary home_dict as before
  home_dict_str: |
    {% for i in home[6:-2].split(' ') %}
    {% set arr = i.split('=') %}
    {{ arr.0 }}: {{ arr.1 }}
    {% endfor %}
  home_dict: "{{ home_dict_str|from_yaml }}"

A: This is almost trivial to do with awk:
Formatted as a script file:
/<HOME NAME=.*TYPE=.*IDX=/ {
    if ($3 == "LOC=\"/oracle/19.0.0\"") {
        split($2, a, /"/);
        print a[2];
        exit;
    }
}'

Command line:
cat your_input_file | awk '/<HOME NAME=.*TYPE=.*IDX=/{ if ($3 == "LOC=\"/oracle/19.0.0\"") { split($2, a, /"/); print a[2]; exit }  }'

You can probably convert this relatively easily to something similar in python.

A: awk -v loc='LOC="/oracle/19.0.0"' '
    index($0,loc){
        print gensub(/^.*NAME="([^"]*)".*$/,"\\1",1)
    }
' inputfile

or
awk -F'=|"' -v loc='LOC="/oracle/19.0.0"' 'index($0,loc){print $3}' inputfile
awk -F'=|"' -v loc="/oracle/19.0.0" '/ LOC="[^"]*" / && $6 == loc {print $3}' inputfile

Output
OraDB19Home1

A: For me the use case looks like a
Similar Q&A

*

*Ansible: How to pull a specific string out of the contents of a file?
It is assumed that the unfavorable data structure within your configuration example file stays as it is provided and you are looking for a grep approach in Ansible.
- name: Gather home directory
  shell:
    cmd: "grep '{{ VERSION }}' inventory.xml | cut -d '=' -f 2 | cut -d ' ' -f 1 | tr -d '"'"
  register: home_dir

How to proceed further?
If such lookup's are necessary frequently or on a greater scale, one might take advantage from implementing a specific solution.
If the installation of ansible.utils.collection and Python library xmltodict is possible or already available, you should definitely go with the recommended solution from Vladimir Botka of from_xml filter – Convert given XML string to native python dictionary by converting XML to YAML before further processing.
Otherwise you could give a try for
Custom Module Examples

*

*Bash: File search ... with Ansible

*Bash: How to check if a file is of type human-readable in Ansible?

*Python: How to search for a string in a Remote File using Ansible?


text:
Q: glob not picking up some files? $files = glob("*.*");
for ($i=1; $i<count($files); $i++){
    $file = $files[$i];
    echo "$file<br />";
}

I'm trying to display all the files in a directory, this is picking up the .php files i have in this directory but it isn't finding mp3 files. Any idea why?

A: May be this works :)
for ($i=0; $i<count($files); $i++){

Why don't you use foreach
foreach (glob("*.*") as $filename) {
    echo "$filename size " . filesize($filename) . "\n";
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Собрать рабочий APK в Unity3D При компиляции самого простого приложения - вращающийся куб, сборка проходит успешно, получаю APK весом в 18МБ, закидываю на реальный телефон, устанавливаю, запускаю - ориентация экрана применяется (горизотальная, как и хотел), фон становится чёрный (собственно, ожидаю хоть что-то), но приложение сворачивается и висит в процессах. Любая попытка переключиться на процесс даёт чёрный фон длительностью ~0.5 секунд, и приложение снова сворачивается.
На каких этапах я допустил ошибки? Ведь, судя по документации, я выполнил все пункты.
Объясню что у меня есть и что использовал:

*

*Следуя документации поставил Android Studio

*Открыл Android SDK, установил нужные пакеты

Чтобы было понятно, поставил ВСЁ, для выбранных версий, в том числе и образы для эмулятора:

Установил все инструменты и обновления:

*Далее, по новой выкачал юнити (при установке я не учитывал что буду работать с андроидом), поставил инструменты для компиляции под андроид. Всё успешно работает.

*Создаю новый проект, называю Box, режим - 3D, без ассетов.

*Добавляю куб, пишу скрипт на шарпе - вращение по времени. (одна строчка)

*Изменяю настройки проигрывателя, устанавливаю идентификатор приложения, минимальный уровень API 14 - Ice Cream Sandwich

*Сохраняю сцену. Добавляю её в список сцен с индексом 0.

*Выполняю сборку

*Достаю телефон, открываю настройки, раздел "для разработчиков", соглашаюсь на "установку сторонних приложений".

*Полученный APK передаю на телефон. Там открываю и устанавливаю.

*Запускаю приложение - никаких ошибок, программа висит 1 сек с чёрным фоном и сворачивается. Процесс работает, могу переключиться на него - но, всё по кругу - чёрный фон, затем сворачивается. Никаких сообщений.

Пытался менять минимальный уровень API до 5.0 и до 2.3 - всё одно, та же самая проблема. Скинул APK знакомому, у него планшет под KitKat - та же ерунда, программа просто сворачивается без ошибок, и висит в фоне.
Телефон - дешёвый "Билайн Смарт 4", характеристики:

*

*Операционная система - Android 5.0 (Lollipop)

*Процессор - Четырехъядерный МТК 6582M 1,3 ГГц

*Экран - IPS, мультитач, 4,5 дюйма, 480*854; цветной 16М

*Память - ПЗУ 8ГБ + ОЗУ 1 ГБ, поддержка MicroSD до 32 ГБ

Что это может быть и как нужно настроить Unity/AndroidSDK, чтобы элементарное приложение с кубом собиралось и работало корректно?

A: Скорее всего, из-за третьего пункта:

Далее, по новой выкачал юнити (при установке я не учитывал что буду работать с андроидом), поставил инструменты для компиляции под андроид. Всё успешно работает.

повредился контент юнити. Компилируемый проект просто неправильно собирался...
Полное удаление и повторная установка Unity исправила ошибку. Приложение успешно собралось.


text:
Q: How to invoke the same maven build twice in one call Is it possible to invoke the same maven build a number of times with different configuration parameters?
I have a maven build that creates a number RPMs with the rpm-maven-plugin. I pass it a variable (environment) which specifies which environment the RPM is targeted for: development, staging or production.
To create all RPMs for all environments, I call mvn package -Denvironment=... 3 times; and I'd like to simplify that. It would be great if I could call mvn package once, and it, in turn, would build three RPMs for all environments.
Do you see any way of doing this?
Edit 1
So far (based on dm3's great answer), I can create three independent RPMs in one build, with the same properties. The problem now is to be able to change the environment property for each execution. Any suggestions?
<project>
  <properties>
    <!-- Default Environment -->
    <environment>development</environment>
  </properties>

  <build>
    <plugins>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>rpm-maven-plugin</artifactId>
        <version>2.1-alpha-1</version>
        <executions>
          <execution>
            <phase>package</phase>
            <id>package-development</id>
            <goals><goal>rpm</goal></goals>
          </execution>

          <execution>
            <phase>package</phase>
            <id>package-staging</id>
            <goals><goal>rpm</goal></goals>
          </execution>

          <execution>
            <phase>package</phase>
            <id>package-production</id>
            <goals><goal>rpm</goal></goals>
          </execution>
        </executions>
      </plugin>
    </plugins>

    <pluginManagement>
      <plugins>
        <plugin>
          <groupId>org.codehaus.mojo</groupId>
          <artifactId>rpm-maven-plugin</artifactId>
          <version>2.1-alpha-1</version>
          <extensions>true</extensions>

          <configuration>
          ... VERY LONG CONFIG ...
          </configuration>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

A: I believe the only way to achieve that during one maven execution is to bind several executions of the plugin (with different configurations) to a lifecycle phase, like this:
<build>
    <plugins>
        <plugin>
            <artifactId>maven-surefire-plugin</artifactId>
            <executions>
                <execution>
                    <phase>test</phase>
                    <id>test-1</id>
                    <configuration>
                        ...
                    </configuration>
                    <goals><goal>test</goal></goals>
                </execution>
                <execution>
                    <phase>test</phase>
                    <id>test-2</id>
                    <configuration>
                        ...
                    </configuration>
                    <goals><goal>test</goal></goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
    ...
</build>

You can attach this configuration to some profile triggered by one property (e.g. by mvn package -Denvironment=all).


text:
Q: Is there a way to llog every time change detection runs on component level? Is there a way to log every time Angular runs change detection on the component?
for example I have three components: foo, bar and baz.
when change detection runs it will console.log:
Run change detection on `foo`.
Run change detection on `bar`.
Run change detection on `baz`.

So this way I'll know which component is running change detection.

A: Yes, implement DoCheck and console.log inside it.
@Component({selector: 'my-cmp', template: `...`})
class MyComponent implements DoCheck {
  ngDoCheck() {
    console.log("Change detection reached MyComponent")
  }
}

Explanation:
the ngDoCheck method is actually your extension of the component dirty check. Its code will be compiled and added to the factory of your component in the change detection part.
Notice: If you don't see the console.log then the change detection haven't reach your component. This might happen for example of you use onPush strategy and the inputs of the parent component haven't change.


text:
Q: Ruby lambda arguments This code works as expected (does nothing, even doesn't produce warning/errors):
l = lambda {|i|}
l.call(1)

This code produces warning (warning: multiple values for a block parameter (0 for 1)):
l = lambda {|i|}
l.call

And this code fails with error (ArgumentError: wrong number of arguments (0 for 2)):
l = lambda {|i, y|}
l.call

I thought that lambda requires all argument to be passed.
And from the second example I see that it isn't. Why does it work when only one argument is given, and works as expected (fails with error) with more than one argument?
PS: ruby 1.8.6 (2008-08-11 patchlevel 287) [universal-darwin9.0]
UPDATE: I've checked these samples with ruby 1.9.1p376. And it works as expected - the second example also produces an error. Looks like this is a feature of 1.8 version (or <=1.8)

A: This script will teach you everything you need to know about closures in Ruby.
# So, what's the final verdict on those 7 closure-like entities?
#
#                                                     "return" returns from closure
#                                    True closure?    or declaring context...?         Arity check?
#                                    ---------------  -----------------------------    -------------------
# 1. block (called with yield)       N                declaring                        no
# 2. block (&b => f(&b) => yield)    N                declaring                        no
# 3. block (&b => b.call)            Y except return  declaring                        warn on too few
# 4. Proc.new                        Y except return  declaring                        warn on too few
# 5. proc                                    <<< alias for lambda in 1.8, Proc.new in 1.9 >>>
# 6. lambda                          Y                closure                          yes, except arity 1
# 7. method                          Y                closure                          yes

A: Lambdas are weird like that, their behavior is different when you have less than two arguments. Check this article for more information.

A: When a lambda expects arguments and we don't provide them, or we provide the wrong number of arguments, an exception is thrown.
l = lambda { |name| puts "Today we will practice #{name} meditation." }
l.call
ArgumentError: wrong number of arguments (given 0, expected 1)

We can use the arity method to find out the number of expected arguments:
l.arity  # Output: => 1

Just like methods, lambdas accept all of the following types of parameters/arguments:

*

*Positional parameters (required and optional)

*Single splat parameter (*);

*Keyword parameters (required and optional);

*Double splat parameter (**);

*Explicit block parameter prefixed with ampersand (&).

The following examples illustrate the syntax of a lambda that takes multiple types of arguments.
# Stabby syntax
l = -> (cushion, meditation="kinhin", *room_items, time:, posture: "kekkafuza", **periods, &p) do
  p.call
end

# Regular syntax
l = lambda do |cushion, meditation="kinhin", *room_items, time:, posture:     "kekkafuza", **periods, &p|
  p.call
end

l.call("zafu", "zazen", "zabuton", "incense", time: 40, period1: "morning", period2: "afternoon" ) { puts "Hello from inside the block, which is now a proc." }

Output:
Hello from inside the block, which is now a proc.

Lambdas handle arguments the same way as methods. There is a comprehensive explanation of all the above parameter/argument types in this blog post about methods.


text:
Q: How to parse a more complicated JSON object in Ruby on Sinatra I'm a Java guy, new to Ruby. I've been playing with it just to see what it can do, and I'm running into an issue that I can't solve.
I decided to try out Sinatra, again, just to see what it can do, and decided to play with the ESPN API and see if I can pull the venue of a team via the API.
I'm able to make the call and get the data back, but I am having trouble parsing it:
{"sports"=>[{"name"=>"baseball", "id"=>1, "uid"=>"s:1", "leagues"=>[{"name"=>"Major League Baseball", "abbreviation"=>"mlb", "id"=>10, "uid"=>"s:1~l:10", "groupId"=>9, "shortName"=>"MLB", "teams"=>[{"id"=>17, "uid"=>"s:1~l:10~t:17", "location"=>"Cincinnati", "name"=>"Reds", "abbreviation"=>"CIN", "color"=>"D60042", "venues"=>[{"id"=>83, "name"=>"Great American Ball Park", "city"=>"Cincinnati", "state"=>"Ohio", "country"=>"", "capacity"=>0}], "links"=>{"api"=>{"teams"=>{"href"=>"http://api.espn.com/v1/sports/baseball/mlb/teams/17"}, "news"=>{"href"=>"http://api.espn.com/v1/sports/baseball/mlb/teams/17/news"}, "notes"=>{"href"=>"http://api.espn.com/v1/sports/baseball/mlb/teams/17/news/notes"}}, "web"=>{"teams"=>{"href"=>"http://espn.go.com/mlb/team/_/name/cin/cincinnati-reds?ex_cid=espnapi_public"}}, "mobile"=>{"teams"=>{"href"=>"http://m.espn.go.com/mlb/clubhouse?teamId=17&ex_cid=espnapi_public"}}}}]}]}], "resultsOffset"=>0, "resultsLimit"=>50, "resultsCount"=>1, "timestamp"=>"2013-08-04T14:47:13Z", "status"=>"success"}

I want to pull the venues part of the object, specifically the name value. Every time I try to parse it I end up getting an error along the lines of "cannot change from nil to string" and then also I've gotten an integer to string error.
Here's what i have so far:
get '/venue/:team' do

    id = ids[params[:team]]
    url = 'http://api.espn.com/v1/sports/baseball/mlb/teams/' + id + '?enable=venues&apikey=' + $key
    resp = Net::HTTP.get_response(URI.parse(url))
    data = resp.body
    parsed = JSON.parse(resp.body)
    #venueData = parsed["sports"]

    "Looking for the venue of the #{params[:team]}, which has id " + id + ", and here's the data returned: " + venueData.to_s

end

When I do parsed["sports"} I get:
 [{"name"=>"baseball", "id"=>1, "uid"=>"s:1", "leagues"=>[{"name"=>"Major League Baseball", "abbreviation"=>"mlb", "id"=>10, "uid"=>"s:1~l:10", "groupId"=>9, "shortName"=>"MLB", "teams"=>[{"id"=>17, "uid"=>"s:1~l:10~t:17", "location"=>"Cincinnati", "name"=>"Reds", "abbreviation"=>"CIN", "color"=>"D60042", "venues"=>[{"id"=>83, "name"=>"Great American Ball Park", "city"=>"Cincinnati", "state"=>"Ohio", "country"=>"", "capacity"=>0}], "links"=>{"api"=>{"teams"=>{"href"=>"http://api.espn.com/v1/sports/baseball/mlb/teams/17"}, "news"=>{"href"=>"http://api.espn.com/v1/sports/baseball/mlb/teams/17/news"}, "notes"=>{"href"=>"http://api.espn.com/v1/sports/baseball/mlb/teams/17/news/notes"}}, "web"=>{"teams"=>{"href"=>"http://espn.go.com/mlb/team/_/name/cin/cincinnati-reds?ex_cid=espnapi_public"}}, "mobile"=>{"teams"=>{"href"=>"http://m.espn.go.com/mlb/clubhouse?teamId=17&ex_cid=espnapi_public"}}}}]}]}]

But nothing else parses. Please help!
Like I said, I'm not trying to do anything fancy, just figure out Ruby a little for fun, but I have been stuck on this issue for days now. Any help would be appreciated!
EDIT:
JSON straight from the API:
{"sports" :[{"name" :"baseball","id" :1,"uid" :"s:1","leagues" :[{"name" :"Major League Baseball","abbreviation" :"mlb","id" :10,"uid" :"s:1~l:10","groupId" :9,"shortName" :"MLB","teams" :[{"id" :17,"uid" :"s:1~l:10~t:17","location" :"Cincinnati","name" :"Reds","abbreviation" :"CIN","color" :"D60042","venues" :[{"id" :83,"name" :"Great American Ball Park","city" :"Cincinnati","state" :"Ohio","country" :"","capacity" :0}],"links" :{"api" :{"teams" :{"href" :"http://api.espn.com/v1/sports/baseball/mlb/teams/17"},"news" :{"href" :"http://api.espn.com/v1/sports/baseball/mlb/teams/17/news"},"notes" :{"href" :"http://api.espn.com/v1/sports/baseball/mlb/teams/17/news/notes"}},"web" :{"teams" :{"href" :"http://espn.go.com/mlb/team/_/name/cin/cincinnati-reds?ex_cid=espnapi_public"}},"mobile" :{"teams" :{"href" :"http://m.espn.go.com/mlb/clubhouse?teamId=17&ex_cid=espnapi_public"}}}}]}]}],"resultsOffset" :0,"resultsLimit" :50,"resultsCount" :1,"timestamp" :"2013-08-05T19:44:32Z","status" :"success"}

The result of data.inspect:
"{\"sports\" :[{\"name\" :\"baseball\",\"id\" :1,\"uid\" :\"s:1\",\"leagues\" :[{\"name\" :\"Major League Baseball\",\"abbreviation\" :\"mlb\",\"id\" :10,\"uid\" :\"s:1~l:10\",\"groupId\" :9,\"shortName\" :\"MLB\",\"teams\" :[{\"id\" :17,\"uid\" :\"s:1~l:10~t:17\",\"location\" :\"Cincinnati\",\"name\" :\"Reds\",\"abbreviation\" :\"CIN\",\"color\" :\"D60042\",\"venues\" :[{\"id\" :83,\"name\" :\"Great American Ball Park\",\"city\" :\"Cincinnati\",\"state\" :\"Ohio\",\"country\" :\"\",\"capacity\" :0}],\"links\" :{\"api\" :{\"teams\" :{\"href\" :\"http://api.espn.com/v1/sports/baseball/mlb/teams/17\"},\"news\" :{\"href\" :\"http://api.espn.com/v1/sports/baseball/mlb/teams/17/news\"},\"notes\" :{\"href\" :\"http://api.espn.com/v1/sports/baseball/mlb/teams/17/news/notes\"}},\"web\" :{\"teams\" :{\"href\" :\"http://espn.go.com/mlb/team/_/name/cin/cincinnati-reds?ex_cid=espnapi_public\"}},\"mobile\" :{\"teams\" :{\"href\" :\"http://m.espn.go.com/mlb/clubhouse?teamId=17&ex_cid=espnapi_public\"}}}}]}]}],\"resultsOffset\" :0,\"resultsLimit\" :50,\"resultsCount\" :1,\"timestamp\" :\"2013-08-05T19:44:24Z\",\"status\" :\"success\"}"

A: parsed["sports"] does not exist, parse your input and inspect it/ dump it

A: With the data you've provided in the question, you can get to the venues information like this:
require 'json'

json = JSON.parse data

json["sports"].first["leagues"].first["teams"].first["venues"]
# => [{"id"=>83, "name"=>"Great American Ball Park", "city"=>"Cincinnati", "state"=>"Ohio", "country"=>"", "capacity"=>0}]

By replacing each of the first calls with an iterator, you can search through without knowing where the data is:
json["sports"].each{|h|
  h["leagues"].each{|h|
    h["teams"].each{|h|
      venues = h["venues"].map{|h| h["name"]}.join(", ")
      puts %Q!name: #{h["location"]} #{h["name"]} venues: #{venues}!
    }
  }
}

This outputs:

name: Cincinnati Reds venues: Great American Ball Park

Depending on how stable the response data is you may be able to cut out several of the iterators:
json["sports"].first["leagues"]
              .first["teams"]
              .each{|h|
                venues = h["venues"].map{|h| h["name"] }.join(", ")
                puts %Q!name: #{h["location"]} #{h["name"]} venues: #{venues}!
              }

and you'll most likely want to save the data, so something like each_with_object is helpful:
team_and_venues = json["sports"].first["leagues"]
              .first["teams"]
              .each_with_object([]){|h,xs|
                venues = h["venues"].map{|h| h["name"]}.join(", ")
                xs << %Q!name: #{h["location"]} #{h["name"]} venues: #{venues}!
              }
# => ["name: Cincinnati Reds venues: Great American Ball Park"]

team_and_venues
# => ["name: Cincinnati Reds venues: Great American Ball Park"]

Notice that when an iterator declares variables, even if there is a variable with the same name outside the block, the scope of the block is respected and the block's variables remain local.
That's some pretty ugly code if you ask me, but it's a place to start.


text:
Q: uint32_t does not name a type - VSCode with STM32 in Windows I am currently writing code for a project, specifically interfacing with sensors via an STM32 Nucleo F411RE board. I set the pins/peripherals etc. using STM32CubeMX, then generated the code with the Makefile toolchain for programming in  Visual Studio Code. Everything is compiling fine, but the IDE/Intellisense for some reason doesn't pick up any use of uint32_t; any occurences are red-squiggled, with the error reading variable "uint32_t" is not a type name.
I have #include <stdint.h> at the top, and uint16_t and uint8_t are both recognized in the same file. Peeking the definition of those reveals their lines in stdint.h, while the same does not work for uint32_t. I have attempted the solutions suggested here and here, neither of which worked.
I am working in C11 (not c++, which isn't an option for my project) on Windows, here is my c_cpp_properties.json file (with all the extra defines cut out for compactness):
{
    "configurations": [
        {
            "name": "Win32",
            "includePath": [
                "${workspaceFolder}/**"
            ],
            "defines": [
                "_DEBUG",
                "UNICODE",
                "_UNICODE"
            ],
            "databaseFilename": "${workspaceFolder}/.vscode/browse.vc.db",
            "windowsSdkVersion": "10.0.17763.0",
            "compilerPath": "C:/Program Files (x86)/Microsoft Visual Studio/2017/Community/VC/Tools/MSVC/14.16.27023/bin/Hostx64/x64/cl.exe",
            "cStandard": "c11",
            "cppStandard": "c++17",
            "intelliSenseMode": "clang-x64",
            "compileCommands": "${workspaceFolder}/compile_commands.json"
        }
    ],
    "version": 4
}

Here is <stdint.h> - all types are clearly declared together, with no apparent condition for uint32_t:
#pragma once
#define _STDINT

#ifndef RC_INVOKED

#include <vcruntime.h>

typedef signed char        int8_t;
typedef short              int16_t;
typedef int                int32_t;
typedef long long          int64_t;
typedef unsigned char      uint8_t;
typedef unsigned short     uint16_t;
typedef unsigned int       uint32_t;
typedef unsigned long long uint64_t;

typedef signed char        int_least8_t;
typedef short              int_least16_t;
typedef int                int_least32_t;
typedef long long          int_least64_t;
typedef unsigned char      uint_least8_t;
typedef unsigned short     uint_least16_t;
typedef unsigned int       uint_least32_t;
typedef unsigned long long uint_least64_t;

typedef signed char        int_fast8_t;
typedef int                int_fast16_t;
typedef int                int_fast32_t;
typedef long long          int_fast64_t;
typedef unsigned char      uint_fast8_t;
typedef unsigned int       uint_fast16_t;
typedef unsigned int       uint_fast32_t;
typedef unsigned long long uint_fast64_t;

typedef long long          intmax_t;
typedef unsigned long long uintmax_t;

// These macros must exactly match those in the Windows SDK's intsafe.h.
#define INT8_MIN         (-127i8 - 1)
#define INT16_MIN        (-32767i16 - 1)
#define INT32_MIN        (-2147483647i32 - 1)
#define INT64_MIN        (-9223372036854775807i64 - 1)
#define INT8_MAX         127i8
#define INT16_MAX        32767i16
#define INT32_MAX        2147483647i32
#define INT64_MAX        9223372036854775807i64
#define UINT8_MAX        0xffui8
#define UINT16_MAX       0xffffui16
#define UINT32_MAX       0xffffffffui32
#define UINT64_MAX       0xffffffffffffffffui64

#define INT_LEAST8_MIN   INT8_MIN
#define INT_LEAST16_MIN  INT16_MIN
#define INT_LEAST32_MIN  INT32_MIN
#define INT_LEAST64_MIN  INT64_MIN
#define INT_LEAST8_MAX   INT8_MAX
#define INT_LEAST16_MAX  INT16_MAX
#define INT_LEAST32_MAX  INT32_MAX
#define INT_LEAST64_MAX  INT64_MAX
#define UINT_LEAST8_MAX  UINT8_MAX
#define UINT_LEAST16_MAX UINT16_MAX
#define UINT_LEAST32_MAX UINT32_MAX
#define UINT_LEAST64_MAX UINT64_MAX

#define INT_FAST8_MIN    INT8_MIN
#define INT_FAST16_MIN   INT32_MIN
#define INT_FAST32_MIN   INT32_MIN
#define INT_FAST64_MIN   INT64_MIN
#define INT_FAST8_MAX    INT8_MAX
#define INT_FAST16_MAX   INT32_MAX
#define INT_FAST32_MAX   INT32_MAX
#define INT_FAST64_MAX   INT64_MAX
#define UINT_FAST8_MAX   UINT8_MAX
#define UINT_FAST16_MAX  UINT32_MAX
#define UINT_FAST32_MAX  UINT32_MAX
#define UINT_FAST64_MAX  UINT64_MAX

#ifdef _WIN64
    #define INTPTR_MIN   INT64_MIN
    #define INTPTR_MAX   INT64_MAX
    #define UINTPTR_MAX  UINT64_MAX
#else
    #define INTPTR_MIN   INT32_MIN
    #define INTPTR_MAX   INT32_MAX
    #define UINTPTR_MAX  UINT32_MAX
#endif

#define INTMAX_MIN       INT64_MIN
#define INTMAX_MAX       INT64_MAX
#define UINTMAX_MAX      UINT64_MAX

#define PTRDIFF_MIN      INTPTR_MIN
#define PTRDIFF_MAX      INTPTR_MAX

#ifndef SIZE_MAX
    #define SIZE_MAX     UINTPTR_MAX
#endif

#define SIG_ATOMIC_MIN   INT32_MIN
#define SIG_ATOMIC_MAX   INT32_MAX

#define WCHAR_MIN        0x0000
#define WCHAR_MAX        0xffff

#define WINT_MIN         0x0000
#define WINT_MAX         0xffff

#define INT8_C(x)    (x)
#define INT16_C(x)   (x)
#define INT32_C(x)   (x)
#define INT64_C(x)   (x ## LL)

#define UINT8_C(x)   (x)
#define UINT16_C(x)  (x)
#define UINT32_C(x)  (x ## U)
#define UINT64_C(x)  (x ## ULL)

#define INTMAX_C(x)  INT64_C(x)
#define UINTMAX_C(x) UINT64_C(x)

#endif // RC_INVOKED

/*
* Copyright (c) 1992-2012 by P.J. Plauger.  ALL RIGHTS RESERVED.
* Consult your license regarding permissions and restrictions.
V6.00:0009 */

Both uint_fast16_t and uint_fast32_t have no problems when I use them, which rules out type being an issue - they are both unsigned int, the same as uint32_t.
EDIT: While making an MCVE, I narrowed the problem down to #include-ing "stm32f4xx_hal.h" - without this #include, a uint32_t declares fine. Here is a file that demonstrates the problem (changing the order of the includes does not make a difference):
#pragma once

#include <stdint.h>
#include "stm32f4xx_hal.h"

#define MA302_READ_MASK 0x4000
#define MA302_WRITE_MASK 0x8000
#define MA302_ADDRESS_MASK 0x1F
#define MA302_READ_BLANK_VALUE 0x0000

typedef struct {
    uint32_t tester; // 'variable "uint32_t" is not a type name"'
    uint16_t current_raw_16; // declares fine
    uint8_t current_raw_8; // declares fine
    float current_angle;
} ma302gq_p_t;

uint8_t ma302_read_register(SPI_HandleTypeDef *hndlr, uint8_t address);
float ma302_get_angle(SPI_HandleTypeDef *hndlr);
float ma302_raw_to_degrees(uint8_t raw_bit_size, uint16_t raw_angle);
void ma302_init(SPI_HandleTypeDef *hndlr);

"stm32f4xx_hal.h" is part of the code generated by STM32CubeMX, and itself #includes "stm32f4xx_hal_conf.h". Adding #include <stdint.h> to "stm32f4xx_hal.h" allows uint32_ts to temporarily declare in that file; however, switching to the above file and back in VSCode causes the declaration to glitch, and when hovered over, show <error-type> uint32_t
EDIT 2:
Here is the first problem file; I didn't include it before as it is automatically generated.
"stm32f4xx_hal.h":
/**
  ******************************************************************************
  * @file    stm32f4xx_hal.h
  * @author  MCD Application Team
  * @brief   This file contains all the functions prototypes for the HAL
  *          module driver.
  ******************************************************************************
  * @attention
  *
  *
© COPYRIGHT(c) 2017 STMicroelectronics

  *
  * Redistribution and use in source and binary forms, with or without modification,
  * are permitted provided that the following conditions are met:
  *   1. Redistributions of source code must retain the above copyright notice,
  *      this list of conditions and the following disclaimer.
  *   2. Redistributions in binary form must reproduce the above copyright notice,
  *      this list of conditions and the following disclaimer in the documentation
  *      and/or other materials provided with the distribution.
  *   3. Neither the name of STMicroelectronics nor the names of its contributors
  *      may be used to endorse or promote products derived from this software
  *      without specific prior written permission.
  *
  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  *
  ******************************************************************************
  */

/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __STM32F4xx_HAL_H
#define __STM32F4xx_HAL_H

#ifdef __cplusplus
extern "C" {
#endif

/* Includes ------------------------------------------------------------------*/
#include "stm32f4xx_hal_conf.h"

/** @addtogroup STM32F4xx_HAL_Driver
  * @{
  */

/** @addtogroup HAL
  * @{
  */

/* Exported types ------------------------------------------------------------*/
/* Exported constants --------------------------------------------------------*/

/** @defgroup HAL_Exported_Constants HAL Exported Constants
  * @{
  */

/** @defgroup HAL_TICK_FREQ Tick Frequency
  * @{
  */
typedef enum
{
  HAL_TICK_FREQ_10HZ         = 100U,
  HAL_TICK_FREQ_100HZ        = 10U,
  HAL_TICK_FREQ_1KHZ         = 1U,
  HAL_TICK_FREQ_DEFAULT      = HAL_TICK_FREQ_1KHZ
} HAL_TickFreqTypeDef;
/**
  * @}
  */

/**
  * @}
  */

/* Exported macro ------------------------------------------------------------*/
/** @defgroup HAL_Exported_Macros HAL Exported Macros
  * @{
  */

/** @brief  Freeze/Unfreeze Peripherals in Debug mode
  */
#define __HAL_DBGMCU_FREEZE_TIM2()           (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_TIM2_STOP))
#define __HAL_DBGMCU_FREEZE_TIM3()           (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_TIM3_STOP))
#define __HAL_DBGMCU_FREEZE_TIM4()           (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_TIM4_STOP))
#define __HAL_DBGMCU_FREEZE_TIM5()           (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_TIM5_STOP))
#define __HAL_DBGMCU_FREEZE_TIM6()           (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_TIM6_STOP))
#define __HAL_DBGMCU_FREEZE_TIM7()           (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_TIM7_STOP))
#define __HAL_DBGMCU_FREEZE_TIM12()          (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_TIM12_STOP))
#define __HAL_DBGMCU_FREEZE_TIM13()          (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_TIM13_STOP))
#define __HAL_DBGMCU_FREEZE_TIM14()          (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_TIM14_STOP))
#define __HAL_DBGMCU_FREEZE_RTC()            (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_RTC_STOP))
#define __HAL_DBGMCU_FREEZE_WWDG()           (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_WWDG_STOP))
#define __HAL_DBGMCU_FREEZE_IWDG()           (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_IWDG_STOP))
#define __HAL_DBGMCU_FREEZE_I2C1_TIMEOUT()   (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_I2C1_SMBUS_TIMEOUT))
#define __HAL_DBGMCU_FREEZE_I2C2_TIMEOUT()   (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_I2C2_SMBUS_TIMEOUT))
#define __HAL_DBGMCU_FREEZE_I2C3_TIMEOUT()   (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_I2C3_SMBUS_TIMEOUT))
#define __HAL_DBGMCU_FREEZE_CAN1()           (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_CAN1_STOP))
#define __HAL_DBGMCU_FREEZE_CAN2()           (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_CAN2_STOP))
#define __HAL_DBGMCU_FREEZE_TIM1()           (DBGMCU->APB2FZ |= (DBGMCU_APB2_FZ_DBG_TIM1_STOP))
#define __HAL_DBGMCU_FREEZE_TIM8()           (DBGMCU->APB2FZ |= (DBGMCU_APB2_FZ_DBG_TIM8_STOP))
#define __HAL_DBGMCU_FREEZE_TIM9()           (DBGMCU->APB2FZ |= (DBGMCU_APB2_FZ_DBG_TIM9_STOP))
#define __HAL_DBGMCU_FREEZE_TIM10()          (DBGMCU->APB2FZ |= (DBGMCU_APB2_FZ_DBG_TIM10_STOP))
#define __HAL_DBGMCU_FREEZE_TIM11()          (DBGMCU->APB2FZ |= (DBGMCU_APB2_FZ_DBG_TIM11_STOP))

#define __HAL_DBGMCU_UNFREEZE_TIM2()           (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_TIM2_STOP))
#define __HAL_DBGMCU_UNFREEZE_TIM3()           (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_TIM3_STOP))
#define __HAL_DBGMCU_UNFREEZE_TIM4()           (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_TIM4_STOP))
#define __HAL_DBGMCU_UNFREEZE_TIM5()           (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_TIM5_STOP))
#define __HAL_DBGMCU_UNFREEZE_TIM6()           (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_TIM6_STOP))
#define __HAL_DBGMCU_UNFREEZE_TIM7()           (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_TIM7_STOP))
#define __HAL_DBGMCU_UNFREEZE_TIM12()          (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_TIM12_STOP))
#define __HAL_DBGMCU_UNFREEZE_TIM13()          (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_TIM13_STOP))
#define __HAL_DBGMCU_UNFREEZE_TIM14()          (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_TIM14_STOP))
#define __HAL_DBGMCU_UNFREEZE_RTC()            (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_RTC_STOP))
#define __HAL_DBGMCU_UNFREEZE_WWDG()           (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_WWDG_STOP))
#define __HAL_DBGMCU_UNFREEZE_IWDG()           (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_IWDG_STOP))
#define __HAL_DBGMCU_UNFREEZE_I2C1_TIMEOUT()   (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_I2C1_SMBUS_TIMEOUT))
#define __HAL_DBGMCU_UNFREEZE_I2C2_TIMEOUT()   (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_I2C2_SMBUS_TIMEOUT))
#define __HAL_DBGMCU_UNFREEZE_I2C3_TIMEOUT()   (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_I2C3_SMBUS_TIMEOUT))
#define __HAL_DBGMCU_UNFREEZE_CAN1()           (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_CAN1_STOP))
#define __HAL_DBGMCU_UNFREEZE_CAN2()           (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_CAN2_STOP))
#define __HAL_DBGMCU_UNFREEZE_TIM1()           (DBGMCU->APB2FZ &= ~(DBGMCU_APB2_FZ_DBG_TIM1_STOP))
#define __HAL_DBGMCU_UNFREEZE_TIM8()           (DBGMCU->APB2FZ &= ~(DBGMCU_APB2_FZ_DBG_TIM8_STOP))
#define __HAL_DBGMCU_UNFREEZE_TIM9()           (DBGMCU->APB2FZ &= ~(DBGMCU_APB2_FZ_DBG_TIM9_STOP))
#define __HAL_DBGMCU_UNFREEZE_TIM10()          (DBGMCU->APB2FZ &= ~(DBGMCU_APB2_FZ_DBG_TIM10_STOP))
#define __HAL_DBGMCU_UNFREEZE_TIM11()          (DBGMCU->APB2FZ &= ~(DBGMCU_APB2_FZ_DBG_TIM11_STOP))

/** @brief  Main Flash memory mapped at 0x00000000
  */
#define __HAL_SYSCFG_REMAPMEMORY_FLASH()             (SYSCFG->MEMRMP &= ~(SYSCFG_MEMRMP_MEM_MODE))

/** @brief  System Flash memory mapped at 0x00000000
  */
#define __HAL_SYSCFG_REMAPMEMORY_SYSTEMFLASH()       do {SYSCFG->MEMRMP &= ~(SYSCFG_MEMRMP_MEM_MODE);\
                                                        SYSCFG->MEMRMP |= SYSCFG_MEMRMP_MEM_MODE_0;\
                                                        }while(0);

/** @brief  Embedded SRAM mapped at 0x00000000
  */
#define __HAL_SYSCFG_REMAPMEMORY_SRAM()       do {SYSCFG->MEMRMP &= ~(SYSCFG_MEMRMP_MEM_MODE);\
                                                  SYSCFG->MEMRMP |= (SYSCFG_MEMRMP_MEM_MODE_0 | SYSCFG_MEMRMP_MEM_MODE_1);\
                                                }while(0);

#if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx)|| defined(STM32F417xx)
/** @brief  FSMC Bank1 (NOR/PSRAM 1 and 2) mapped at 0x00000000
  */
#define __HAL_SYSCFG_REMAPMEMORY_FSMC()       do {SYSCFG->MEMRMP &= ~(SYSCFG_MEMRMP_MEM_MODE);\
                                                  SYSCFG->MEMRMP |= (SYSCFG_MEMRMP_MEM_MODE_1);\
                                                }while(0);
#endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx */

#if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx)|| defined(STM32F439xx) ||\
    defined(STM32F469xx) || defined(STM32F479xx)
/** @brief  FMC Bank1 (NOR/PSRAM 1 and 2) mapped at 0x00000000
  */
#define __HAL_SYSCFG_REMAPMEMORY_FMC()       do {SYSCFG->MEMRMP &= ~(SYSCFG_MEMRMP_MEM_MODE);\
                                                SYSCFG->MEMRMP |= (SYSCFG_MEMRMP_MEM_MODE_1);\
                                                }while(0);

/** @brief  FMC/SDRAM Bank 1 and 2 mapped at 0x00000000
  */
#define __HAL_SYSCFG_REMAPMEMORY_FMC_SDRAM()       do {SYSCFG->MEMRMP &= ~(SYSCFG_MEMRMP_MEM_MODE);\
                                                      SYSCFG->MEMRMP |= (SYSCFG_MEMRMP_MEM_MODE_2);\
                                                      }while(0);
#endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F469xx || STM32F479xx */

#if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) || defined(STM32F413xx) || defined(STM32F423xx)
/** @defgroup Cortex_Lockup_Enable Cortex Lockup Enable
  * @{
  */
/** @brief  SYSCFG Break Lockup lock
  *         Enables and locks the connection of Cortex-M4 LOCKUP (Hardfault) output to TIM1/8 input
  * @note   The selected configuration is locked and can be unlocked by system reset
  */
#define __HAL_SYSCFG_BREAK_PVD_LOCK()      do {SYSCFG->CFGR2 &= ~(SYSCFG_CFGR2_PVD_LOCK); \
                                              SYSCFG->CFGR2 |= SYSCFG_CFGR2_PVD_LOCK;    \
                                              }while(0)
/**
 * @}
 */

/** @defgroup PVD_Lock_Enable PVD Lock
  * @{
  */
/** @brief  SYSCFG Break PVD lock
  *         Enables and locks the PVD connection with Timer1/8 Break Input, , as well as the PVDE and PLS[2:0] in the PWR_CR register
  * @note   The selected configuration is locked and can be unlocked by system reset
  */
#define __HAL_SYSCFG_BREAK_LOCKUP_LOCK()     do {SYSCFG->CFGR2 &= ~(SYSCFG_CFGR2_LOCKUP_LOCK); \
                                                SYSCFG->CFGR2 |= SYSCFG_CFGR2_LOCKUP_LOCK;    \
                                                }while(0)
/**
 * @}
 */
#endif /* STM32F410Tx || STM32F410Cx || STM32F410Rx || STM32F413xx || STM32F423xx */
/**
  * @}
  */

/** @defgroup HAL_Private_Macros HAL Private Macros
  * @{
  */
#define IS_TICKFREQ(FREQ) (((FREQ) == HAL_TICK_FREQ_10HZ)  || \
                          ((FREQ) == HAL_TICK_FREQ_100HZ) || \
                          ((FREQ) == HAL_TICK_FREQ_1KHZ))
/**
  * @}
  */

/* Exported functions --------------------------------------------------------*/
/** @addtogroup HAL_Exported_Functions
  * @{
  */
/** @addtogroup HAL_Exported_Functions_Group1
  * @{
  */
/* Initialization and Configuration functions  ******************************/
HAL_StatusTypeDef HAL_Init(void);
HAL_StatusTypeDef HAL_DeInit(void);
void HAL_MspInit(void);
void HAL_MspDeInit(void);
HAL_StatusTypeDef HAL_InitTick (uint32_t TickPriority);
/**
  * @}
  */

/** @addtogroup HAL_Exported_Functions_Group2
  * @{
  */
/* Peripheral Control functions  ************************************************/
void HAL_IncTick(void);
void HAL_Delay(uint32_t Delay);
uint32_t HAL_GetTick(void);
uint32_t HAL_GetTickPrio(void);
HAL_StatusTypeDef HAL_SetTickFreq(HAL_TickFreqTypeDef Freq);
HAL_TickFreqTypeDef HAL_GetTickFreq(void);
void HAL_SuspendTick(void);
void HAL_ResumeTick(void);
uint32_t HAL_GetHalVersion(void);
uint32_t HAL_GetREVID(void);
uint32_t HAL_GetDEVID(void);
void HAL_DBGMCU_EnableDBGSleepMode(void);
void HAL_DBGMCU_DisableDBGSleepMode(void);
void HAL_DBGMCU_EnableDBGStopMode(void);
void HAL_DBGMCU_DisableDBGStopMode(void);
void HAL_DBGMCU_EnableDBGStandbyMode(void);
void HAL_DBGMCU_DisableDBGStandbyMode(void);
void HAL_EnableCompensationCell(void);
void HAL_DisableCompensationCell(void);
void HAL_GetUID(uint32_t *UID);
#if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx)|| defined(STM32F439xx) ||\
    defined(STM32F469xx) || defined(STM32F479xx)
void HAL_EnableMemorySwappingBank(void);
void HAL_DisableMemorySwappingBank(void);
#endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F469xx || STM32F479xx */
/**
  * @}
  */

/**
  * @}
  */
/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/** @defgroup HAL_Private_Variables HAL Private Variables
  * @{
  */
/**
  * @}
  */
/* Private constants ---------------------------------------------------------*/
/** @defgroup HAL_Private_Constants HAL Private Constants
  * @{
  */
/**
  * @}
  */
/* Private macros ------------------------------------------------------------*/
/* Private functions ---------------------------------------------------------*/
/**
  * @}
  */

/**
  * @}
  */

#ifdef __cplusplus
}
#endif

#endif /* __STM32F4xx_HAL_H */

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/

STM has a huge web of files all #include-ing each other, there's only so much I can put in one post. Anyone with STM32CubeMX and VSCode should be able to replicate this.

A: The stm32f4xx_hal.h header will mess with your stdint.h types if you have not defined your MCU in the vscode workspace. In c_cpp_properties.json, make sure you include:
"defines": [
    "STM32F411xx", // (or whatever your makefile defines)
    (...)
],

A: New answer from vscode-cpptools issue. The same problem as mentioned by @vxhht: some STM32 library mass up the stdint.h. But it is not caused by missing MCU definition:

It's not a bug -- in core_cm3.h, it needs to have a compiler define set, such as __CC_ARM or it hits a "#error Unknown compiler".

So add __CC_ARM to defines section of c_cpp_properties.json solve the problem.

A: all you need to do is:

*

*define your microcontroller

*define USE_HAL_DRIVER

*define your compiler __CC_ARM

in cpp_properties.json file

A: Oddly uint8_t and unit16_t types for declarations in Visual Studio 2019 C++14 are fine, but uint32_t is not.  All these types are fine for IAR compiler cross compiled for STM32F413.  But goal is to unit test the target code with Boost Test on Visual Studio C++.  Preprocessor symbol STM32F413xx was added to Visual Studio project but did not improve situation.
It is true comment out the stm32f4*.h and #include <stdint.h> is fine for uint32_t
but must have the stm32f4*.h headers to BoostTest target code though #ifdef out hardware accesses.  Previous answer does not say how stm32f4xx_hal.h messes with uint32_t.


text:
Q: Excel: Cell Value as Excel Document Metadata Property I know you can add custom Document Properties in Excel 2007.
see: http://office.microsoft.com/en-us/excel/HA100475241033.aspx#5
But I thought there was a way to pull a value from a cell as a custom metadata property
without code. Maybe I'm searching for it with the wrong terminology. Maybe it has to be done as a Named Range. I know this can be done. Anyone know how?

A: Here is a detailed explanation about how I got around this:
In Excel:

*

*Select a cell to be the exported metadata property

*Change the cell's Name Box (found to the left of the formula bar) to a name you can reference later (this value does not have to match any column in the SharePoint library)

*Go to File > Info > Properties > Advanced Properties > Custom

*Check the box Link to content and the cell that you named should appear as the Source

*Fill in the Name box to a value that will match a column name in a SharePoint library where the excel file will be published

In SharePoint:

*

*Create a column in a document library that will match the property name created in the Custom tab (make sure to specify if the imported cell value will be text/number/etc.)

*Upload document (the actual document needs to be closed)

*There should be an extra column containing the cell value

A: I just used the Named Range for the value on the new metadata type.  Then I made sure the same field was in the Sharepoint Library I was publishing to.
Hope this helps!


text:
Q: Loop though xml and display values in alerts I have a string that is set up as Xml. This was a data set which i filled and then returned as string getXml().
I would like to grab all values under Sub-categories and have a alert show displaying each sub category.
I tried something like this but could not come right:
$.parseXML(xml).find('Table').each(function(index){
            var SubCategorySystem = $(this).find('SubCategorySystem').text();
            var SubCategory = $(this).find('SubCategory').text();
            alert(SubCategory);
        });

This is how my string looks.
<NewDataSet>

    <SubCategorySystem>Building</SubCategorySystem>
    <SubCategory>Building</SubCategory>

    <SubCategorySystem>Electrical</SubCategorySystem>
    <SubCategory>Electrical</SubCategory>

    <SubCategorySystem>Engineering</SubCategorySystem>
    <SubCategory>Engineering</SubCategory>

    <SubCategorySystem>Inspection</SubCategorySystem>
    <SubCategory>Inspection</SubCategory>

    <SubCategorySystem>Landscaping</SubCategorySystem>
    <SubCategory>Landscaping</SubCategory>

    <SubCategorySystem>Mechanical</SubCategorySystem>
    <SubCategory>Mechanical</SubCategory>

    <SubCategorySystem>Painting</SubCategorySystem>
    <SubCategory>Painting</SubCategory>

    <SubCategorySystem>Plumbing</SubCategorySystem>
    <SubCategory>Plumbing</SubCategory>

    <SubCategorySystem>Safety & Security</SubCategorySystem>
    <SubCategory>Safety & Security</SubCategory>

</NewDataSet>"

A: Use this function to load the xml
function loadXMLString(txt) {
        try {
            xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
            xmlDoc.async = "false";
            xmlDoc.loadXML(txt);
            return (xmlDoc);
        }
        catch (e) {
            try {
                parser = new DOMParser();
                xmlDoc = parser.parseFromString(txt, "text/xml");
                return (xmlDoc);
            }
            catch (e) {
                alert(e.message)
            }
        }
        return (null);
    }

and then call the function like this:
var xmlData = loadXMLString(originalxml);

Now you can simply do this:
var data =  xmlData.getElementsByTagName('SubCategory');
for(var i=0;i<data.length;i++)
{
    alert(data[i].textContent);
}

Check out this fiddle

A: I think the wrong part is that $.parseXML(xml) creates a XML Document but it does not return it as an object, so you won't be able to use jQuery methods on it.
Wrap it in an object and it should work
$($.parseXML(xml)).find('Table')

A: you can reference this two functions first
function getExtendedNodeValue(nodeName, xmlNode, i)
{
    var node = "";

    if(typeof(xmlNode.getElementsByTagName(nodeName)[i]) != "undefined" && xmlNode.getElementsByTagName(nodeName)[i].hasChildNodes())
    node = xmlNode.getElementsByTagName(nodeName)[i].firstChild.nodeValue;

    return node;
}

function getNodeLength(nodeName, xmlNode){
    return xmlNode.getElementsByTagName(nodeName).length;
}

And below you can loop through
var len = getNodeLength("Table",xml);
var SubCategorySystem = "";
var SubCategory = "";

for(i=0;i<len;i++)
{
    SubCategorySystem = getExtendedNodeValue("SubCategorySystem",xml,i);
    SubCategory = getExtendedNodeValue("SubCategory",xml,i);

    console.log(SubCategorySystem + " == " + SubCategory);
}

You can find this FIDDLE


text:
Q: Calling ASP.NET Web API in jQuery from an Area I have an ASP.NET MVC project with an Area named MyArea. A View in there, Index, contains this javascript at the bottom (triggered during onclick of button):
<script>
    function x() {
        var url = WebApi.Url() + "orders";
        url = "http://localhost:43292/api/employees";
        $.ajax({
            type: "GET",
            contentType: "application/json",
            url: url,
            dataType: "json",
            success: function (result) {
                alert(result);
            },
            error: function (xhr, err) {
                alert(xhr.status);
            }
        });
    }
</script>

the Web API is like this:
[Route("api/employees")]
[HttpGet]
public IEnumerable<Employee> Get()
{
    List<Employee> employees = null;

    //... get employees

    return employees;
}

but it is always returning "Resource not found".
I think it is a problem when it is inside an Area, as when I move the same script inside a View that is not in an Area, the Web API gets called succesfully.
Can anyone shed some light on this? Thanks.
Oh, and I am using MVC 5 if that helps.
EDIT
Looks like it works when I tried a bare bones project just as SBirthare said. And I think the problem lies when I alter the Area route config. As I want that Area to be the default page, I've remove the leading Area name in its route config. So from:
context.MapRoute(
    "Employee_default",
    "Employee/{controller}/{action}/{id}",
    new { controller = "Dashboard", action = "Index", id = UrlParameter.Optional }
);

to
// No leading Employee
context.MapRoute(
    "Employee_default",
    "{controller}/{action}/{id}",
    new { controller = "Dashboard", action = "Index", id = UrlParameter.Optional }
);

Removing the leading Area name results in "Resource not found (404)" when calling Web API.
So my question would be what can I do in this situation to make this work?


text:
Q: On an interesting subalgebra of the functions on the cotangent bundle of the flag variety Setup
Let $G$ be a semisimple algebraic group over a field $k$ of characteristic $p$ where $p = 0$ or $p > 0$ is a good prime for $G$. Fix a Borel subgroup $B \subseteq G$ corresponding to the positive roots. Set $\mathfrak g := \textrm{Lie}(G)$. Let $U \subseteq B$ be the unipotent radical and let $U^- \subseteq G$ be the opposite unipotent radical. Set $ \mathfrak n := \textrm{Lie}(U) $ and $\mathfrak n^- = \textrm{Lie}(U^-)$.
Let me first recall the following general fact about sections of bundles on the flag variety $G/B$. Let $V$ be any $B$-module. Then we have a left $G$-action on $k[G] \otimes V$ given by the left action in $k[G]$ and we have a right $B$-action given by $(f \otimes v).b = f.b \otimes b^{-1}.v$. The global sections of the $G$-equivariant bundle $G \times^B V$ on $G/B$ now identify with the $G$-submodule $(k[G]\otimes V)^B \subseteq k[G] \otimes V$ of invariants under the right $B$-action. It is also known that the projection map $(k[G] \otimes V)^B \to k[U^-] \otimes V$ given by restriction of functions in the first coordinate is an inclusion which corresponds geometrically to the open inclusion $(G \times^B V) |_{\mathfrak B} \hookrightarrow G \times^B V$, where $\mathfrak B$ is the big cell $U^-B \subseteq G/B$.
In particular let us take $V = \mathfrak n$ so that we have the cotangent bundle $\mathcal T^* := G \times^B \mathfrak n$ of $G/B$. Denote by $\mathcal N \subseteq \mathfrak g$ the nullcone of nilpotent elements. $\mathcal T^*$ is a resolution of singularities of $\mathcal N$ and there is an isomorphism $k[\mathcal T^*] \cong k[\mathcal N]$. Also, there is a natural $B$-equivariant surjection $\mathcal N \twoheadrightarrow \mathfrak g / \mathfrak b \cong \mathfrak n^-$ induced by the projection $\mathfrak g \twoheadrightarrow \mathfrak g / \mathfrak b$. Thus we obtain a $B$-equivariant inclusion $$  k[\mathfrak n^-] \hookrightarrow k[\mathcal T^*] .$$
Putting this all together, we obtain an interesting algebra inclusion $$ i: k[\mathfrak n^-] \hookrightarrow k[U^-] \otimes k[\mathfrak n] . $$
Remark
It's possible that the above description is overcomplicated, since the inclusion $i$ is just the comorphism of the variety morphism $U^- \times \mathfrak n \to \mathfrak n^-$ given by the composition of the action morphism $U^- \times \mathfrak n \to \mathfrak g, u \times X \mapsto u.X$ and the projection $\mathfrak g \twoheadrightarrow \mathfrak n^-$. However, when described in this way it's not a priori clear to me that $i$ is a dominant morphism, so perhaps the above description is necessary.
Question
It seems highly likely that someone has considered this algebra inclusion before. If so, I would like a reference. In particular, it would be nice to have some sort of concrete description of the image of the algebra morphism $i$, perhaps in terms of generating eigenfunctions for $k[U^-]$ and $k[\mathfrak n]$.


text:
Q: RPM-SPEC - Bash Script not installing packages specified in %post SPEC file I wrote a bash script to install multiple packages and calling the bash script in %post. But its not executing the script. I am new to this area and I am not sure what I am missing.
If i manually execute the script its working fine but not through the rpm package.
InstallRPM.spec file:
Name:           InstallRPM
Version:        1
Release:        1%{?dist}
Summary:        Install RPM Packages

License:        Script
URL:            NA
Source0:        InstallRPM-1.tar.gz
BuildArch:      noarch
BuildRoot:      %{_tmppath}/%{name}-buildroot
Requires:       /bin/sh

%description
Install RPM files from the /tmp/ folder

%prep
%setup -q

%install
mkdir -p "$RPM_BUILD_ROOT"
cp -R * "$RPM_BUILD_ROOT"

%post
echo "Executing the script /tmp/InstallRPM.sh"
/tmp/InstallRPM.sh

%clean
rm -rf $RPM_BUILD_ROOT

%files
%defattr(-,root,root,-)
/tmp/InstallRPM.sh

Shell Script:
#!/bin/bash
echo "Installing package using YUM"
package="vim zip"

echo "Install $package ..."
if [ "`cat /etc/centos-release | awk '{print $1}'`" == "CentOS" ]
then
{
        for i in $package
        do
        {
                #if [ "`/bin/rpm -qa $i | cut -d. -f1`" == "" ]
                if [ "`/bin/rpm -qa $i`" == "" ]
                then
                {
                        echo "Clean Install"
                        /usr/bin/sudo /bin/yum install -y $i
                }
                else
                {
                        echo "Upgrade"
                        /usr/bin/sudo /bin/yum update -y $i
                }
                fi
                echo "****************"
        }
        done
}
fi

I ran the rpmbuild -ba InstallRPM.spec and it created a rpm file which I executed but nothing happened. Its getting hung in the below mentioned spot.
Downloading packages:
vim-enhanced-7.4.629-6.el7.x86_64.rpm                                                                                | 1.1 MB  00:00:02
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
Warning: RPMDB altered outside of yum.
^C

A: You are using rpm the wrong way. Don't install dependencies in a %post script. I suggest you to read the rpm packaging guide first.
You should use Requires in your spec file, like this:
Requires: vim
Requires: zip


text:
Q: Create arrays from JavaScript objects I have some data which looks like this:
{
  "obj":
  [
    {
      "name": "name1",
      "age": "24"
    },
    {
      "name": "name2",
      "age": "17"
    }
  ]
}

What I need to do is to create 2 arrays from it.
For example:
namelist[];
agelist[];

so the result would be:
namelist: ['name1', 'name2'];

agelist: [24, 17];

My question is, how can I do this?

A: var namelist = [];
var agelist = [];
for(var i in obj.obj){
    namelist.push(obj.obj[i].name);
    agelist.push(obj.obj[i].age);
}

console.log(namelist, agelist);

A: Is this what U wanted ?
var zz={
    "obj": [
        {
            "name": "name1",
            "age": "24"
        },
        {
            "name": "name2",
            "age": "17"
        }
    ]
}

namelist=[];
agelist=[];
zz.obj.forEach(function(rec){
  namelist.push(rec.name);
  agelist.push(rec.age);
})

console.log(namelist,agelist)

A: Make use of jquery map function or otherwise you can loop over the object and push it into array using javascript for loop and use the push() function. Refer Loop through an array in JavaScript
Jquery

var data = {
    "obj": [
        {
            "name": "name1",
            "age": "24"
        },
        {
            "name": "name2",
            "age": "17"
        }
    ]
}

var name = $.map(data.obj, function(value, index) {
    return value.name;
});
var age = $.map(data.obj, function(value, index) {
    return value.age;
});

console.log(name);
console.log(age);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Javascript

var data = {
        "obj": [
            {
                "name": "name1",
                "age": "24"
            },
            {
                "name": "name2",
                "age": "17"
            }
        ]
    }
    var names = [], ages=[];
    data.obj.forEach(function(value, index) {

        names.push(value.name);
        ages.push(value.age);
    });
console.log(names,ages);

A: var arr = $.map(myObj, function(value, index) {
return [value];
});

console.log(arr);

if you are not using Jquery then:
var arr = Object.keys(myObj).map(function (key)
 { return obj[key];
});`

A: You could use this ES6 code, and use the unitary plus for getting the ages as numbers. Assuming your object is stored in variable data:
var namelist = data.obj.map( o => o.name );
var agelist = data.obj.map( o => +o.age );

var data = {
    "obj": [
        {
            "name": "name1",
            "age": "24"
        },
        {
            "name": "name2",
            "age": "17"
        }
    ]
};

var namelist = data.obj.map( o => o.name );
var agelist = data.obj.map( o => +o.age );

console.log(namelist);
console.log(agelist);


text:
Q: Using sinon.spy to test global functions (such as parseInt) throwing error when running Karma I'm having some trouble with spying on how often parseInt is run in my function. This is a PoC for my company's Typescript integration
I've followed two separate guides on testing Sinon, but none of them have mentioned working with functions from the global namespace.
Further, I haven't found any posts regarding the subject of using spy on global functions except this one, which suggests it works..
Hovering over the spy function (sinon.spy(global, "parseInt")) also suggests that parseInt definitely is part of the global object / namespace in TypeScript
I'm getting this error which refers to a line that doesn't exist in the test-file:
PhantomJS 2.1.1 (Windows 8 0.0.0) ERROR
  {
    "message": "SyntaxError: Unexpected token '>'\nat scripts/fortress/typescript/tests/dependencies/func.spec.ts:119:0",
    "str": "SyntaxError: Unexpected token '>'\nat scripts/fortress/typescript/tests/dependencies/func.spec.ts:119:0"
  }

Removing all the lines but the one setting up the spy makes the test run fine.

The PoC test:
    /**
     * @description Takes two parameters and determines if they are of the same type.
     * @param {string} property A Date string (example: 'Date(1231231311231)')
     * @returns {number} A number indicating the time from epoch.
     */
export class Functions {
    getDateNumberFromJsonPropertyString(property : string) : number {
        return parseInt(property.substring(property.indexOf("(") + 1, property.indexOf(")")));
    }
}

    describe("GetdateNumberFromJsonPropertyString", function() {
        it("should call parseInt once", function() {
            let parseIntSpy = sinon.spy(global, "parseInt"); // <-- Breaks here

            func.getDateNumberFromJsonPropertyString("(1)");

            parseIntSpy.restore();
            sinon.assert.calledOnce(parseIntSpy);
        });
    });

Karma scafolding:
/*
    KarmaJS defintion file for all required unit tests.
*/

let webpackConfig = require('./webpack.config');

module.exports = function (config) {
    config.set({
        basePath: '',
        frameworks: ['mocha', 'chai', 'sinon'],
        files: [
            "scripts/fortress/typescript/tests/**/*.ts"
        ],
        exclude: [
            "node_modules/"
        ],
        preprocessors: {
            "scripts/fortress/typescript/tests/**/*.ts" : ["webpack"]
        },
        webpack: {
            mode: "development",
            module: webpackConfig.module,
            resolve: webpackConfig.resolve
        },
        reporters: ["progress"],
        port: 9876,
        colors: true,
        logLevel: config.LOG_INFO,
        autoWatch: true,
        browsers: ["PhantomJS"],
        singleRun: false,
        concurrency: Infinity
    })
}

A: I think you are restoring the spy before the assertion try:
sinon.assert.calledOnce(parseIntSpy);
parseIntSpy.restore();


text:
Q: How to generate similar to Qt documentation via Doxygen? The default Doxygen HTML output produces this kind of documentation.
Is it possible to make the HTML output similar to Qt3 or Qt4 documentation style? How to achieve this?
Qt4 style is preferred, however Qt3 also will do.

A: See http://www.qtcentre.org/threads/30535-Doxygen-and-Qt...-is-there-a-FAQ?p=143676#post143676
Sorry busy to write full answer


text:
Q: How to take $\int \sqrt{a^2\cos^2 t + b^2\sin^2 t}\sqrt{a^2\sin^2 t + b^2 \cos^2 t}\ dt$
Calculate $\int_{\lambda} f \ ds$ where $f:\mathbb{R^2}\to\mathbb{R}$ is
  given by $f(x,y) = \sqrt{x^2+y^2}$ and
  $\lambda:[0,2\pi]\to\mathbb{R^2}$ is the path $\lambda(t) = (a\cos t,
 b\sin t)$ which describes an ellipsis

Here's what I did:
$$\int_{\lambda} f \ ds = \int \sqrt{(a\cos t)^2 + (b\sin t)^2}|\lambda'(t)| \ dt= \int \sqrt{a^2\cos^2 t + b^2\sin^2 t}\sqrt{a^2\sin^2 t  + b^2 \cos^2 t}\ dt$$
I'm stuck here. If I multiply the insides of the square roots I get an even worse integral. Does someone know a method?

A: Considering the problem of the antiderivative $$I=\int \sqrt{a^2\cos^2 (t) + b^2\sin^2 (t)}\,\sqrt{a^2\sin^2 (t)  + b^2 \cos^2 (t)}\ dt$$consider first $$A=(a^2\cos^2 (t) + b^2\sin^2 (t))\,(a^2\sin^2 (t)  + b^2 \cos^2 (t))$$ and replace $\cos^2(t)$ by $(1-\sin^2(t))$ and finish using double angle formulae to end with
$$A=a^2 b^2+\frac{a^2-b^2}{4}  \sin ^2(2 t)$$ which makes $$I=\int \sqrt{a^2 b^2+\frac{a^2-b^2}{4}  \sin ^2(2 t) }\,dt=\sqrt{a^2b^2}\int\sqrt{1+\frac{a^2-b^2}{4a^2b^2}  \sin ^2(2 t) }\,dt$$  which is  an incomplete elliptic integral of the second kind  in trigonometric form (see here).
So, finally, $$I=\frac{\sqrt{a^2b^2} }2 E\left(2 t\left|-\frac{\left(a^2-b^2\right)^2}{4 a^2 b^2}\right.\right)$$ which is much simpler than I was expecting in my comment.
$$J=\int_0^c \sqrt{a^2\cos^2 (t) + b^2\sin^2 (t)}\,\sqrt{a^2\sin^2 (t)  + b^2 \cos^2 (t)}\ dt=\frac{\sqrt{a^2b^2} }2 E\left(2 c\left|-\frac{\left(a^2-b^2\right)^2}{4 a^2 b^2}\right.\right)$$


text:
Q: How to use Amplify Auth Class to add "remember me" functionality? I am creating a custom auth component for an application using Vue and AWS Amplify. I am trying to create a checkbox to remember the device upon login, this would allow users to opt-in to not have to use the mfa code to log-in after successfully logging-in. Looking through the Auth Class docs, it does not seem to have a "remember me" or "remember this device" option included.
Is there a way to store a users session, so they do not use mfa on the device after that logging in or any other way?
Also, I have already configured my cognito user pool to be able to remember devices upon user's opt-in, as well as suppressing mfa if they choose to opt-in. It just seems like they do not have any current methods to run that option...

A: The below is all based on discussion about this issue here: https://github.com/aws-amplify/amplify-js/issues/2552
There is a way to easily add "remember me" functionality with Amplify, along the lines of what you ask in your question. However, keep in mind that my proposed method uses localStorage vs sessionStorage, which is discouraged by OWASP (discussed here: Can local storage ever be considered secure?, and documented here: https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html).
However, it's a simple solution for testing and getting something working quickly (just don't forget to secure it before going live -- famous last words hahaha).
Here are the steps:

*

*Create an awsConfig object with all the configuration you want to set, like what's described in amplify docs: https://docs.amplify.aws/lib/auth/start/q/platform/js/#re-use-existing-authentication-resource
// awsConfig.tsx module:
const awsConfig = {
    // REQUIRED only for Federated Authentication - Amazon Cognito Identity Pool ID
    identityPoolId: 'XX-XXXX-X:XXXXXXXX-XXXX-1234-abcd-1234567890ab',

    // REQUIRED - Amazon Cognito Region
    region: 'XX-XXXX-X',

    //...etc...

    //storage: window.sessionStorage OR .localStorage <--- LEAVE THIS OUT OF THIS CONFIG
}

export default awsConfig

*Go into your App.tsx or App.js, and inside the App function, call Auth.configure(), and pass the awsConfig object to it from #1 above:

// App.tsx module:
import { Auth } from '@aws-amplify/auth'
import awsConfig from './awsConfig'

//...etc...

const App: React.FC = () => {
  Auth.configure(awsConfig)

//...etc...

*Go into your Login component, and add a check for whether that "remember me" checkbox was ticked or not, and re-do the call to the Auth.configure() function, but this time also passing the preferred storage parameter:

//Login.tsx module
import { Auth } from '@aws-amplify/auth'
import awsConfig from './awsConfig'
//...etc...

rememberLogin
     ? Auth.configure({ ...awsConfig, storage: localStorage })
     : Auth.configure({ ...awsConfig, storage: sessionStorage });

//...etc...

try {
     const awsUser = await Auth.signIn(username, password);

//...etc...

*There is not step #4... that's it... you're done...


text:
Q: SetCurrentConsoleFontEx() doesn't work with custom installed fonts I have a custom font installed on my environment (Pixel Operator Mono) and I'm developing some console application which needs this font. This is my function:
void set_font() {
    CONSOLE_FONT_INFOEX cfi;
    cfi.cbSize = sizeof(cfi);
    cfi.nFont = 0;
    cfi.dwFontSize.X = 0;
    cfi.dwFontSize.Y = 27;
    cfi.FontFamily = FF_DONTCARE;
    cfi.FontWeight = FW_NORMAL;
    std::wcscpy(cfi.FaceName, L"Pixel Operator Mono");
    SetCurrentConsoleFontEx(GetStdHandle(STD_OUTPUT_HANDLE), FALSE, &cfi);
}

Using "Consolas", "Courier New" or even "MS Gothic" seems to work fine. But "Pixel Operator Mono" doesn't. This font is displayed on my CMD properties and I can even set as default font. But why exactly I can't change this way? I already checked and SetCurrentConsoleFontEx is returning success.
Edit 1:
I use this function to get the errors as strings. But debugging I can see errorMessageId always gets 0. I call this function right after SetCurrentConsoleFontEx() call.
std::string GetLastErrorAsString()
{
    //Get the error message, if any.
    DWORD errorMessageID = ::GetLastError();
    if(errorMessageID == 0)
        return std::string(); //No error message has been recorded

    LPSTR messageBuffer = nullptr;
    size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
                                 NULL, errorMessageID, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&messageBuffer, 0, NULL);

    std::string message(messageBuffer, size);

    //Free the buffer.
    LocalFree(messageBuffer);

    return message;
}

A: First make sure that the custom font and other normal fonts are in the same code page (usually 437), which can be set through SetConsoleOutputCP.
Next, for the setting of FontFamily, try to modify to FF_MODERN << 4 | TMPF_VECTOR | TMPF_TRUETYPE for testing.
Here is the Sample:
#include <iostream>
#include <Windows.h>
using namespace std;
void set_font() {
    CONSOLE_FONT_INFOEX cfi;
    SetConsoleOutputCP(437);
    cfi.cbSize = sizeof(CONSOLE_FONT_INFOEX);
    cfi.nFont = 0;
    cfi.dwFontSize.X = 0;
    cfi.dwFontSize.Y = 27;
    cfi.FontFamily = FF_MODERN << 4 | TMPF_VECTOR | TMPF_TRUETYPE;
    cfi.FontWeight = FW_NORMAL;

    wcscpy(cfi.FaceName, L"Pixel Operator Mono");
    SetCurrentConsoleFontEx(GetStdHandle(STD_OUTPUT_HANDLE), FALSE, &cfi);
    cout << "Hello" << endl;
}

int main(int argc, const char* argv[])
{
    set_font();

    return 0;
}


text:
Q: Linux glibc tsearch() doesn't appear to have state (so there are no next() or previous() functions) I'm using glibc features tsearch(), tfind() to build an index.  This works well, but there appears to be no concept of "current key".  This in turn means that there are no documented functions like first(), previous(), next() or last().
-- Does anyone know of extensions to tsearch() which provide these functions?
-- If not, does anyone have any other suggestions (API in C required)?


text:
Q: Angular9 routing with modules I created auth-routing.module.ts to include the modules of components I think I should include some thing but I don't know I should include for example compoents !! but it is included already in the modules of each module inside the components so what's wrong please ? what should I do?
with this code:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AuthComponent } from './auth.component';

const routes: Routes = [

  {
    path: "",
    component: AuthComponent,
    children: [
        {
            path: "",
            redirectTo: "login",
            pathMatch: "full"
        },
        {
            path: "login",
            loadChildren: () =>
                import("./login/login.module").then(m => m.LoginModule)
        },
        {
            path: "reset-password",
            loadChildren: () =>
                import("./reset-password/reset-password.module").then(
                    m => m.ResetPasswordModule
                )
        },
        {
            path: "forget-password",
            loadChildren: () =>
                import("./forget-password/forget-password.module").then(
                    m => m.ForgetPasswordModule
                )
        }
    ]
}
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class AuthRoutingModule { }

and in the app-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [
{
  path: "home",
  loadChildren: () =>
      import("./main/pages/home/home.module").then(
          m => m.HomeModule
      )
},
{
  path: "auth",
  loadChildren: () =>
      import("./main/pages/auth/auth.module").then(m => m.AuthModule)
},
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Routing isn't working yet I don't know Why!!


text:
Q: Update query taking time to execute I have a table xx_wr which has a column action_code which i want to
update according to the action_code column of PER_ASG.
This PER_ASG has columns effective_start_date and effective_end_date .
Only the max effective_start_date from this table that is the latest record should be picked to update the xx_wr.
PER_ASG

EFFECTIVE_START_DATE EFFECTIVE_END_DATE ACTION_CODE PERSON_ID
01-JAN-2016          31-DEC-4712         HR          10
02-FEB-2015          31-DEC-2015         TERM        10

So from this table, the latest row from 01-JAN-2016 should be picked and Action_code HR should update the action_code in WR.
I Have written the below query for this. But it is taking 3 hrs to update 10k rows. Is there any way I can modify my query to improve the performance ?
 update XX_WR wr
            set wr.action_code =
            (
            select pam.action_code
            from PER_ASG pam
            where 1=1
            and pam.person_id=wr.person_id
            and pam.effective_start_date = (select max(ppm.effective_start_date) from PER_ASG ppm
            where 1=1
            and ppm.person_id = pam.person_id
            ))
            where 1=1;

A: Instead of nested sub-queries to find the maximum effective_start_date for each person_id use ROW_NUMBER window function to find it
Try this way
MERGE INTO XX_WR AS wr
using (SELECT Row_number()OVER(partition BY person_id ORDER BY effective_start_date DESC ) AS rn,
              action_code,
              person_id
       FROM   PER_ASG) pam
ON wr.person_id = pam.person_id
   AND pam.rn = 1
WHEN matched THEN
  UPDATE SET action_code = pam.action_code;

Note : Here we dont have to use MERGE since am not sure about Update from Join syntax in Oracle am using MERGE statement but the idea is same

A: This is the query:
update XX_WR wr
    set wr.action_code =
        (select pam.action_code
         from PER_ASG pam
         where pam.person_id = wr.person_id and
               pam.effective_start_date =
                   (select max(ppm.effective_start_date)
                    from PER_ASG ppm
                    where ppm.person_id = pam.person_id
                   )
        );

This is updating all rows in XX_WR.  That might be the cause of the performance problem.
However, the query can still be made more efficient.  I would recommend indexes.  Start with PER_ASG(person_id, effective_start_date).  I would also rewrite this as:
update XX_WR wr
    set wr.action_code =
        (select max(pam.action_code) keep (dense_rank first order by effective_date)
         from PER_ASG pam
         where pam.person_id = wr.person_id
        );

A: try this:
 WITH
sub1 AS
(  /*+ materialize */
SELECT pam.action_code,pam.person_id
  FROM PER_ASG pam
 WHERE     1 = 1
       AND pam.effective_start_date =
              (SELECT MAX (ppm.effective_start_date)
                 FROM PER_ASG ppm
                WHERE 1 = 1 AND ppm.person_id = pam.person_id)
)
update XX_WR wr
            set wr.action_code =sub1.action_code
where sub1.person_id=wr.person_id


text:
Q: Topologically Ordered Families of Disjoint Cantor Sets in $I$? Suppose that we have an uncountable collection $C_\alpha$ of disjoint Cantor Sets contained in the closed unit interval $I$.  Suppose we have ordered the indices $\alpha \in [0,1]$ as well.  Then is it possible for the collection to satisfy the following property: If $x_n \in C_{\alpha_n}$ and $x_n \rightarrow y$ with $y \in C_\beta$ from the left then every accumulation point of $(\alpha_n)$ is contained in $[0, \beta]$ and similarly if they converge to $y$ from the right then every accumulation point of $(\alpha_n)$ is contained in $[\beta, 1]$.
In other words, if you converge to a point in one of the Cantor Sets $C_\beta$ from the left, then you can only do so via points coming out of Cantor Sets that are less than $\beta$ in the order and vice-versa.  Can you order the Cantor Sets in this way that agrees with the index order 'up to the existence of limit points'?
This problem is coming from a general problem concerning admissible ensembles of continua in the plane.  But this order theory aspect is very far removed from my expertise, what little I have haha  So I need some help!  My intuition is that it is impossible.
Thanks!

A: Such an enumeration does not exist. To derive a contradiction, take any family of Cantor sets $(C_\alpha)_{\alpha\in A}$ in $[0,1]$, indexed by an uncountable  subset $A\subset[0,1]$.
Let $\mathcal K[0,1]$ be the space of non-empty compact subsets of $[0,1]$, endowed with the Hausdorff metric $d_H$. It is well-known that the metric space $\mathcal K[0,1]$ is compact and hence second-countable. Since second-countable spaces do not contain uncountable discrete subspaces, the uncountable set $\{(\alpha,C_\alpha):\alpha\in A\}\subset [0,1]\times\mathcal K[0,1]$ contains a non-isolated point $(\beta,C_\beta)$, which allows us to find a sequence $(\alpha_n)_{n\in\omega}$ in $A$ such that $\alpha_n\to\beta$ and $C_{\alpha_n}\to C_\beta$.
Using the Ramsey Theorem, we can find an increasing sequence $(n_k)_{k\in\omega}$ such that the sequence $(\alpha_{n_k})_{k\in\omega}$ is either strictly increasing or strictly decreasing. Replacing $(\alpha_n)$ by this subsequence, we can assume that the sequence $(\alpha_n)_{n\in\omega}$ is either increasing or decreasing.
First assume that the sequence $(\alpha_n)_{n\in\omega}$ is increasing. Let $x_\beta$ be the smallest element of the Cantor set $C_\beta\subset[0,1]$. Since $C_\beta$ has no isolated points, the Cantor set $C_\beta$ contains a strictly decreasing sequence $(y_n)_{n\in\omega}$ of real numbers that converges to the point $x_\beta$. For every $n\in\omega$ select a neighborhood $U_n\subset [0,1]$ of the point $y_n$ such that for any $n<m$ and $u\in U_n$, $v\in U_m$ we have $v<u$ and $|u-y_n|<1/2^n$. Since $C_{\alpha_n}\to C_\beta$, for every $k\in\omega$ there exists a number $n_k$ such that $U_k\cap C_{\alpha_n}\ne\emptyset$ for every $n\ge n_k$. Replacing each $n_k$ by a larger number, we can assume that the seqeunce $(n_k)_{k\in\omega}$ is strictly increasing. Then $U_k\cap C_{\alpha_{n_k}}\ne\emptyset$ for all $k\in\omega$.
Replacing the sequence $(\alpha_n)_{n\in\omega}$ by $(\alpha_{n_k})_{k\in\omega}$, we can assume that $U_k\cap C_{\alpha_k}\ne\emptyset$ for all $k\in\omega$. Then for every $k\in\omega$ we can choose a point $x_{\alpha_n}\in C_{\alpha_n}\cap U_n$. The choice of the sequence $(U_n)_{n\in\omega}$ ensures that the sequence $(x_{\alpha_n})_{n\in\omega}$ is strictly decreasing and converges to $x_\beta$ (whereas the sequence $(\alpha_n)_{n\in\omega}$ is increasing and converges to $\beta$. But this contradicts the choice of the enumeration $(C_\alpha)_{\alpha\in A}$.
By analogy we can consider the case of decreasing sequence $(\alpha_n)_{n\in\omega}$. In this case we should take $x_\beta$ to be the largest element of $C_\beta$.


text:
Q: Contextual type 'AnyObject' cannot be used with dictionary literal multi level dictionary I'm running into an issue with creating a multi-level dictionary in Swift and have followed some of the suggestions presented here:
var userDict:[String:AnyObject]? = ["SystemId": "TestCompany",
                                     "UserDetails" : ["firstName": userDetail.name, "userAddress" : "addressLine1" userDetail.userAdd1]]

The use of [String:AnyObject]? works for the first level of the Dict, but Swift is throwing the same error at the next level Dict, UserDetail[]. Any suggestions would be greatly appreciated

A: I'm not pretty sure what are the types of userDetail.name and userDetail.userAdd1 but if they are Strings you should let it [String:String]?
However, [String:Any]? should solve your problem. If you are sure that you want to let it [String:AnyObject]? (I don't think that you want to), you can do something like this:
var userDict:[String:AnyObject]? = ["SystemId": "TestCompany" as AnyObject,
                                            "UserDetails" : ["firstName": userDetail.name, "userAddress" : userDetail.userAdd1] as AnyObject]

Hope this helped.


text:
Q: Swiping multiple questions on Android app feed interferes with the side drawers When I try to swipe multiple questions in the feed - from left to right, I almost always open the left-side navigation drawer instead.
That's not handy.


text:
Q: My command will not run, even though it is recognised as an executable Here is the command I have typed in order. I expect it to run my "simple hello work" program.
vagrant@vagrant-ubuntu-trusty-64:~$ ls
    filename.zip  tester
    vagrant@vagrant-ubuntu-trusty-64:~$ file -b tester
    ELF 64-bit LSB  executable, x86-64, version 1 (SYSV), statically linked, not stripped
    vagrant@vagrant-ubuntu-trusty-64:~$ tester
    No command 'tester' found, did you mean:
     Command 'gtester' from package 'libglib2.0-dev' (main)
     Command 'jester' from package 'jester' (universe)
     Command 'testr' from package 'testrepository' (main)
    tester: command not found

A: Your binary is not in the $PATH variable/environment and therefor not known to the shell.
You need either to call it by using
./tester

or add it to the path
set PATH=$PATH:/path/to/tester

To make the the change to the path permanent put this line into your ~/.bashrc
export PATH=$PATH:/path/to/tester


text:
Q: Trigger a written function just when is changed just one cell of the sheet linked I have a web page which provides free diets for everybody. These diets change according to your weight, age, sex...
So, to send (via mail and in PDF) the right diet I need to change some parameters of the sheet.
I have tried single triggering (onedit) but, as many cells change when including the parameters, the function runs too many times, or even collapses sending emails.
So, I need to be triggered the function just when only one cell is changed.
I am using the function sendSheetToPdfwithA1MailAdress (which I take advantage to thanks the developer)
Below is the whole code.
Could someone help me to trigger the whole function?
function sendSheetToPdfwithA1MailAdress(){ // this is the function to call
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sh = ss.getSheets()[0]; // it will send sheet 0 which is the first sheet in the spreadsheet.
  // if you change the number, change it also in the parameters below
  var shName = sh.getName()
  sendSpreadsheetToPdf(0, shName, sh.getRange('h1').getValue(),"test email with the address in cell A1 ", "This is it !");
}
function sendSpreadsheetToPdf(sheetNumber, pdfName, email,subject, htmlbody) {
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var spreadsheetId = spreadsheet.getId()
  var sheetId = sheetNumber ? spreadsheet.getSheets()[sheetNumber].getSheetId() : null;
  var url_base = spreadsheet.getUrl().replace(/edit$/,'');

  var url_ext = 'export?exportFormat=pdf&format=pdf'   //export as pdf

      + (sheetId ? ('&gid=' + sheetId) : ('&id=' + spreadsheetId))
      // following parameters are optional...
      + '&size=A4'      // paper size
      + '&portrait=true'    // orientation, false for landscape
      + '&fitw=true'        // fit to width, false for actual size
      + '&sheetnames=true&printtitle=false&pagenumbers=true'  //hide optional headers and footers
      + '&gridlines=false'  // hide gridlines
      + '&fzr=false';       // do not repeat row headers (frozen rows) on each page

  var options = {
    headers: {
      'Authorization': 'Bearer ' +  ScriptApp.getOAuthToken(),
    }
  }

  var response = UrlFetchApp.fetch(url_base + url_ext, options);
  var blob = response.getBlob().setName(pdfName + '.pdf');
  if (email) {
    var mailOptions = {
      attachments:blob, htmlBody:htmlbody
    }
MailApp.sendEmail(
      email,
      subject+" (" + pdfName +")",
      "html content only",
      mailOptions);

MailApp.sendEmail(
      Session.getActiveUser().getEmail(),
      "FRWD "+subject+" (" + pdfName +")",
      "html content only",
      mailOptions);
  }
}

A: If you want your script to be triggered when only one cell is modified the you could use the following if condition:

onEdit(e){
// your code
  if(e.range.getValues().length ==1){
  // the code you want to run when a single cell is changed
  }
}

This will check how many cells were modified and if only one has been changed it will run the rest of your code.
Edit
From your information provided in the comments I understand you want to know if A1 has been changed, in that case use the following code:

onEdit(e){
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sh = ss.getSheets()[0];
  var shName = sh.getName();
   if(e.range.getA1Notation()=='A1'){
      sendSpreadsheetToPdf(0, shName, sh.getRange('h1').getValue(),"test email with the       adress in cell A1 ", "This is it !");
   }
}

References

*

*OnEdit events

*getValues()


text:
Q: IBM Worklight V6 logout not working I have deployed a war file on the worklight server.  e.g. BPMWorklightV6.war.
I have used the ant script to deploy and the //hostname:port/BPMWorklightV6/console works.  It prompts for a login and will display the applications and adpaters that are installed.
When I click "logout" to logout of the console it  just redisplays the console page.

A: By default your worklight console will be logged in as Guest. So only when you click logout nothing happening.
However you can protect the worklight console by setting user name and password ( both plain text and encrypted format is possible ). Refer this for more info to protect your worklight console.


text:
Q: php re-sorting an array I have an array of entries that are separated by year and month like below. I need to sort this array so that entries are "grouped" by year and then by category.
Array
(
    [Oct 2011] => Array
        (
            [0] => Array
                (
                    [title] => CAD Drawing Updates
                    [file] => /gm-June2010-driver.pdf
                    [category] => Windows
                )
        )

    [Sep 2011] => Array
        (
            [0] => Array
                (
                    [title] => title
                    [file] => /gm-June2010-driver.pdf
                    [category] => Windows
                )

            [1] => Array
                (
                    [title] => edges
                    [file] => /gm-June2010-driver.pdf
                    [category] =>Walling
                )

            [2] => Array
                (
                    [title] => Specification update
                    [file] => /gm-June2010-driver.pdf
                    [category] => Windows
                )
        )
)

So this is the sort of thing I'm after.
Array
(
    [Oct 2011] => Array
        (
                [Windows] => Array
                        (
                            [0] => Array
                                (
                                    [title] => CAD Drawing Updates
                                    [file] => /gm-June2010-driver.pdf
                                )
                        )
        )

    [Sep 2011] => Array
        (
                [Windows] => Array
                                (
                            [0] => Array
                                (
                                    [title] => title
                                    [file] => /gm-June2010-driver.pdf
                                    [category] => Windows
                                )

                            [1] => Array
                                (
                                    [title] => Specification update
                                    [file] => /gm-June2010-driver.pdf
                                    [category] => Windows
                                )
                                )
                [Walling] => Array
                                (
                            [0] => Array
                                (
                                    [title] => edges
                                    [file] => /gm-June2010-driver.pdf
                                    [category] => Curtain Walling
                                )
                                )
        )
)

I'm not sure if this is a job for the sort functions, any help would be appreciated, thanks.

A: No, that can't be done with the sort function, you need to create a new array by iterating through your original array with nested foreach loops.
$newArr = array();
foreach($arr as $month => items) {
  foreach($items as $data) {
    $newArr[$month][$data["category"]][] = $data;
  }
}

A: You don't want to sort but just to rename keys. PHP Arrays do not support to rename keys directly, so you need to create a new array first that is build with the new keys while maintaining the existing values.
At the end you can replace the original array with the new one:
$rekeyed = array();
foreach($array as $monthYear => &$value)
{
    $r = sscanf($monthYear, '%s %d', $month, $year);
    if ($r != 2) throw new Exception(sprintf('Invalid Key "%s".', $monthYear));
    $categories = array();
    foreach($value as &$item)
    {
        $category =& $item['category'];
        unset($item['category']);
        $categories[$category][] =& $item;
    }
    unset($item);
    $value =& $categories;
    unset($categories);
    $rekeyed[$year][$month] =& $value;
}
unset($value);
$array =& $rekeyed;
unset($rekeyed);
print_r($array);

Output:
Array
(
    [2011] => Array
        (
            [Oct] => Array
                (
                    [Windows] => Array
                        (
                            [0] => Array
                                (
                                    [title] => CAD Drawing Updates
                                    [file] => /gm-June2010-driver.pdf
                                )

                        )

                )

            [Sep] => Array
                (
                    [Windows] => Array
                        (
                            [0] => Array
                                (
                                    [title] => title
                                    [file] => /gm-June2010-driver.pdf
                                )

                        )

                    [Walling] => Array
                        (
                            [0] => Array
                                (
                                    [title] => edges
                                    [file] => /gm-June2010-driver.pdf
                                )

                        )

                )

        )

)

Demo

A: I think the function you should be looking at is uasort.
http://www.php.net/manual/en/function.uasort.php
First do a sort on the main array, the for each element in the array, do a usort on the child array.


text:
Q: When should you use multithreading? And would multi threading be beneficial if the different threads execute mutually independent tasks? This were the only two questions I couldn't answer in the interview I got rejected from last night.

A: You should definitely use multithreading in GUI applications when you invoke time consuming tasks from the main event loop. Same applies for server application that might block while doing the I/O.
For the second question, it is usually yes when you have machine with multiple CPU cores. In this case these independent tasks can be executed in parallel.

A: You can use multithreading if the tasks can be broken down which can be executed in parallel. Like produce and consume , Validate and save , Read and Validate.
For the second question , Yes, it is beneficial for make a program into Multi threading if they are executing independent tasks.

A: This article gives very good reasons:
https://marcja.wordpress.com/2007/04/06/four-reasons-to-use-multithreading/

To summarize, the reasons are:

*

*Keep your program responsive.

*Make better use of your CPU. CPU may be blocked by IO or other stuff. While waiting, why not letting other threads use it

*Multiple threads can be scheduled to multiple CPU cores

*Some problems are naturally to be solved by multi-threading. Such solution can simplify your code.

A: In general, multithreading is used in cases where execution time is throttled/bottlenecked by the CPU as opposed to other areas such as IO. The second question is really quite subjective to the circumstance. For example if they are mutually independent but both do heavy IO, you might not necessarily get a large gain.

A: Multithreading is used when we can divide our job into several independent parts. For example, suppose you have to execute a complex database query for fetching data and if you can divide that query into sereval independent queries, then it will be better if you assign a thread to each query and run all in parallel.
In that way, your final result output will be faster.
Again, this is an example when you have the leverage to run mutliple database queries.
And to answer your second question, it is better to have threads for independent tasks. Otherwise, you will have to take care of synchronization, global variables, etc.

A:
When should you use multithreading?

Multithreading is a process of executing multiple threads simultaneously. You should use multithreading when you can perform multiple operations together so that it can save time.

Would multithreading be beneficial if the different threads execute mutually independent tasks?

it is usually yes. Multithreading would usually be beneficial if the different threads execute mutually independent tasks so that it doesn't affect other threads if exception occur in a single thread.

A: Q: When should you use multithreading?
A: "Your question is very broad.  There are few non-trivial systems where the functionality can be met simply, quickly and reliably with only one thread.  For example: [pick out a typical system that the target company sells and pick out a couple aspects of its function that would be better threaded off - heavy CPU, comms, multi-user - just pick out something likely & explain].
Q: Would multithreading be beneficial if the different threads execute mutually independent tasks?
A: "Depends on what you mean by 'executing tasks'.  Multithreading would surely be beneficial if the threads process mutually independent data in a concurrent fashion - it reduces requirements for locks and probabilty of deadlocks increases in a super-linear fashion with the number of locks. OTOH, there is no issue with threads executing the same code, this is safe and very common."

A: You should use multithreading when you want to perform heavy operations without "blocking" the flow.
Example in UIs where you do a heavy processing in a background thread but the UI is still active.
If the threads execute mutually exclusive tasks it is the best since there is no overhead for synchronization among threads needed

A: Multithreading is a way to introduce parallelness in your program. In any case if there can be parallel paths (parts which do not depend on result from a other part) in your program, use can make use of it.
Specially with all these multiple core machines now days, this is a feature which one should exploit.
Some examples would be processing of large data where you can divide it in chunks and get it done in multiple threads, file processing, long running I/O works like network data transfers etc.
To your second question, it would be best if the tasks are mutually independent - reasons

*

*no shared data means no contentions

*no need for any ordered processing (dependency), so each thread can work when have resources

*more easy to implement