Window socket programming with Python

Question: I'm trying to implement Window socket using Python.
Mostly, everything has been so far solved using ctypes.windll.ws2_32 and pywin32 lib.
However, I haven't been able to find out how to translate the following C++ codes into Python and I wonder if anyone is kind enough to help:
LRESULT WINAPI AsyncSocketProc(
                           __in  HWND hwnd,
                           __in  UINT uMsg,
                           __in  WPARAM wParam,
                           __in  LPARAM lParam
                          )
switch(uMsg) {
    case WM_CREATE:
        //...
    case WM_SOCKET: {# this is basically an int constant
        switch(WSAGETSELECTEVENT(lParam)){
              case FD_ACCEPT:
                  //accepting new conn
              case FD_READ:
                  //receiving data
        }
    }
}

In the above code, I couldn't find Python's equivalent for WSAGETSELECTEVENT.
For the FD_ACCEPT, FD_READ, I could find them inside win32file package (of pywin32 lib)
Lastly, the reason why I'm trying to implement this Window socket programming is that the C++ version of the window socket server (above) is non-blocking for an application of mine but Python's built-in select.select is blocking. So I'm trying to see if I can port the C++ version to Python and see if it works.
EDITED:
I would like to clarify that the socket server works as a 'plug in' to an existing C++ program, which doesn't support threading.
The socket server needs to wait (indefinitely) for clients to connect so it needs to continuously listen.
So using a normal Python socket or select.select would entail a while loop (or otherwise how can it acts as a server continuously listening for events? Please correct me I'm wrong), which would block the main program.
Somehow, using the Window Socket server callback above, the main program is not blocked. And this is the main reason while I'm trying to port it to Python.
The socket server is preferably in Python because many related libs the server needs are written in Python.
Thanks a lot.
Comment: If you use a zero timeout to `select.select` then it will not block.
Comment: @JoachimPileborg Thank you: this would make the select not blocking. However, for my purpose the server still blocks the main program as we need a while loop outside the select.select. I've edited my question to clarify my purpose. Thanks.
Answer: Have a look at the socket module instead. It already contains all the code you need to work with sockets without using the win32 API.
[EDIT] You can write multi threaded code that can handle several connections. Just accept the connection and then start a new thread, give it the connection and let it read the data in a while 1: data = conn.recv(1024) ... kind of loop.
That said, Python also has a module for just that: SocketServer
[EDIT2] You say

the socket server works as a 'plug in' to an existing program, which doesn't support threading.

It's a bit hard to help with so little information but think about it this way:
You can run the socket server loop in a new thread. This code is isolated from the rest of your app, so it doesn't matter whether the other code uses/supports threads. This solves your "endless loop" problem.
Now this socket server loop will get connections from clients. My guess is that the clients will call methods from the rest of the app and here, things get hairy.
You need a way to synchronize these calls. In other places (like all UI frameworks), there is a single thread which runs any UI calls (drawing something, creating the UI, responding to user input).
But if I understand you correctly, then you can in fact modify the "main loop" of the existing app and let it do more things (like listening to new connections). If you can do this, then there is a way out:
Create a new thread for the socket server as described above. When the server gets a connection, spawn a new thread that talks to the client. When the client sends commands, create "work objects" (see command pattern) and put them into a queue.
In the main loop, you can look into the queue. If something is in there, pop the work objects and call it's run() method.
Comment: Set the sockets non-blocking if you don't want to block. And, of course, don't use a `while` loop like that.
Comment: Thank you. The socket module is definitely good but it blocks the main program, which doesn't seem to support threading.

The while 1:
     data = conn.recv(1024)
     ...
The while 1 blocks my main program.
Comment: You can have both blocking and non blocking read/writes with the regular socket methods. If you want to use blocking reads then you must use multi-threading/process, if you want to use non blocking read   you will need to use selec.select ot some other socket polling facility.
Comment: @DavidSchwartz: Thank you. Can you please clarify how to avoid the while loop for a server. I think we need it loops to be able to continuously listen for events?
Comment: @JoãoPinto. Thank you for your suggestion. the select.select can be non-blocking with timeout=0 but I still have the issue with the outer while loop, which I can't get rid of because it's a server. I've re-clarified my situation again in the question. Thanks!
Answer: You don't need or want to port this code. This code is specific to how the WIN32 API notifies native code that a socket operation has completed. It doesn't apply in Python.
The equivalent in python would be, roughly, to paste the "accepting new conn" code in wherever your python code accepts a new connection. And paste the "receiving data" code wherever your python code receives data.
You can also use select, just keep in mind that the semantics are a bit of the reverse of async sockets. With async sockets, you start an operation whenever you want and you get a callback when it completes. With 'select', it tell you when to perform an operation such that it completes immediately.
Comment: Thank you. According you explanation, it appears that Window's Async socket is what I actually need. Is there any way to implement it in Python?

Window socket programming with Python


two people meeting, uniform distribution

Question: Two people, A and B meet in a bar between 6 pm and 7 pm. They arrive independently of each other, evenly distributed between 6 pm and 7 pm. The first person who arrived, do not wait more than 15 minutes. What is the probability that they meet?
I have a geometric argument correction for this exercice but I would like to try it with formula argument.
Let $T_A,T_B$ uniform distribution from 0 to 60.
$P(T_A-T_B<15)=\int_{-\infty}^{\infty}f_{T_B}(x)f_{-T_B}(15-x)dx$ by a proposition.
But I don't know how to write the next step, I would like to write $=\int_{-\infty}^{\infty}\frac{\mathbb{1_{[0,60]}}}{60}\frac{\mathbb{1_{[0,45]}}}{45}dx$ but I feel that it is wrong.
Comment: It is more handsome to go for $P(T_A<T_B<T_A+15)+P(T_B<T_A<T_B+15)$. By symmetry the probabilities are the same so it is enough to find $P(T_A<T_B<T_A+15)$. Use conditional distribution.
Comment: For a graphical approach see https://math.stackexchange.com/questions/103015/chance-of-meeting-in-a-bar and the posts linked to it.  For a couple with a more analytical approach see https://math.stackexchange.com/questions/1275612/coffee-shop-meeting and https://math.stackexchange.com/questions/1168454/two-people-meeting-expected-time-of-waiting
Answer: It is simpler to express time in hours rather minutes. The joint PDF is $f_{X,Y}(x,y)=1$. Now consider the three cases:
$$\begin{cases}0\le x\le \frac14 \\ 0\le y\le x+\frac14\end{cases} \ \ \text{or} \ \ \begin{cases}\frac14\le x\le \frac34 \\ x-\frac14\le y\le x+\frac14\end{cases} \ \ \text{or} \ \ \begin{cases}\frac34\le x\le 1 \\ x-\frac14\le y\le 1\end{cases}$$
Integate on each domain:
$$\int_0^{\frac14}\int_{0}^{x+\frac14} 1 \ dydx + \int_{\frac14}^{\frac34}\int_{x-\frac14}^{x+\frac14} 1 \ dydx + \int_{\frac34}^{1}\int_{x-\frac14}^{1} 1 \ dydx =\\
\left(\frac3{32}\right)+\left(\frac14\right)+\left(\frac3{32}\right)=\frac7{16}.$$


PHP session_id( ) null

Question: I am having some difficulty with sessions.
On my local MAMP test server, if I do:
session_start( );
echo session_id( );
I get a nice looking session id.
If However, I the same thing on my web server, all I can get back from session_id is 'null'.  Testing the return from session_start( ) and using sessions everything is working, but session_id( ) $SID and $PHPSESSID are all null.
Is this hidden on purpose for added security?  I want to be able to allow flash to make changes to a shopping cart through PHP calls and have the cart (which is stored in the session) reflected using the browser.
Comment: What happens if you do session_start(); var_dump($_SESSION);
Comment: Valid session variable:

array(1) { ["product"]=>  &array(1) { [0]=>  string(21) "frame-13-1-260-237-18" } }

Then session_id( ) still reports null...
Comment: null? Strange as session_id should only return the id or an empty string.
Comment: If I " echo 'Session is: ' . session_id( ); "  I get "Session is: null".
Comment: If I var_dump( session_id( ) ) I get: string(4) "null"...

So it is actually a string of "null".  Not NULL
Comment: Multiple browsers / multiple computers all show different $_SESSIONS but all return a string of "null" from session_id( ).  Must be a new security issue / setting?
Answer: Make sure the return value of session_start() is TRUE.
Make sure you are calling session_start() before your script outputs anything to the browser.
Check that apache has write access to the session path. Mine is /tmp
Comment: session_start( ) TRUE.

Very beginning of file is <?  session_start( ); ...

Mine is /tmp and sessions are indeed working.  (Cart is functional, ...)  and the script works on MAMP.
Answer: I had a similar problem (session_id() returned "", I hope, this is related to your question). I closed all corresponding tabs and deleted all relevant cookies, then re-opened the site and now session_id() returns a beautiful hash value.
Answer: Perhaps an edge case, but for me, I solved it by testing the return value of session_start() which showed it to be false.
The issue turned out to be the encoding of the actual file. It was emitting something invisible before the session started, even though it looked like nothing was there.
I solved it by copying the relevant files into a plain text editor (I used https://www.editpad.org/), deleting the source file on, recreating the empty file, pasting that code I had run through editpad, and reuploading.
After that everything started populating normally.
Comment: Another good example of plain text editor is https://pasteepad.com/
Answer: I had a similar issue on Windows and for me it was caused by the ini setting session.save_path having an invalid path defined.

PHP session_id( ) null


Rails join table A to table C where A has many B and B has many C

Question: So in rails, I have
class Organization < ActiveRecord::Base
has_many :boxes

class Box < ActiveRecord::Base
has_many :items
belongs_to :organization

class Item < ActiveRecord::Base
belongs_to :box

Without adding the association on Organization, how can I query for all items that belong to an organization? I don't want to add orgaization_id to Item.
Answer: Take a look at has_many :through Association.
In your case, you can add the following to your Organization model
has_many :items, through: :boxes

Then you'll be able to write something like this: Organization.find_by(id: ..., name: ....).items
Comment: That seems totally reasonable! I was thinking about joins but probably not necessary. Thx


Is batt_attr_text file vendor-independent in Android

Question: I would like to know whether in Android the batt_attr_text file's location and content is the same regardless of the vendor or not? (Btw. same content means now that it has the same "attributes" listed in it...)
The reason I ask this is because of another post here. In the mentioned question, the questioner wants to know Voltage and Current. He/She gets an answer indicating, that the information can be found in a vendor-dependent file.
However what I'm looking for is the mAh capacity of the battery. I found that /sys/class/power_supply/battery/batt_attr_text contains what I need, but I'm not sure, that this file will be found on every Android device in the same form and in the same place.
Every constructive answer is appreciated. Thanks!
Answer: It's device specific, so it depends on the manufacturer. Have a look at this project: https://code.google.com/p/currentwidget/


Using a C macro within a makefile

Question: I have a shell script that will create a version information header file, version.h, which looks like
echo -e "\
#pragma once\n\
\n\
#include \"build_config.h\"\n\
\n\
\n\
#define COMMIT_REVISION                 \"${GIT_HEAD^^}\"\n\
#define COMMIT_FIRST_FOUR_BYTES         0x$(cut -c 1-8 <<< ${GIT_HEAD^^})\n\
#define CHECKOUT_SHA                    \"${CHECKOUT_SHA}\"\n\
#define CURRENT_SHA                     \"${CURRENT_SHA}\"\n\
#define DATE_OF_SHA                     \"${DATE_OF_SHA}\"\n\
#define BUILD_TYPE                      \"${BUILD_TYPE}\"\n\
\n\
#define BINARY_BASE_NAME               BUILD_TYPE \"_\" DATE_OF_SHA \"_\" CURRENT_SHA\n\" > ${1}

The environment variables used in the script are set during the execution of the script file.  For instance, GIT_HEAD="$(git rev-parse HEAD)"
The resulting header file the script creates looks like
#pragma once

#include "build_config.h"

#define COMMIT_REVISION                 "D70B1A73915F11BF5BF3A9D531BF57BA3D58CD73"
#define COMMIT_FIRST_FOUR_BYTES         0xD70B1A73
#define CHECKOUT_SHA                    "d70b1a73"
#define CURRENT_SHA                     "d70b1a7391"
#define DATE_OF_SHA                     "220621"
#define BUILD_TYPE                      "E"

#define BINARY_BASE_NAME               BUILD_TYPE CONTROLLER_CHIP_ID_CHAR CONTROLLER_CHIP_VERSION_CHAR DATE_OF_SHA "_" CURRENT_SHA

Within a makefile is there a way to use the macro BINARY_BASE_NAME within a target recipe?  Something like
bin/$(BINARY_BASE_NAME): bin/binary_object.o version.h
  $(V)cp bin/object.o bin/$(BINARY_BASE_NAME)

Would I need to export BINARY_BASE_NAME as an environment variable?  Can the makefile use the macro directly?
Comment: Your shell script is bogus (the final double-quote should probably not be escaped) and, more important, it is not consistent with the example header file you show. Where do these `CONTROLLER_CHIP_ID_CHAR` and `CONTROLLER_CHIP_VERSION_CHAR` in the header file come from? There is nothing like this in your script. Moreover your script separates the 3 macros that form `BINARY_BASE_NAME` by underscores but your example header file does not. Please provide a consistent example.
Answer: Not really.  Make is not a C compiler, and a header file is not a makefile: make can't parse C code.
You could try to play a trick like, write a C file that included the above file then simply assigned it, and only run that C file through the preprocessor and not the compiler.  It would be kind of a hack.  Something like this MIGHT work:
# trick to get a variable $S that contains a single space
E :=
S := $E $E

include version.mk
_basename := $(subst ",,$(subst $S,,$(_basename)))

version.mk : version.h
        (echo '#include "$<"'; echo '_basename := BINARY_BASE_NAME') > $@.c
        $(CC) $(CFLAGS) -E $@.c > $@

it might work.
ETA
Just to promote my comment below: the best way to do this is to either write another shell script that generates the makefile info like version.mk, or else enhance the shell script that creates version.h so that it also writes the same information to a file version.mk.  That would be a lot safer and more reliable.
Comment: We could also generate a real piece of C code that prints this macro, compile it, execute it and redirect the output to the included Makefile.
Comment: _it might work_ ... as long as none of the macros contain spaces (e.g. `#define BUILD_TYPE "E F"`). But considering the use of `BINARY_BASE_NAME` in the OP we can probably exclude this.
Comment: Yes.  I said it was "kind of a hack".  Really, that's probably underselling it and it should be "a total hack" :).  If I were doing it I would just create a second shell script that would write out a `version.mk` for makefiles containing the same content as `version.h`.  Or, enhance the existing `version.h`-generating script to also write out `version.mk`.
Comment: Yes, good point.  This might be the better way since I now notice that some of the values in `BINARY_BASE_NAME` are not defined here, and presumably come from the `build_config.h` header file.
Answer: Pushing MadScientist's approach one step further you could generate a real piece of C code that prints this macro, compile it, execute it and redirect the output to the included Makefile. Simplified demo:
The simplified version.h:
#define CURRENT_SHA         "d70b1a7391"
#define DATE_OF_SHA         "220621"
#define BUILD_TYPE          "E"

#define BINARY_BASE_NAME    BUILD_TYPE DATE_OF_SHA "_" CURRENT_SHA

The Makefile file:
include version.mk

define C_code
#include <stdio.h>
#include "$<"

int main(void) {
  printf("BINARY_BASE_NAME := %s\n", BINARY_BASE_NAME);
  return 0;
}

endef
export C_code

version.mk : version.h
    printf '%s\n' "$$C_code" > "$@.c"
    $(CC) $(CFLAGS) -o "$@.exe" "$@.c"
    "./$@.exe" > "$@"

.PHONY: all clean

all:
    @printf '%s\n' "$(BINARY_BASE_NAME)"

clean:
    rm -f version.mk.c version.mk.exe version.mk

And then:
$ make all
printf '%s\n' "$C_code" > "version.mk.c"
cc  -o "version.mk.exe" "version.mk.c"
"./version.mk.exe" > "version.mk"
E220621_d70b1a7391

$ cat version.mk.c
#include <stdio.h>
#include "version.h"

int main(void) {
  printf("BINARY_BASE_NAME := %s\n", BINARY_BASE_NAME);
  return 0;
}

$ cat version.mk
BINARY_BASE_NAME := E220621_d70b1a7391

$ make clean
rm -f version.mk.c version.mk.exe version.mk

Answer: If your shell script creates a header, why not make it also create a Makefile snippet that gets included by your main Makefile?
echo "BINARY_BASE_NAME := ${BUILD_TYPE}_${DATE_OF_SHA}_${CURRENT_SHA}" > makefile.inc

Then use a GNU make include makefile.inc directive.
Comment: This would work only in "simple" cases where the shell script has access to all bits. But if the header file generated by the script imports some macros from an included other header file, this would not work. And it seems to be the case (see the `#include "build_config.h"`, and the `CONTROLLER_CHIP_ID_CHAR` or `CONTROLLER_CHIP_VERSION_CHAR` macros) in the example of generated header file (but the shown script and the shown generated header file are not consistent).

Using a C macro within a makefile


Nagios: Could not resolve hostname

Question: My setup:
hosts.cfg - contains definitions for each host under monitoring, e.g.:
define host{
        use                     linux-server
        host_name               rdss-vpn
        display_name            VPN
        address                 54.***.***.176
        }

hosts_groups.cfg - define groups:
define hostgroup{
        hostgroup_name   rdss-service-server
        alias            RDSS services
        members          [...],  rdss-vpn
        }

services.cfg:
define service{
        use                             local-service
        hostgroup_name                  rdss-web-server, rdss-service-server
        service_description             Memory usage
        check_command                   check_linux_memory!50!80
        notifications_enabled           1
        }

And check_linux_memory in commands.cfg:
define command{
        command_name    check_linux_memory
        command_line    $USER1$/check_nrpe -H $HOSTNAME$ -c check_linux_memory -a '-f -w $ARG1$ -c $ARG2$'
        }

Here is example of host, where check_linux_memory works:
define host{
        use                     linux-server
        host_name               www.dev.domain.com
        display_name            DEV
        address                 54.***.***.136
        }

It's group:
define hostgroup{
        hostgroup_name   rdss-web-server
        alias            RDSS web servers
        members          www.dev.domain.com, www.qa.domain.com, www.staging.domain.com
        }

Problem is with few new added hosts, like rdss-vpn - Nagios won't get it's IP from hosts (please note - I have few other servers (also in groups) in check_linux_memory - all works).
Instead - I have an error in nagios.log:

[1437473407] SERVICE ALERT: rdss-vpn;Memory usage;WARNING;HARD;4;(No
  output on stdout) stderr: Could not resolve hostname rdss-vpn: Name or
  service not known
Comment: It might be a bit pedantic, but your  [question](http://meta.serverfault.com/a/3609/37681) appears to be missing an actual question with a question mark "`?`" :-)  . - Please improve your question or run the risk of leaving your problem unresolved and/or having your question closed.
Comment: Well, tried to resolve the domain name with dig or host?
Comment: @sebix Nagios must get IP from `address` in `define host` - correct?
Answer: Your problem is that you wrote your check command to use $HOSTNAME$ instead of $HOSTADDRESS$.
This happens to work for your other hosts, because they are named with FQDNs (e.g., www.dev.domain.com). It doesn't work for rdss-vpn because that's not a valid hostname from the perspective of your Nagios box.
You should use the address, not the hostname, in checks. This removes DNS as a dependency for Nagios checks. If you really need to use a hostname instead of the IP, put the hostname in as the host address.
Also, traditionally one would just pass the check to check_nrpe as an ARG, like check_nrpe!check_memory or check_nrpe!check_memory!50 80. But it's up to you, ultimately.
Comment: I normally link to the docs, but yes they're mostly unavilable currently. Google has most of it cached, if you know the exact page you need.
Comment: Yes! Thanks! That's exactly what I need! I remember about Nagios own documation - but it's located on Sourceforge - and unavailable last.... one? two weeks?

Nagios: Could not resolve hostname


Transcribing Jazz Piano Chord Voicings

Question: I have just started to play jazz piano after many years of classical piano and one of the big things I have to do as a jazz musician is to transcribe (by ear) famous jazz recordings. When I am transcribing, many jazz pianists play chords and I am having difficulty playing the exact chords that they play. Are there any tips or tricks to transcribing chords by ear?
Comment: I assure you that they can. Reproducing complex harmonies is one of those things that is way easier to do via talent and hard practice than to describe in a textbook.
Comment: I wonder if even many top jazz pianists can play the exact chords and voicings of other pianists just like that ... I guess many probably have to do at least some trial and error to get the exact same sounds. Transcribing is a good exercise for learning, but it's ok if you can make your own version of the tune. :) If the chord works as a dominant, then at least play some kind of a dominant, etc.
Comment: I'm pretty good with hearing altered chords on one go (I like to tell myself that, at least), and I can get most jazz chords on one or two listens, and I'm not even a jazz pianist. I can imagine that the really good jazz pianists can probably recognise the complicated, dense chords just as easily as we can hear triads.
Comment: @KilianFoth I want to believe such people exist ... I've been watching Rick Beato on Youtube and he's pretty good with harmony, but even he seems to need some trial and error to find things. Myself, I've transcribed some jazz stuff and sometimes getting the exact voicing is really difficult ... there's some additional thickness somewhere and finally I find it, some fifth and octave were doubled in the lower register, or something. But it's so hard to get exactly right, I'm thinking even good players must settle with approximations, as long as it sounds good, close enough and does the job.
Comment: Agreed, @KilianFoth. It's just like anything else--it takes practice, ear training, and lots of experience with different chord voicings. If I played a Bud Powell shell voicing, most pro pianists would be able to recognize it immediately. If I played a 3-note quartal voicing (a la Chick), most would recognize it. With enough repetition, it's possible to recognize many/most chord voicings occurring simply because they're so familiar. If you transcribe the same person over and over, you can start to hear the same voicings getting used. It's slow work at the beginning but gets better.
Comment: Or you can have [perfect pitch](https://www.youtube.com/watch?v=vXivZlPu0ms).
Comment: @Haversine through practice!
Comment: @jdjazz but how did he learn?
Answer: It can be very hard to hear specific chord voicings that jazz pianists play on recordings for several reasons, recording quality, other instruments playing, song tempo to name a few. What I would suggest is start by knowing the harmony of the song first. If it is a standard you can probably find it in a fake book. If not then try transcribing just the harmony, not the actual voicings themselves. Listening to the bass can be helpful in this regard. If you know the chord progression of the song it will be easier to figure out what the pianist is playing note for note.
The next step is learning and understanding the different ways pianists voice their chords. You will likely need some help with this, either a jazz piano harmony book or a few private lessons with an accomplished player. Once you learn the different ways jazz players construct their chords you may start to recognize voicings when you hear them. I am curious to know which recordings and what era of jazz you are working on because there has been much evolution in the way pianists create their voicings over the years.
Comment: This tune is widely published in fake books so it shouldn't be hard to find. A few things to be aware of, jazz musicians commonly play this song in Bb and many printed versions are in Bb but the original key is G and Bud plays it in that key. Also there are some widely used jazz reharmonizations which Bud doesn't play. For example the first bar Bud plays the original Go7 where as most jazz players play a ii-V7 of C#m7b5 F#7. Another example is bar 10 Bud plays an Em where as many jazz players will play C#m7b5 F#7. His bass notes should help with transcribing, good luck!
Comment: I am transcribing this recording of Stella by Starlight by Bud Powell: https://www.youtube.com/watch?v=pK9P4z7GKYc
Answer: I think it's really helpful to try and internalise the sound of various common jazz chord qualities. It is a lot easier to hear the complicated harmonies when you have a large mental database of sounds from which to work. For example, obviously any jazz musician should know by heart all the seventh chords, but some great useful sounds to know are:

maj9
m9
9
6
m6
6/9
m11
m13
7♯11 (7♭5)
maj7♯11 (maj7♭5)
7♭9
7♯9
+9 (9♯5)
9sus
13sus
13♭9
9
13

If you are familiar with these sounds, a lot of jazz harmonies will seemingly transcribe themselves, and the more complicated chords can mostly be related back to these chords above. Now, dominant chords can be altered nearly beyond recognition, and you'll occasionally hear some chords with two or three crazy alterations, but with a couple listens it should be much easier to pick out individual notes. If you're not sure, the bass note and the top note are often the easiest to hear.
The reason why it's important to know those basic harmonies above is because sometimes on the recording it won't be possible to hear every note and piece together the chord. If you can just listen and hear "okay, that's a minor 9 chord, to a diminished 7th chord, and oh, 13♭9, aaaand back to maj7", you can figure out the chord roots easily by ear. With practice, this can allow one to really play some complex stuff by ear and transcribe jazz music much more efficiently. Of course, it'll take time and effort to develop one's ear to that point, but with regular active listening to jazz music, it shouldn't be too hard to do.
Jazz is also a very functional genre; chords tend to follow predictable patterns. By far the most important pattern in the genre is the ii V I and its minor variant ii° V i. When you listen to a lot of jazz music, you start to hear the tonic, predominant, and dominant roles on the harmonies, which will help determine both the quality of the chord and its root. As a simple example, suppose you know a chord progression is Cmaj7, E♭°7, X, and G7, but you can't tell what's being played at X. The only real option for that chord X is some kind of Dm7 chord, unless the E♭°7 chord is functioning differently than the way I labelled it (actually, maybe a D7 of some sort could work). Knowing chord progressions will let you "know your options" at a moment in the piece, so to speak. Secondary Dominants and Tritone Substitutions also are really important concepts to understand, as they can easily explain some of the more challenging harmonies to hear. This is why it's very important to be up on your theory to transcribe jazz music: if you have to get out your circle of fifths to determine the V of every E♭ chord, you're much too slow. Also, jazz gets written in plenty of keys, and uses chords on every root, so better get away from just "thinking in C" every time.
Comment: I suppose it would then be important to sort of internalise the difference between closely-spaced voicings and wide, open voicings. Or, if possible, you could try to hear every note, but that can be hard. If I ever can't tell by ear immediately, I just mess around on the keyboard until I figure out what I think the exact voicing is.
Comment: Yes, I can hear some chord qualities but how would I transcribe to the note of particular voicings?
Answer: In addition to the tips described in other posts, here are some common techniques:

Transcribe the lowest and highest notes of the chord voicing first, as these are usually the easiest to hear. In many jazz piano contexts, the lowest note in a piano voicing will rarely be the root.
Identify the root and the chord quality. This really is the first step, and it's already been mentioned by others. The chord quality is different from the voicing, of course, but if you can identify that you're hearing a C13(b9) chord, then you'll immediately have some candidate notes to try and listen for. In the C13b9 example, you'd be on the lookout for C, Db, E, G, A, Bb. They may not all be present in the voicing, but now it's a matter of (a) figuring out which of the candidate notes are included vs. excluded in the voicing and (b) the ordering of the notes.
Pause the recording immediately after the chord sounds. Try singing the notes you think you hear. Pick one of those notes, and test it out in the following way: sing the candidate note while you play the chord back again in the recording. Listen to see if the note you sing is being matched in the voicing on the recording. This can help you determine whether the note is present.
Different intervals have sound different. 2nds sound crunchy, 3rds sound more closed and traditional, 4ths sound more amorphous, 5ths sound open, etc. Try to use these qualities to identify the intervals being used. This can inform which notes to try singing in step 2.
Use a lead sheet while transcribing. The voicings usually follow the chord progression of the song. Pull up a lead sheet (or create one yourself), and when listening to a voicing, you can look for important tones from the chord (e.g., the 3rd and 7th). These won't always be present though, so this will only help some of the time.
Research some info about the pianist you're listening to, and familiarize yourself with the styles of that era. Many important pianists like Bud Powell, Red Garland, Bill Evans, Chick Corea, etc. use the same voicings in many different songs. Try out well-known voicings from that style of jazz and from the particular pianist.
Transcribe high-quality recordings. When first learning to transcribe chord voicings, life will be much easier if you start out on recordings where you can hear the notes clearly. Old recordings have pitch issues and may sound muddy, which can make the task extremely difficult (or impossible, in some cases). Maybe those older recordings could become transcriptions that you tackle after gaining some practice on clearer recordings.
Improve your ear through ear training exercises. This is the hardest (and slowest) step, but it's also the highest-yield. If you've practiced combination triad voicings in all 12 keys, then you are much more likely to immediately recognize them in a Bill Evans recording. If you've practiced right-hand octaves with a third down from the top note, then you'll hear this technique instantly in Red Garland recordings. Upper structure chords, Bud Powell shell voicings, rootless A/B voicings, inner voice movement, etc. are all easier to hear if you've practiced them extensively.
Comment: @Fefo, my reading of the question is that it's not asking how to transcribe a chord progression. Instead, it seems to ask how to transcribe the *voicings* themselves. Some may place a higher value on transcribing the chord progression, while others may place a higher value on transcribing the voicings themselves. I think it depends a lot on one's goals and existing knowledge. For example, if someone is already really skilled at determining a chord progression from ear, then going through this step may not be worth the time; that time might be better spent on getting the voicings themselves.
Comment: @Fefo, but to your point, if someone is interested in practicing *both* transcribing the chord progression and transcribing the voicings, then the lead sheet they pull up could be one they've created themselves!
Comment: isn't using a lead sheet cheating? for me, to identify the chords is more important than the voicing.
Comment: yes, i think this is the most interesting approach in transcribing. understanding the chords by ear, and then understanding what the musician is doing with them in terms of voice leading. and i don't think it's a problem to take a look in a lead sheet if you have written your own sheet before.
Comment: @Fefo, many of us have probably heard a pianist play a lick in the right hand, have immediately known the notes, and have thought "Wow! What a cool place to use that lick!" It's the exact same with transcribing chord voicings. Granted, this is *harder* to do, but as one makes progress in that realm, they unlock an entirely new way of listening to music. We can listen to a Keith Jarrett track, immediately recognize the inner voice movement and thinking "What a cool place to use that!" Or we can hear a Mehldau track and think "What a cool place to voice the 11th in the major chord!"
Comment: @Fefo, many jazz pianists listen to music in this way, and it definitely impacts how they think about their voicings and how they play. Some people can just do this naturally and can pick out the notes in a voicing without much effort (I had several close friends like this in college), and other people develop that skill through the things I've described above (though this skill tends to develop naturally as one expands their knowledge of different chord voicings).
Comment: @Fefo, these are the reasons why I think it's incorrect to suggest that transcribing chord progressions is more important than transcribing voicings. But 'importance' is a value judgment; it depends on one's goals. Many great jazz pianists (especially those who play solo) put a lot of thought into how *every note* of a voicing moves and resolves to the next voicing. We lose something if we can't hear that level of detail and only hear, e.g., voice leading or general shapes. But this skill is really slow to develop (for most). Whether it's actually worth the time/effort is a value judgment.
Comment: i'm not disagreeing with you. as i said, voice leading is the ultimate goal. it's just that if you get a lead sheet before transcribing, you're jumping the simpler step (identifying the chords) and going for the harder one (identifying all voice movements).

Transcribing Jazz Piano Chord Voicings


Interligar 3 tabelas sql entre si, utilizando INSERT

Question: Olá, antes de eu tentar caprichar em PHP mais a fundo, ando estudando melhor a logica do mySQL, com select, delete,insert etc. Mas na hora que estudar o banco de dados sql com o tempo, percebi que na prática não é correto inserir todas os elementos em uma tabela só, já que causa uma bagunça na lógica. E então estou nesse impasse tentando entender essa lógica.
Exemplo, tenho 3 tabelas... Uma é "Pessoa", "Profissao" e "Universidade", que ao inves de colocar profissao e universidade dentro da propria tabela Pessoa, resolvi separá-los p/ tentar entender o funcionamento entre si através da interligação entre as 3 tabelas. Sendo que conseguiria conectar a tabela profissão e universidade para Pessoa, problema que não estou conseguindo, e não quero ficar fazendo gambiarras. Como eu faria para inserir um elemento de uma tabela em outra ? Estou colocando um link dos arquivos p/ você tentar entender de acordo com o formulario que fiz, de forma separada...
[LINK DOS ARQUIVOS] [1]: https://drive.google.com/drive/folders/1HxMz4WRrPfAa-X153rxZOOQntpgGk2C4?usp=sharing
Demonstração: (Ou segue, o arquivos que deixei no link, para poder entender melhor, é simples de entender)
public function addPessoa($nome, $sobrenome, $telefone) {
    global $pdo;

    $sql = $pdo->prepare("INSERT INTO pessoa SET nome = :nome, sobrenome = :sobrenome, telefone = :telefone");
    $sql->bindValue(":nome", $nome);
    $sql->bindValue(":sobrenome", $sobrenome);
    $sql->bindValue(":telefone", $telefone);

    $sql->execute();
}

public function addProfissao($nome) {// como eu faria para inserir o nome da universidade da tabela Profissão para tabela Pessoa ?
    global $pdo;

    $sql = $pdo->prepare("INSERT INTO profissao SET nome = :nome");
    $sql->bindValue(":nome", $nome);

    $sql->execute();
}

public function addUniversidade($nome) { // como eu faria para inserir o nome da universidade da tabela Universidade para tabela Pessoa ?
    global $pdo;

    $sql = $pdo->prepare("INSERT INTO universidade SET nome = :nome");
    $sql->bindValue(":nome", $nome);

    $sql->execute();
}

Answer: Vou tentar esclarecer algumas coisas para você de SQL.

Você fez certo em criar as tabelas separadas.

Você deve colocar o campo que tem a referência de outra tabela (Chave Estrangeira), na tabela principal, no caso na tabela "pessoas".

Resumidamente, a "Chave estrangeira" ou "Foreign Key" serve para você relacionar as suas tabelas, elas vão "conversar" uma com a outra, elas ajudam a você não inserir dados incorretos em seu banco de dados, ajuda em uma análise futura caso precise, e também deixa  mais estruturado/elaborado.
Na prática, o seu SQL da maneira correta:
CREATE TABLE profissao (
  id_profissao int(11) PRIMARY KEY AUTO_INCREMENT NOT NULL,
  nome_profissao varchar(45) NOT NULL
);

CREATE TABLE universidade (
  id_universidade int(11) PRIMARY KEY AUTO_INCREMENT NOT NULL,
  nome_universidade varchar(45) NOT NULL
);

-- Por ultímo a tabela principal, para não gerar conflitos na hora da criação.
-- Pois os campos "fk" estão se referindo a campo de outra tabela.

CREATE TABLE pessoa (
  id_pessoa int(11) PRIMARY KEY AUTO_INCREMENT NOT NULL,
  nome varchar(45) NOT NULL,
  sobrenome varchar(45) NOT NULL,
  telefone varchar(45) NOT NULL,

  -- Criando chaves estrangeiras
  fk_profissao INT(5),
  foreign key (fk_profissao ) references profissao(id_profissao),

  fk_universidade INT(5),
  foreign key (fk_universidade ) references universidade(id_universidade)
);

Após a criação da tabelas, você faz a inserção de dados, como você fez o seu.
Eles devem ter algum ID que você tenha criado, na tabela "profissao" e "universidade", caso contrário, o próprio banco de dados, irá mostrar o erro, pois eles estão referenciados.

Após as inserções, você consegue realizar consultas, utilizando
JOINS.

SELECT A.id_pessoa, A.nome, A.sobrenome, A.telefone, B.nome_profissao, C.nome_universidade
FROM pessoa A
JOIN profissao B ON A.fk_profissao = B.id_profissao
JOIN universidade C ON A.fk_universidade = C.id_universidade;

Caso tenha alguma dúvida, pode perguntar, não tem problema algum nisso, espero que tenha ajudado.
UPDATE:
Agora, respondendo as perguntas do seu code.
// como eu faria para inserir o nome da universidade da tabela Profissão para tabela Pessoa ?
// como eu faria para inserir o nome da universidade da tabela Universidade para tabela Pessoa ?
R: Simples e fácil, você não irá inserir o nome da universidade ou o nome da profissão, você irá inserir o ID delas, com o ID salvo na tabela, você consegue trazer o nome dela, entendeu?

Primeiramente, você deve refazer a estrutura do seu banco de dados,
como eu mostrei acima.
Comment: Caso não tenha entendido, faça as perguntas por aqui, obrigado.
Comment: Samuel, primeiramente obrigado pela explicação objetiva com mysql com a chave estrangeira. Mas como ficaria encaixado com as minhas lógica PHP que deixei, sendo que existe agora uma chave estrangeira... Na parte do "public function addProfissao() e "function addUniversidade" para "addPessoa()" ?
Comment: Cara, seu code php não vai mudar, você só precisa adicionar o campo "fk_profissao" e "fk_universidade" no seu `INSERT INTO pessoa`, simples... reforçando mais uma vez, que o valor desse dois campos que a gente criou, deve ser de tipo `INT`, e ele deve ser o `ID` das outras duas tabelas...
Comment: Pode manter o INSERT profissao e universidade, só precisa alterar o INSERT da tabela pessoa... Exemplo `INSERT INTO pessoa SET nome = 'Kleber', sobrenome = 'Souza', telefone = '40028922', fk_profissao = '1', fk_universidade = '2';`
Comment: Só que tem uma coisa, as paginas php que criei com os formularios, cada um possui só os campos de index.php(PESSOA), profissao.php(PROFISSAO) e universidade.php(UNIVERSIDADE), ou seja, paginas separadas de uma da outra. Não é um formulário numa página só não, Aqui o prints: https://drive.google.com/drive/folders/1Ii28eDf_7qCVO5X39EcBuqME8rfeBxoc?usp=sharing
Comment: Nesse caso, você pode adicionar os 2 campos no formulário pessoa... Pode criar 2 selects puxando direto da tabela "profissao" e "universidade", seria isso que você precisa?
Answer: A resposta do @Samuel Verissimo, já resolve a questão. Você precisa de um "link" entre uma tabela e outra, e isso é feito usando o Foreign Key.

Se você sabe com o foreign key funciona, o que o @Samuel Verissimo explicou, então basta aplica-lo em seu código do PHP, basicamente você deve utilizar o ->lastInsertId(); como documentado em https://www.php.net/manual/en/pdo.lastinsertid.php.
Portanto, pelo que parece teria que fazer algo como:
public function addPessoa($nome, $sobrenome, $telefone, $id_p, $id_u) : int {
    global $pdo;

    $sql = $pdo->prepare("INSERT INTO pessoa SET nome = :nome, sobrenome = :sobrenome, telefone = :telefone, profissao = :id_p, universidade = :id_u");
    $sql->bindValue(":nome", $nome);
    $sql->bindValue(":sobrenome", $sobrenome);
    $sql->bindValue(":telefone", $telefone);
    $sql->bindValue(":id_p", $id_p);
    $sql->bindValue(":id_u", $id_u);

    $sql->execute();

    return $sql->lastInsertId();
}

public function addProfissao($nome) : int {
    global $pdo;

    $sql = $pdo->prepare("INSERT INTO profissao SET nome = :nome");
    $sql->bindValue(":nome", $nome);
    $sql->bindValue(":id", $id);

    $sql->execute();

    return $sql->lastInsertId();
}

public function addUniversidade($nome) : int {
    global $pdo;

    $sql = $pdo->prepare("INSERT INTO universidade SET nome = :nome");
    $sql->bindValue(":nome", $nome);

    $sql->execute();

    return $sql->lastInsertId();
}

Dessa forma ao chamar o addProfissaoa retornará o id a profissão recém criada. Você também deve verificar se a profissão já não existe e retornar possíveis erros, já que caso contrário retornará id = 0. Isso funciona assumindo que tenha um AUTO_INCREMENT.

Eu recomendaria criar uma Transaction, usando beginTransaction(); (https://www.php.net/manual/en/pdo.begintransaction.php). Afinal, imagine que uma profissão seja inserida, mas a inserção do usuário venha a falhar?! Nestes caso é importante que consiga dar um rollback (https://www.php.net/manual/en/pdo.rollback.php), cancelando todas as inserções feitas.
Comment: É, vou tentar estudar direito isso. É pq meu prof não explicou de forma objetiva sobre essas chaves estrangeiras do mysql juntamente com o codigo php. Explicou de uma forma mt simples, que de tanto falar e falar, não explicou nada que só criou confusão rs. Vou procurar uns codigos em githubs p/ tentar entender. Obrigado a vocês!


Função randint não retorna um valor

Question: Eu queria fazer o randint chamar um número aleatório, guardar o valor desse número, abrir uma pergunta pro usuário e se; a resposta do usuário for igual o número, dizer que ele acertou, se for diferente, dizer que ele errou. Porém, no código que fiz está sempre dizendo que está errado. segue o código
def adivinharnumero():
  from random import randint
  numeroaleatorio=randint(0,1)
  print(numeroaleatorio)
  resposta=input("Adivinhe o valor aleatório")
  print(resposta)
  print(numeroaleatorio)
  if resposta==numeroaleatorio:
    print("parabéns, você acertou!!!")
  if resposta!=numeroaleatorio:
    print("você errou")

adivinharnumero()

Answer: Isso está acontecendo por conta dos tipos das variáveis numeroaleatorio e resposta.
Quando você solicita o número ao usuário, você usa a função input, que retorna uma string, porém você compara com o retorno da função randint, que retorna um inteiro... Logo esses dados sempre serão diferentes.

Você pode corrigir de forma bem simples, convertendo o valor informado pelo usuário para inteiro, utilizando a função int:
resposta = int(input("Adivinhe o valor aleatório: "))

Também é possível fazer o inverso, transformar o valor retornado pelo randint em uma string, usando a função str:
numeroaleatorio = str(randint(0,1))

Documentações:
https://docs.python.org/3/library/functions.html#input
https://docs.python.org/3/library/functions.html#func-str
https://docs.python.org/3/library/functions.html#int
Comment: Valew cara! Você é fera!!!!!

Função randint não retorna um valor


Webpack + Typescript is compiling external imports into require, causing an error

Question: I'm using TypeScript 4.5.5 and Webpack 5.67.0. I can import internal modules just fine, but when I attempt to import a module from my node_modules directory (in this case, howler), it gets compiled into a require() statement and my browser doesn't understand it.
Example: on line 1 of my file, I have:
import * as howler from 'howler';

Then when I compile my client.js (transpiled from source TS files, browser facing, and accessed by index.html) and open the browser console, the JS has errored at this line:
/***/ "howler":
/*!*************************!*\
  !*** external "howler" ***!
  \*************************/
/***/ ((module) => {

module.exports = require("howler"); // <--- Right here: "Can't find variable: require"

/***/ })

I have experimented with a number of different configurations but none of them seem to work. It's worth noting that require() statements in my server.js (transpiled from a single server.ts file, server-facing code run by express to serve my API and /public directory) work just fine.
This is my tsconfig.json in my project root (same level as package.json)
{
    "compilerOptions": {
        "outDir": "./dist",
        "rootDir": "src",
        "noImplicitAny": true,
        "allowJs": true,
        "target": "ES6",
        "sourceMap": true,
        "module": "ES6",
        "moduleResolution": "node",
        "allowSyntheticDefaultImports": true,
    },
    "include": [
        "src/ts/**/*"
    ],
}

This is my webpack.config.js
const nodeExternals = require('webpack-node-externals');
const CopyWebpackPlugin = require('copy-webpack-plugin');

module.exports = {
    mode: 'development',
    entry: {
        'server': './src/server.ts', 'public/client': './src/ts/index.ts',
    },
    target: 'node',
    module: {
        rules: [
            {
                test: /\.ts?$/,
                use: 'ts-loader',
                exclude: /node_modules/
            }, {
                test: /\.html$/i,
                loader: "html-loader",
            },
        ]
    },
    resolve: {
        extensions: ['.ts', '.tsx', '.js']
    },
    externals: [nodeExternals(), "express", "howler"],
    output: {
        filename: '[name].js',
        chunkFilename: '[name].js',
        clean: true,
    },
    plugins: [
            new CopyWebpackPlugin({ patterns: [
                { from: 'src/html/index.html', to: 'public/index.html' },
                { from: 'src/html/index.css', to: 'public/index.css' },
            ]
        })
    ]
};

Additional notes:

I see  external "howler" 42 bytes [built] [code generated] during the npx webpack build process.
I have installed @types/node and @types/howler
This happens with any external modules used in the ts files that are transpiled into client.js
Answer: It turns out the best solution was to:

Split the webpack config into two configs, one for client, one for server
Remove externals from the client config. It stopped compiling it into a node dependency and I was all set.


Can I copy a directory from some location outside the docker area to my dockerfile?

Question: I have installed a library called fastai==1.0.59 via requirements.txt file inside my Dockerfile.
But the purpose of running the Django app is not achieved because of one error. To solve that error, I need to manually edit the files /site-packages/fastai/torch_core.py and site-packages/fastai/basic_train.py inside this library folder which I don't intend to.
Therefore I'm trying to copy the fastai folder itself from my host machine to the location inside docker image.
source location:  /Users/AjayB/anaconda3/envs/MyDjangoEnv/lib/python3.6/site-packages/fastai/
destination location: ../venv/lib/python3.6/site-packages/ which is inside my docker image.
being new to docker, I tried this using COPY command like:
COPY /Users/AjayB/anaconda3/envs/MyDjangoEnv/lib/python3.6/site-packages/fastai/ ../venv/lib/python3.6/site-packages/
which gave me an error:
ERROR: Service 'app' failed to build: COPY failed: stat /var/lib/docker/tmp/docker-builder583041406/Users/AjayB/anaconda3/envs/MyDjangoEnv/lib/python3.6/site-packages/fastai: no such file or directory.

I tried referring this: How to include files outside of Docker's build context?
 but seems like it bounced off my head a bit..
Please help me tackling this. Thanks.
Dockerfile:
FROM python:3.6-slim-buster AS build
MAINTAINER model1
ENV PYTHONUNBUFFERED 1

RUN python3 -m venv /venv
RUN apt-get update && \
    apt-get upgrade -y && \
    apt-get install -y git && \
    apt-get install -y build-essential && \
    apt-get install -y awscli && \
    apt-get install -y unzip && \
    apt-get install -y nano && \
    apt-get install -y libsm6 libxext6 libxrender-dev

RUN apt-cache search mysql-server
RUN apt-cache search libmysqlclient-dev
RUN apt-get install -y libpq-dev
RUN apt-get install -y postgresql
RUN apt-cache search postgresql-server-dev-9.5
RUN apt-get install -y libglib2.0-0

RUN mkdir -p /model/
COPY . /model/
WORKDIR /model/

RUN pip install --upgrade awscli==1.14.5 s3cmd==2.0.1 python-magic
RUN pip install -r ./requirements.txt

EXPOSE 8001

RUN chmod -R 777 /model/

COPY /Users/AjayB/anaconda3/envs/MyDjangoEnv/lib/python3.6/site-packages/fastai/ ../venv/lib/python3.6/site-packages/

CMD python3 -m /venv/activate
CMD /model/my_setup.sh development
CMD export API_ENV = development
CMD cd server && \
    python manage.py migrate && \
    python manage.py runserver 0.0.0.0:8001

Comment: @AjayBhagchandani you would have to move that file into the build context (copy from site-packages to where the dockerfile is)
Comment: @AjayBhagchandani Instead of modifying the source, have you tried monkeypatching `torch.load` to set the pickle arg before importing `fastai` in your own code? You can see an example of this in [fastai itself](https://github.com/fastai/fastai/blob/master/fastai/torch_core.py#L69).
Comment: Post your Dockerfile.
Comment: Any time you have to edit a file in `site-packages` is a red flag. What kind of change needs to be made? Can you post your Dockerfile so we can see what you are attempting to do?
Comment: @C.Nivs - The folder ```fastai``` in host machine has extra lines ```import dill``` on top and  ```state = torch.load(source, map_location='cpu', pickle_module=dill) if defaults.device == torch.device('cpu') else torch.load(source, pickle_module=dill)```  on line 403 in these files., that are not in library by default.  This way the error would be solved.
Comment: @00 The error that I got without the ```COPY``` statement in Dockerfile is ```AttributeError: Can't get attribute '__main__' on ``` which is solved in our local machines is by editing the ```fastai``` files., which reside outside the docker scope. Therefore asked this question just to know if I could copy a directory from a remote location on the machine to a location inside docker image.
Comment: @tzaman - unfortunately, didn't know about this. Thanks for helping it out. I ain't a data scientist, just a backend developer here who integrates the models in Django app. Will forward it to the concerned person and will let him know about this approach.
Comment: @C.Nivs - That helped me a lot and now the server is running smooth. It didn't click me earlier. Thanks a lot.
Answer: Short Answer
No
Long Answer
When you run docker build the current directory and all of its contents (subdirectories and all) are copied into a staging area called the 'build context'. When you issue a COPY instruction in the Dockerfile, docker will copy from the staging area into a layer in the image's filesystem.
As you can see, this procludes copying files from directories outside the build context.
Workaround
Either download the files you want from their golden-source directly into the image during the build process (this is why you often see a lot of curl statements in Dockerfiles), or you can copy the files (dirs) you need into the build-tree and check them into source control as part of your project. Which method you choose is entirely dependent on the nature of your project and the files you need.
Notes
There are other workarounds documented for this, all of them without exception break the intent of 'portability' of your build. The only quality solutions are those documented here (though I'm happy to add to this list if I've missed any that preserve portability).
Comment: That was very helpful. Thanks a lot!


Como percorrer corretamente todos os itens de um checkedListBox C#?

Question: Eu tenho um checkedListBox num tabControl do form. No checkedlListBox há vários itens que podem ser selecionados.
Quando o usuário clica no botão abaixo do checkedListBox, é lançado um loop que verifica se teve itens selecionados ou não, caso teve, o usuário é redirecionado para uma outra tabPage.
Caso não selecionou nenhuma opção, aparece a MessageBox. Mas o grande problema é que isso apenas para o primeiro item do checkedListBox.
Caso seja selecionado o segundo ou o terceiro e etc, aparece o MessageBox como se o usuário não tivesse selecionado nada.
Então, retomando ao título: como percorrer todos os itens de um checkedListBox?
Código que está funcionando com o primeiro item:
    private void btnEditarValores_Click(object sender, EventArgs e)
    {
        for (int i = 0; i <= (ListBoxSAdicionais.Items.Count - 1); i++)
        {
            if (ListBoxSAdicionais.GetItemChecked(i))
            {
                this.tabControl1.TabPages.Add(dados3);
                this.tabControl1.SelectTab(2);
                break;
            }
            else if ((ListBoxSAdicionais.GetItemChecked(i) == false))
            {
                MessageBox.Show("Você deve selecionar algum Status Adicional para editar os valores.");
                break;
            }
        }

Comment: não seria o break dentro do if o problema?
Comment: Quando o usuário é redirecionado pra tabPage(dados3) não deve aparecer o MessageBox do outro if e se eu tirar o break do primeiro if, ele fica aparecendo. Se eu tirar o break do else if, vai ficar mandando MessageBox até o loop percorrer a quantidade de items do checkedListBox. Já tentei remover a alternar os breaks, não funciona.
Answer: O problema é que vc não está verificando todos os itens pois seu "for" para na primeira tentativa, pois cai no "if" ou "else if";
Sugestão:
bool isChecked = false;

private void btnEditarValores_Click(object sender, EventArgs e)
{
    foreach(CheckBox item in ListBoxSAdicionais.Items)
    {
        if (item.IsChecked == true)
        {
            isChecked = true;

            break;
        }
    }

    if(isChecked == true)
    {
         this.tabControl1.TabPages.Add(dados3);
        this.tabControl1.SelectTab(2);
        break;
    }
    else
    {
        MessageBox.Show("Você deve selecionar algum Status Adicional para editar os valores.");
        break;
    }
}

Comment: Eu entendi o código e, inclusive, irei usá-lo para outra coisa, pois este problema atual já resolvi. Muito obrigado pela ajuda!
Comment: Só pra deixar claro, o meu comentário era pra pergunta e não pra sua resposta (que está certa). Eu me confundi e comentei no lugar errado. E, embora este `isChecked == true` me incomode, não fui eu quem negativou =D
Comment: Concordo, a resposta do PabloVargas foi melhor.

Nem vi que haviam negativado. Sempre há alguns downvotes perambulando pelo site. hahaha

Mas me fala sobre o isChecked, irei melhorar minha lógica.
Answer: Você primeiramente pode usar o método CheckedItems que irá retornar se existem ou não itens selecionados. Caso o Count seja zero, você mostra a mensagem, senão você faz a troca da aba
private void btnEditarValores_Click(object sender, EventArgs e)
{
    if (ListBoxSAdicionais.CheckedItems.Count == 0)
        MessageBox.Show("Você deve selecionar algum Status Adicional para editar os valores.");
    else
    {
        this.tabControl1.TabPages.Add(dados3);
        this.tabControl1.SelectTab(2);
    }
}

Comment: Era isso... Bom, como eu não pensei nisso? haha.C# é minha primeira linguagem de programação e estou tentando fazer o famoso "learn by doing". Muito obrigado ;)
Answer: E assim ficou meu código no final de tudo: (Foi adicionado else if para não dar Unreachable code detected, pois se retirar alguns dos break vai ficar repetindo o MessageBox em algum local)
    public void btnEditarValores_Click(object sender, EventArgs e)
    {
        for (int i = 0; i <= (ListBoxSAdicionais.Items.Count - 1); i++)
        {
            if (ListBoxSAdicionais.CheckedItems.Count == 0)
            {
                MessageBox.Show("Você deve selecionar algum Status Adicional para editar os valores.");
                break;
            }
            else if (ListBoxSAdicionais.CheckedItems.Count > 0)
            {
                this.tabControl1.TabPages.Add(dados3);
                this.tabControl1.SelectTab(2);
                break;
            }
        }

Comment: Wevelly Felipe, você não precisa do for e nem dos break.
Comment: Editei minha resposta com o evento click do botão
Comment: Outro detalhe, você não precisa responder mostrando como ficou seu código, basta somente aceitar minha resposta como correta.
Comment: Ah ok, obrigado mais uma vez ^^.


Problem with SVD in Input Output model

Question: Here is a problem I was looking at: Let production of Steel, Coal and electric power be $P_s, P_c$ and $P_e$ respectively. Their output (in column) and consumption (in row) are given:
$$
\begin{array}{|l|c|c|c|}
\hline
& Steel & Coal & Electricity \\
\hline
Steel & 0.1 & 0.1 & 0.5 \\
Coal & 0.3 & 0.2 & 0.4 \\
Electricity & 0.6 & 0.7 & 0.1 \\
\hline
\end{array}
$$
To find equilibrium solution following system of equations is formed:
$$
\underbrace{\begin{pmatrix}
-0.9 & 0.1 & 0.5 \\
0.3 & -0.8 & 0.4 \\
0.6 & 0.7 & -0.9
\end{pmatrix}}_A
\begin{pmatrix}
P_s \\ P_c \\ P_e
\end{pmatrix}
=
\underbrace{\begin{pmatrix}
0 \\ 0 \\ 0
\end{pmatrix}}_b
$$
Neither of $P=A^{-1}b$ and $P=A^+b$ works, so they've come up with SVD to produce a solution. To find $A=U\Sigma V^T$ following code is used:
<code>A = [-0.9  0.1  0.5;
      0.3 -0.8  0.4;
      0.6  0.7 -0.9];

sigma1 = A*A'; sigma2 = A'*A;
U = eye(3); V = eye(3);

for i = 1:15
    [Q1,R1] = qr(sigma1);
    [Q2,R2] = qr(sigma2);
    U  = U * Q1; sigma1 = R1 * Q1;
    V  = V * Q2; sigma2 = R2 * Q2;
end

S = diag(diag(sigma1)); S = sqrt(S);
U = round(U,5); Sigma = round(S,5); V = round(V,5);
</code>
With these $U,\Sigma$ and $V$ I get $U\Sigma V^T=-A$. To get correct result I've to multiply $V$ or $U$ by $-1$. With 15 iteration $U,\Sigma$ and $V$ are:
$$
\underbrace{\begin{pmatrix}
 -0.4852 &  0.6567 &  0.5774 \\
 -0.3262 & -0.7485 &  0.5774 \\
  0.8113 &  0.0918 &  0.5774
 \end{pmatrix}}_U\:
\underbrace{\begin{pmatrix}
 1.5836 & & \\
 & 1.0547 & \\
 & & 0
 \end{pmatrix}}_{\Sigma}\:
\underbrace{\begin{pmatrix}
   -0.5214 &  0.7211 &  0.4563 \\
 -0.4928 & -0.6910 &  0.5289 \\
  0.6967 &  0.0509 &  0.7156 \end{pmatrix}}_V
$$
If I change for i = 1:15  to for i = 1:115  and type U, Sigma and V in command window I get same thing but when I multiply $U\Sigma V^T$ I get:
$$
\underbrace{\begin{pmatrix}
 0.9000  & -0.1000 &  -0.5000 \\
   -0.3000  &  0.8000 &  -0.4000 \\
   -0.6000  & -0.7000  &  0.9000
 \end{pmatrix}}_{\texttt{for i = 1:15}}\quad\quad
\underbrace{\begin{pmatrix}
 -0.0989  &  0.8572 &  -0.5705 \\
0.8385 &  -0.2910  & -0.3197 \\
   -0.7396  & -0.5662   & 0.8901 \end{pmatrix}}_{\texttt{for i = 1:115}}
$$
Q1: What is the problem?
To find a solution last column of $V$ is chosen and normalized:
$$
P=
\frac{1}{0.7156}
\begin{pmatrix}
  0.4563 \\
  0.5289 \\
  0.7156
\end{pmatrix}
=
\begin{pmatrix}
  0.6377 \\
  0.7391 \\
  1.0000
\end{pmatrix}
$$
Q2: Why to choose last column of $V$?
Q3: Can I get same solution using $U$?
Q4: It is not unique and not least-square solution, What it is?
Comment: @Moo Can it be solved by Gaussian Elimination? If I use rational numbers, results are same. How to use infinite precision?
Comment: @Moo, Here [Gaussian Elimination](http://www.wolframalpha.com/input/?i=rref+%7B%7B-.9,+.1,+.5%7D,%7B.3,+-.8,+.4%7D,+%7B.6,+.7,+-.9%7D%7D) probably they have used Eigenvalue Decomposition. SVD is similar to that.
Comment: Instead of doing it one by one by hand, you should use elementary matrices for multiple row operation in a single shot, that is easier. @Moo
Answer: A similar conundrum is discussed here: Query about the Moore Penrose pseudoinverse method. On to your question.
Existence
Given the matrix
$$
\mathbf{A} = \frac{1}{10}
\left[
\begin{array}{rrr}
 -9 & 1 & 5 \\
 3 & -2 & 4 \\
 6 & 7 & -1 \\
\end{array}
\right]
$$
and the data vector
$$
b
=
\left[
\begin{array}{c}
 0 \\
 0 \\
 0 \\
\end{array}
\right]
$$
what can we say about the linear system
$$
\mathbf{A} x = b?
$$
Using Gauss-Jordan elimination,
$$
\begin{align}
\left[
\begin{array}{c}
 \mathbf{A} & \mathbf{I}_{3}
\end{array}
\right]
%
&\mapsto
%
\left[
\begin{array}{c}
 \mathbf{E_{A}} & \mathbf{R}
\end{array}
\right]  \\
%%
\left[
\begin{array}{rrr|ccc}
 -\frac{9}{10} &  \frac{1}{10} &  \frac{1}{2}  & 1 & 0 & 0 \\
  \frac{3}{10} & -\frac{1}{5}  &  \frac{2}{5}  & 0 & 1 & 0 \\
  \frac{3}{5}  & \frac{7}{10}  & -\frac{1}{10} & 0 & 0 & 1 \\
\end{array}
\right]
%
&\mapsto
%
\left[
\begin{array}{ccc|rrr}
 1 & 0 & 0 & -\frac{130}{213} & \frac{60}{71} & \frac{70}{213} \\
 0 & 1 & 0 & \frac{45}{71} & -\frac{35}{71} & \frac{85}{71} \\
 0 & 0 & 1 & \frac{55}{71} & \frac{115}{71} & \frac{25}{71} \\
\end{array}
\right]
\tag{1}
%
\end{align}
$$
Conclusion:
All columns are fundamental. The matrix has full rank. The nullspace is trivial:
$$\mathcal{N}\left( \mathbf{A}^{*} \right)=\emptyset$$
A nontrivial solution to the homogeneous equation does not exist. Solving the equation $\mathbf{A}x=\mathbf{0}$ is tantamount to asking for a vector in the nullspace. There are no such nontrivial vectors.
The existence drum is beaten often and loudly here on MSE:
Exact solution of overdetermined linear system
Existence of least squares solution to Ax=b
Unique least square solutions
Is a least squares solution to $Ax=b$ necessarily unique
Let $A$ be an 8 x 5 matrix of rank 3, and let $b$ be a nonzero vector in $N(A^{})$. Show $Ax=b$ must be inconsistent.
null space of a matrix for a matrix with a 0 column
Why does $A^{T}Ax=A^{T}b$ have infinitely many solution algebraically when $A$ has dependent columns?
Will 2 linear equations with 2 unknowns always have a solution?
When does the least squares solution exist?
SVD
$$
 \mathbf{A} =
  \mathbf{U} \, \mathbf{S} \, \mathbf{V}^{*}
\tag{2}
$$
To clear up confusion of building the SVD, the steps are detailed.

Construct the product matrix $\mathbf{A}^{*} \mathbf{A}$.
Resolve eigensystem of product matrix: Construct $S$, $V$.
Using $(2)$, construct $\mathbf{U} = \mathbf{A} \mathbf{V} \mathbf{S}^{-1}$.

1 Product matrix
$$
\mathbf{A}^{*} \mathbf{A} =
\left[
\begin{array}{rrr}
 1.26 & 0.27 & -0.39 \\
 0.27 & 0.54 & -0.10 \\
 -0.39 & -0.10 & 0.42 \\
\end{array}
\right]
$$
2 Eigensystem decomposition
Eigenvalues:
$$
 \lambda \left( \mathbf{A}^{*}\mathbf{A} \right) =
\left\{
  1.49952 , 0.453789 , 0.266694
\right\}
$$
The singular values are computed using
$$
 \sigma = \lambda \left( \mathbf{A}^{*}\mathbf{A} \right)
$$
Construct the $\mathbf{S}$ matrix:
$$
 \mathbf{S} =
\left[
\begin{array}{ccc}
 1.22455 & 0 & 0 \\
 0 & 0.673639 & 0 \\
 0 & 0 & 0.516425 \\
\end{array}
\right]
$$
Eigenvectors:
$$
v_{1} =
\left[
\begin{array}{l}
 -0.892021  \\
 -0.287368 \\
 \phantom{-}0.348883 \\
\end{array}
\right], \quad
%
v_{2} =
\left[
\begin{array}{l}
 \phantom{-} 0.256905 \\
 -0.957414 \\
 -0.131749
\end{array}
\right], \quad
%
v_{3} =
\left[
\begin{array}{l}
 \phantom{-} 0.371886 \\
 -0.0278925 \\
\phantom{-}  0.927859
\end{array}
\right]
%
$$
Construct the matrix $\mathbf{V}$, an orthonormal span for the row space:
$$
 \mathbf{V} =
\left[
\begin{array}{ccc}
 \frac{v_{1}}{\lVert v_{1} \rVert} &
 \frac{v_{1}}{\lVert v_{2} \rVert} &
 \frac{v_{1}}{\lVert v_{3} \rVert}
\end{array}
\right]
=
\left[
\begin{array}{lll}
 -0.892021 & \phantom{-}0.256905 & \phantom{-}0.371886 \\
 -0.287368 & -0.957414 & -0.0278925 \\
 \phantom{-}0.348883 & -0.131749 & \phantom{-}0.927859 \\
\end{array}
\right]
$$
3 Column space matrix
$$
\mathbf{U} = \mathbf{A} \mathbf{V} \mathbf{S}^{-1} =
\left[
\begin{array}{llc}
 \phantom{-}0.774591 & -0.583147 & 0.244844 \\
 -0.0576372 & \phantom{-}0.320431 & 0.945517 \\
 -0.629831 & -0.746501 & 0.214592 \\
\end{array}
\right]
$$
Moore-Penrose Pseudoinverse
The pseudoinverse is easily assembled using the SVD decomposition matrices.
$$
 \mathbf{A}^{+} =
  \mathbf{V} \, \mathbf{S}^{-1} \, \mathbf{U}^{*} =
\left[
\begin{array}{llc}
 -0.610329 & \phantom{-}0.84507 & 0.328638 \\
 \phantom{-}0.633803 & -0.492958 & 1.19718 \\
 \phantom{-}0.774648 & \phantom{-}1.61972 & 0.352113 \\
\end{array}
\right]
\tag{2}
$$

Problem with SVD in Input Output model


What is the cross product of two probability distributions $P \times Q$?

Question: In many papers on machine learning and statistics, I encounter the following notation
Let $P$ be a distribution, and let $Q$ be another distribution.
Then the author creates an object $P \times Q$
However, this object is not defined.
It is not known if $\times$ means the usual product, cross product, cartesian product, or some other product.
Example: https://arxiv.org/pdf/1903.08560.pdf (Equation 1)
Can someone please offer an explanation to the precise mathematical operation $\times$ is doing to these distributions and offer at least a simple example when $P, Q$ are simple probability distributions such as the Gaussian probability density function?
In other words, can someone please provide simple examples of $F$ where $F = P \times Q$?
Comment: Isn't it simply the product measure?
Comment: @User1865345 Hi, could you please provide a reference to the "product measure" and make it into an answer? I will accept it.
Comment: It's the product measure, the underlying variables are assumed independent (in this example the independent variables and the additive error)
Answer: I haven't read the specifics of the paper in question but the author meant by $P_x\times P_\epsilon$ the product measure. This measure is used when you have to equip a measure to a new measurable space
\begin{equation}
\big(X_1\times X_2\times \cdots \times X_n, \sigma(\boldsymbol{\mathfrak A}_1\times\boldsymbol{\mathfrak A}_2\times \cdots \boldsymbol{\mathfrak A}_n)\big)
\end{equation}
created from the product of $n\geq 2$ measure spaces
\begin{equation}
\langle (X_i, \boldsymbol{\mathfrak A}_i, \mu_i)\rangle_{i=1}^n
\end{equation}
defined as
\begin{align}
\mu(A) :=&\mu_1(A_1) \cdot \mu_2(A_2) \cdot \cdots \cdot\mu_n(A_n) \\
 ~A=&A_1\times A_2\times \cdots\times  A_n\in\boldsymbol{\mathfrak A}_1\times \boldsymbol{\mathfrak A}_2\times\cdots \times \boldsymbol{\mathfrak A}_n
\text{.}
\end{align}
Same concept is applicable for probability measures.
For details, please check any measure theory book/probability book. For a quick reference, check the Wikipedia article.
Comment: Is it possible to provide a concrete example of product measure function? For example, suppose $P_x$ and $P_\epsilon$ are two Gaussian probability density functions (as the authors intended), then what is the product measure function resulting from the operation $P_x \times P_\epsilon$?
Comment: Product measure $\mathbb P_{X_1X_2} = \mathbb P_{X_1}\times\mathbb P_{X_2}$ when $X_i\overset{\textrm{iid}}{\sim}\mathcal N(0, \sigma^2) $ and the pdf would be $f_1\times f_2.$
Comment: @User1865345 : Can one think of the pdf of the product measure in the $n=2$ case to be the joint density or does the product measure always assume independence of $x$ and $y$ so that the joint density is the product of the two pdf's ? thanks.
Comment: The latter is the correct observation @mlofton.
Comment: @User1865345  I appreciate the clarification.
Comment: (+1) The Wikipedia page you linked says this, but might also be worth emphasizing that the events that a product measure $P\times Q$ can measure are more complicated than just Cartesian products $A\times B$ (although via Carathéodory it is characterized by its values on such sets). E.g. in the bivariate Gaussian case we can ask about the measure of the unit disk even though that set is not a Cartesian product of two subsets of $\mathbb R$
Answer:
In other words, can someone please provide simple examples of $F$
where $F=P\times Q$?

User1865345's answer is correct, however you need to know  a bit of measure theory notation to understand it. Therefore I will add another one and try to explain in simple terms.
The notation $P\times Q$ stands for the joint distribution of two independent random variables, one of which has distribution denoted by $P$, and the other has a distribution denoted by $Q$.
In the paper you cited, they look at random variables $x_i$ and $\epsilon_i$ with distributions given by $P_x$ and $P_\epsilon$. The statement
$$
  (x_i,\epsilon_i)\sim P_x\times P_\epsilon
$$
just means that the simultaneous probability for $x_i\in A$ and $\epsilon_i \in B$ is obtained as the product of the probabilities of $x_i\in A$ and of $\epsilon_i\in B$. This is a way of saying that the $x_i$ and the $\epsilon_i$ are independent.
The joint probability density of independent random variables is also obtained as the product of the two probability densities.
Say, we have a random variable $X\sim N(0,1)$ and another random variable $Y\sim N(0,2)$. If these are independent, their probability density is
$$
\begin{align}
  f_{X,Y}(x,y) = f_X(x)\cdot f_Y(y) &= \frac{1}{\sqrt{2\pi}}\exp(-\frac{x^2}{2})\frac{1}{\sqrt{2\pi}\sqrt{2}}\exp(-\frac{y^2}{2\cdot 2})
\\&= \frac{1}{2\sqrt{2}\pi}\exp(-\frac{2x^2 +y^2}{4}).
\end{align}
$$
Now consider another random variable $\tilde{Y}=X+Z$, where $Z\sim N(0,1)$ is independent of $X$. Again, $\tilde{Y}\sim N(0,2)$, but $\tilde Y$ is no longer independent of $X$. The joint density is calculated using the formula for convolution of distributions,
$$
\begin{align}
f_{X,\tilde Y}(x,y) = f_X(x)f_Z(y-x) &= \frac{1}{\sqrt{2\pi}}\exp(-\frac{x^2}{2})\frac{1}{\sqrt{2\pi}}\exp(-\frac{(x-y)^2}{2})
\\&= \frac{1}{2\pi}\exp(-\frac{2x^2 +y^2-2xy}{2}).
\end{align}
$$
This extends to the case of more than two independent random variables in the same way: the joint (simultaneous) probability is simply the product of the corresponding probabilities for each of the variables. That is why the joint probability measure is called product measure. When the variables are not independent, the joint probability is not the product measure.
Comment: @Fraïssé, sorry I overlooked that you asked for an example of Gaussian random variables - I added one :-)
Answer: Expanding upon @User1865345's and @Ute's answers, here is another way of understanding product measures on $\mathcal B(\mathbb R^d)$, the Borel $\sigma$-algebra on $\mathbb R^d$, via their associated (multivariate) CDFs:
Recall that for each (multivariate) CDF $F: \mathbb R^d \to \mathbb R$ there is exactly one probability measure $\mathbb P_F$ on $\mathcal B(\mathbb R^d)$ with CDF $F$, i.e.,
$$
\mathbb P_F((-\infty, t_1] \times \ldots \times (-\infty, t_d]) = F(t_1, \ldots, t_d) \;\forall\,t_1, \ldots, t_d \in \mathbb R
$$
holds for exactly one $\mathbb P_F$.
The CDF of the product measure $\mathbb P_{F_1} \times \cdots \times \mathbb P_{F_d}$ is, $\forall\,t_1, \ldots, t_d \in \mathbb R$, given by
\begin{align}
F_{\mathbb P_{F_1} \times \cdots \times \mathbb P_{F_d}}(t_1, \ldots t_d)
&= (\mathbb P_{F_1} \times \cdots \times \mathbb P_{F_d})((-\infty, t_1] \times \ldots \times (-\infty, t_d]) \\
&= \mathbb P_{F_1}((-\infty, t_1]) \cdot \ldots \cdot \mathbb P_{F_d}((-\infty, t_d]) \\
&= F_1(t_1) \cdot \ldots \cdot F_d(t_d),
\end{align}
i.e., by the product of the corresponding marginal (univariate) CDFs.
Now, letting $X_1 \sim F_1, \ldots, X_d \sim F_d$, we find that $(X_1, \ldots, X_d) \sim \mathbb P_{F_1} \times \cdots \times \mathbb P_{F_d}$ iff the joint CDF of $(X_1, \ldots, X_d)$ factorizes into the marginal CDFs (i.e., iff $X_1, \ldots, X_d$ are independent).
In the example in the arXiv paper you link to, $P_x$ is a probability measure on $\mathcal B(\mathbb R^p)$ and $P_\epsilon$ is a probability measure on $\mathcal B(\mathbb R)$.
Thus, $(x_i, \epsilon_i) \sim P_x \times P_\epsilon$ in equation $(1)$ just means that the joint CDF $F_{x_i, \epsilon_i} \equiv F_{P_x  \times P_\epsilon}$ of $(x_i, \epsilon_i)$ is the product of the marginal CDFs $F_{x_i} \equiv F_{P_x}$ and $F_{\epsilon_i} \equiv F_{P_\epsilon}$ of $x_i$ and $\epsilon_i$, respectively:
$$
F_{x_i, \epsilon_i}(t_1, \ldots, t_p, t_{p+1}) = F_{x_i}(t_1, \ldots, t_p) \cdot F_{\epsilon_i}(t_{p+1}) \;\forall\,t_1, \ldots, t_{p+1} \in \mathbb R.
$$


I need help getting age from D.O.B

Question: I have a prebuilt website that takes a import of a CSV file and pulls data from that. The CSV file has a date of birth in (1994-12-31) format and is supposed to calculate from that the age. The code below is what is happening and I dont know what is wrong with it. Because instead of it outputting an age it is taking 1994-12-31 and showing -1995 for age.
$timestamp=strftime($data[5]);

            if(substr_count($timestamp,"-") > 0){
                $DateDelim = "-";
            } elseif (substr_count($timestamp,".") > 0){
                $DateDelim = "0";
            } else {
                $DateDelim = "/";
            }

            //$TMP_AGEDATE = date("m-d-Y", strtotime($data[5]));
            $TMP_AGEDATE=convertdate($timestamp,$_SESSION['current_DateFormat'],'usa',$DateDelim);
            $TMP_AgeDate=strftime("%m-%d-%Y", strtotime($TMP_AGEDATE));
            //echo $TMP_NAME." - ".$newDate." - age  ".getAge($newDate)."
";
            //

Comment: 1. Remove irrelevant lines . 2. Use better variable names. 3. Fix your indentation. 4. Provide sample input *in* your code sample, we don't have a variable called $data. 5. Make sure people can *run* your test code. We don't have your `convertdate` function either.
Comment: Where does MySQL factor in?
Comment: Tip: It's really odd to see things like `$TMP` in variable names. It's understood that some variables are temporary by nature, but that should be implicit in how they're scoped and used. What you really need here is a function that encapsulates what's going on here.
Comment: use carbon for this :) https://carbon.nesbot.com/docs/ you will have an ->age attribut
Comment: Pretty bad idea to base this on `strftime` to begin with. Why work with a date formatted in a _localized_ format for this? And we don't know what `convertdate` does, but I doubt feeding it `0` as the date delimiter, when a `.` was found, makes much sense either.
Answer: You can use carbon (https://carbon.nesbot.com/docs/)
Carbon::createFromFormat("Y-m-d", "1985-08-06")->age // returns 37

I need help getting age from D.O.B


Chord substituion in Django's Belleville

Question: In the lead sheet I have been working from for Django's Belleville, the A section progression is D - Fdim7 - Emin7 - A7.
In most of the backing tracks I can find, the Fdim7 is substituted for a Bmin7 making it a I - vi - ii - V.
Fdim7 having F Ab B D
Bmin7 having B D F# A
My ears like the way either sound, but find the Fdim7 to be much more interesting. I'm having trouble understanding how the Fdim7 is functioning, and the theory behind why it works.
Is it some sort of tritone substitution? I'm only familiar with the tritone sub when it comes to V7 chords.
Thanks!
Steve
Answer: The Fdim7 is enharmonically equivalent to a G#dim7, which functions as a #IVdim7 leading to V7. The V7 is delayed by the IIm7, which is very common. So what you basically have is
I - #IVdim7 - V7 (via IIm7)
There are many examples where the I chord in that progression is replaced by the III chord resulting in a chromatically descending bass line:
F#m7 - Fdim7 - Em7 - A7 - D
You could as well use a D/F# instead of the F#m7. But in any case, concerning its function, the diminished chord is a #IV borrowed from the melodic minor scale (otherwise you wouldn't get the note 'F').


Integrate Word Online Editor in my website

Question: As the title said, I would like to integrate the Word Online Editor (you need an office account) in my website to facilitate the document editing for my users. Is there a way to do it ? I've been looking left and right but couldn't find a way, only how to a plug-ins for your use.
Thanks in advance.
Answer: I don't think you can do that. However, for viewing/rendering only you can put the Google Documents viewer in an iframe.
However, check out WOPI framework. Requires some efforts but might be what you need.


"fwrite(): supplied argument is not a valid stream resource"

Question: drush throws an error

"Notice:  Use of undefined constant STDERR - assumed 'STDERR'
  in /kunden/192766_10587/bin/drush/includes/drush.inc on line
  1668  Warning:  fwrite(): supplied argument
  is not a valid stream resource in
  /kunden/192766_10587/bin/drush/includes/output.inc on line
  34

What I did is the following. (I followed the instruction from the README.)

Cloned drush
git clone --branch 7.x-5.x http://git.drupal.org/project/drush.git

Wrote into the ~/.bashrc
export PATH="$PATH:~/bin/drush:/usr/local/bin"
alias drush=~/bin/drush/drush.php

Refreshed the bashrc
source ~/.bashrc

Set the 'drush' command executable:
 chmod u+x /path/to/drush/drush

Drush is working but it shows errors every time.
What did I do wrong?
Comment: If you solved your query consider posting the solution as an answer and approve it as correct answer.
Answer: You should not run drush.php directly.  It is preferable to define DRUSH_PHP, like this:

export DRUSH_PHP='/usr/local/bin/php'

Then you may continue to use the drush script as usual.  This is documented in the README.
Comment: I have the same problem, with your answer i can resolved this with drush, but for this way.
`export COLUMNS
alias drush='/usr/local/bin/php ~/drush/drush.php --php=/usr/local/bin/php'
alias php='/usr/local/bin/php'`


How to get the selected items (with VBO) in the buildConfigurationForm of a custom Action

Question: I have made a custom action which have a configuration form:
class MyAction extends ConfigurableActionBase

Thus, I have the opportunity to create a form that allows the user to set some options. This form is created inside
public function buildConfigurationForm(array $form, FormStateInterface $form_state)

I need to get the list of the selected items that will be processed at this stage in order for me to exclude some option in the configuration form. In my use case, I need to exclude some option depending of the bundle of the selected entities (by my VBO view)
Answer: Provided you use the Views Bulk Operations contrib module, you can use code similar to the following, inside the buildConfigurationForm() method. Most importantly, you need to extend ViewsBulkOperationsActionBase instead of ConfigurableActionBase.
class YourAction extends ViewsBulkOperationsActionBase

...
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    ...
    $selectedItems = array_map(function ($listItem) {
      return reset($listItem);
    }, $this->context['list']);
    ...
  }
...

This will give you an array whose values are the entity ids of the selected items in your view. The keys of the array are the bulkFormKey for each selected entity.
See ViewsBulkOperationsFormTrait::calculateEntityBulkFormKey() and ViewsBulkOperationsFormTrait::getListItem() for more information about bulkFormKeys.
Hope this helps, good luck!
P.S.: And for anyone else landing here, the related VBO's documentation page is over at https://www.drupal.org/docs/8/modules/views-bulk-operations-vbo/configuring-an-action
Comment: This looks like it is exactly what I was looking for!!! I will try this code this evening and will give you the bounty if it is working.
Comment: Good to know, cheers!


Pacote pandas não reconhecido no jupyter notebook

Question: Olá, alguém pode ajudar a entender pq o jupyter notebook não reconhece o pacote panda?
criei um ambiente virtual e instalei os pacotes para fazer analise de um conjunto de dados do enem, mas ao chamar o jupyter notebook e digitar: import pandas as pd surge a mensagem abaixo.
NameError                                 Traceback (most recent call last)
<ipython-input-3-0efef42136cf> in <module>
----> 1 microdadosEnem = pd.read_csv("brutos/microdados_enem_2018/DADOS/MICRODADOS_ENEM_2018.csv")

NameError: name 'pd' is not defined

Comment: Olá Michele, você está usando o Jupyter na sua máquina local, ou atraves de algum site? E porque fazer um ambiente virtual para usa-lo? Pois, o mesmo já é meio que um ambiênte virtual isolado.
Comment: Antes de importar o pandas use `!pip install pandas` com o ponto de exclamação na frente. Depois é só rodar a célula
Comment: Olá @Elias Oliveira, eu criei um ambiente virtual e chamo o jupyter do prompt de comando ai vou para o navegador...
Comment: Olá @PauloMarques, vou fazer o que vc disse para ver se dá certo...
Comment: Entendi, nesse caso é só fazer como o @PauloMarques falou e usar o !pip install pandas
Comment: O erro é `NameError: name 'pd' is not defined`, e não `ImportError: No module named pandas`. Ou seja, vc não rodou o comando `import pandas as pd` e tentou utilizar o `pd`. O Paulo já fez um comentário disso na "resposta" da Michele (que não é uma resposta e deveria ser um comentário), mas só estou ressaltando.
Answer: Acredito que deveria realizar o seguinte comando no seu terminal.
pip install pandas

Lembrando que depois de realizar esse procedimento do pip, você deverá colocar no inicio do seu código:
import pandas as pd

Aí sim o modulo pandas será executado com sucesso!
Deve-se lembrar que se você estiver tentando fazer isso localmente é recomendável que se instale a variavel de ambiente. Segue um link de como realizar esse procedimento:
https://medium.com/@victorromariopazdejesus/python-3-configurando-vari%C3%A1veis-de-ambiente-no-windows-10-63059c7192e6


Ionic InAppBrowser on iOS Loading White Blank Screen Error

Question: I have been working with InAppBrowser for awhile now and have not run into this issue before. It was loading my URL and now it doesn't seem to want to do so.
First I have imported InAppBroswer properly, it's working 100% on Android. This is an iOS-only issue.
in my config.xml:
<access origin="https://www.mydomain.or/*" />
<allow-intent href="*" />
<allow-intent href="http://*/*" />
<allow-intent href="https://*/*" />

<plugin name="cordova-plugin-whitelist" spec="1.3.3" />
<plugin name="cordova-plugin-device" spec="2.0.2" />
<plugin name="cordova-plugin-splashscreen" spec="5.0.2" />
<plugin name="cordova-plugin-ionic-keyboard" spec="2.0.5" />
<plugin name="cordova-plugin-inappbrowser" spec="^3.0.0" />
<plugin name="cordova-plugin-statusbar" spec="^2.4.2" />
<plugin name="cordova-plugin-app-update" spec="^1.6.0" />
<plugin name="cordova-plugin-app-version" spec="^0.1.9" />
<engine name="android" spec="~7.0.0" />
<engine name="ios" spec="~4.5.4" />

My plugins seem to run fine, no lint or compile errors.
I call the browser per their documentation:
//construct the instance of browser we are using to launch with Ionic Native
const browser = this.iab.create('https://www.mydomain.or', '_blank','location=no');
//If Browser is Hidden Display
browser.show();

There are NO errors being reported in the console for WKWebView at all, but I get this below image on both simulator and device.

Steps Taken to Try and resolve this issue are:
Securty Steps with iOS, WhiteList is added to the Plugins--Please see above plugin list.
I have added the checks to the plist file:
<key>NSAppTransportSecurity</key>
<dict>
  <key>NSExceptionDomains</key>
  <dict>
    <key>localhost</key>
    <dict>
      <key>NSExceptionAllowsInsecureHTTPLoads</key>
      <true/>
    </dict>
    <key>www.mydomain.or</key>
    <dict/>
  </dict>
</dict>

This has been known to help with similar issues in the past.
I also added a Meta Tag to my index as this was something that has helped others in the past as well:
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; style-src 'self'; connect-src https://www.mydomain.or; script-src 'self'; media-src *">

This also did not help me out at all. Anyone who may know what the cause of this is would be of great help. I feel like I am at my wits end with this error and want to be able to solve this but know the underlying reason why this is happening as well to avoid it in the future.
Thanks in Advance!
Answer: I have struggle with this problem until recently.
In config.xml
    <allow-navigation href="*" />

This tag seems to solve this problem.
--- update --
info.plist
<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
    <key>NSExceptionDomains</key>
    <dict>
        <key>localhost</key>
        <dict>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <true/>
        </dict>
    </dict>
</dict>

Comment: Interesting. It can be more secure solution. However, **** is related to 'Webview navigation', whereas **** is related to ''system to open".
https://stackoverflow.com/a/35374403/6627660
Comment: This didn't seem to solve the issue for me, I still get the same result. What are some of the methods you used to troubleshoot this? hopfully the information i provied was enough detail to help get an idea of the steps ive done so far
Comment: Could you upload your **config.xml** for clarifying the problem?
I will also upload my info.plist for clarifying. Please check my answer again.
Comment: I didn't have systemical approach to solve this problem because it is obvious that this is one of permission problems. So I just browsed lots of documents and pages with trials and errors.
Comment: Thank you, I did find out the problem. info.plist should be updated by defualt now with Ionic CLI when you run 'ionic cordova platform add ios'. It also appears that '' is the same as . The issue was security related but was able to address it with the answer i provided
Comment: I did not know this, thank you. I will also add this.
Answer: SOLVED
I was able to address this issue by adding:
<meta http-equiv="Content-Security-Policy" content="default-src gap://ready file://* *; script-src 'self' 'unsafe-inline' 'unsafe-eval' *; style-src 'self' 'unsafe-inline' *">

This is added to the header of your index.html file.
My above question clearly has some syntax errors in this but won't call an error when building to Android or iOS.
You could, however, add a Build tool to write a script to check for this tag in your index.html.


What software generates the SMTP bounce message "550 Envelope blocked - User Entry"?

Question: I'm troubleshooting an issue where email sent from a specific user is blocked every time to only a specific sender.  The NDR generated (from our Exchange server) has the following message:
#550 Envelope blocked - User Entry ##

The recipient says that the sending address is not in the blocked senders list.  The recipient can also receive mail sent from other addresses sent from our MTA, and other users at the recipient's company can receive mail from the sender in question.
What I'm really trying to figure out is what software in the mail flow might be generating this specific message.  Web searching hasn't come up with anything yet.  Thanks for your help!
Comment: The headers should tell you the path that the message took on it's travels and it should say who through the error.
Comment: It seems fairly clear that M. S **already knows who**, and is asking whether xe can determine _what software that "who" is using_, to gain some clue as to where this restriction might have been configured, given that the final recipient doesn't seem to know.  (Obviously the final recipient and xyr own postmaster are not on speaking terms. ☺)  The correct place to be looking is not message headers but SMTP Relay server greeting banners.
Answer: Any software can generate such a message. You can configure almost all mail servers to generate such a message; even on a recipient or sender basis or content basis.
You have to ask this question to the recipient (or better it's postmaster). But you can try to identify this on your own. Therefore you need the IP of the host that rejected the mail. Try to telnet <ip> 25 and you can see the server greeting of that host. In many cases it also displays the server software and it's version. But this can also mislead in the wrong direction as even a before-Queue-SMTP-filter in front of the real server can generate this message.
Whatever software the recipient uses it won't help you to know. You have to discuss this with the postmaster of the recipient's server. Nothing else will help.


.ttf file does not work

Question: I've a .ttf file to be loaded to a captcha image. But my .ttf just doesn't work. When I include a.ttf file, the image does not load and gives an error.
Here's my captcha code:
<?php

session_start();

$md5_hash = md5(rand(0,999));

$captcha = substr($md5_hash, 16, 5);

$_SESSION["captcha"] = $captcha;

$width = 205;
$height = 60;

$image = imagecreate($width, $height);

$white = imagecolorallocate($image, 255, 255, 255);
$black = imagecolorallocate($image, 0, 0, 0);
$grey = imagecolorallocate($image, 204, 204, 204);

imagefill($image, 0, 0, $white);

$font = imageloadfont('Xeron.ttf');
imagestring($image, $font, 70, 20, $captcha, $black);

imagerectangle($image, 0, 0, $width-1, $height-1, $grey);
imageline($image, 0, $height/2, $width, $height/2, $grey);
imageline($image, $width/2, 0, $width/2, $height, $grey);

header("Content-type: image/jpeg");

imagejpeg($image);

imagedestroy($image);

?>

I'm new to php, Help please..
Edit
I've even tried it with the following code and still my image doesn't load
$captcha_num = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890abcdefghijklmnopqrstuvwxyz';
$captcha_num = substr(str_shuffle($captcha_num), 0, 6);
$_SESSION["code"] = $captcha_num;

$font_size = 30;
$img_width = 70;
$img_height = 40;

header('Content-type: image/jpeg');

$image = imagecreate($img_width, $img_height); // create background image with dimensions
imagecolorallocate($image, 255, 255, 255); // set background color

$text_color = imagecolorallocate($image, 0, 0, 0); // set captcha text color

imagettftext($image, $font_size, 0, 15, 30, $text_color, 'Xeron.ttf', $captcha_num);
imagejpeg($image);

Comment: what is location of font xeron.ttf ??
Comment: it is in the same location as my captcha.php
Comment: ok.. do u tried with another .ttf font ??
Comment: Try changing 'Xeron.ttf' to './Xeron.ttf' to clarify that you want the current working directory. Or specify the full path. What does your error log show? FYI: https://stackoverflow.com/questions/1053424/how-do-i-get-php-errors-to-display
Comment: @DrMJ yes i've tried with a different .ttf file. But still it doesn't load.
Comment: How do i modify php.ini file @WillBickford
Comment: @Lublaut - if you take a closer look at the doc page for imageloadfont, you'll see the following text `imageloadfont() loads a user-defined *bitmap* and returns its identifier.` Reading further, you may reach the end of the man page and see the comment that says: `"Remember - GD fonts aren't antialiased.  If you're planning on using a pre-existing (TrueType) font, you may want to consider using imagettftext() instead of phillip's function."` ;) Docs. Always read the docs....
Comment: Question edited!!
Answer: I am providing a sample code for php captcha... you can try it with your values, fonts, font colors etc..
captcha.php
<?php
session_start();
//Settings: You can customize the captcha here
$image_width = 210;
$image_height = 60;
$characters_on_image = 7;
$font = './monofont.ttf';

//The characters that can be used in the CAPTCHA code.
//avoid confusing characters (l 1 and i for example)
$possible_letters = '23456789ABDEFGHLMNQRTWY';
$random_dots = 15;
$random_lines = 3;
$captcha_text_color="#4593BC";
$captcha_noice_color = "#34495e";

$code = '';

$i = 0;
 while ($i < $characters_on_image) {
 $code .= substr($possible_letters, mt_rand(0, strlen($possible_letters)-1), 1);
 $i++;
}

$font_size = $image_height * 0.6;
$image = @imagecreate($image_width, $image_height);

/* setting the background, text and noise colours here */
$background_color = imagecolorallocate($image, 255, 255, 255);

$arr_text_color = hexrgb($captcha_text_color);
$text_color = imagecolorallocate($image, $arr_text_color['red'],
    $arr_text_color['green'], $arr_text_color['blue']);

$arr_noice_color = hexrgb($captcha_noice_color);
$image_noise_color = imagecolorallocate($image, $arr_noice_color['red'],
    $arr_noice_color['green'], $arr_noice_color['blue']);

/* generating the dots randomly in background */
for( $i=0; $i<$random_dots; $i++ ) {
imagefilledellipse($image, mt_rand(0,$image_width),
 mt_rand(0,$image_height), 2, 3, $image_noise_color);
}

/* generating lines randomly in background of image */
for( $i=0; $i<$random_lines; $i++ ) {
imageline($image, mt_rand(0,$image_width), mt_rand(0,$image_height),
mt_rand(0,$image_width), mt_rand(0,$image_height), $image_noise_color);
}

/* create a text box and add 6 letters code in it */
$textbox = imagettfbbox($font_size, 0, $font, $code);
$x = ($image_width - $textbox[4])/2;
$y = ($image_height - $textbox[5])/2;
imagettftext($image, $font_size, 0, $x, $y, $text_color, $font , $code);

/* Show captcha image in the page html page */
header('Content-Type: image/jpeg');// defining the image type to be shown in browser window
imagejpeg($image);//showing the image
imagedestroy($image);//destroying the image instance
 $_SESSION['captcha'] = $code;

function hexrgb ($hexstr){
  $int = hexdec($hexstr);
  return array("red" => 0xFF & ($int >> 0x10),
           "green" => 0xFF & ($int >> 0x8),
           "blue" => 0xFF & $int);
}
?>

index.php
 //to display captcha image

<img src="captcha.php?rand=<?php echo rand();?>" id='captchaimg' >

Comment: I have edited some part... create captcha.php file and keep it in root folder and then add code given for index.php
Comment: please poke me on my whatsapp no 9881150272

.ttf file does not work


Navigation Properties between Views in EF Code First

Question: Is it possible to define navigation properties between Views in EF with code first? Please, note that I do not need any tool generating any code for me. I would like to know whether or not this can get done and the logic behind this.
Suppose you have a project in which you will only work with views. No data will be created, updated or deleted (at least by you). All you need to do is queries and all you have are views.
Suppose now a second scenario in which you can also have tables, but your purpose is only to visualize data (you will treat them as views). However, there is not always a foreign key referencing the primary key of the parent table in relationships.
My question is: Can I define navigation properties in these scenarios? Or do I have to relay on joins only?
Thanks!
Answer: I'm working on this myself. Everything I'm reading indicates you have to manually edit the .edmx files so that the views are considered tables and manually add the nativation properties yourself. Downside is if you resync against the database you have to repeat the process all over again.
Re:
https://social.msdn.microsoft.com/Forums/en-US/dcbdfe52-6ba7-4e75-94aa-51c88b57635c/adding-navigation-property-to-a-view?forum=adodotnetentityframework