How do i write Blood Type in Health kit in iOS

Question: I have a HKHealthStore object properly set up, and I am now trying to write user characteristics (i.e Date of Birth, Biological Sex, Blood Type and Fitzpatrick Skin Type). I can't find that type in HKQuantityTypeForIdentifier. How do I write blood type to HealthKit in Objective-C? I am trying the following:
int Dateofbirth=20-10-1995;

NSLog(@"%d", Dateofbirth);

sex=gender;

BloodType= A+ve;

Fitzpatrick Skin Type= something;

HKQuantityType* bodytemp = [HKQuantityType quantityTypeForIdentifier: HKQuantityTypeIdentifier];

Comment: your code is not even close to actual code. you need to learn how this works on your own
Comment: help me any body please..
Comment: @JAGAT will you plz help me...??
Comment: Sorry for inconvenient but i haven't work on health kit.
Comment: @OscarApeland Thanks for your response.. i have no idea about health kit.. i already check this issue. but i can't find out a proper solution.. so thats why i am posting here.. if u have any idea plz tell me
Answer: You may have to use characteristicTypeForIdentifier: with HKBloodType.
https://developer.apple.com/library/ios/documentation/HealthKit/Reference/HKObjectType_Class/index.html#//apple_ref/occ/clm/HKObjectType/characteristicTypeForIdentifier:
Constants from Blood type:
typedef enum : NSInteger {
   HKBloodTypeNotSet = 0,
   HKBloodTypeAPositive,
   HKBloodTypeANegative,
   HKBloodTypeBPositive,
   HKBloodTypeBNegative,
   HKBloodTypeABPositive,
   HKBloodTypeABNegative,
   HKBloodTypeOPositive,
   HKBloodTypeONegative,
} HKBloodType;

https://developer.apple.com/library/ios/documentation/HealthKit/Reference/HealthKit_Constants/index.html#//apple_ref/c/tdef/HKBloodType
Comment: Thanks for your response.. how to modify my code?? will you guide me
Comment: will you help me plz how to do this thing??
Comment: I need to read Blood Group.
Answer: There is no API to modify user characteristics. The user must update the characteristics themselves in Health.
Comment: Thanks for your response. But i can't understand what you are saying is.. you mean user can enter manually in device or some thing?? plz tell me it is priority task for me
Comment: Launch Health, go to the Health Data tab, tap Me, tap the Edit button in the top right, and then Blood Type to set your HealthKit blood type.
Comment: thanks for your response.. my issue is solved i faced some other issue.. plz check the link.."http://stackoverflow.com/questions/36596731/displaying-menstruation-details-in-health-kit-app-in-ios" if you have any idea plz tell me
Comment: @satya How was your issue solved? Please be sure to either accept the correct answer or document the solution yourself for future Stack Overflow users reading this question.


Which scales for particular chords (ii-V-I )?

Question: Two part question:

If I'm playing a ii-V-I (e.g., Dm7, G7, CM7) and just want to improvise, what scales can I play with my right hand while on each chord, and why (so I can follow the logic and apply it to other chords in the future)?
According to the Circle of 5ths, I know I can play the major/minor scale of the major/minor counterpart. But aside from showing the major/minor counterpart, is the Circle of 5ths helpful for the previous question (i.e., figuring out which scales to play)?

Aside: It didn't sound very nice/cohesive when I played the D minor blues scale while on ii, the G major blues scale while on V, and the C major blues scale while on I. I feel like I'm doing something wrong.
Answer: If you play a ii-V-I in C major, all chords are taken from the key of C major, so in principle you can just play the C major scale over all three chords. Over the Dm7 chord this would be a D dorian scale, and over G7 it is a G mixolydian scale. But note that D dorian, G mixolydian, and C major all share the same notes; they're basically just the C major scale started on different roots.
Apart from chromatic passing and approach notes, which are always possible, you can add extra notes when playing over the V chord (G7). In jazz, it is common to add alterations to the V chord:

b9    Ab
#9    Bb (actually A#)
#11   C#
b13   Eb

You don't need to add all of them. You can try starting with the b9, which means that you'd still play G mixolydian over G7, but you exchange the note A for an Ab, which is usually resolved to the note G over Cmaj7.
A scale that has all altered notes is the G altered scale (7th mode of Ab melodic minor):
G Ab Bb B C# Eb F
So if you like you can switch from D dorian over Dm7 to G altered over G7 and back to C major over Cmaj7.
There are many other possible scales that can be played over G7 (e.g., whole tone, half-whole, phrygian dominant), but note that the way you resolve tension is at least as import as the exact notes that you choose over the V chord. As long as you resolve nicely, anything goes.
If you're not yet familiar with playing over a ii-V-I progression, I'd suggest that you mainly stick to the C major scale, concentrating on emphasizing chord tones over each of the three chords. Later on you can be more adventurous and use alterations and the scales I suggested above.
Concerning the second part of your question, I don't see how the circle of fifths will help you with improvising over a ii-V-I progression.
Answer: When you say scale, I hope you mean the notes from that scale rather than just running up and down. Playing Dm scale notes, either full minor or minor blues, usually works well over Dm. As does G major blues (or just G major, without the F#) over G, and the same with C. Actually, C minor blues and pents - maj. or min. work over C.
Since you mention ii - V - I, the I is telling. You could just stay within the C maj. scale notes. Dmin. will have the 'foreign' Bb, and G maj. the 'foreign' F#, both occurring in C blues. However, if you play CM7, the min. blues scale note will clash. Maybe for starters, you need to establish a change of chord by playing the root note on beat one, which puts the shape of the tune into perspective.


Mean Value Theorem related proof

Question: For what real values does the polynomial
φ (x):= 1+x+x^2+...+x^(2m-1)
take the value 0? What can you say about the sign of φ(x) varies?
Prove that the function
f(x):= 1+x+x^2/2+...+(x^n)/n
has no real roots when n is even. What can you say about the roots of f when n is odd?
Comment: Why do you ask those questions?
Comment: @copper.hat: Obviously? These polynomials are the Taylor approximants to $1-\log(1-x)$. So, for example, their value at $x=-\frac12$ ought to converge to $1-\log\frac32\approx 0.595$.
Comment: @HenningMakholm: I goofed. I misread the question. Need an eye check...
Comment: Related discussion of the same problem: http://math.stackexchange.com/q/696128/115115
Answer: Note that the derivative of
$$
φ (x):= 1+x+\frac{x^2}2+...+\frac{x^n}n
$$
is
$$
φ' (x):= 1+x+x^2+...+x^{n-1}=\frac{x^n-1}{x-1}
$$
with well known root set. This allows to find the regions of monotonicity of $φ$.
Answer: Are you sure it's MVT? Using Intermediate Value Theorem, you can say that if $f$ changes sign in the interval $(a,b)$, that is, if $f(a) < 0$ and $f(b) > 0$ or vice versa, then there exists $c \in (a,b)$ such that $f(c)=0$.
Comment: I should say I've only taken Real and I may not even be able to tell how far over my head this is. We didn't cover Taylor series in my Real class. Generally speaking, if it's homework, use the most recently covered topics to as a guide to the likely best methods of proving it.

Mean Value Theorem related proof


Why would a method have const and non const arguments for the same variable?

Question: I have seen a code which accepts first arg as const and another as modifiable.
Is it good practice to pass the same variable for both the arguments during the implementation?
I could not understand the motive of the developer who uses the method in such a crude way. Is this something uncommon?
void manipulate(const string& a, string& b)
{
  if (a.length() > 0 )
    b.append("_ok");
}

int main()
{
  string a("Hello");
  manipulate(a, a);

}

I want to understand whether using such a crude way of implementation a correct approach or not.
Comment: What's crude about it?
Comment: It's not particularly common but also not inherently problematic. It may well be the clearest way to do things, that really depends on the problem being solved.
Comment: Imagination time: Lets say you had a bunch of strings that you wanted to examine for illegal characters, and you want the result of every examination to be written to a common log. You could then make a function like the one above, and pass the string to be inspected as const, and the log as non-const. But then what if you needed to inspect the log for illegal characters? Well, you might just pass the log itself as both arguments to the function you already have.
Comment: _@RonakSHAH_ This question looks like that ypu have simplified the real use case of what you found too much. Can you please post what the original code was, and where you found it? The function itself cannot know what is passed as paremeter, and if the parameters refer to the same variable.
Answer: A const reference only means: You cannot modify the object via the reference.
It does not mean: The instance cannot be modified through other means.
This is perfectly legal:
void foo(const std::string& a, std::string& b) {
     b = a + "foo";
}

int main() {
    std::string x { "hello world"};
    foo(x, x);
}

In general methods should be written without hidden constraints, eg it should be possible to pass the same parameter for two different arguments (as above). Moreover, this is not in contrast to const-correctness. To the contrary, the example above is a good example for const-correctness helping to avoid mistakes. Eg you cannot call it as
const std::string y{"hello const"};
foo(y, y);  // error

Answer:
I want to understand whether using such a crude way of implementation a correct approach or not.

There's nothing crude or wrong in the implementation.
The intend is pretty clear:
 b.append("_ok");

changes the value of b, thus it needs to be passed as non const reference parameter.

A more common way to write such function would be
string& manipulate(string& a)
{
  if (a.length() > 0 )
    a.append("_ok");
  return a;
}

though.

Why the particular implementation of the function has specified a const and a non const reference parameter can't be answered without seeing a specific use case.
The function itself cannot know that the references point at the same variable.
Comment: The OP's point is that by passing the same variable as both const *and* non-const violates const correct-ness.
Comment: @suspectus Modifiying variables while someone holds a const reference isnt something you can avoid, if you assume a variable cannot change just because you have a const reference to it, then you better change that false assumption ;)
Comment: I dont get the downvote. Given that the quesiton isnt quite clear (it misses to explain what is supposed to be "crude" about the method) answers necessarily have to do some guessing
Comment: @suspectus I can't see any violaiton of const correctness.
Comment: You are correct in that technically the compiler doesn't see any violation. The point is that b is a reference to a. So the code changes a variable passed as a non-const reference but also passed as a const reference. I would say the code lacks clarity because it wangles a change to a variable which is passed as const parameter.
Comment: @suspectus That's why I added an example how this would be commonly be implemented.
Comment: I would say the code *is* crude.
Answer: If the method void manipulate(const string& a, string& b) should only be called with same arguments, changing signature to void manipulate(string&) would make sense.
If not it is valid.
We should be care in implementation with this kind of aliasing to behave correctly when identical parameter is given. Here once b is modified, a is too.
Comment: There might be many reasons why the function is implemented as is. Required signatures for callbacks, whatever.


XSLT 2.0 Transformation on .Net 2.0 Framework

Question: Is .Net 2.0 Framework supports XSLT 2.0 Transformation and XML Schema validation in Windows 2000 Server? Since our client environment is Windows 2000 server and we need to implement XSLT 2.0 transformation on that.
We dont want to use 3rd party API's such as Saxon, XMLPrime, LightWeight XPath2 for .NET.
If not,
Is .Net 3.5 Framework supports Full XSLT 2.0 Transformation and XML Schema validation?
Please help me by providing suggestions.
Answer: XML schema 1.0 validation is supported by the classes in Microsoft's .NET framework. However XSLT 2.0 is not supported, System.Xml.Xsl.XslCompiledTransform only supports XSLT 1.0. If you want XSLT 2.0 you would need to use one of the third party options you have already ruled out.


Error: Cannot find module 'update-notifier'

Question: Everytime time I run npm on mac terminal, I've got this error
Mac01:~ qa$ npm
module.js:515
    throw err;
    ^

Error: Cannot find module 'update-notifier'
    at Function.Module._resolveFilename (module.js:513:15)
    at Function.Module._load (module.js:463:25)
    at Module.require (module.js:556:17)
    at require (internal/module.js:11:18)
    at /usr/local/lib/node_modules/npm/bin/npm-cli.js:29:19
    at Object.<anonymous> (/usr/local/lib/node_modules/npm/bin/npm-cli.js:92:3)
    at Module._compile (module.js:612:30)
    at Object.Module._extensions..js (module.js:623:10)
    at Module.load (module.js:531:32)
    at tryModuleLoad (module.js:494:12)

-> http://prntscr.com/h1r3yu
how can i solve that?
Answer: Ran into this issue. Even a simple npm --version was bombing with the same message. This lead me on a wild goose chase of brew uninstalls,  symlink errors, rm's to remove files /node_modules/npm & /node,  chowning directories -- you get the gist. Unsure the root cause of my brew-failings, but it might be related to npm being installed as standalone prior, whereas node now includes npm, which lead to brew config-hell on my machine.
I suggest the tips above, but if all else fails, what worked for me was to uninstall via brew, then go to the https://nodejs.org/en/download site and re-install. Believe me, I don't want to get out of terminal and not use brew, but in this case, this was the only solution that worked for me.

Uninstall node via brew : brew uninstall --ignore-dependencies node or brew uninstall --force node
Go to https://nodejs.org/en/download download and reinstall.
Now test to see if the error is gone with a npm --version
Answer: I had the same issue before with the module update-notifier and then I solved the error by installing it globally
Try installing the update-notifier
 npm install update-notifier

If you need more information, you can click on this update-notifier
Answer: I have this problem because I installed nodejs from distro and by nvm, as solution I just removed the nodejs from disto. Since I'm using fedora the command was this: sudo dnf remove -y nodejs npm. Also make sure that nvm is being sourced at your shell rc. Here is ~/.zshrc which works for bash too:
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"  # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"  # This     loads nvm bash_completion

Answer: If you are using nvm and node 9.5.0, you can solve this problem by running:
nvm use --delete-prefix v9.5.0 --silent
Answer: Try to do this npm install -g update-notifier
UPD
Try to reinstall node with npm:
brew uninstall node;
# or `brew uninstall --force node` which removes all versions
brew prune;
rm -f /usr/local/bin/npm /usr/local/lib/dtrace/node.d;
rm -rf ~/.npm;

To install:
brew install node;
which node # => /usr/local/bin/node
export NODE_PATH='/usr/local/lib/node_modules' # <--- add this ~/.bashrc

Comment: Try to reinstall node with npm:

`brew uninstall node; `
# or `brew uninstall --force node` which removes all versions
brew prune;
rm -f /usr/local/bin/npm /usr/local/lib/dtrace/node.d;
rm -rf ~/.npm;
To install:

brew install node;
which node # => /usr/local/bin/node
export NODE_PATH='/usr/local/lib/node_modules' # <--- add this ~/.bashrc
Comment: I don't understand that @Rostislav, can you post that as an answer? with step by step procedure?
Comment: Updated my answer
Comment: what do you mean by this command `export NODE_PATH='/usr/local/lib/node_modules' # <--- add this ~/.bashrc'
Comment: I mean, open file `~/.bashrc` in vim, for example: `vi ~/.bashrc`, and add line  `export NODE_PATH='/usr/local/lib/node_modules` in this file if this line doesn't exist there.
Comment: thanks for your help, i already solved it by installing node.js pkg instead in terminal command


Is there a word for a section of music where many of the instruments suddenly stop playing?

Question: I literally know nothing about music, so this will probably seem like a very novice question. Is there a word for the part of a song where many of the instruments drop away very suddenly? To give you an example, I'm referring to moments like the one featuring from 1:19-1:23 in The Batman Trailer Theme:

.
Here, many of the instruments suddenly stop playing, but you get the sense they're about to start up again. Would it be correct to call this a 'rest'?
Thanks.
Comment: Hi @Aaron. Yes, that's great, thank you. I think I scanned over this when looking through previously asked questions because the title seemed to focus on tempo, but it does actually fit and the bit about 'the drop' was also very helpful.
Comment: There's a lot of room to think about how silence (or sudden reduction in instrumentation) can be used in music. The Batman example reminds me of the first episode of the podcast "Pitch," about "the Clearmountain pause" as featured in the song "Closing Time." Sadly, it looks like it's hard to find today, but it did a good job of exploring how inserting a brief pause (a "fermata" of negative space) just before the final chorus made the song more effective.
Answer: Rest: when an individual instrument plays, is silent, then plays again. The silence is called a rest.
Break: when all or most of the instruments drop out, usually before a climactic moment.
The part of the piece referenced in the question is a break.
From Wikipedia: Break (music)

In popular music, a break is an instrumental or percussion section during a song derived from or related to stop-time – being a "break" from the main parts of the song or piece. A break is usually interpolated between sections of a song, to provide a sense of anticipation, signal the start of a new section, or create variety in the arrangement.
Comment: In that case, and many others, I'd call that a drum break.


OG groups: How to check if user is a member or not?

Question: What code can I use to check if a user is a member of a group?
Answer: For the 7.x-2.x branch of Organic Groups you need to use the following code.
og_is_member('node', $gid, 'user', $user)

'node' is the entity type. The function og_is_member requires 4 parameters to return the correct value.
Comment: Which Drupal version are you using? The parameters you use are different from [the ones defined from the Drupal 7 version of OG](http://api.drupalize.me/api/drupal/function/og_is_member/7).
Answer: In Drupal 7 for the For the 7.x-1.x branch of Organic Groups, you can use og_is_member().
$gid = 12;
if (og_is_member($gid)) {
  drupal_set_message('Current logged in user is member');
}

$gid = 12;
$account = user_load(3);
if (og_is_member($gid, 'user', $account)) {
  drupal_set_message('User id 3 is member of group 12');
}

Comment: And where do i put this code? I put it in node.tpl.php but its not working.. Can you help me please? Thank you!
Comment: You could put it anywhere, but make sure you use the correct group id (gid)
Comment: I get an error: Illegal offset type in og_get_entity_groups() (line 1986 ... ) . when i add:
Comment: @Dzoni I don't know if that makes a difference, but the gid should be a number not a string.


Ansible: Loop over registered output in the next task

Question: Ansible version: ansible 2.6.2 python version 2.7.5
I am struggling to loop over registered IP addresses from one task in other using with_items and have a debug output from an ansible playbook which gives this:
The playbook:
- name: Check DVS portgroup from vCenter and allocate IP address from EPG description
  hosts: localhost
  connection: local
  gather_facts: no
  vars:
    nios_provider:
     host: "dns1"
     username: ""
     password: ""

  tasks:
  - name: Find unused IP address from EPG
    local_action: command sh /free.sh "{{ item }}"
    with_items: "DM-SNAP (VLAN-869) in DM AMZ, IP: 188.8.131.52/24 BD: BD-DH-VLAN-869 BD: BD_AZX_NO1, IP: 188.8.131.52/24"
    register: dvs_output

  - name: The IP
    debug: msg={{ dvs_output.results | map(attribute='stdout_lines') | list }}
#    debug: msg={{ dvs_output }}
    register: ip_dns

  - name: return next available IP address for network {{ ip_dns }}
    set_fact:
      ipaddr: "{{ lookup('nios_next_ip', '{{ item }}', num=10, provider=nios_provider) }}"
    with_items: "{{ ip_dns.msg }}"
    ignore_errors: true
    register: lookup

This is the the play output. Here the play fails due to unformatted input from previous registered variable.
    PLAY [Check DVS portgroup from vCenter and allocate IP address from EPG description] ***********************************************************************************************************************

TASK [Find unused IP address from EPG] *********************************************************************************************************************************************************************
changed: [localhost -> localhost] => (item=DM-SNAP (VLAN-869) in DM AMZ, IP: 184.108.40.206/24 BD: BD-DH-VLAN-869 BD: BD_AZX_NO1, IP: 22.214.171.124/24)

TASK [The IP] **********************************************************************************************************************************************************************************************
ok: [localhost] => {
    "msg": [
        [
            "18.104.22.168",
            "188.8.131.52"
        ]
    ]
}

TASK [return next available IP address for network {'msg': [[u'22.214.171.124', u'188.8.131.52']], 'failed': False, 'changed': False}] ***************************************************************************

ok: [localhost] => (item=184.108.40.206)
fatal: [localhost]: FAILED! => {"msg": "Unexpected templating type error occurred on ({{ lookup('nios_next_ip', '{{ item }}', num=10, provider=nios_provider) }}): 'dict' object is not callable"}
...ignoring

TASK [Debug IP] ********************************************************************************************************************************************************************************************
fatal: [localhost]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'dict object' has no attribute 'ansible_facts'\n\nThe error appears to have been in '/etc/ansible/playbooks/vmware/dev/test_allocate.yml': line 37, column 5, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n  - name: Debug IP\n    ^ here\n"}

PLAY RECAP *************************************************************************************************************************************************************************************************
localhost                  : ok=3    changed=1    unreachable=0    failed=1

How can i better make the loop work inside the second task where value of IP is not correctly feeded to {{ item }} and thereby looped ?
Answer: What you do is, you register a variable in the first task. That var contains the IPs, then you filter that var to be a list and output it as debug and register that debug output and then you try iterate over the output of the debug. Thats not good.
Why don't you iterate over the filter that you output in the debug? So use:
- name: return next available IP address for network {{ ip_dns }}
  set_fact:
    ipaddr: "{{ lookup('nios_next_ip', '{{ item }}', num=10, provider=nios_provider) }}"
  with_items: "{{ dvs_output.results | map(attribute='stdout_lines') | list }}"

Also - next problem - you iterate over a list and set a variable with a value. So, after that task, there is still one variable ipaddr which contains the last IP. If you want to do something with all the IP addresses, then you should use:
- name: return next available IP address for network {{ ip_dns }}
  include_tasks: loop_over_an_ip.yml
  with_items: "{{ dvs_output.results | map(attribute='stdout_lines') | list }}"

The loop_over_an_ip.yml contains a list of tasks that should be done per IP (which is stored in item). You could rename it via loop_var.
- name: return next available IP address for network {{ ip_dns }}
  include_tasks: loop_over_an_ip.yml
  with_items: "{{ dvs_output.results | map(attribute='stdout_lines') | list }}"
  loop_control:
    loop_var: newip


What do these arrows mean?

Question: I've noticed on Edson Lopes pieces he highlights (I think) certain phrases. Not sure what he is trying to tell us when he puts a section between these arrows. Notice arrow pointing left and down, then right and down.  I never ran into these arrows before. Here's an example from his transcription of Bach's Toccata and Fugue in D minor, BWV 565.
Comment: @CarlWitthoft No. I can READ! But in all seriousness, I'd put bar 19 32nds and bar 21 32nds down stem and just get rid of those rests to make it more readable.
Comment: It would be helpful to know what piece this is. Being able to listen to it or look at an original score (this is a Bach transcription, yes?) might be illuminating.
Comment: [Youtube of Edson Lopes playing Toccata and Fugue, BWV 565 (J. S. Bach) at 01:29, matches above](https://youtu.be/SYHAA-gP6o4?t=89)
Comment: @OwainEvans to the rescue!
Comment: @Aaron Just lucky [Edson Lopes has a youTube channel](https://www.youtube.com/channel/UCwVcJ7gSCsXHE_aSQeZkqEg) and [an IMSPL page with scores](https://imslp.org/wiki/Category:Lopes%2C_Edson) but even just the D minor to E minor transposition (and for guitar) does make the so popular piece much less recognisable.
Comment: @OwainEvans you aren't one of us Otters are you?
Comment: @OwainEvans "Otter" is an obscure reference to a bunch of xkcd fans. Did not mean to offend
Comment: @CarlWitthoft thanks for explaining, I genuinely didn't know. No offence taken. Ah. Click. I think I get, the cartoon stuff. Not a fan, but can appreciate the art form and that it can REALLY be misunderstood / be offensive so not everyones cup-of-tea
Answer: Based on their placement in the score, they appear to mark phrase boundaries. Note that they come in pairs: e.g., m. 18 has a leftward mark and m. 19 has a rightward mark. Similarly mm. 21-22.
As @OldBrixtonian points out, these marked passages are played like cadenzas, with some rhythmic freedom, which can be heard in this recording (thanks to @OwainEvans):
Comment: I'd love to hear this on a guitar! It looks to me as if the arrows surround *libero*, cadenza-like passages. I'm surprised there's no footnote explaining them.
Comment: @OldBrixtonian Agreed about the candenzas. Hopefully the OP posts an original. I left that out of my answer until there was a way to confirm.
Comment: You mean the original organ version? Yes, some edition might mark those passages. I don't think Bach would have done. Maybe a guitarist will show up and tell us what they are.
Comment: Thanks for granting my wish :-) I thought you KNEW what the piece was BTW.
Comment: @OldBrixtonian I confess to being a bit chagrined at not recognizing it immediately. Owain Evans found the YouTube vid.
Comment: Lovely word! I haven't been properly chagrined for *years*. It's gone a bit quiet round here, hasn't it? Too many cowboys and not enough rainbow nation peoples. I wonder why.
Comment: @OldBrixtonian Perhaps people are too chagrined to show up. :-) Truthfully, I was considering bringing up the seeming lack of traffic on chat, but I'm still pretty new, so I don't really have a feel for what a normal pace is.
Comment: :-) Maybe they are. Maybe it's the prospect of another lockdown. I've only been here a year (this week, I think) but I've never seen it so quiet. I get a bit lost when I find I've somehow wandered into chat or meta. But yes, it'd be interesting to know what the old lags say. I did see some discussion in one place or the other, about relaxing the rules a little to allow people to ask questions like "Isn't THIS interesting?" Something like that might help.

What do these arrows mean?


Doxygen how use git hooks for run doxygen before each push?

Question: I search how generate documentation from doxygen using git hooks.
I have already read git hooks example but i see nothing like i want
root project:
|- documentation/
|- src/
|- .git/
for generate doc from root project i do:
 $ doxygen documentation/doc.doxyfile
thanks for your help
Comment: Are you sure you want large amounts of generated HTML in your repo?
Comment: or do another commit. On your repo you put only your source code? Me i put source and documentation. Just i want a documentation up to date
Answer: There is no pre-push hook.
And even if there were, I highly doubt you'd want to generate and commit a huge amount of HTML.
What you may want to do, however, is trigger something from the post-update hook of the repository you've pushed to. It could update a non-bare clone and run doxygen in that, leaving the results somewhere public.
Comment: last thing could be interesting, did you have an example?


Toast materialize

Question: Estou tentando implementar um toast (código abaixo), porém, não há nenhum resultado ao clicar no botão. Não sei o que posso estar fazendo de errado.

      <button id="btn" class="waves-effect waves-light btn-small">access_alarmEnviar</button>

Código completo da página
 <!DOCTYPE html>

    <base target="_top">
     <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
     <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
     <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
    <?!= include("page-css"); ?>

<?= title; ?>

         <select id="app">
          <option disabled selected>Auditor Responsável</option>
          <?!= list; ?>
         </select>
        Auditor

      <input id="prefDate" type="text" class="datepicker">
      Prazo(se houver)

          <input placeholder="Ex.:Achado 1.1. Falhas nas contratações de TI" id="fn" type="text" class="validate">
          Achado

          <input placeholder="Ex.: Discorda-se da conclusão de auditoria pelas razões: " id="ln" type="text" class="validate">
          Manifestação do Auditado

          <input id="zip" type="text" class="validate">
          Conclusão de Auditoria

          <input disabled id="est" type="text" class="validate">
          Estimativa

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">

          <button id="btn" class="waves-effect waves-light btn-small">access_alarmEnviar</button>

DADOS CADASTRADOS

              ACHADO
              MANIFESTAÇÃO
              AUDITOR
              CONCLUSÃO AUDITORIA
              PRAZO

        <? for (var i = 1; i < 100; i++) { ?>

          <?= data[i][0] ?>
            <?= data[i][1] ?>
            <?= data[i][2] ?>
            <?= data[i][3] ?>
            <?= data[i][4] ?>

<?}?>

   <?!= include("page-js"); ?>

Answer: Duas coisas a corrigir:

a API de .toast espera um objeto de opões como primeiro argumento, passa {html: 'Item Inserido com sucesso'} em vez de somente a string 'Item Inserido com sucesso'
a variável global que o Materialize expõe é M e não Materialize

$("#btn").click(function() {
  M.toast({html: 'Item Inserido com sucesso'}, 4000);
});

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">

  <button id="btn" class="waves-effect waves-light btn-small">
  access_alarmEnviar
  </button>

Comment: Opa, consegui resolver inserindo os trechos de código que você postou no segundo código(fiz a edição da pergunta). Obrigado.
Comment: Não sei por que, mas no código da minha aplicação não executa. Eu vi que executou por aqui, e o código está idêntico, mas quando atualizo a pagina, nada ocorre. Editei o post e inseri o código completo da paǵina. Grato se puder auxiliar.

Toast materialize


access database changes didn't reflect on IIS

Question: I've an ASP.NET application uses access database. I added a new table into database. I filled a dropdownlist with data that selected from the new table. The application works on my local machine. But after I deployed the application on IIS there is no data in the dropdownlist. In a weird way the changes made to database didn't reflect to IIS. Is there any setting on IIS I should set to make IIS perceive the new table?
Comment: Have you copied your database along with other project files to your remote server?
Comment: Yes, I can see the database in my project folder on IIS.
Answer: Make certain there are modify permissions for IUSR, IIS_IUSR, LOCAL & NETWORK SERVICE to the folder where the access db file is, usually that's the problem on updates or creates with them.


tb_userspace to auto start?

Question: I'm using tb_userspace provided by tb-tun to use HE.net's tunnelbroker service in an openvz vps, but all references and how-tos are telling me to do something like:
setsid /path/to/tb_userspace ipv6 SERVER.ADDRESS
I do have this running correctly if I run it in a shell myself, and then bring the interface up and set correct route using ifconfig:
ifconfig ipv6 up
ifconfig ipv6 inet6 add CLIENT.IP/64
ifconfig ipv6 mtu 1480
route -A inet6 add ::/0 dev ipv6

But when I put all of this into /etc/rc.local, strange thing happen: All commands after tb_userspace are ignored and not executed, but the tb_userspace does run correctly. So I have to run the other four commands manually every time after a reboot.
Any suggestion on this? Many thanks.
Answer: Here's a diagnostic that I often find useful with rc scripts.  Change this:
#!/bin/sh

command1
confusing_command2
confusing_command3

To:
#!/bin/sh

set -x
exec > /tmp/rc-stuff.out 2>&1
command1
confusing_command2
confusing_command3

...Then after a boot, inspect /tmp/rc-stuff.out to see what's happening during the boot.
...Also, make sure your rc script isn't running forever using the ps command, like "ps axf".
Comment: Argh, thanks! I tried it and it stops at the tb_userspace line, and using `ps axf` shows the script is running forever... but I do not get this result if I run the setsid line in shell myself, what could be problem?

tb_userspace to auto start?


How do I modify uib-typeahead async google maps api example to show only cities?

Question: Apologies if this answer is already somewhere, but I looked through all similar questions and didn't see the exact issue.
I would like to simply modify UI-Bootstrap's beautifully working uib-typeahead 'Asynchronous Results' Example to show only cities (with state and country). http://angular-ui.github.io/bootstrap/#/typeahead
I'd like to see if it's possible to do this without including a  linking to the google maps api, which uib-typeahead is also NOT doing. In addition, I'd like to see if it's possible to do it on the front end, instead of using the back end with a developer key, although if this doesn't work, then I will default to that option.
I've tried modifying the 'params' object like this:
params: {
     address: val,
     sensor: false,
     types: (cities) // also tried types: ('cities') and types: (regions)
}

Is it possible to do this on the front end without a developer key?
Answer: In the specified example Geocoding service is consumed and according to Google Maps Geocoding API Request Format neither type nor types are supported.
Since reverse geocoding response contains among another properties also a types property you could consider to filter results on the client side. The following example demonstrates how to modify the provided examples to display only cities in results:
$scope.getLocation = function(val) {
    return $http.get('//maps.googleapis.com/maps/api/geocode/json', {
      params: {
        address: val,
        sensor: false
      }
    }).then(function(response){
      var items = response.data.results.filter(function(item){
           return isCityType(item);
      });

      return items.map(function(item){
        return item.formatted_address;
      });

    });
  };

  var isCityType = function(item) {
       var result = item.types.filter(function(t){
          return t == "locality" ||  t == "administrative_area_level_3";
       });
       return result.length > 0;
  };

Modified plunker


API working fine in postman but not in angular2

Question: I have an API to send an OTP to mobile. It is working fine via PostMan but not via angular2.
I am getting this error "Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response."
Any help
Thanks in advance
Comment: The browser checks if the headers are present and throws an error if not. Postman works around the browser and doesn't check for these headers. Either you reconfigure the server to provide the expected headers, or you use your own server that forwards requests to the other server, so that the browser doesn't recognize the CORS situation.
Answer: This is a backend issue, backend developer has to write code to allow headers and allow origin for all APIs.
Answer: Include Allow-Cross-Origin header in your POST call.


yii remove leftover code after removing the standard sidebar in create form

Question: I have a create form which is loaded using renderPartial (standard after using the yii crud tool):
<?php echo $this->renderPartial('_form', array('model'=>$model)); ?>

I removed the code which renders the sidebar menu, and the menu doesn't show anymore. But still there's some generated code left when I look into browser my source code:

This messes up my layout and I can't find where I can remove this last part. Does someone know where this happens?
Answer: There are two things to consider here, do you want this removed over the whole site (i'll explain all methods). If so go to the following directory
/protected/views/layouts

Then edit the column2 layout, which is likely the default layout being used and remove the sidebar code. Now all pages should no longer have the sidebar.
If you want to remove this either on all actions of a controller or for a specific controller action, do the following. Duplicate colum2.php and call it say nosidebar.php. Then in the nosidebar.php file, remove the sidebar code.
To change all actions in a controller specifiy the layout like so.
class AccountsController extends Controller
{

public $layout='//layouts/nosidebar';

or to change a specific action add this inside the action method
$this->layout='nosidebar';


Alinhamento de Caracteres

Question:
Gostaria que alguém pudesse me dizer como faço para os números alinharem dessa forma com as palavras do índice superior, estou fazendo uma replica desse exemplo para um trabalho da faculdade, mas não consigo fazer com que os números se alinhem sem nunca expandir para fora da tela. Estou usando o pyhton 3.4.
Agradeço se puderem me ajudar
Answer: Você pode usar a biblioteca tabulate e ir adaptando a sua necessidade, veja um exemplo de uso baseado em alguns dados que você apresentou:
<code>>>> from tabulate import tabulate
>>> data = [[2000, 0.00, 0.01, 0.00, 0.00, 1485, 2128, 79, 286], [4000, 0.01, 0.02, 0.00, 0.00, 2286, 4673, 264, 92]]
>>> headers = ['n', 'Insercao', 'Selecao', 'Merge', 'Quick', 'Insercao', 'Selecao', 'Merge', 'Quick']
>>> print(tabulate(data, headers, tablefmt='psql'))
+------+------------+-----------+---------+---------+------------+-----------+---------+---------+
|    n |   Insercao |   Selecao |   Merge |   Quick |   Insercao |   Selecao |   Merge |   Quick |
|------+------------+-----------+---------+---------+------------+-----------+---------+---------|
| 2000 |       0    |      0.01 |       0 |       0 |       1485 |      2128 |      79 |     286 |
| 4000 |       0.01 |      0.02 |       0 |       0 |       2286 |      4673 |     264 |      92 |
+------+------------+-----------+---------+---------+------------+-----------+---------+---------+
</code>

Alinhamento de Caracteres


Why isn't the code in my implementation of hook_form_alter() being called?

Question: When I test to see if my form is called by checking for its $form_id, there is no output. Why is it that under the comment form it can't invoke the mymodule_ask_form?
/**
 * @Implement of hook_form_alter()
 */
function mycaptcha_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'comment_form') {
      mycaptcha_ask_form($form);
      echo 'test';
    }
  }

function _mycaptcha_get_ask($key = NULL) {

  $ask = array(
    'test 1' => 'example 1',
    'test 2' => 'example 2',
  );

  return isset($key) ? $ask[$key] : $ask;
}

function mycaptcha_ask_form(&$form) {
  $ask = _mycaptcha_get_ask();
  if (isset($_SESSION['mycaptcha_ask_key']) && $ask[$_SESSION['mycaptcha_ask_key']]) {
    $ask_key = $_SESSION['mycaptcha_ask_key'];
  }

  if (!$ask_key) {
    $_SESSION['mycaptcha_ask_key'] = $ask_key = array_rand($ask);
  }

  $form['mycaptcha_ask'] = array(
    '#type' => 'textfield',
    '#required' => 1,
    '#title' => 'tetst'.$ask_key,
    '#weight' => -1
  );
}

Answer: First of all - have you checked that Drupal sees your function at all, and calls it?
Then, have you tried printing out $form_id? As for default D7's content types (article and basic page) comment form ids are not "comment_form", but:

comment_node_article_form - for article
comment_node_page_form - for basic page
Comment: You can drupal_set_message($form_id) in your hook_form_alter() (or just print, var_dump, whatever) and just go to the page the form is displayed on, then you will see your id (you could see more than one if there are more forms on the page, but it's usually pretty easy to know which id is for which form).
Comment: you're right. my $form_id is wrong. how do you know the $form_id? thank you. but why when i used "comment_form" in template.php. it can alter the comment field title. thank you.


Practicing piano scales

Question: I am a late adult learner, learning piano for around 7-8 months. My tutor and I take a free wheeling approach towards my learning and cover books like John Thomson's Teaching Little Fingers to Play (started with that), Alfred's Basic Adult All-in-One and Wright Piano Forte Tutor by Albert Oswald (a book printed in London but very popular in India for decades).
Of course I started with basic fingering and C Major scale. We also agreed to do scales from time to time and by now I have practiced C, Am, G, Em, D scales. I was wondering what would be the best sequence of practicing and learning scales.
I. a) Go through all majors with sharps and b) then all majors with flats and c) then the minors (all 3 types) along the circle of fifths
II. Go through a major (C/G/D...) and its relative minors (Am/Em/Bm...)
III. Go through a major (C/G/D...) and its own minors (Cm/Gm/Dm...)
IV. A corollary question to II & III, is how to progress through the scales - along circle of fifth or through harmonic, or any other sequence
I know there are no right and wrong answers but it would be great to receive perspectives.
Comment: Actually a common order of scales isn't among the options you listed: go through the scales in increasing number of sharpes and flats. That is, C, then G (one sharp) then F (one flat) then D (two sharps) then Bb (two flats), etc.
Answer: A good way to decide on an order is to find a book or website that shows all the fingerings, and look for the different "patterns."
Limiting the discussion just to major scales, to explain what I mean:
C is unique in not using any black keys.
The "sharp" keys G D, A ... all follow the pattern of having a black key on the leading note (the one before the tonic for a scale going up). Apart from adding more black keys, the fingering stays the same for the right hand, from 1 up to 5 sharps (B). The left hand fingering for B is different, because starting "5 4 3 2 1" would put the thumb on the black F# key. See below for 6 and 7 sharps.
The "flat" keys have a different pattern. F is unique, because it starts on a white note, but the right hand fingering 1 2 3 1 2 3 4 for the sharp keys doesn't work because it would put the thumb on the B flat.
The other flat keys all start on a black keys, which gives another different set of fingering patterns. The two most extreme "sharp" keys F# and C# fit better into these "flat key" patterns, since they are equivalent to Gb and Db.
So to summarize all that: the scales for keys with a few sharps (G D A E) are relatively "easy" because they are all similar. You want to introduce scales of F and B flat at a fairly early stage, to cover more of the options, and because they are commonly used keys.
Exercise for the OP: now make a similar analysis yourself of melodic and harmonic minor scales!
And finally - the scales with a small number of black keys can be fingered in several different ways, any of which can occur in "real" pieces. Don't just practice the "standard" fingering - explore all the possibilities, including mixing and matching different fingerings for right and left hands. That will teach you more in the long run than just concentrating on the one "correct" fingering.
In fact, eventually you will want to practice all the scales even with "bad" fingerings where the thumb goes on black notes. Sometimes in "real" pieces, that is the least worst option available.
Comment: +1 for your penultimate para. alone! It's so important to try out different fingerings. Everybody has different anatomy and one man's best fingering is another's useless. Also, tunes quite often have little scale runs, but need to start and/or finish on a different finger than that you used practising the scale.
Comment: Thanks for your advice/ suggestions. I have, on my own, started doing F and Bb majors, after doing the C/Am, G/Em and D. I also realise that both the answers so far are focused on fingering aspect. Coming from India, we have a slightly different perspective on scales, and I realised that if I take any Key and play its majors and 3 minors it is doing interesting things to my ears. I guess I will do a bit of mix and match. Thanks again.
Comment: You are right that Western music "scales" are a different (and  simpler) concept than "ragas" - but since you mentioned three keyboard tutors all written in the Western tradition, that explains why the answer follows the same tradition!
Answer: When I practiced scales and scale patterns, I was told by my teacher to use a variety of different "routes" through the 12 keys. For example, here are the routes I most frequently used to get through all 12 keys:

go around the circle of fifths (e.g., C, G, D, A, etc.)
go around the circle of fourths (e.g., C, F, Bb, Eb, etc.)
go up by minor thirds (C, Eb, Gb, A then up a half step to Db, E, G, Bb, then up a half step to D, F, Ab, B)
go up by tritones (e.g., C, Gb, Db, G, D, Ab, Eb, A, etc.)

There are other ways to get through all 12 keys--these are just the sequences I used and preferred. For example, you could go up major thirds, increasing by half steps (C, E, Ab, then Db, F, A, then D, F#, Bb, then Eb, G, B). Additionally, for every ascending pattern I've listed, you can play through the 12 keys using the same intervals but in descending form.
Variety is useful because it makes us more flexible. It gives our brain more avenues for accessing/retrieving our memory of a given scale (and muscle memory), which ultimately makes us quicker at retrieving the information. However, variety serves a more practical function: it presents a challenge which keeps us interested and willing to do something as monotonous as practicing scales in all 12 keys. So any amount of variety will be beneficial to your technique and motivation.
Regarding the different types of scales (major, natural minor, melodic minor, etc.), I would recommend sticking to one type and taking it through all 12 keys before moving to the next type of scale. For example, I would take the major scale through all 12 keys, then the melodic minor scale through all 12 keys (by a different route), then the harmonic minor, etc. This will emphasize the underlying structure and intervals which make up each type of scale. I think this is more beneficial than the alternative, playing C maj and A natural minor together. Playing C maj and A natural minor back-to-back will emphasize the fingering and modal relationships, which I think isn't worth focusing on because it the connection between the types of scales is straightforward and requires less practice to grasp.
Once you are comfortable with the different types of scales (major, melodic minor, etc.), it could be valuable to alternate between different types of scales as you go through the 12 keys. If it were me, though, this sort of practice would be secondary, and would only occur once I had mastered the different types of scales in all 12 keys.
To summarize:

practice a single type of scale (major, melodic minor, etc.) at a time in all 12 keys
go through the 12 keys using a variety of different routes and intervals
once you are comfortable with the different types of scales, you can cycle through different types of scales as you cycle through the 12 keys
Answer: C major is the hardest scale to PLAY (though perhaps the easiest to understand).   There are so many ways you can finger it wrong!   Start with B major or F# major.  You CAN'T do a wrong fingering.  So you don't need to waste brain power on what finger goes where, you can concentrate on drilling your fingers and achieving fluency.
Comment: Thank you for your comments. I am done and dusted with Cmaj. And Am, Gmaj, Em and Dmaj. No "hardness" there. My question was a bit different.
I also realise that both the answers so far are focused on fingering aspect. Coming from India, we have a slightly different perspective on scales, and I realised that if I take any Key and play its majors and 3 minors it is doing interesting things to my ears. I guess I will do a bit of mix and match. Thanks again.
Comment: @SubirNag Could you elaborate on what you mean by a different perspective on scales?
Comment: As pointed out by someone above, Indian classical music, both North and South, are based on Ragas, which are numerous combinations of scales and improvisations within the boundaries of that scales. That's the different perspective that I'm talking of. There thousands of Ragas. And then Raga isn't a key. But more a scale progression that can be played/ sung on any key. Please look up Raga and Indian music.
Answer: More importantly is the physics of playing.  If you are using the incorrect muscles to play (most pianists do), if you ever have fatigue, pain, stiffness in the morning, cramps or just can't play evenly or fast, chances are you are first and foremost doing something wrong.  Since you can't beat a dead horse, practicing incorrectly with incoordinate movement is the starting point for a downward spiral.
Fixing that right off the bat is far more important than ingraining bad habits and incorrect movement into your muscle memory.  That is why mediocrity is so prevalent.  We should all be prodigious in our technique but most teachers have no idea what they are doing so mediocrity is blindly passed down from generation to generation.  The teacher's response is you need to practice more when all along the solution is to practice correctly.
The hand surgeons love it though.

Practicing piano scales


Where can I find melodies to practice basic four-part writing?

Question: I'm a first year Music Student. In our theory classes, we're learning four part writing (SATB).
In every class, our teacher brings a soprano or bass melodic line and asks us to harmonize it. I've tried practicing on my own, but I haven't really found a website or a resource that can provide melodies I can practice harmonization with.
Does anyone know a resource that could help me out? Any suggestions would be appreciated!
Comment: In my understanding there is no melody you can't harmonize, though it may be tricky sometimes. So you could pick anything, from children's song to top-10 hit.
Comment: Couldn't you write melodies? They don't have to be good
Comment: How about some of the choruses in Handel's Messiah or either of the Bach Passions? When you're done you can look to see how your harmonisation differs from the masters'. Otherwise folk tunes.
Comment: This type of music can be found in the public domain, so there will be a lot online. Try looking for Church tune books, hymns, plainsong, etc. You may need to browse a bit to find what you want. This has the tune solo, then harmonized https://books.google.com/books?id=OP1LAAAAYAAJ&printsec=frontcover.
Comment: With a bit of searching you can find unharmonized tunes... https://books.google.com/books?id=AH4yAQAAMAAJ&pg=PA56
Comment: More than anyone could ever exhaust... https://imslp.org/wiki/Die_Melodien_der_deutschen_evangelischen_Kirchenlieder_(Zahn%2C_Johannes)
Answer: Get hold of Bach's 371 Harmonized Chorales and 69 Chorale Melodies with figured bass, published by Schirmer, then pick one and harmonize it. If you get stuck you can see what Bach did.
371 should be enough!


How to mark packets depending on hostname?

Question: We can mark packets on the basis of IP addresses in the following way -
iptables -A FORWARD -t mangle -s 188.8.131.52 -j MARK --set-mark 1
How to mark packets depending on the hostname? I tried this -
iptables -A FORWARD -t mangle -s google.co.in -j MARK --set-mark 1
But the iptables utitlity gets the IP address of google.co.in from the DNS and adds the entry to the mangle table. How to mark all the packets from google.co.in, and not just from the single server of Google. As there are thousands of servers, manually adding all IP addresses is also not possible.
Is there any way to read the packet and get the hostname and mark it?
Thank you.
Comment: You cannot inspect all packets (think: TLS) & you cannot obtain a full list of Google IPs used for this domain anyway. Rather explain the original problem you are attempting to solve with iptables here, other strategies may be viable.
Answer: Firewall rules do not operate at the DNS level. In some cases iptables will do a DNS resolution for you, but the result will not be what you are looking for and will not follow and IP changes in the DNS name.
Instead you need a HTTP proxy such as Squid and its Outgoing Packet Mark (http://www.squid-cache.org/Doc/config/tcp_outgoing_mark/) feature to handle this kind of behavior.
For incoming traffic, if you are particularly interested in GoogleBot, you could look at the unofficial IP range lists such as https://evert.meulie.net/faqwd/googlebot-ip-ranges/ and set up your iptables for that.
Comment: Google specifically punishes sites trying to fool the bot, so there likely isnt any use case for trying.
Comment: One might want to segregate bot traffic to a sacrificial cluster. I would be helpful if the poster elaborated on _why_ they want to do this.
Answer: " As there are thousands of servers, manually adding all IP addresses is also not possible. "
You can build and maintain a small list of all google AS, and then add firewall rules based on these network ranges.
Maybe you can even find all google AS on the internet.
(have a look at

Need an IP Range for google's CDN to set up a firewall
https://www.reddit.com/r/starcitizen/comments/3lce2k/list_of_google_cloud_ip_addresses_for_firewall/)


Establishing Groupings Based on Behavior

Question: Consider the following scenario:
Collection of user data from a community site similar to StackExchange reveals that certain users tend to "agree" with other users; e.g., when participating in the same posts, they tend to upvote or downvote together. Simultaneously, certain users tend to "disagree" with each other. Again, when they participate in the same posts, they vote the same.
An example of collected data might look like this:
<code>thread1:
    upvotes:
        8fsygfs // Each key (e.g., "8fsygfs") represents a user
        atw9g87
        atw923swg87
        34j2njk"
    downvotes:
        jne280n
        892ned9
        28hd0ye
        cjsnd09
        02jd0d2
 thread2:
    upvotes:
        02jd0d2
        8fsygfs
        7dr4229
        232c3f25
        34j2njk
        atw9g87
        atw923swg87
    downvotes:
        jne280n
        9ah8229
        89h208d
        28hd0ye
        cjsnd09
 thread3:
    upvotes:
        02jd0d2
        9ah8229
        838w32l
        78awg2l
        34j2njk
    downvotes:
        jne280n
        atw9g87
        892ned9
        28hd0ye
</code>
If we parse this data, we can extract the absolute number of times that a given user votes the same as the rest of the users.
<code> 34j2njk:          // The users below have "agreed" with this user
   8fsygfs: 2,     // 2 times...
   atw9g87: 2,     // 2 times...
   atw923swg87: 2, // 2 times...
   02jd0d2: 2,     // 2 times...
   7dr4229: 1,     // 1 time ...
   232c3f25: 1,
   9ah8229: 1,
   838w32l: 1,
   78awg2l: 1
</code>
There are a number of other ways to parse this data. Another example is to look at how often a user agrees with other users. Here I've set a threshold where users must participate in the same thread at least 3 times before we calculate how often they "agree."
<code> 34j2njk: // The users below "agree" with this user...
    atw9g87: 0.6666666666666666, // 66% of the time
    02jd0d2: 0.6666666666666666
 atw9g87:  // ... and this user...
    34j2njk: 0.6666666666666666,
    jne280n: 0.3333333333333333, // 33% of the time
    28hd0ye: 0.3333333333333333,
    02jd0d2: 0.3333333333333333
</code>
How might I approach this data if I want to establish "poles" that represent user behavior? For example, toward one pole you'd have a group of users who tend to agree with each other. Toward the other pole, you'd have a group of users who tend to disagree with the former group. In the real world, users would fall somewhere between. I'd like to create an index that represents where in the space between each user falls.
To be specific, I'm looking for exposure to any concepts that would be helpful in this goal. I'm not looking for anyone to approach the data for me. As a lay person, I'd like to know what terms, concepts and areas of statistics and math in general would be helpful to me in exploring this further.
Comment: Sounds interesting but how do you approach this? I am not familiar with the programming language you used for the code in your example.
Comment: Hmm. You have a good point. These are just objects. They don't perform any tasks. They only act as models, in this case lists. But they may be a distraction for people without programming backgrounds. Can you suggest a format that would be more appropriate for this community?
Comment: I've edited the models a bit to be more agnostic. Hope this is helpful.
Answer: I suggest, you represent the data as a matrix with users in rows and questions in columns and with binary values, say 1 for upvote, 0 for downvote.
Then use Multiple correspondence analysis which, similar to PCA, finds the most relevant factors and the factor loadings will tell you how the individual users distribute along each factor.
Your biggest problem are missing values, since I guess that not all user will provide an answer to every thread. This answer suggest that there are solutions for MCA with missing values.
Comment: Excellent. I made the same observation that missing values complicates this. I'll let you know how this works out for me!


MySQL Show available times?

Question: +-----------+----------+------------+--------------+-------------+------------------+-----------------+
| bookingID | schoolID | customerID | instructorID | bookingDate | bookingStartTime | bookingStopTime |
+-----------+----------+------------+--------------+-------------+------------------+-----------------+
|         1 |        1 |          1 |           15 | 2015-01-01  | 09:00:00         | 10:00:00        |
|         2 |        1 |          1 |           15 | 2015-01-01  | 15:00:00         | 16:00:00        |
|         3 |        1 |          1 |           15 | 2015-01-01  | 12:00:00         | 13:30:00        |
|         4 |        1 |          1 |           15 | 2015-01-01  | 11:00:00         | 12:00:00        |
+-----------+----------+------------+--------------+-------------+------------------+-----------------+

The above table shows customer bookings (bookingDate, bookingStartTime, bookingStopTime).
I'm trying to figure out an SQL query that will allow me to query the table and find all available times/slots for a given day for a specific amount of time.
For example, a customer requests a 1 hour booking on the 1st Jan 2015 and we are open from 09:00 to 17:00.  I would like to query the table and receive the following results...
10:00 > 11:00
14:00 > 15:00
16:00 > 17:00

Is this possible with just SQL or would I need some PHP in there also?
I have also tried a few queries by using datetime fields instead of date (as show above).
Any help would be appreciated.
Comment: You need to join with a table that lists all the hours.
Comment: You *can* join a table that lists all hours, but you don't *need* to.
Comment: I'd rather not have another table listing hours as I should be able to specify the hours in the SQL?
Comment: Well, as a caveat to what I said above, you *do* need to identify which days you're open (or closed)
Answer: SELECT
  *
FROM
  your_table
WHERE
  bookingDate = '$your_date' AND
  ('$your_start_time' >= bookingStartTime AND '$your_start_time' < bookingStopTime OR
  (bookingStartTime >= '$your_start_time' AND bookingStartTime < '$your_end_time'))

The query will give you all the hours which are available during the day. (You may add the time constraint for the opening hours)

MySQL Show available times?


How to properly secure user's folders?

Question: On a file server, a base folder contain user's folders:

This base folder is protected against user's actions (deletion, rename, dump of files, etc), users can only read and traverse it:

To protect each user's root folder, I explicitly deny them the right to delete their own folder:

This imply to add a deny on each folder.
Doing it on the base folder does not work: deny to the group Users to delete sub-folders, for This foler only --> they still can delete their own folder, because inherited permissions (deny to delete) have less precedence than explicit permissions (allow to modify).
With my method, users can still hide their own root folder. This is not a problem, but it show the folder is not 100% protected against actions.

do I use the "canonical" method?
how to prevent the users to hide their own folder? Or whatever other annoying things
any suggestions?
Comment: As an FYI, many organizations don't share the base folder. User folders typically have their own share. But that isn't a hard rule, if this works for you that's fine. Usually where this or other folder schemes can go sideways is if the permissions are modified incorrectly and no-one notices for a long period of time.
Comment: We do similar, but use ABE. That way the users only see what is theirs. IN that case we do not get this granular on permissions, as their folder would just be recreated by the system if they were to delete it. And if it had anything in it, they needed back, they would put in an IT ticket and have it restored from backup. UNdelete server is a godsend, veeam covers the rest ;) (Has the added benefit of making users admit they deleted their stuff, because only they could have!)
Answer: It appears to be the "This folder" in the applies to....

The deny...

The Specials.

This folder, once owner is returned to administrator (Just quicker in my environment to d on my desktop), can be seen, traversed, added to, modified below, but cannot be hidden or deleted by user QUADWORD.
It is denied delete on the folder explicit, denied reading attributes by not being granted, and the permissions you want are set from that point down.
On the plus side, they can create and delete data from that point down, but cannot hide it there either :-)

Edit (More detail):
Allow me to elaborate further...
It appears that you would like the parent folder (The users' folders) to be treated differently than all the subfolders thereof.
So you have to specify settings for "this folder only" and then have more control form that point down. So you effectively need to be explicit on what you want for that "one folder", then be explicit on what you want for "all child objects of this folder", being different. And you have to make sure that the user has neither permissions to change that, or is by proxy allowed to by being owner or a member of any group that can.". In NTFS a delete always overrides a deny, you can test this by making two identical ACLs one with delete the other with allow, and it matters not what order you put them in they will enumerate deletes first, and ignore allows after. Whether or not that ACL is inherited or not is not relevant. It is a resolved level of  access from all ACLs that apply to that object. With one exception, no matter what you set, the "Owner" can retake ownership and change. Otherwise you can create mistakes you cannot fix, as owner you can cosmetically lock even yourself out, but you would have the power to go change that (Useful sometimes) ;)
And remember
The "effective access" tab is your friend!
Comment: If I replicate your settings, the users can not create files into their root folder. They can only create sub-folders (inside of which they can create files). It appear that "write [extended] attributes" are both needed to create files, but this also allow for hidding. Tested on Windows 10 and 2016.
Comment: The permissions reflect that. On the "subfolders and files only", you can create those permissions for attributes. Will still prevent manipulation of the parent / root (Cannot hide or delete). The crux of the solution is however to set special permissions direct on the folder for "This folder only" and then set separate permissions for "Subfolders and files only" And since you want two conditions that are mutually exclusive (Some deny some allow) you have to do it in layers. Just tested server 22 and 12R2 which are the only I have immediate access to, both worked as prescribed.
Comment: "Whether or not that ACL is inherited or not is not relevant" You are wrong. Inherited ACLs are superseded by explicit ones, this is easily tested, and widely documented.
Comment: My assertion was the deny/delete would not care, an explicit deny overrides an inherited allow. We are saying the same thing ;)
Answer: 1. do I use the "canonical" method?
You use the most straightforward and less error-prone method: the allow item is usual, and the deny item is only one check-mark.
2. how to prevent the users to hide their own folder? Or whatever other annoying things
The fact that users can hide their own folder is related to the fact they also can modify other desirable attributes (but very few do it). I never seen anyone fighting against this, probably because this never cause problems.
3. any suggestions?
Lots of admins prefer to create a share for every "root folder". This can be handy, but this can reveal private informations because shares are visible.

How to properly secure user's folders?


java.sql.SQLException: Can not issue data manipulation statements with executeQuery()

Question: A minha inserção de chaves não está sendo feita.
E o erro que dá no console é:
java.sql.SQLException: Can not issue data manipulation statements with executeQuery().
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1086)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:989)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:975)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:920)
    at com.mysql.jdbc.StatementImpl.checkForDml(StatementImpl.java:502)
    at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:2224)
    at dao.ChaveDAO.adicionar(ChaveDAO.java:27)
    at logicas.AddChave.executa(AddChave.java:26)
    at servlet.ControllerServlet.service(ControllerServlet.java:35)

A linha 27 de ChaveDAO:             ResultSet rs = p.executeQuery();
A linha 26 de AddChave:             dao.adicionar(chave);
A linha 35 de ControllerServlet:            String pagina = logica.executa(req, resp);

Código ControllerServlet:
@WebServlet("/sistema")

public class ControllerServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String parametro = req.getParameter("logica");
    String nomeDaClasse = "logicas." + parametro;

    System.out.println("Lógica: " + parametro);
    System.out.println("Comando: " + nomeDaClasse);

    try {
        Class<?> classe = Class.forName(nomeDaClasse);
        Logica logica = (Logica) classe.newInstance();

        String pagina = logica.executa(req, resp);

        req.getRequestDispatcher(pagina).forward(req, resp);
    } catch (Exception e) {
        throw new ServletException("A lógica causou uma exceção", e);
    }
}

}

Código AddChave:
public class AddChave implements Logica {
public String executa(HttpServletRequest req, HttpServletResponse res) throws Exception {
    Chave chave = new Chave();
    ChaveDAO dao = new ChaveDAO();

    String idTexto = req.getParameter("id");

    String nome = req.getParameter("nome");
    // int numero = Integer.parseInt(req.getParameter("numero"));
    String numero = req.getParameter("numero");

    chave.setNome(nome);
    chave.setNumero(numero);

    if (idTexto == null || idTexto.isEmpty()) {
        dao.adicionar(chave);
    } else {
        chave.setId(Long.parseLong(idTexto));

        dao.alterar(chave);
    }

    List<Chave> chaves = dao.getLista();
    req.setAttribute("chaves", chave);
    return "sistema?logica=ListaChaves";
}
}

Código ChaveDAO:
public class ChaveDAO {
private Connection con;

public ChaveDAO() {
    con = ConexaoBanco.getConnection();
}

// Método ADICIONA
public void adicionar(Chave c) {

    String query = "insert into chaves (nome, numero) values (?, ?);";

    try {
        PreparedStatement p = con.prepareStatement(query);
        ResultSet rs = p.executeQuery();

        p.setString(1, c.getNome());
        p.setString(2, c.getNumero());

        p.execute();
        p.close();
        System.out.println("Gravado!");
        con.close();

        // issso aqui manda pro BD
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

// Método LISTA
public List<Chave> getLista() {
    try {

        List<Chave> chaves = new ArrayList<Chave>();
        PreparedStatement stmt = con.prepareStatement("select * from chaves");
        ResultSet rs = stmt.executeQuery();

        while (rs.next()) {
            Chave chave = new Chave();
            chave.setId(rs.getLong("id"));
            chave.setNome(rs.getString("nome"));
            chave.setNumero(rs.getString("numero"));
            chaves.add(chave);
        }
        rs.close();
        stmt.close();
        return chaves;
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }

}

Comment: Você está chamado o p.executeQuery() antes de setar os valores, primeiro faça o p.setString(1, c.getNome()) e depois o execute.
Comment: O que o @DiegoSchmidt e também é desnecessário/danoso o `p.execute()` no final. Além disso, para mudar os dados, você deveria usar `executeUpdate`. A premissa do `executeQuery` é que ele não vai alterar a base de dados; ou seja, de toda a DML, apenas o subconjunto DSL
Answer: O Diego Schmidt achou um outro bug no seu código no comentário que ele fez, mas ainda não foi o seu bug. Depois de ajeitar o bug da questão, seus dados não estariam atualizados, ou daria um erro ao inserir nulos, ou daria erro por não terminar de fazer os bindings da PreparedStatement.
O seu erro se deu por você estar usando diretrizes de atualização de dados na sua consulta. No caso, você está usando insert. Todas as diretrizes de atualização de dados (mais padrões) são:

insert
update
delete

Isso aí junto com a chamada DQL forma a DML. Alguns preferem dizer que DML seria só essas atualizações, vai depender do autor/SGBD/documentação que está definindo os termos.

DQL => data query language
DML => data manipulation language

A DQL estaria inclusa apenas a parte de seleção/consulta de dados; tudo que envolvesse SELECT estaria aqui. Então a parte de FROM, JOINS e WHERE seriam classificadas como DQL. O preparedStatement.executeQuery só aceita DQL.
Para conseguir usar a DML que está fora da DQL (chamemos essa linguagem de DML\DQL), você deveria usar preparedStatement.executeUpdate.
Resumo

ouça o Diego, prepare antes de executar
DQL => executeQuery
DML\DQL => executeUpdate
mais sobre essas siglas: O que são as siglas DDL, DML, DQL, DTL e DCL?

sidenotes
Uma outra sublinguagem de SQL é a DDL, data definition language. Essa é a parte do SQL responsável por criar e alterar tabelas e views. Para executar qualquer DDL, você não pode usar nem o executeQuery nem o executeUpdate, mas sim statement.execute. Também não vejo muito sentido em preparar uma DDL, por isso que pus statement, não preparedStatement.


Explicit Loading with DBContext In generic repository pattern

Question: Our context.Configuration.LazyLoadingEnabled = false;
and this is my reference: http://www.entityframeworktutorial.net/EntityFramework4.3/explicit-loading-with-dbcontext.aspx
We have a method in our API that gets an entity with all of its children:
[IsQuery]
[HttpGet]
public async Task<IEnumerable<Blog>> GetAllBlogs()
{
    return this.EntityProvider.Get(this.CachedReader, BlogCore.AllIncludes);
}

These are navigate property that is included
public static Expression<Func<Blog, object>>[] AllIncludes = new Expression<Func<Blog, object>>[]
        {
            i => i.Community.Name,
            i => i.Categories.Select(c => c.Children),
            i => i.Categories.Select(c => c.Name),
            i => i.Categories.Select(c => c.Description),
            i => i.Submitter,
            i => i.Champion,
            i => i.Properties,
            i => i.Challenge.Name,
            i => i.Challenge.Description,
            i => i.Challenge.RestrictToSubmit,
            i => i.Challenge.Prize,
            i => i.Status.Name,
            i => i.Tags,
            i => i.Contributors,
            i => i.Watchers,
            i => i.Documents.Select(d => d.Form.Name),
            i => i.Documents.Select(d => d.Form.Fields.Select(f => f.Metadata)),
            i => i.Documents.Select(d => d.Responses.Select(r => r.Field.Metadata)),
            i => i.Documents.Select(d => d.Responses.Select(r => r.BlobReferences.Select(b => b.Blob))),
            i => i.StatusComments.Select(s => s.User),
            i => i.StatusComments.Select(s => s.Status.Name),
            i => i.StatusComments.Select(s => s.Status.StatusIcon.Blob),
            i => i.BlogThumb,
            i => i.BlogThumb.Blob
        };

and also we have mapping class
public override void ExtendDomainModel([NotNull] IRepositoryMetadata metadata, [NotNull] EntityTypeConfiguration<Blog> map)
        {
            map.Property(p => p.DateSubmitted).IsRequired();
            map.Property(p => p.LastEdited).IsRequired();
            map.HasRequired(p => p.Status);
            map.HasRequired(p => p.Community);
            map.HasOptional(p => p.Challenge);
            map.HasOptional(p => p.Champion);
            map.HasRequired(p => p.Submitter);
            map.MapManyToMany(metadata, p => p.Contributors, "blogContributor", "blogID", "userID");
            map.MapManyToMany(metadata, p => p.Tags, "blogTag", "blogID", "tagID");
            map.MapManyToMany(metadata, p => p.Categories, "blogCategories", "blogID", "categoryID");
            map.MapManyToMany(metadata, p => p.Watchers, "blogWatchers", "blogID", "userID");
            map.MapManyToMany(metadata, p => p.Documents, "blogdocument", "blogID", "responseID");
            map.HasMany(p => p.StatusComments).WithRequired(p => p.Blog);
            map.HasAddedProperties(metadata, "blogProperty");
            map.HasOptional(p => p.BlogThumb).WithOptionalDependent().WillCascadeOnDelete();
        }

My query takes 4 secs. without Categories and Documents and StatusComments
and with those takes 20 secs. on local machine.
Using SQL profiler I noticed there are lots of sub queries getting second level properties. I want to omit sub queries.
and it goes to a generic method and add all include children:
[NotNull]
public IQueryable<TEntity> Get(ICacheableReader reader, params Expression<Func<TEntity, object>>[] includes)
{
    return reader.Get<TEntity>(opt => opt.Include(includes));
}

/// Construct a query which retrieves all entities from the repository.
        /// <typeparam name="TEntity">The entity type.</typeparam>
        /// <param name="options">The entity query configuration.</param>
        /// <returns>Returns a deferred query.</returns>
        /// <exception cref="ObjectDisposedException">This reader has been disposed.</exception>
        public IQueryable<TEntity> Get<TEntity>(Action<IQueryConfig<TEntity>> options = null) where TEntity : class, IEntity
        {
            this.AssertAccessible();
            return this.ApplyOptions(this.Context.Set<TEntity>(), options);
        }

Comment: These includes can't even work. An include like `i => i.Community.Name` should throw "A specified Include path is not valid. The EntityType 'xxx' does not declare a navigation property with the name 'Name'." (Unless Name is an entity, but I don't think so). So how do you use this code?
Comment: No it's working right now, we have mapping for them. https://msdn.microsoft.com/en-us/data/jj574232.aspx you can also look at this
Answer: something like (for the first level properties):
public IQueryable<TEntity> Get<TEntity>(
    Action<IQueryConfig<TEntity>> options = null,
    IEnumerable<Expression<Func<TEntity, Object>>> includeProperties = null) where TEntity : class, IEntity
{
    this.AssertAccessible();
    IQueryable<TEntity> query = this.Context.Set<TEntity>();
    if ( includeProperties != null )
        query = includeProperties.Aggregate(query, (current, includeProperty) => current.Include(includeProperty));

    return this.ApplyOptions(query, options);
}

Comment: Thanks but your code is use ".include" I don't want use ". include" because when you are use lots of property and some property in second level for example .include(x=>x.property.propertychild) it change to subquery and we'll have performance issue. I want to join child property instead of sub query. I don't know .Entry(query).Reference( is helping or not?
Comment: are your performance issue due to querying or to materialization ? I don't believe that Entry can help as it is related to Entity and not to collection. Btw, `Load` hits the database. By using it, you are in a path leading to load all database in your local memory.


How to only get inner text of a tag in BeautifulSoup, excluding the embedded one?

Question: For example,

        Hey, sexy!
        Hello

I want only 'Hello' from the li tag.
If I use soup.find("ul").li.text It includes the b tag as well.
Answer: You could use the find function like so
from bs4 import BeautifulSoup

html = '''

Hey, sexy!Hello

'''
soup = BeautifulSoup(html)
print soup.find('li').find(text=True, recursive=False)

Comment: Thanks a ton, man!
Not sure how I missed that in documentation.
Comment: One thing though, what does text=True do?
Comment: It returns the text value for that child only (or None if there isnt any text) and does not consider child elements. If you take away the recursive=False then you get just 'Hey, sexy!' as it recurses into the  tag.
Comment: Does not work for me. I used `contents` and then the index where it is between the tags.
Comment: @Adam thanks. I'll take a look it's been a while since that answer, so it's not fresh in my mind. Why not consider posting a new answer?
Answer: You can use extract(), which will remove a tag from the tree.
In your case:
soup.find("ul").b.extract() # removes the  tag
soup.find("ul").li.text     # contents of
 without


How to play chords from a tab where a capo is used

Question: I am using Ultimate Guitar to get chords to play songs. I have noticed that most songs start out by giving you a background, tuning, and where to put the capo. Afterwards, it gives you the chords and lyrics, looking something like this:
http://www.ultimate-guitar.com/tab/42283781
In the song, it tells me to use a standard tuning, capo on the second fret, and play a C, Em, G, D, and F chord thoughout the song. My question is, should I be playing the shapes of those chords when I play, or should I be transposing the chords and playing the chord that, with a capo on the second fret, would sound like a C or a G or the others mentioned above. I'm very confused, as most of the songs I want to learn use capos and have barre chords which I, at the moment, can't do unless playing a chord that sounds like it.
Comment: As a side note, Hey There Delilah is a great beginner song as-is so you might want to try learning it directly rather than approximating with the chords.  It's not much more difficult to play without the capo using the D-F#m-A-C-G shapes either, which has the benefit of avoiding the barring.
Comment: F#m without barring?
Comment: @Tim The song does not involve full chords, you never hold more than 3 notes at a time (and never pluck more than two) except for the final stroke.
Comment: @MatthewRead - I was going just from the screenshot - which said 'you can just strum the chords'. Didn't realise.
Answer: You simply need to play the chord shapes as indicated in the tab. They will sound higher with the capo. So, e.g., with the capo on the 2nd fret the C shape you play will sound like a D chord, and this is exactly the purpose of the capo. The Em chord will sound like F#m, which would normally (i.e. without capo) be played as a barre chord. Note that often it's hard to completely avoid barre chords, even when using a capo.
Comment: Agreed.  There will be the odd amateur tab that uses the chord names based on the actual notes (so say "D" for the "C" shape with a capo on the 2nd fret), but the majority use the chord names to refer to the shapes.


Separated regression analysis vs control the covariate

Question: I am conducting a data analysis on an Epidemiology cross-sectional study.
Suppose the outcome variable is an binary variable for health status (1=health, 0= unhealth). And the exposue is infection at early year.  The hypothesis is that exposed to early infection can affect later health.
Another variable is gender which people which can affect the health status. There also a bunch of other variables that could be confounders.
The analysis we did pretty simple, we used a logistic regression analysis, we treat gender and other potential confounders as predictors and include some interactions such as gender*infection term in the model.
However, some professors (non-statisician)  insisted that we should do the analysis separately, one model for male and one model for female.
I think separated model cannot even study the interactions.
My question is  what are the advantages to run regression analysis separately (one for male and one for female)?
Thanks
Answer: There almost never is an advantage to throwing away data, which is effectively what you do when you analzye males and females separately: you can't use information about males to inform your analysis of females, or vice-versa. Having more cases in an analysis typically provides more power to discern truly significant results. For example, if males and females have the same relation between exposure and outcome, then it's quite possible to have a situation in which neither gender-specific analysis shows a significant result while a combined analysis would, simply because of the numbers of cases that enter the significance calculations. Confidence intervals would be expected to be narrower for the combined analysis in any event
An exception might be if there is an inherent difference in the underlying biomedical issues between males and females, such as in breast cancer. But other than that, if your professors are concerned with differences between genders, the combined analysis provides a better way to test for such differences (and make possible interaction tests, as you note). Tests of gender differences come immediately from combined analysis, while comparing coefficients of models across the two separated data sets, while possible, is likely to provide less power for identifying true gender differences.
Comment: Thanks, anyway, since the professor are much more powerful, we have to follow her way.
Comment: There is nothing to prevent you from doing the analyses both ways and documenting any superiority of the combined analysis. Sometimes professors can learn from their students, and reputable journals are more frequently requiring high-quality statistical analysis of studies that they publish.


Is there a fuzzy distinction between discrete and categorical variables?

Question: Are there some variables where it can be difficult to assess whether they are purely categorical?
For example:
To assess the level of pain that a patient is in, you use a scale between 1 and 10.I wouldn't consider pain score to be a categorical variable here, just discrete; this is because it is a measurement (even if it is subjective).
Conversely if I have something such as tumour stage, it is still a discrete variable between say 1 and 4, however I am more tempted to say these are categories.  The thing is, increasing value in the Tumour stage does actually have meaning: more likely to have aggressive disease. For categories such as hair colour, or gender, there is no numerical relationship between the categories!
The only thing I can really see is that in discrete variables, each step increase has the same meaning (thus increase of 1-2, 5-6 and 9-10) is the same. Whereas with tumour stage va the step sizes don't mean the same thing : 1-2 is different than 2-3 and 3-4 because the tumour aggression is probably not linear.
This has implications when running logistic regression models, where you could treat categorical variables differently (names you code them differently).
Comment: I don't get this question. To me, discrete and categorical mean the same thing: you have labeled categories, that's all. There's a subset of categorical/discrete variables called "ordinal" variables, where the categories have a well-defined ordering. For any two numbers on the pain scale, and for each individual, the greater number means greater pain (although one could argue that a pain of 3 for one person may be another person's 5). Likewise, with tumor progression, the greater number means the more serious condition. Is this question about terminology, really?
Answer: You can have ordered or unordered factors.  The equivalent of a logistic model for these variable types are the ordered logit and multinomial logit.  For the ordered logit you can have known or unknown cut points.
Comment: Whether to use ordinal logistic regression (or whatever kind of regression) depends on the nature of the *dependent* variable, not the independent variables.
Comment: In addition to @Tristan's answer, I just want to add that ordered and unordered factors can also be referred to as [ordinal](http://en.wikipedia.org/wiki/Nominal_variable#Ordinal_scale) and [nominal](http://en.wikipedia.org/wiki/Nominal_variable#Nominal_scale) variables
Comment: If I have several variables, and only one of them is ordinal, would I still need to use ordered logit (if I were perfomring a multiple regression)? In R I can usually account for categorical variables using as.factor, is that insufficient or is it necessary to use ordered logit or multinomial logit whenever you have ordinal variables?
Comment: My concern isn't so much between ordinal and nominal variables so much as ordinal and discrete variables. Age is a discrete variable, which we would not consider ordinal. Tumour stage is also a discrete variable, but we would consider it ordinal. The only difference between these examples is that a 1-unit  increase in age always means the same thing (1 year); but a one unit increase in tumour stage doesn't translate to the same thing (tumour aggression is exponential, not linear). Is step size the determining factor? Otherwise pain score, which I mentioned is an ordinal variable.


How to preload a css/js library programmatically after module installation? is there api for changing *.library.yml file?

Question: i would like to develop a module where i cached internally html,css,js statically for pages.
1) in a admin setting page i can add a bundle with 1 html page + css/js files.
2) for each bundle i have different path
3) Normally in drupal8 i can define a file *.library.yml where i can set css/js but in this case is not defined statically when i install the module, but is changed every time in admin section i add a bundle.
Is there drupal API for loading programmatically the register where there are saved libraries and where i can change and save again the configuration? it is not possible do you have other suggestions?
Comment: `*.library.yml` needs to be called ***.libraries.yml**
Answer: Drupal allows modules to add dynamic library definitions by implementing hook_library_info_build(). Drupal core doesn't implement this hook, except in a test module.
function common_test_library_info_build() {
  $libraries = [];
  if (\Drupal::state()->get('common_test.library_info_build_test')) {
    $libraries['dynamic_library'] = [
      'version' => '1.0',
      'css' => [
        'base' => [
          'common_test.css' => [],
        ],
      ],
    ];
  }
  return $libraries;
}

If you instead need to alter the library definitions given from another module, hook_library_info_alter() is the correct hook to use.
function locale_library_info_alter(array &$libraries, $module) {
  if ($module === 'core' && isset($libraries['jquery.ui.datepicker'])) {
    $libraries['jquery.ui.datepicker']['dependencies'][] = 'locale/drupal.locale.datepicker';
    $libraries['jquery.ui.datepicker']['drupalSettings']['jquery']['ui']['datepicker'] = [
      'isRTL' => NULL,
      'firstDay' => NULL,
    ];
  }

  // When the locale module is enabled, we update the core/drupal library to
  // have a dependency on the locale/translations library, which provides
  // window.drupalTranslations, containing the translations for all strings in
  // JavaScript assets in the current language.
  // @see locale_js_alter()
  if ($module === 'core' && isset($libraries['drupal'])) {
    $libraries['drupal']['dependencies'][] = 'locale/translations';
  }
}


AS400 DB2 SQL7008 : Table name not valid for operations when inserting a record via Spring Boot

Question: We have schemas / libraries created directly by OS/400 commands in DB2. Hence journaling will not be enabled by default for any physical file (table) If we would create newly. We are using DB Migration tool like liquibase for all DB changes like table / view creation in spring boot. while trying to insert or update, I am getting error "java.sql.SQLException: [SQL7008] X in TABLE_NAME not valid for operation". This error is due to the journaling not done on the newly created table via liquibase. Now, I am trying to find the below possibilities If available

Is there any possibility of creating table (SQL) under the DB2 library 9created in OS/400) so that the journaling is not required while inserting or updating ?
Is there any possibility of creating a journal on a table via Java/Spring Boot?
or any suggestions rather than journaling the table everytime in DB2 side ?

Please give your comments
Answer: When commitment control (transaction isolation) is used, journaling of the tables is required.
You have two options:

turn off commitment control
Turn on journaling for the tables

For option 1, you can include
transaction isolation=none;
in the connection string, see this question for more detail
For option 2, if you use the SQL CREATE SCHEMA and CREATE TABLE commands, to create the library and files, then the tables will be automatically journaled.
You can also use the Start Journal Library (STRJRNLIB) command after creating a library via the Create Library (CRTLIB) command.  Thereafter, when you create a table or physical file in the library it will be journaled automatically.
Comment: Thanks, transaction isolation=none; worked fine
Answer: I had this error and fixed it using iAccess client tool.
You can add DB2 journal using IBM i Access client tool.
Steps
Open the schema ,
Right click on Tables , then click include on the right click menu.

MYTABLE (the table I want to add journal) will be appeared on the list, then right click on the table name then and go to journaling, now add the values for Journal and library


Select unique rows with where in clause (SQL Server)

Question: I am trying to return one json per unique value in a column.
However, when I try to select from a sub-query the entire result set is returned.
Example Table
| json   | column |
|--------|--------|
| {obj1} | 1      |
| {obj2} | 1      |
| {obj3} | 2      |

Example Query
select distinct
[json]
from someTable
where [column] in (
  select distinct
  [column]
  from someTable
)

Actual Output
| json   |
|--------|
| {obj1} |
| {obj2} |
| {obj3} |

Expected Output
| json   |
|--------|
| {obj1} |
| {obj3} |

How can I select just 1 json per unique column value?
Comment: Is there a primary key like and id in the table?
Comment: @forpas Yes, an auto-incrementing integer primary key.
Answer: If doesn't Matter output Related To Column is  obj1 Or obj2 you must Use Group By Like this :
SELECT
  Min(JSon) AS Json ,Column
FROM
 someTable
Group By column

Answer: If you want the 1st [json] of each column then use row_number():
select t.[json] from (
  select
    [json],
    row_number() over (partition by column order by id) rn
  from someTable
) t
where t.rn = 1


Why aren't rounded corners behaving properly?

Question: I really don't know how to explain what's going on, so I'll just show some screenshots:

I set the bottom 'li' in my webpage to have a border-radius of 20px.  I set the 'li's to grow when I hover over them.  However, as seen in the second picture, part of the background image is 'leaking' over into the 'li'.
ul {
    height: 30px;
    margin: 0; padding: 0;
    position: absolute;
}

ul li {
    line-height: 30px;
    float: left;
    list-style-type: none;
    margin: 0; padding: 0;
    font-size: 18px;
}

ul li a {
    display: block;
    height: 30px;
    padding: 5px 10px;
}

.subnav {
    height: 50px;

    width:105px;
    z-index: 9999;
    top:0px;
    margin-right:60px; padding: 0;
    transition:0.3s 0s;
    -webkit-transition:0.3s 0s;
    -moz-transition:0.3s 0s;
    -o-transition::0.3s 0s;
    opacity:0;
}

.subnav:hover {
    height: 200px;
    opacity:1;
    transition-delay:0;
    -webkit-transition-delay:0;
    -o-transition-delay:0;
    -moz-transition-delay:0;
}

.subnav li {
    clear: left;
    height: 30px;
    z-index: 9999;
    background: #c1c1c1;
    width: 100%;
    height: 25px;
    font-size: 15px;
    line-height: 20px;
    transition:0.3s 0s;
    -webkit-transition:0.3s 0s;
    -moz-transition:0.3s 0s;
    -o-transition::0.3s 0s;

}

.subnav li:hover
{

    -moz-box-shadow:0px 0px 0px 6px #c1c1c1;
    transition-delay:0;
    -webkit-transition-delay:0;
    -o-transition-delay:0;
    -moz-transition-delay:0;
}

.subnav li:first-child {
    clear: none;
    background:transparent;
    font-size:xx-large;
    line-height: 50px;
    border-bottom-left-radius:0px;
    height: 50px;
    margin-right:60px;
    float:left;
    -moz-box-shadow:none;
}

.subnav li:first-child:hover
{

}

.subnav li:last-child
{
    border-bottom-right-radius:5px;
    border-bottom-left-radius:20px;
}

Here's the relevant HTML:

Tutorials

After Effects

Photoshop

Web design

Programming

Computers

Blog

News

Contact

Comment: Does it behave the same in all browsers?  Different browsers, of course, render things differently.
Comment: @DavidStratton It's working in Chrome, just not Firefox.
Comment: What's if you add "padding: 0 20px;" in your ".subnav li" ? Can you make a JSFiddle with your code ?
Comment: can you post the html as well? also trying to match the css you posted against the images you posted seems to create a disconnect...like you didn't post all the code, or the same code from the images.
Comment: @Timmerz I included the relevant HTML.
Comment: do you have a link to the site in question? it's not making sense to me from your css.
Answer: I can't see any problem. Your images show that the rounded corners behave exactly like you have putted it in your css.
The "leaking what you decribe is because you set a rounded border over a rounded border with different radi. You must play a bit around with some number to close the gap.
.subnav li:hover
{

    -moz-box-shadow:1px 0px 0px 6px #c1c1c1;
    transition-delay:0;
    -webkit-transition-delay:0;
    -o-transition-delay:0;
    -moz-transition-delay:0;
}

Play with the first pixel value in the box-shadow a bit, that might help. You can try to shift it with it 1 or 2 pixel to the right.
Comment: I don't see where he is setting a rounded border over a rounded border...can you point that out from his code?
Comment: Perhaps a little unhappy explained. He sets a border radius for the last li and on hover he sets a box shadow with specific values. The box shadow is in this case very similar to setting a second border radius around the element with specific features. The values he has given put the shadow very flat around and I have had myself often the problem that the shadow is then a bit shifted away from the original border radius. manual shifting in that direction then helped.
Comment: I guess I'm confused because he said it worked in chrome, yet he didn't set a box-shadow for chrome, only the firefox version. I think the whole way he is going about this is wrong. it's a weird effect to have it expand on the sides...typically it's just highlighted, which would have fixed all this I think...weird css, which leads to weird results.
Comment: Enlarging hovered menu items is an often used effect, but using box-shadows over rounded corners can depending on the given values be a bit of a pain. As I said I have had that several times. I develop on Firefox and when that stands I go over to other browsers, so I can't say really say anything about a different behavior in Chrome. For sure the whole effect would be much easier to realize if he would just scale the width higher on hover. Yeah the CSS is a bit strange made