Formula 1: KERS and DRS

Question: Over the past couple of seasons, overtaking in Formula 1 has moved from sheer car power and driver skill to also include technology like KERS and DRS.

What exactly are these KERS and DRS?
How does it work?
How much control does a driver have for both KERS and DRS apart from activating and using it  over the course of the race lap?
Answer: KERS stands for Kinetic Energy Recovery System. It's a system similar to those used in many hybrid cars: It recovers the kinetic energy of the vehicle when braking and stores it either mechanically in a flywheel or electrical in a battery or capacitor. This energy is then used later under acceleration. The use of KERS in Formula is limited to an additional 60kW (82PS) for 6.6 seconds per lap controlled by the driver. In 2014 they plan to double the allowed power and increase the usage time to 8.3 seconds. The time gained by this system is about 0.3 to 0.4 seconds per lap.
DRS stands for Drag Reduction System and is a adjustable flap on the rear wing of the car. It can be adjusted to reduce aerodynamic drag thus increasing the maximum velocity of the car (10-12kph). It was implemented to promote overtaking and is by FIA activated only if the car is maximum one second behind the leading car (can be altered race by race) and within a defined DRS zone of which there can be two per race. When activated the driver gets a signal on his dashboard and can then use it. The system is deactivated when the driver brakes or released the DRS button after usage. Activating the system reduced downforce thus reducing cornering speed so it can only be (sensibly) used on straights.
Source: Wikipedia
Comment: They all manage to max out their KERS during a lap, so as Trudbert says, it is limited (in software). They can use it whenever they like, at the press of a button, and can decide not to use it if they want.
Comment: What I mean is, does the driver have any control over it apart from activating and using it? As in, apart from braking, is there any way a driver can tune or power the amount of KERS he gets over a lap?

Formula 1: KERS and DRS


See what database a site is connected to

Question: Is there a page in Drupal 7 (or a module) that will show me what the name of the database is that the site is pointing to?
I know this can be done via settings.php, but I am setting up a build procedure that I can have lower level developers (or even non-developers) handle and a UI would be better.  I recently had an issue with two sites pointing to the same database and it borked some things up.  I want to add checking this setting to our build procedures.
Answer: I think this is what you are looking for:
https://drupal.org/project/show_database_name

Display the host and database name of the default database on the status report, toolbar (Drupal 7) and/or on the admin_menu bar if enabled (either Drupal 6 or 7) and/or in a block (to use with the admin module).

It is marked as dev but it looks like a simple use-case and I don't expect there should be any problems.
Comment: I am also going to check out https://drupal.org/project/dbinfo, which was referenced as a related project.
Comment: That is EXACTLY what I am looking for.  Thx and green check box to you, Sir.


How to decode a unicode character in string?

Question: I have the following String:
Conversely, companies that aren\u0019t sharp-eyed enough to see that their real Dumbwaiter Pitches are lame, tired, or just plain evil \u0014 well, they usually end up facing extinction.

This string contains '\u0019t'. I cannot decode, because it's already a string. If I encode first, then decode, it still shows '\u0019t'. How do I get this to show a ' ?
Comment: Unicode 19 is not a printable character, so there was a mistake made during encoding I presume. Whatever you try, it is unlikely that it will result in a apostrophe. Unless you find / decode it yourself by explicitely creating a map from value `0019` hex to the apostrophe.
Answer: One option is to literal_eval it:
import ast
s = r"Conversely, companies that aren\u0019t sharp-eyed enough to see that their real Dumbwaiter Pitches are lame, tired, or just plain evil \u0014 well, they usually end up facing extinction. \u2661"
r = ast.literal_eval(f'"{s}"')
print(r)

Output:
Conversely, companies that arent sharp-eyed enoughto see that their real Dumbwaiter Pitches are lame, tired, or just plain evil  well, they usually endup facing extinction. ♡

Comment: This [doesn't seem to work](https://repl.it/repls/HarmoniousAdvancedLegacysystem)
Comment: @Error-SyntacticalRemorse without `r` the code example does not really prove the solution, because all the codes are substituted already before calling `literal_eval` :)
Comment: @bereal Missed some quotes. Try now
Comment: Of course, Unicode 19 is not a printable character, so it is still missing in action.
Comment: Yeah. I added a heart to the end for that reason... @FelipeFaria The unicode characters in the OPs string aren't printable.
Comment: Well, that won't make it anymore printable. That's more of a problem of the question of course, but yeah.
Comment: Yup -- @Maarten-reinstateMonica clarified right before I pressed "Add Comment." Checked it again and it is working. Good solution.
Comment: @bereal did turning into a raw string change anything? I don't mind but it seems the effect is the same. Since the OP doesn't have it as a raw string I am going to keep it as a regular string to match the OPs predicament.
Answer: Somehow, the Unicode escape string is 2000 hex off the mark. Unicode dash and apostrophe are:
Unicode Character 'EM DASH' (U+2014)
and
Unicode Character 'RIGHT SINGLE QUOTATION MARK' (U+2019)
So lets fix it anyway, even if the error is at the source (THEM) not the destination:
import re
text = r'Conversely, companies that aren\u0019t sharp-eyed enough to see that their real Dumbwaiter Pitches are lame, tired, or just plain evil \u0014 well, they usually end up facing extinction.'
pattern = r'\\u([0-9a-fA-F]{4})'

# used to indicate the end of the previous match
# to save the string parts that don't need character encoding
off = 0
# start with an empty string
s = r''
# find and iterate over all matches of \uHHHH where H is a hex digit
for u in re.finditer(pattern, text):
    # append anything up to the unicode escape
    s += text[off:u.start()]
    # fix encoding mistake, unicode escapes are 2000 hex off the mark
    # then append it
    s += chr(int(u.group(1), 16) + 0x2000)
    # set off to the end of the match
    off = u.end()
# append everything from the last match to the end of the line
s += text[off:len(text)]
print(s)

prints out
Conversely, companies that aren't sharp-eyed enough to see that their real Dumbwaiter Pitches are lame, tired, or just plain evil — well, they usually end up facing extinction.

Note though that I've happily ignored any possible presence of \\u00xx in the text (where the backslash itself is escaped), that's something I'll leave for you to solve. Any correct Unicode escapes in the text will, of course, be altered as well.
Comment: "Conversely, companies that aren't sharp-eyed enough to see that their *character encoding routines* are lame, tired, or just plain evil - well, they usually end up facing extinction."


How to add information here on topics on which you already provide information elsewhere online?

Question: As can be seen when clicking on my name here I founded the ReplicationWiki. Replication is my field of expertise. I came across stack exchange because I saw someone had linked to the ReplicationWiki in the Quant Stack Exchange and someone had found this helpful. The information provided there was incomplete so I explained in more detail.
I then looked what other questions are already asked here and saw someone asked for journals that publish replication of experiments, someone else wanted to know what software is used most in economics and I saw a question for examples of code for instrumental variables. All this information is readily available in the wiki, that's why I provided it here and posted the links to show how to find it. I searched for further questions that are already answered in the wiki and found one in the quant stack exchange on replication of a specific study and several questions on datasets in the open data stack exchange that I could answer with the help of the wiki and several users voted that they found the information useful: a, b, c.
I see that this can be seen as a way of self-promotion, and someone already complained about this. I am open about the fact that I founded the wiki, and I am grateful for advice how to deal with this appropriately. I already found the feedback useful that I should not edit answers of others with links to the project because even though it
is shown that I edited them it is not directly clear that I as founder of the project added that information and that does not mean the original author of the answer endorses it.
There are two points that I would like to add here and that I need some advice for, a tag for replication related questions and the question how to identify studies that the community thinks should be replicated.
For questions that are related to replication of empirical studies I think it would be nice to have a tag and I created one. So far in the economics stack exchange there is only one question where I clearly see it should fit, the one on journals that publish replications of experiments. For a tag creation one is asked to provide relevant links. The most relevant links  in this case as far as I would say are the web project that I founded myself and the literature list that I compiled in a different project. I am however obviously biased and would like to know what you think about it. I have worked on the topic for several years and already posted much of the information I have on the internet, so I thought I should also share it here. Unavoidably that can be seen as a conflict of interest and I would like to have your advice. On the one hand I would like to encourage the stack exchange community to ask their questions on replication, on the other hand I don't want to harm the project (and in the end myself) by attaching too much importance to my own work.
The second point is my question how to find a mechanism to identify studies that should be replicated. In the economics stack it was only partly answered in some comments and then after complaints about self-promotion some voted it down and I removed it. The same question in the quant stack exchange already got a relevant answer, maybe because there I could already refer to an example question someone has asked on a specific study they wanted to replicate. I have not yet understood why such questions are not asked here more often. Strangely I found three such questions on economics studies in the stats stack (d, e, f) and none here, so I asked there, too and it is upvoted there. The point is that I wonder why in psychology voting on such studies works whereas in economics we do not yet have anything alike that is used much. Could you help me to ask this in a way appropriate for this site?
Comment: I'm not sure how to answer your question right now, but I'd thought that I'd mention that I think the Replication Wiki is a great idea. It is something that is very much needed. I'd love to contribute to it some time.
Answer: I think that if you were to ask the question now it (with the disclaimer) it would not be closed. But then again I did not vote to close it earlier either so perhaps I am wrong.
The wording of the question on the psychology site is very nice:

What are important studies that your field of Psychology gives credence to, but which--as far as you know--have not been replicated in any published follow-up work?

A main component of the question is finding studies that are accepted, "given credence to" by the community. I don't know if there are empirically proven theories that are widely accepted in economics. There seem to be a lot of paradigm shifts in macro and international economics, where theory and data meet. Perhaps by now people are skeptical about all encompassing theories. If this is true than nominating such studies would be difficult.
Perhaps there should be two questions:

Are there important/general empirically testable economic theories that are currently accepted?
In your opinion which of these can and should be replicated?
Answer: The thing is, this is a Question and Answer site, not a forum. The best answers get voted to the top, and the one that meets the asker's requirements, gets accepted by the asker as the answer.
That's the system. And it depends on there being a right answer.
Big-list questions such as the one you propose are a poor fit to Q&A sites such as this. They are suitable for forums; this is not a forum.
Just pointing to the existence of some big-list questions elsewhere does not make them alright here.
So the correct way to ask a big-list question here, is to not ask it. Such questions should be closed and deleted. You can help keep this site useful, by flagging or voting to close such questions as too broad.
Comment: With "big list question" I assume you mean a question like "please list studies that should be replicated". I agree that this would not be a question to ask here, and I do not ask it here. What I asked in the main forum is how to find a mechanism to identify such studies. That is not a big list question. It may however be a question that should getter be asked in a discussion forum, so a good answer might be to recommend one. Here in meta I asked a meta question, how to add information on a topic on which you already provide information elsewhere online. Do you have an answer to that?
Comment: Ok, I've tried again to understand what it is you're actually asking, and have posted another answer that tries to interpret what you're saying. As it stands, you've got a very long question with a bunch of irrelevant links, and your actual question remains unclear.
Comment: I agree that that the question is too long and has many aspects.
Comment: @JanHöffler then cut out everything irrelevant (the entire body text), start with your title, and just elucidate on the title as you've done in the comment above ^
Answer: It's very unclear what you are asking, because you seem to be asking "how do I write an answer", which is trivial. You type the words into the box. It makes no difference whether you've provided the information elsewhere or not, the answer is the same: type the information into the box, then press "Post Your Answer".
Just posting a link to content elsewhere is unacceptable. We're building a body of content here. This is not a link farm, and must not be used as such. So if you've the answer to a question, put it in an answer here. Type it into the answer box and submit it. Do not merely link to the information elsewhere. Links rot. Tens of thousands of wikis like yours have been set up and abandoned over the last twenty years, and links to them just suffer link rot and become useless. We're trying to build a library of content here that will have longevity.
Comment: In some questions people ask for content that cannot be provided here like "how can I find data on...". A short explanation with a link to a list of such datasets then feels appropriate to me. And no, there is no other wiki with the specific information that we collected and that helped me to answer several questions here.
Comment: Then post the list of datasets in the answer. Merely linking to a list elsewhere is useless, and is always going to look like spamming.
Comment: In the case of the [instrumental variable datasets](http://replication.uni-goettingen.de/wiki/index.php/Instrumental_variable_(IV)) that would have meant a full screen of datasets. I don't think anyone would want that here, and it is common practice to point to external websites where the information asked for can be found, of course together with a short explanation.


Numeric field type in Form API

Question: I am trying to add a "number" field type to a form using FAPI:
$form['phone_number']['areacode'] = array(
  '#type' => 'textfield',
  '#title' => '---',
  '#width' => '30%',
  '#align' => 'center',
  '#required' => true,
  '#maxlength' => 3
);

I change the TYPE to "number" and the field doesn't get generated at all. The number module is enabled. I have implemented the following theme functions:

MYTHEME_form_element
MYTHEME_textfield
MYTHEME_container

What could be behind this field not showing up when I use #type = number or #type = number_integer, etc?
This might have something to do with it:
Creating Number fields (integer and decimal) manually in code for custom forms
However I actually want the type to render as "number" in HTML so smart phones show a numeric dialer
Any ideas?
Answer: $form['my_element'] = array(
    '#type' => 'textfield',
    '#attributes' => array(
        ' type' => 'number', // insert space before attribute name :)
    ),
    '#title' => 'My number',
    '#required' => true,
    '#maxlength' => 3
);

Comment: Why does it ned to have a space?
Comment: This leads to invalid HTML btw.: ``
Comment: You can now use `'#type' => 'number'`, in Drupal 8/9
Comment: What's not clear?
_"Numeric field type in Form API"_ is need?
Define attribute " type" (**with space**) in #attributes array with a desired value: number, date, color...
dirty hack
Comment: max length is not working
Answer: As noted by @fritzmg , the Number element is included in core as of Drupal 8.0.
For example:
$form['phone_number']['areacode'] = array(
  '#type' => 'number',
  '#title' => '---',
  '#required' => true,
);

Comment: There is an interesting option that is `#step` :
`'#step' => '.1'` allows a precision of 1 decimal : 0.1, 0.2, ...
`'#step' => '.01'` would allow a precision of 2 decimals like 23,23 or 56,76 etc
Answer: You can install and use module Elements for it.
Comment: This module is already included in the core in Drupal 8. The correct way to create a number field is by using `'#type' => 'number'` (not `'numberfield'`) in the render array.
Comment: `#type="numberfield"` is the correct way to adjust the field when using this module.
Comment: This is the correct way to get a HTML5 number field.
Answer: I'm a bit late to the party. The problem is that theme_textfield (D7: includes/form.inc , lines 3924ff) hard-codes $element['#attributes']['type'] = 'text';.
You may wrap said call in a if (!isset($element['#attributes']['type'])) { ... } or wait for the patch https://www.drupal.org/node/2545318 to be applied.
Answer: this is your code below..
$form['phone_number']['areacode'] = array(
'#type' => 'textfield',
'#title' => '---',
'#width' => '30%',
'#align' => 'center',
'#required' => true,
'#maxlength' => 3
);

please tell me what is ['phone_number'] , it's a container or not or its exist in your form or not and if you want to create custom field in your form then you should use hook_form_alter hook_form_alter
like
  function mymodule_form_alter($form_id, &$form) {
 if ($form_id == 'form_id') {

$form['field_name'] = array(
 '#type' => 'textfield',
 '#title' => t('title'),
 '#description' => t('Description.'),
 '#width' => '30%',
 '#align' => 'center',
 '#required' => true,
 '#maxlength' => 3
 );
  }
   }

hope this help you..
Answer: I don't see it working with invalid value for the #type field, however you can do something like that:
The form element:
$form['my_element'] = array(
    '#type' => 'textfield',
    '#attributes' => array(
        'data-type' => 'number',
    ),
    '#title' => '---',
    '#width' => '30%',
    '#align' => 'center',
    '#required' => true,
    '#maxlength' => 3
);

And implementing theme_textfield
if(isset($element['#attributes']['data-type']) && $element['#attributes']['data-type'] === 'number'){
    $output = '<input type="number" />';
}else{
    $output = '<input' . drupal_attributes($element['#attributes']) . ' />';
}

Comment: I was thinking the same thing for a solution -- but what do you mean it won't work with an invalid #value???
Comment: Well if you don't put a valid value for the **#type** the form element won't be rendered at all, as you stated before.

Numeric field type in Form API


Switch git provider in buildnumber-maven-plugin

Question: When using the buildnumber-maven-plugin, the execution fails when no git executable is in the %PATH% during a build on command line:

[ERROR] Failed to execute goal org.codehaus.mojo:buildnumber-maven-plugin:1.4:create (default) on project test: Cannot get the revision information from the scm repository :
[ERROR] Exception while executing SCM command. Error while executing command. Error while executing process. Cannot run program "git" (in directory "C:\dev\test"): CreateProcess error=2, Das System kann die angegebene Datei nicht finden

However, when executing the same build via eclipse Run as -> Maven clean verify, a commit id can be retrieved.
Since it works in eclipse, I tried to use the maven-scm-provider-jgit instead of maven-scm-provider-gitexe with buildnumber-maven-plugin, but apparently I did not configure it correctly.
This is the relevant part of my pom.xml:
<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>buildnumber-maven-plugin</artifactId>
    <version>1.4</version>
    <executions>
        <execution>
            <phase>validate</phase>
            <goals>
                <goal>create</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <doCheck>false</doCheck>
        <doUpdate>false</doUpdate>
    </configuration>
    <dependencies>
        <dependency>
            <groupId>org.apache.maven.scm</groupId>
            <artifactId>maven-scm-provider-jgit</artifactId>
            <version>1.9.4</version>
        </dependency>
    </dependencies>
</plugin>

How can I switch to maven-scm-provider-jgit?
Comment: @centic The same as mentioned above Cannot run program "git" It looks like the maven-scm-provider-jgit is not used
Comment: What error/response did you get?
Answer: The buildnumber-maven-plugin needs to know, which git provider to use. The following configuration changes the git provider to jgit.
It is necessary to use at least version 1.9.5 of maven-scm-provider-jgit, since the InfoCommand is not implemented in 1.9.4.
<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>buildnumber-maven-plugin</artifactId>
    <version>1.4</version>
    <executions>
        <execution>
            <phase>validate</phase>
            <goals>
                <goal>create</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <doCheck>false</doCheck>
        <doUpdate>false</doUpdate>
        <providerImplementations>
            <git>jgit</git>
        </providerImplementations>
    </configuration>
    <dependencies>
        <dependency>
            <groupId>org.apache.maven.scm</groupId>
            <artifactId>maven-scm-provider-jgit</artifactId>
            <version>1.9.5</version>
        </dependency>
    </dependencies>
</plugin>


Make local 24h day from utc timestamp, and convert back to utc

Question: I have utc date 2017-04-22T21:03:54 (local date is 2017-04-23 00:03:54, offset +3)
I would like to get data from server for 1 day. For this example, local day is:
start: 2017-04-23 00:00:00
end: 2017-04-23 23:59:59

And UTC params for server:
start: 2017-04-22 21:00:00
end: 2017-04-23 20:59:59

How I can receive this dates with moment.js? Local offset may be different
I try:
moment.utc(startTime).format() // 2017-04-22T21:03:54Z, but I need 2017-04-22T21:00:00Z
// for example, if local timezone will be +6, I need 2017-04-22T18:00:00Z

Comment: 1) your back end server should store all times in UTC to start with, there should be no conversion to local on server. 2) you never mention what your back end stack is. But parsing ISO and converting to local is straight forward in every language/library I know of.
Comment: `moment.utc('2017-04-22T21:00:00Z').local().toDate()`
Comment: The UTC params for server should be [ISO 8601](http://stackoverflow.com/questions/25725019/how-do-i-format-a-date-as-iso-8601-in-moment-js) and the server code should parse them as ISO 8601.
Comment: @RemusRusanu utc params for server - it's not problem. I can't understand, how I can convert UTC date to local with offset and make 24h start/end params.
Comment: @RemusRusanu local() is method what I looking for! Thank you.
Comment: @RemusRusanu—please don't answer in comments, it leaves the question unanswered and is not useful for others looking for an answer to the same question ([*Help Center > Answering*](http://stackoverflow.com/help/how-to-answer)). ;-)
Comment: @RemusRusanu ofc, at time when i finish issue, I put answer, or check suggested.
Answer:
I have utc date 2017-04-22T21:03:54

A date string without a time zone is treated as local (except for ISO 8601 date-only forms, which ECMAScript treats as UTC, contrary to ISO 8601). If you want to treat a string like "2017-04-22 21:00:00" as UTC then you have to tell the parser (in moment.js you can use the utc method).
You should also always tell the parser the format it's trying to parse, otherwise you're hoping it guesses correctly. If utc is used, moment uses offset +0000 by default (its "UTC mode" * ), not the local offset. If you want the host offset, you can use the local method or convert to a Date object and use built-in methods.

var s = '2017-04-22 21:00:00';
var format = 'YYYY-MM-DD HH:mm:ss';

// Tell parser to treat as UTC and the format
var m = moment.utc(s, format);

// Once the string has been parsed, you can output it in any format you like
console.log(
     'Original format, offset +0000 : ' + m.format(format)
  +'\nBuilt-in toISOString, offset Z: ' + m.toDate().toISOString()
  +'\nBuilt-in toString, host offset: ' + m.toDate().toString()
  +'\nOriginal format, host offset  : ' + m.local().format(format)
);

* I'm not sure this is a good idea as it means the code using the object needs to know it's in UTC mode. If you get a moment.js object from elsewhere, it would be good practice to set it to the "mode" you want. Calling local or utc multiple times has no bad effects.
Answer: (Putting my comments as answer)

The representation of datetimes in a text encoded transport/protocol (as HTTP) should follow ISO-8601. The time portion should include a timezone designator (for UTC time this is the simple Z, see link). These convention removes any ambiguity between client and server about what moment does the time literal represent.
Back ends should store times in UTC:

This removes any ambiguity when the database moves (failover to standby in different timezone, move of server to new location from east coast to west coats etc).
It removes any ambiguity for literals that fall into the DST time overlaps.
It removes any ambiguity from rushed legislative changes modifying timezones (of which several occur every few years)

Now that being said, if you need to convert an UTC time to local time in JavaScript/Node with MomentJS, use Moment's local().


Why is Western European music harmonically driven?

Question: I was reading an article where they said that the lute was derived from the oud, a fretless melodic Middle Eastern instrument. But they added frets to the lute in order to make it easier to harmonize multiple notes at the same time, that way it could better integrate with Western European music which was "harmonically-driven".
But it got me wondering what made Western European music based on harmony in the first place. This isn't the first article I've seen that mentioned this. Is it because Europe had instruments such as the harpsichord that had the ability to play multiple notes together. Is that the context that was going on in Europe before the lute hit the scene? Or is there another reason harmony was a big factor in Western Europe?
Edit: on second thought, there were instruments far before the harpsichord like the Lyre that could play multiple notes together too.
Comment: You don't need special instruments to have rich harmonies. Just get three or four singers together. Stick 'em in a monastery for a few hundred years and see what happens...
Comment: That quote doesn't say that western traditions are _driven_ by harmony. No argument that harmony is important, but musicians and composers are constantly talking about melody too; jazz players disparage players who don't know the melody, or who don't acknowledge the melody in their improvisations; some players have built careers on motivic approaches; players _reharmonize_ melody; a melody is what you remember; composers often say that melody comes first. Even if harmony is always there in western music, that is not the same thing as western music being _driven_ by harmony.
Comment: Very good question. It **might** have to do with technological progress at some specific seminal time and place (it takes a lot more effort to build a harpsichord or organ than a drum), but I have no idea whether that's true or not. I'm not even sure where to look up extremely high-level questions like this.
Comment: What do you mean by "harmonically driven"? Melodic structures are very important in much of western music; does harmony drive the music, or is harmony a lens through which we view it? Saying that western music is harmonically driven seems like an over-simplification.
Comment: @DavidBowling from wikipedia: "Descriptions and definitions of harmony and harmonic practice may show bias towards European (or Western) musical traditions." https://en.wikipedia.org/wiki/Harmony
Answer: The history of harmony is related to the history of polyphony.
The lyra of the  Greek had different strings according to different modes but their music was monophone (only melodic).
The polyphony has been developed by the monks (organii, bourdon, fauxbourdon). Mind that  the church organ has been introduced before the harpsichord and the oud.
Melody and rhythm can exist without harmony. By far the greatest part of the world's music is nonharmonic. Many highly sophisticated musical styles, such as those of India and China, consist basically of unharmonized melodic lines and their rhythmic organization. In only a few instances of folk and primitive music are simple chords specifically cultivated. Harmony in the Western sense is a comparatively recent invention having a rather limited geographic spread. It arose less than a millennium ago in the music of western Europe and is embraced today only in those musical cultures that trace their origins to that area.
https://www.britannica.com/art/harmony-music#targetText=The%20organized%20system%20of%20Western,that%20gave%20rise%20to%20polyphony.

Why is Western European music harmonically driven?

Some will answer that harmony is a natural - or  even a divine - law that western musician have discovered, others may think it is a cultural concept as a result of musical practice (playing around with tones and overtones)
Comment: "polyphony has been developed by the monks":  maybe.  They were just the first to write it dpesn.  We don't know the extent to which they borrowed these practices from other (unwritten and possibly secular) music.  "...the church organ has been introduced before the harpsichord and the oud": the organ was also invented before polyphony.
Answer: Western music has never been "harmonically driven".
To get the misinformation about the lute out of the way first: lutes never had frets to impose "precise tuning". The frets were simply loops of gut tied around the neck of the instrument and were intended to be moveable at will by the performer
They were simply playing aids, when the number of strings increased from 3 on the earliest ouds up to as many as 12 on a lute.
The article itself says the lute was largely a melodic instrument, until a playing style that allowed polyphony (not harmony) was developed. "Strumming chords" on a lute was never the basic playing technique.
The theoretical notion of "chords" and "chord progressions" was very late on the scene in western music. Originally it was simply a convenient shorthand for common polyphonic voice-leading patterns. Later, some theorists forgot its origins and started to use it to "explain" things which it can't.
You only have to look at the complexity of Jazz chord notation to see the disconnect between the attempt to describe something in terms of "chords" and explain what it really going on, which is often quite simple, once you get past all the magical incantations like "C7#5b9" and "tritone substitutions" and see what the voice leading - i.e. the polyphony, not the harmony - is doing.
But musical rabbits have colonized this rabbit hole to such an extent that the misguided idea of teaching "harmony" based on "chords" isn't going to disappear any time soon - and it has the unfortunate attraction that it allows people to write unimaginative music, which requires mininal attention from the listener, with very little training or intellectual effort.
Comment: This sounds very interesting! Can you post some links to this awesome music that requires attention, training and intellectual effort from the listener? And doesn't use "harmony" based on "chords"?
Comment: Problem is that there's absolutely nothing to back this up. It's one guy on the internet claiming that everyone else is wrong. Without any references to real research it's very difficult to judge this answer.
Comment: @DavidBowling the last paragraph of the answer implies in polemic internet style that commonly represented ideas about harmony are somehow wrong/bad/harmful and the people using them are ignorant or stupid. And that some better things exist that the poster knows about and others don't. Which is of course very interesting, the only thing missing is links to the supposedly better stuff. Anyway, I think the controversy is unnecessary. Chords are a helpful tool, an abstraction used in common music-making processes, and as such they also provide a means for exchanging harmony-related ideas.
Comment: Can you elaborate more on what polyphony based explanations would actually look like in more complex settings like Jazz? I have difficulty imagining how to describe such things without referring to chord structure. What has developed around this alternative point of view and why do you think the standard way of describing harmony does not capture what is actually going on?
Comment: I would downvote this for the first sentence, but the rest of it is too good for a downvote, so I'm upvoting instead.
Comment: @pipe -- who is claiming that everyone else is wrong, and who is everyone else?
Comment: @DavidBowling yeah ok, well, this answer does make a point, and I can understand the point of view, being annoyed by chords being seen as almost like a law of nature instead of a tool in a particular way of working. Any single answer can only provide one partial point of view... (now I'll remove that other comment to avoid stepping over the line of "extended discussion" which is deemed bad for some inexplicable reason - I think extended discussion is exactly what the world needs instead of "correct" answers ... )
Comment: I think the last part of the last sentence is an allusion to the (at least reputed) 4-chord, 3-melody-note pop songs written in this decade. I've listened to plenty of classical music with thick chords and thought-provoking chord progressions (and even the starting portion of a Pokemon Sword and Shield trailer--a trailer for an upcoming game--had a intriguingly unorthodox chord progression I want to rip and use some day).
Comment: 'the attempt to describe something in terms of "chords" and explain what it really going on, which is often quite simple, once you get past all the magical incantations like "C7#5b9" and "tritone substitutions" and see what the voice leading [...] - is doing.' Why the name-calling? Chord notation is as clear as it can be, given what it needs to distinguish. And players who use it aren't playing tunes; even if harmony were irrelevant to tunes, that wouldn't prove that it's no part of what's really going on.


Using T -test results to find probability of an event occurring

Question: Given two samples, one consisting of a different number of times someone made sales calls to different potential clients who ended up buying the product. the other one consists of a different number of times someone made sales calls to different potential clients who ended up NOT buying the product.
Any idea if possible how I can find the maximum number of calls the salesperson needs to make before giving up?
I did a t-test and below are the results.
Group One (bought): Mean  4.40897500, SD 4.15437900, SEM 0.12088744, N  1181.
Group Two (didn't buy):
Mean 3.23937500,
SD2.80748100,
SEM 0.02661269,
N 11129.
P value is less than 0.0001
t = 12.8971
df = 12308
Answer: Welcome to the site.
A $t$-test is a test for a difference in means. You current setup does not answer your question, it will only tell you if there is a significant difference between the mean number of calls of the group that ended up buying the product and the mean number of calls of the calls of the group that did not.
What you should do instead is make a prediction interval for the number of calls until a product is bought. The number of calls until success can be considered a negative binomial process.
There is a complication, however: Can you assume that customers who did not buy the product never would have, regardless of the number of calls? If the answer is yes, you can simply fit a negative binomial distribution to the subset of customers who ended up buying the product. If the answer is no, however, the resulting prediction interval will underestimate the number of calls until success, because you have a selection bias towards those who bought the product in under $X$ calls.
This does not seem like a trivial problem, and it is certainly not something you can estimate from the results of a $t$-test, so I would recommend hiring a statistical consultant.


What Unity API's are not allowed in async callbacks?

Question: I saw somewhere that within a Thread in Unity, you couldn't use Unity API's.
I'm wondering if this is also the case for async callbacks in general (for example a function assigned to WebSocket.OnMessage when using WebSocketSharp), and if so then is there a way to know what is allowed and what isn't (i.e. what are "Unity API's")?

As an example, when using WebSocketSharp's WebSocket.OnMessage, I put this in my Start function of a MonoBehavior:
// ws is a WebSocketSharp.WebSocket
// displayText is a UnityEngine.UI.Text

ws.OnMessage += (sender, evt) =>
  {
    // 1
    boo = UnityEngine.Random.Range(1, 1000).ToString();
    // 2
    displayText.text = "Heyoo";
  };

The line under 1 errors (no logs just beyond it) but no error message shows. Whereas when that line is not inside this callback (top-level of Update for example), I can see its result no problem.
As for the line under 2, the Inspector in Unity shows the updated text, but the Play screen does not, until I update an attribute in the Inspector, as if the text field did get updated, but when it needed to use a Unity API to update the screen, it failed, so it's not until a separate update happens that it actually appears.
That's my hypothesis for these odd behaviors, so please let me know if that is correct, and if there's a succinct (or documented) way to describe what I'm describing.
Answer: async in general means exactly this: Not in the main thread.
It is hard to answer what is supported and what not in other threads then the mainthread ... short: Most things are not supported.
The UnityEngine.Random.Range(1, 1000).ToString(); should work. But be carefull with assignments!
A known workaround is to create like a callback worker and pass Actions to execute back to the main thread like e.g.:
public class MainThreadWorker : MonoBehaviour
{
    // singleton pattern
    public static MainThreadWorker Instance;

    // added actions will be executed in the main thread
    ConcurrentQueue<Action> actions = new ConcurrentQueue<Action>();

    private void Awake()
    {
        if (Instance)
        {
            this.enabled = false;
            return;
        }
        Instance = this;
    }

    private void Update()
    {
        // execute all actions added since the last frame
        while (actions.TryDequeue(out var action))
        {
            action?.Invoke();
        }
    }

    public void AddAction(Action action)
    {
        if(action != null) actions.Enqueue(action);
    }
}

Having this in your scene somewhere you can now pass an action back to the main thread like
ws.OnMessage += (sender, evt) =>
    {
        MainThreadWorker.Instance.AddAction(()=>
            {
                // 1
                boo = UnityEngine.Random.Range(1, 1000).ToString();
                // 2
                displayText.text = "Heyoo";
            });
    };


rotation of the image in all axes

Question: I have pictures of bottle from six sides (front, back, bottom, top, left, right).
I need to implement rotation on all axes using range sliders. That is, when we rotate one slider and then another, the rotation logic should continue from where we left off.

the first slider rotates the bottle from left to right(back upside down, bottom, front, top,back upside down)
the second slider rotates the bottle from left to right(back, left, front, right,back)
the third slider rotates the bottle from left to right(-180deg, -90deg, 0deg, 90deg,180deg)

Now i'am using hardcoded if else blocks to check what image to show depend on slider values
Please help to correctly form the data structure and the implementation of rotations.
This is how slider looks like
Comment: Please show the code you have so far. See https://stackoverflow.com/help/minimal-reproducible-example
Answer: You could try creating 3 map arrays, where you determine the order of the pictures. You can store in a variable what is the currently shown picture. Based on which slider you use, you know what array you should use the next image from. And the slider ticks can represent all the values in the said array. Hope you get where I am trying to lead.

rotation of the image in all axes


How can I assign a property to a jQuery object?

Question: It is in my understanding that referencing any DOM element in jQuery via the dollar sign (like this: $("#mydiv")), returns an object.
I am looking to add an additional property to an object as such:
$("#mydiv").myprop = "some value";

but this does not seem to work.
I am trying to store a value in this object so I can reference it later.
The following code, though, gives me an undefined value even immediately after I set the property.
$("#mydiv").myprop = "some value";
alert($("#mydiv").myprop);

this code does not work either:
$("#mydiv")["myprop"] = "some value";
alert($("#mydiv").myprop);

Is there a way to achieve this? Or do I need to store all my properties as attributes on the DOM object via $("#mydiv").attr("myprop", "some value") (this is much less desirable).
Thanks!
Comment: i don't think you can do this... you may have to go with your last statement...
Answer: jQuery exposes the concept of a property-bag with the data method.
// set some arbitrary data
$('#selector').data('example-property', exampleValue);

// get the value later
var theValue = $('#selector').data('example-property')

This avoids DOM manipulations which can be expensive in terms of performance.
Answer: The $ function creates a jquery object that represent a dom element. You can change the attributes of the object, but those changes won't be made aparent in the element it "represents" unless jquery knows what to do with them (assigning a click event handler perhaps).
So when you make the first selection, it modifies the object you made, but doesn't do anything to the actual html element. When you run $ again, it creates a SEPARATE object, that does not retain the attribute change you made to the first.
you may be able to make a direct change to an html object: (without jquery)
getElementByID("theid").myprop = "hello world";
resulting in:

 but setting an attribute of a jquery object just won't do it. To get the equivalent effect in jquery, use the .data method that Ken Browning suggested. (too late again...) :D
Comment: thank you very much. this is good to know but not quite what i was looking for. votes up, though.
Answer: I'm not sure wether or not this is due to a change in jQuery. But I've done it pretty much as described in the question...
var domElem = $('#selector');
domElem.myProp = "Hello world";

Now in my case I have to use this object in a method call later on:
Click me!

The method can then do like this:
function SelectAll(domElm){
    alert(domElm.myProp);
}

As I said - it might be an update in the jQuery engine, but it seems that the .data() call is no longer needed :-)


Angular5 - Scrolling to anchor

Question: I am trying to do a scroll to an anchor when I redirect to a new page. I have tried different things but without success. Now it scrolls down but it's not showing the whole HTML element I need, it shows only the header of the element.
Here is the redirect to the new page
this.router.navigate(['/controllo/' + result.id], {fragment: 'assegnazioneContatto'});

And here is how I scroll to the element
ngOnInit() {
    this.routeParams.fragment.subscribe(fragment => {
        if(window.document.getElementById(fragment)) {
          this.fragment = fragment;
          window.document.getElementById(this.fragment).scrollIntoView();
       }
      });
}

Here is the HTML element

What am I doing wrong? I have seen other questions here in stackoverflow but I haven't found any solution.
PS. If I run the code in the console it works fine
Answer: Two options. Have you tried .focus({ preventScroll: false }) or have you tried setting tabindex="1" of the element? Because I had to do that for my own scroll function to have it working properly.
Comment: I tried `tabindex="1"` didn't work. While trying `window.document.getElementById(this.fragment).focus({ preventScroll: false })` gives me this error "Expected 0 arguments, but got 1."
Comment: In my code I don't use window, just document. Not sure why you get an error? The .focus() method can take arguments
Comment: If I run the code in the console works fine also with document. I don't know why is giving me the error
Answer: From your question I have understood that the scroll is behaving in a way that it shows most of the preceding elements and the beginning of your new element.
Does this jsFiddle illustrate your situation? https://jsfiddle.net/eqzkpr8a/3/
Try playing around with the scrollIntoView()'s options: https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView#parameters. Specially the block property, which defines the vertical alignment of the page based on its ancestor element.
In other words, the block property may have four possible values: start, center, end, and nearest.
The properties align the page vertically

start: at the start of its ancestor element;
center: at the center of its ancestor element;
end: at the end of its ancestor element;
nearest: towards the start or the end of its ancestor element, based on whatever is nearest to the scrolled element.
Comment: I tried what you suggested but nothing worked
Comment: could you try instantiating the element as a ViewChild and then performing the `.scrollIntoView()` on its .nativeElement? i.e. @ViewChild('assegnazioneContatto') assegnazioneDiv(): ElementRef; (...) ngOnInit() { this.assegnazioneDiv.nativeElement.scrollIntoView({block:'start'}); }

Angular5 - Scrolling to anchor


EasyOCR script run error - No module named 'torch.backends'

Question: how to deal with such error during script run? Easyocr installed in the new env
File "C:\Users\user\Anaconda3\lib\site-packages\easyocr\detection.py", line 2, in <module>
    import torch.backends.cudnn as cudnn

ModuleNotFoundError: No module named 'torch.backends'

Comment: Does this help you? https://github.com/pytorch/pytorch/issues/4827
Comment: yes, I've seen this one, but solutions there does not help. I've installed pytorch vis this command:
conda install pytorch torchvision torchaudio cudatoolkit=10.2 -c pytorch
Comment: OK, I've noticed couple things:
1. I'm running my script from spyder and I have several environments setup. 1 specifically to run my script.
2. In the custom environment there were no spyder installed, so my script was executed from base environment interpreter and therefore got error from that custom environment.
3. So now I've figure out how to run spyder from specific environment, so current issue is gone. but there is another one related to CUDA memory issues now
Answer: Solved with pip3 install torchvision==0.6, this will install torch 1.5.0 as a dependency automatically.
currently easyocr neither working on the latest 1.11.0 version of torch, nor the 1.4.0 version of torch.


MVC controller not receiving data posted with Invoke-RestMethod

Question: I'm trying to get something similar to this answer and this answer to work where I utilize Invoke-RestMethod to post some variables and a list of files to a controller. However, AFAICT I've correctly adapted the powershell bits, but the MVC controller doesn't like it.
Here's a repro. In a fresh, new MVC 5 application, I've added this method to the Home controller:
[HttpPost]
public ActionResult Upload(string description, HttpPostedFileBase[] files)
{
    if (string.IsNullOrWhiteSpace(description)) return Content("Description is required");
    if (files == null || !files.Any()) return Content("At least one file required");
    return Content("Dummy success.");
}

I try to talk to it like this:
$baseUri = "http://localhost:62441"

$body = @{
    "description" = "Test upload."
    "files" = Get-Content("MyStuff.dll") -Raw
}

Invoke-RestMethod `
    -Method Post `
    -Uri "$baseUri/home/upload" `
    -Body $body `
    -ContentType "multipart/form-data"

# Outputs "Description is required"

Which is a remix of aforementioned (and various other) answers. However, if I run the script the MVC side gets an empty description, and an empty list of files.
Is something in the MVC action causing this? How could I adjust the code (preferably the powershell bit) to make this work?
PS. I've since found this answer that explains how to custom-build the Body, but that's quite a bit of work I'd love to avoid, and given from the answers mentioned in the beginning I suspect that it should actually be possible?
Answer: I welcome anyone with a competing answer, but until that moment I'll claim that this is not (easily) possible with the plain Invoke-RestMethod cmdlet, at least not without wrapping it in another function that builds up the multipart form.
This basically means using my answer to the question I mentioned above, when using that cmdlet you can just call it like this:
$url ="http://localhost:62441/home/upload"
$form = @{ description = "Test upload." }
Get-ChildItem .\MyStuff.dll | Send-MultiPartFormToApi $url $form


Collecting like term of an expression in Sympy

Question: I am currently dealing with functions of more than one variable and need to collect like terms in an attempt to simplify an expression.
Say the expression is written as follows:
x = sympy.Symbol('x')
y = sympy.Symbol('y')
k = sympy.Symbol('k')
a = sympy.Symbol('a')

z = k*(y**2*(a + x) + (a + x)**3/3) - k((2*k*y*(a + x)*(n - 1)*(-k*(y**2*(-a + x) + (-a + x)**3/3) + k*(y**2*(a + x) + (a + x)**3/3)) + y)**2*(-a + k*(n - 1)*(y**2 + (a + x)**2)*(-k*(y**2*(-a + x)))))
zEx = z.expand()
print type(z)
print type(zEx)

EDIT: Formatting to add clarity and changed  the expression z to make the problem easier to understand.
Say z contains so many terms, that sifting through them by eye. and selecting the appropriate terms, would take an unsatisfactory amount of time.
I want to collect all of the terms which are ONLY a multiple of a**1. I do not care for quadratic or higher powers of a, and I do not care for terms which do not contain a.
The type of z and zEx return the following:
print type(z)
print type(zEx)
>>>
<class 'sympy.core.add.Add'>
<class 'sympy.core.mul.Mul'>

Does anyone know how I can collect the terms which are a multiple of a , not a^0 or a^2?
tl'dr
Where z(x,y) with constants a and k described by z and zEx and their type(): How can one remove all non-a terms from z AND remove all quadratic or higher terms of a from the expression? Such that what is left is only the terms which contain a unity power of a.
Answer: In addition to the other answers given, you can also use collect as a dictionary.
print(collect(zEx,a,evaluate=False)[a])

yields the expression
k*x**2 + k*y**2

Answer: In the end it is just an one-liner. @asmeurer brought me on the right track (check the comments below this post). Here is the code; explanations can be found below:
from sympy import *
from sympy.parsing.sympy_parser import parse_expr
import sys

x, y, k, a = symbols('x y k a')

# modified string: I added a few terms
z = x*(k*a**9) + (k**1)*x**2 - k*a**8 + y*x*(k**2) + y*(x**2)*k**3 + x*(k*a**1) - k*a**3 + y*a**5

zmod = Add(*[argi for argi in z.args if argi.has(a)])

Then zmod is
a**9*k*x - a**8*k + a**5*y - a**3*k + a*k*x

So let's look at this more carefully:
z.args

is just a collection of all individual terms in your expression (please note, that also the sign is parsed which makes things easier):
(k*x**2, a**5*y, -a**3*k, -a**8*k, a*k*x, a**9*k*x, k**2*x*y, k**3*x**2*y)

In the list comprehension you then select all the terms that contain an a using the function has. All these terms can then be glued back together using Add which gives you the desired output.
EDIT
The above returns all all the expressions that contain an a. If you only want to filter out the expressions that contain a with unity power, you can use collect and Mul:
from sympy import *
from sympy.parsing.sympy_parser import parse_expr
import sys

x, y, k, a = symbols('x y k a')

z2 = x**2*(k*a**1) + (k**1)*x**2 - k*a**8 + y*x*(k**2) + y*(x**2)*k**3 + x*k*a - k*a**3 + y*a**1

zc = collect(z2, a, evaluate=False)
zmod2 = Mul(zc[a], a)

then zmod2 is
a*(k*x**2 + k*x + y)

and zmod2.expand()
a*k*x**2 + a*k*x + a*y

which is correct.
With the updated z you provide I run:
z3 =  k*(y**2*(a + x) + (a + x)**3/3) - k((2*k*y*(a + x)*(n - 1)*(-k*(y**2*(-a + x) + (-a + x)**3/3) + k*(y**2*(a + x) + (a + x)**3/3)) + y)**2*(-a + k*(n - 1)*(y**2 + (a + x)**2)*(-k*(y**2*(-a + x)))))
zc3 = collect(z3.expand(), a, evaluate=False)
zmod3 = Mul(zc3[a], a)

and then obtain for zmod3.expand():
a*k*x**2 + a*k*y**2

Is this the result you were looking for?
PS: Thanks to @asmeurer for all these helpful comments!
Comment: If you're using strings to manipulate sympy expressions you're doing it wrong.
Comment: @Cleb I removed the downvote. I would just remove the old answer, though. It will still be visible in the edit history.
Comment: @asmeurer: As far as I understood the question, the OP wants to filter all the terms in `z` that contain a parameter `a`. Converting it to a string first was the only way I could get this done since iterating over `z.args` does not allow(?) to check whether `a` is in the element. The `collect` seems not suitable for that either but maybe I use it in a wrong manner. Maybe you could extend your answer, using `z` like I defined it and try to get the same result as I did without converting it to a string first!? I am always glad to broaden my knowledge :)
Comment: Thanks for sharing! Splitting it into a string seems to work well when the expression is all positive. But what if there are negative terms in the expression? I don't think it wouldsplit the terms correctly.

How could I go about doing this is everyother term was negative?
Comment: If ALL of them are negative you have to do `zstr.split('-')` and `' - '.join(res)`.  If there are both `+` and `-`, it becomes a bit trickier. I could try to update the post later on. But according to @asmeurer and at least one other person that is not the way to go - it got even downvoted although it does the job.
Comment: @user2970710: I updated the code. It now also works with mixed signs. Let me know if that answers your question.
Comment: @Cleb you can check if an expression contains a subexpression using `has`, like `term.has(a)`.
Comment: @asmeurer: Ok, thanks, I did not know that. But how would you then glue these terms back together using the appropriate sign for each term?
Comment: In SymPy, subtraction is represented as multiplication by -1. So `x - y` is the same as `Add(x, Mul(-1, y))`. Hence if you split it by args the sign is already on the terms, so to put them back together you just need to do `Add(*terms)`.
Comment: @asmeurer: Thanks so much for those comments! I updated my code; hope it is correct now... Could learn a lot which is worth your downvote ;)
Comment: I have also learned a lot about how to ask a question concisely on this site ^^ Your method workd well @Cleb. However it seems to collect all terms which contain `a`, as opposed to ONLY terms with a unity power of a.

I only wish to "glue together" the terms which contain a**1. Whereas your method provides me with a**9, a**8, a**5 etc.

Apologies for not making this stunningly clear in the first place! I really appreciate your efforts and I think you're pretty close to cracking it :D Hope this helps.
Comment: @user2970710: I updated my post once again; please check the EDIT. Hope that this is the result you were looking for?! :)
Answer: To iterate over the terms of an expression use expr.args.
I'm unclear what a is supposed to be, but the collect function may do what you want.
Comment: Sorry. a should have been defined as another variable:

    a = sympy.Symbol('a')


Must an abstract $C^*$-algebra that is an integral domain be a field?

Question: I'd like to understand a little bit better why the maximal (as opposed to prime) spectrum is the appropriate notion of spectrum for the theory of $C^*$-algebras.
The canonical answer is that $C^*$-algebras have no non-maximal prime ideals: every $C^*$-algebra integral domain is a division ring.  In the commutative case, this is discussed here and here, but both answers use the Gelfand transform in an essential way.  But I'm trying to use that fact to motivate the Gelfand transform in my notes, so this seems a little circular.
Is there an abstract, "algebraic" proof that every $C^*$ integral domain is a division ring?
Some notes:

In general, the class of rings for which maximal spectra suffice to characterize the topology of the prime spectrum is known as Gelfand rings.  But I don't know how to prove that a Gelfand integral domain is a field, or even that a $C^*$-algebra is Gelfand (!!).   (I'm about to ask those questions on MSE too, and will link them when I do.)
My guess is that one should try to mimic the proof that every finite integral domain is a field.  Note that $m_a=(x\mapsto ax)$ is a injective linear operator on $A$.  Showing that $m_a$ is surjective should be possible by some Fredholm theory, whence the claim.
Answer: No; as written, your statement is false.  The correct statement is:

A prime ideal of a $C^*$-algebra is maximal iff it is closed.

In particular, call a $x\in A$ an approximate divisor of $0$ if there exists $\{y_n\}_n$ such that no $y_n=0$ and $\lim_{n\to\infty}{xy_n}=0$.  It is straightforward to see that a prime ideal $P\subseteq A$ is closed iff $A/P$ lacks approximate divisors of $0$.  But then a theorem of Kaplansky (proof below) states that any normed Banach algebra without approximate divisors of $0$ is a division ring.
Kaplansky's proof (in the $C^*$ case)
First, note that we can in fact prove more: the Gelfand-Mazur theorem states that the only normed division algebras over $\mathbb{R}$ are $\mathbb{R}$, $\mathbb{C}$, and $\mathbb{H}$.  $C^*$ algebras are already over $\mathbb{C}$, so we can rule out $\mathbb{R}$ and $\mathbb{H}$.  Thus it suffices to give a proof that $A\cong\mathbb{C}$.
Fix $x\in A$.  $\mathrm{Spec}{(x)}$ is compact and nonempty, so there exists $a+bi\in\partial\mathrm{Spec}{(x)}$.  Swapping $x-(a+bi)$ for $x$, we may assume $a+bi=0$ w/oLoG.
$x$ is not invertible, whilst a limit of invertible elements — say, $\{u_n\}_n$.  If $\{u_n^{-1}\}_n$ were bounded, then $xu_n^{-1}-1=(x-u_n)u_n^{-1}\to0$.  Passing to a weak-*-convergent subsequence of $\{u_n^{-1}\}_n$, we would find an (impossible) inverse of $x$.
Thus $\{u_n^{-1}\}$ is not bounded, and (by passing to a subsequence) increasing in norm.  But $\frac{u_n^{-1}}{\|u_n^{-1}\|}$ is still bounded, so $$0=\lim_{n\to\infty}{(x-u_n)\left(\frac{u_n^{-1}}{\|u_n^{-1}\|}\right)}=\lim_{n\to\infty}{\frac{xu_n^{-1}+1}{\|u_n^{-1}\|}}=\lim_{n\to\infty}{x\cdot\frac{u_n^{-1}}{\|u_n^{-1}\|}}$$  That is, $x$ is an approximate divisor of $0$.
But $A$ lacks approximate divisors of $0$.  So $x=0\in\mathbb{C}$, whence the claim.
Comment: $\{0\}$ is a closed, prime ideal of the Toeplitz algebra but it is not maximal.
Comment: Could you elaborate why for a closed prime ideal $P\subseteq A$, the quotient $A/P$ lacks approximate divisors of zero?


How can a client and a server in seagull diameter work synchronized?

Question: I am working in seagull diameter, This is my scenarios for seagull server and seagull client
Client               Server
   ---- CER ---->
   <--- CEA ----
   ---- AAR ---->
   <--- AAA ----
   ---- STR  --->
   <--- STA  ----

But the Result:

So that it's not follow my scenario, please help me how to config something in  to both server and client could synchronize?
Here is Client Scenario
<?xml version="1.0"?><scenario>

<init>

<send channel="channel-1">
<command name="CER">
</command>
</send>

<receive channel="channel-1">
<command name="CEA"> </command>
</receive>
</init>

<traffic>

<send channel="channel-1">
<command name="AAR">
<avp name="Session-Id" value="trandeptrai"> </avp>
</command>
</send>

<receive channel="channel-1">
<command name="AAA"> </command>
</receive>

<send channel="channel-1">
<command name="STR">
<avp name="Session-Id" value="trandeptrai"> </avp>
</command>
</send>

<receive channel="channel-1">
<command name="STA"> </command>
<action>
<store name="Session-Id" entity="Session-Id"> </store>
</action>
</receive>

</traffic>
</scenario>

Client config:
<?xml version="1.0"?>
<configuration name="jpT DIAMETER client">
<define entity="transport" name="trans-ip-v4" file="libtrans_ip.so" create_function="create_cipio_instance" delete_function="delete_cipio_instance" init-args="type=tcp"> </define>
<define entity="channel" name="channel-1" protocol="diameter-v1"  transport="trans-ip-v4" open-args="mode=client;dest=18.104.22.168:12340"> </define>
<define entity="traffic-param" name="call-timeout-ms" value="10000"> </define>
<define entity="traffic-param" name="files-no-timestamp" value="true"> </define>
<define entity="traffic-param" name="call-rate" value="1"> </define>

</configuration>

Server Scenario:
<?xml version="1.0"?><scenario>
<init>
<receive channel="channel-1">
<action>
 </action>
<command name="CER">
</command>
</receive>

<send channel="channel-1">
<command name="CEA"> </command>
<action>
 </action>
</send>
</init>
<traffic>

<receive channel="channel-1">
<command name="AAR"> </command>
<action>

<store name="Session-Id" entity="Session-Id"> </store>
</action>
</receive>

<send channel="channel-1">
<action>
<restore name="Session-Id" entity="Session-Id"> </restore>
</action>
<command name="AAA">
<avp name="Session-Id" value="1"> </avp>
</command>
</send>

<receive channel="channel-1">
<command name="STR"> </command>
<action>
<store name="Session-Id2" entity="Session-Id"> </store>
</action>
</receive>

<send channel="channel-1">
<action>
<restore name="Session-Id2" entity="Session-Id"> </restore>
</action>
<command name="STA">
<avp name="Session-Id" value="1"> </avp>
</command>
</send>

</traffic>

</scenario>

Server config:
<?xml version="1.0"?>
<configuration name="jpT DIAMETER client">
<define entity="transport" name="trans-ip-v4" file="libtrans_ip.so" create_function="create_cipio_instance" delete_function="delete_cipio_instance" init-args="type=tcp"> </define>
<define entity="channel" name="channel-1" protocol="diameter-v1"  transport="trans-ip-v4" open-args="mode=client;dest=188.8.131.52:12340"> </define>
<define entity="traffic-param" name="call-timeout-ms" value="10000"> </define>
<define entity="traffic-param" name="files-no-timestamp" value="true"> </define>
<define entity="traffic-param" name="call-rate" value="1"> </define>

</configuration>

Comment: Can you add to your post your scenarios and configuration? I created a scenario similar to yours and I'm not seeing the AAR and AAS.
Comment: Hi delepin, i have updated the post
Answer: Both E2E and H2H must be unique to a host that sends request (answer contains the same E2E and H2H). Taking this official guide for example (you may find it in scenario/sar-saa.client.xml):
<traffic>
  <send channel="channel-1">
    <action>

      <inc-counter name="HbH-counter"> </inc-counter>
      <inc-counter name="EtE-counter"> </inc-counter>
      <inc-counter name="session-counter"> </inc-counter>
      <set-value name="HbH-id"
                 format="$(HbH-counter)"></set-value>
      <set-value name="EtE-id"
                 format="$(EtE-counter)"></set-value>
      <set-value name="Session-Id"
                 format=".;1096298391;$(session-counter)"></set-value>
    </action>
    <command name="SAR">
      <avp name="Session-Id" value="value_is_replaced"> </avp>
      <avp name="Vendor-Specific-Application-Id">
        <avp name="Vendor-Id" value="11"></avp>
        <avp name="Auth-Application-Id" value="167772151"></avp>
        <avp name="Acct-Application-Id" value="0"></avp>
      </avp>
      <avp name="Auth-Session-State" value="1"> </avp>
      <avp name="Origin-Host" value="seagull"> </avp>
      <avp name="Origin-Realm" value="ims.hpintelco.org"> </avp>
      <avp name="Destination-Realm" value="ims.hpintelco.org"> </avp>
      <avp name="Server-Name" value="seagull"> </avp>
      <avp name="Server-Assignment-Type" value="3"> </avp>
      <avp name="User-Data-Request-Type" value="0"> </avp>
      <avp name="Public-Identity" value="sip:email@example.com"> </avp>
      <avp name="Destination-Host" value="hss.ims.hpintelco.org"> </avp>
    </command>
    <action>
      <start-timer></start-timer>
    </action>
  </send>

  <receive channel="channel-1">
    <action>
      <stop-timer></stop-timer>
    </action>
    <command name="SAA">
    </command>
  </receive>
</traffic>

There are two actions before and after command which would be run before and after send SAR. Now you are having these terms the same, which would cause 'corruption' and hard to read/identify from package capture, and I believe this is the reason their sequence is disordered. And this is my experience to use SEAGULL:

One can always look up seagull log, whose path is defined in server/client's description file in conf folder, for what might go wrong.

whatever command is defined in <init> will only run once. It means that  for receive, the second time a packets is received would cause unrecognized xxx in log. For example in the example, if a second CER is received, log says received unrecognized CER. If this happens, I usually reboot ksh or put receive CER in traffic.

scenario is run with a sequence. For example, if a scenario defines in sequence receive CER send CEA receive DWR send DWA, a DWR without a proceeding CER would cause received unrecognized DWR. And this would be the most often case, when one looks for reason why a DWA is not received from seagul server.
BTW, it deserves to mention that unless a send or receive is defined in init, otherwise it continues to "ping-pong".`
Answer: You could try setting the simultaneous calls to 1, that way your client will wait until the current call is over to start another one.
Add this line to your server and client configuration:
<define entity="traffic-param" name="max-simultaneous-calls" value="1"></define>

The default value for this property is 100, so surely that's why your capture shows mismatched requests and answers.
Comment: Thanks delephin, but i think that it's seem not match with my question, we have 3 mated pairs commands
Comment: You're right. I should have re-read the question before answering. Let me get back to you later.
Comment: thank so much for you efforts, Delephin, the process run orderly, but do you know how can the flow reaches to STR <---> STA?
Comment: Can you explain further?
Comment: For example the order is:
Client          Server
   ---- CER ---->
   <--- CEA ----
   ---- AAR ---->
   <--- AAA ----
   ---- STR  --->
   <--- STA  ----
Comment: Your flow is not exchanging SessionTermination avps? You can always edit the question to add more info, the comment box is quite restrictive.


angular highlight searched text

Question: I am using AngularJS for a search functionality and created a custom filter to highlight the searched text inside the results.
Below is my filter (JS):
var myApp = angular.module('myApp', []).filter('highlight', function($sce) {
    return function(query, phrase) {
      if (phrase) query = query.replace(new RegExp('('+phrase+')', 'gi'),
        '$1')

      return $sce.trustAsHtml(query)
    }
});

And the related HTML:
<input ng-model="query" ng-keyup="search()" type="text" data-ele="home_search" class="form-control" id="exampleInputAmount" placeholder="">

After adding the filter, errors will appear and I don't know the reason.
Any help is appriciated.
You can also check this behavior at this URL.
Comment: What kind of errors it shows?
Comment: TypeError: Cannot read property 'replace' of undefined. but you can look at the console in that like.
Answer: Are you using angular-sanatize.js file to return the inline style from the controller?
I wrote a non-regex solution to your problem. Not exactly an answer to your issue but feel free to use this Codepen Example.
Hope this helps :)
Comment: *angular-sanitize
Answer:  <input id="searchText" type="search" placeholder="Search Asset..." ng-model="searchText" />

Answer: The code you've provided isn't enough for me to give you a working example with your code. However, I'm assuming you want to highlight a keyword inside a DOM element. Then have a look at mark.js, a keyword/search term or custom regular expression highlighter.
Example:

var markInstance = new Mark(document.querySelector(".context"));
function highlight(){
    var searchTerm = document.querySelector("input").value;
    markInstance.unmark().mark(searchTerm);
}
mark{
    background: yellow;
}

<input type="text" placeholder="Lorem ipsum..." oninput="highlight()">

  Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.

Comment: Yes it can be done with this but as i want to learn that using angular
Comment: @AshishJoshi you can of course put this into a AngularJS function container, e.g. a directive.
Comment: @AshishJoshi Also, you could always open a feature request [here](https://github.com/julmot/mark.js/issues/new), describing your use case and a built-in solution might be implemented soon.

angular highlight searched text


unable to apply css inside shadow root ionic 5

Question: I created tab application and need to expand active tab but I'm not able to apply CSS under the shadow element like below.refrence
I want to give
Overflow : "visible"   to .button-native inside shahow root

expected result.
Please help.
Answer: I got my respective example  the beautiful tabs in ionic 5
https://github.com/rajneshbiz/ionic-custom-components/tree/master/ionic-v4-v5/tabs-custom-icon-floating-button
Answer: I created a recursive method and I called in the AfterViewInit hook..
setStyle() {
    const all = document.querySelectorAll('.tab-has-icon');

    if(all.length === 0) {
      setTimeout(() => {
        this.setStyle();
      }, 0);
      return;
    }

    all.forEach(el => {
      el.shadowRoot.querySelector('.button-native').setAttribute('style','overflow: inherit')
    });
  }

Answer: I find 2 metods in SASS: you cant use pseudoelement ::part, this you can find in your button shadow
<button type="button" class="button-native" part="native"><slot name="icon-only"></slot><slot name="start"></slot><slot></slot><slot name="end"></slot><ion-ripple-effect role="presentation" class="md hydrated"></ion-ripple-effect></button>

you can see part ion-button is "native" so your css can be:
  ion-button::part(native){
overflow: visible!important;}

and in javascript you can access to shadown element like:
 document.querySelector("ion-button")
    .shadowRoot
    .querySelector(".button-native").setAttribute("style","overflow:visible")


Pass IwebElement into html agility pack C#

Question: I have in trouble with this:
I have an internal HTML of my company. In this page, I have a table. I want to convert HTML table to DataTable in C#:
Here is my code:
IWebElement ie = driver.FindElement(By.XPath(".//*[@id='frmClaimSearch']/div[2]/div[1]/div/table"));

ie.GetAttribute("innerHTML");//get Element of the HTML
var doc = new HtmlDocument();

doc.Load("????");

var nodes = doc.DocumentNode.SelectNodes(".//*[@id='frmClaimSearch']/div[2]/div[1]/div/table/tr");
var table = new DataTable("MyTable");

var headers = nodes[0]
            .Elements("th")
            .Select(th => th.InnerText.Trim());
foreach (var header in headers)
{
    table.Columns.Add(header);
}
var rows = nodes.Skip(1).Select(tr => tr
            .Elements("td")
            .Select(td => td.InnerText.Trim())
            .ToArray());
foreach (var row in rows)
{
    table.Rows.Add(row);
}
@id='frmClaimSearch']/div[2]/div[1]/div/table/tr");
var table = new DataTable("MyTable is my XPath of Table.

But these codes line do not work. I tried so much. Help me please. Many Thanks.
Answer: Use LoadHtml() method instead of Load() to populate HtmlDocument from HTML string :
IWebElement ie = driver.FindElement(By.XPath(".//*[@id='frmClaimSearch']/div[2]/div[1]/div/table"));

string innerHtml = ie.GetAttribute("innerHTML");
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(innerHTML);

.......


How do I construct the likelihood function for a series of observed Bernoulli-distributed datapoints?

Question: I have observed N (a_i, p_i) pairs each drawn from a different Bernoulli distribution. Here a_i are observed amplitudes and p_i are observed probabilities of success for the
i^{th} draw.
I would like to model the full likelihood distribution (and not just via the MLE) with a view to identifying which draws belong to the successful class (and hence the statistics of just these draws, especially any irregular uncertainty distributions etc.).
For example, I have
<code>a_i p_i p_true
10 0.2 0
100 0.9 1
11 0.1 0
99 0.93 1
12 0.25 0
</code>
I know the PDFs of the model and of the data (both are obviously Bernoulli distributions), but how do I combine them to obtain residuals that I can use to explore the joint distribution? What distribution does the joint distribution follow and how?
I have tried to unpack the cross-entropy and data and model but don't have a clear solution.
Is the continuous Bernoulli distribution a complete red herring?
Note that ordering doesn't matter in my example. Some other points in response to comments:

The p_i values come from an oracle - these represent the probabilities that the datapoints belong to a common class.

The amplitudes a_i are just weights for the corresponding Bernoulli distributions. The higher the amplitude, the higher the scaling of the Bernoulli distribution in its contribution to the overall process.

See also:
"Weighted" Poisson binomial distribution
Weighted sum of Bernoulli distributions
https://math.stackexchange.com/questions/3481907/sum-of-weighted-independent-bernoulli-rvs
What is the CDF of the sum of weighted Bernoulli random variables?
Please let me know if you need any more information to assist in answering. Thanks as ever!
Comment: What model? Could you explain it.
Comment: *"Is the continuous Bernoulli distribution a complete red herring?"* This sentence is unclear. What is the 'continuous Bernoulli distribution' and how does it connect with the rest of the text?
Comment: Is p_i directly observed or is it some modeled value based on a_i?
Comment: *"a_i are observed amplitudes"* amplitudes of what?
Comment: What is 'p_true' in your table? Is it the true value of p? How do you know it and why does it only have values 0 and 1?
Comment: p_i comes from an entirely separate model.
Comment: @SextusEmpiricus Good point. I am getting at: Since I'd like to explore (sample from) the full likelihood, do I need to invoke a non-discrete version of the PDF?
Comment: *"weights for the corresponding Bernoulli distributions."* I don't have a clear idea what this means. Weights can occur in all sort of ways. The Bernoulli distribution has only a single parameter $p$, how you include the weight in your problem is unclear.
Comment: Each distribution is scaled in value by the weight (amplitude).
Comment: *"Each distribution is scaled in value"* What do you mean by scaling in value of distributions? I do not get this context.
Comment: Feel free to continue asking Qs - I will add clarification into the question as necessary
Comment: I believe that is is better to explain your concrete problem instead of using these abstract terms. None of my questions are really clarified.
Answer:
I know the PDFs of the model and of the data (both are obviously Bernoulli distributions),

Bernoulli distributions are not characterized by a probability density function (PDF) and instead are characterized by a probability mass function (PMF).

but how do I combine them to obtain residuals that I can use to
explore the joint distribution?

In many problems the observations are assumed to be independent and are multiplied. For instance if you have two pmf's depending on some parameter $p$ like $$P(X_1=x_1;p) = f_1(x_1,p)$$ and $$P(X_2=x_2;p) = f_2(x_2,p)$$ then the pmf for the joint probability is $$P(X_1=x_1 \land X_2=x_2 ;p) = f_1(x_1,p)f_2(x_2,p)$$.
For Bernoulli distributions the observations $X_i$ are discrete, but the parameter $p$ is continuous. So if you use this to make a likelihood function, then you get a continuous function.


Is it possible to see the output of cURL in the TravisCI console?

Question: I am integrating HockeyApp with TravisCI, but when using the wrong HockeyApp Token value, I couldn't see any issue in the TravisCI console output. Running the CURL in Terminal quite clearly displayed the error:
{"errors":{"credentials":["api token invalid"]}}

is there anyway to display in the TraveisCI console, the results of cURL, when called from a build-and-upload.sh script?
I tried to do the following with our success:
rtn = $(curl http://....
echo $rtn

The return I got was interesting, but it was displayed even if the build wasn't uploaded.
Trying to echo the rtn value also clearly failed.
***************************
* Uploading to Hockeyapp  *
***************************
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                             Dload  Upload   Total   Spent    Left  Speed
100  216k  100    48  100  216k     27   124k  0:00:01  0:00:01 --:--:--  124k
./scripts/sign-and-upload.sh: line 33: rtn: command not found

Answer: Doh! I was caught out by the space on either side of the =
rtn=$(curl http://....

This works!


Boundedness of the first Fréchet derivative

Question: Let $(E,\Vert\cdot\Vert)$ be a normed vector space and $f:E \rightarrow \mathbb{R}$ be a twice Fréchet differentiable function with $\sup_{x \in E} \frac{\vert f(x)\vert}{1+\Vert x\Vert^3} < \infty$ as well as
\begin{align}
\Vert D^2f(x+h) - D^2f(x) \Vert_L < C_1 \Vert h\Vert \qquad \forall x,h \in E
\end{align}
for some constant $C_1$. For a multilinear form $B$ on $E$ we used here the notation $\Vert B \Vert_L:=\sup_{\Vert x \Vert=1} \vert B[x,\ldots,x]\vert $.
Why does this imply
\begin{align}
\Vert Df(x)\Vert_L < C_2 (1+\Vert x\Vert^2) \qquad \forall x \in E
\end{align}
for some constant $C_2$?
Comment: Apparently the condition on the supremum above is not even needed (see the answer below)
Answer: Let $y\in E$ arbitrary. Then
$$
F(t)=Df(tx)(y), \quad t\in\mathbb R,
$$
is a real valued differentiable function and $F'(t)=D^2f(tx)(x,y)$. Mean Value theorem implies that, there exists a $t^*\in (0,1)$, such that
$$
Df(x)(y)-Df(0)(y)=F(1)-F(0)=F'(t^*)=D^2f(t^*x)(x,y)
$$
Hence
$$
\| Df(x)(y) \| =\|D^2f(t^*x)(x,y)+Df(0)(y)\|\le \|D^2f(t^*x)\|\|x\|\|y\|+\|Df(0)\|\|y\|
$$
and thus
$$
\| Df(x)\| \le \|D^2f(t^*x)\|\|x\|+\|Df(0)\| \\
\le \|D^2f(t^*x)-D^2f(0)\|\|x\|+\|D^2f(0)\|\|x\|+\|Df(0)\|
\\ \le C_1 \|t^*x\|\|x\|+\|D^2f(0)\|\|x\|+\|Df(0)\| \\ \le C_1\|x\|^2+\|D^2f(0)\|\|x\|+\|Df(0)\|
$$


excluir registo de uma tabela sql

Question: Boas pessoal eu quero apagar um registo de uma tabela mas para isso preciso de ir buscar informação a outras tabelas e por causa disso não estou a conseguir apagar.

Eu basicamente precisava de um comando SQL que recebesse o id do paciente da tabela pacientes, via quais os id_agregado pertencem a esse paciente na tabela utenteagregado e apagava tudo pertencente a esse id_agregado na tabela agregado. Eu já tentei mas todos os comandos dão me erro de sintax.
Obrigado
Comment: sua pergunta está muito ampla, por favor, adicione suas consultas SQL que causam erros, se possível crie a estrutura e os dados em http://sqlfiddle.com/ e adicione o link aqui
Comment: Ja esta resolvido, obrigado.
Answer: Olha se ajuda
DELETE FROM AGREGADO
WHERE AGREDADO.ID_AGREGADO IN (
  SELECT utenteagregado.ID_AGREGADO FROM utenteagregado
  WHERE utenteagregado.ID_PACIENTE = ?
)

Comment: Muito obrigado, exatamente isso que eu queria

excluir registo de uma tabela sql


For a Cycle Graph is there only one Spanning tree?

Question: For example a Cycle Graph C200 has only 1 spanning tree right?
Because adding just one edge to a spanning tree will create a cycle?
Answer: Technically, $C_n$ will have $n$ spanning trees ($n$ choices for the edge you you delete). But they are all isomorphic (paths of length $n-1$), so it depends on whether you want to consider them as distinct or the same.
Comment: So would a Cyclic graph ie, $C_100$ will have 100 spanning trees
Comment: @Bloer yes it would
Comment: @Bloer: Hint:  to get multidigit subscripts, enclose them in braces, so C_{100} will give $C_{100}$ instead of C_100 giving $C_100$


Select element by class name AND text content?

Question: I'm trying to select a div with class mstrmojo-ListBox-item selected nAll and content Market Risk. I tried this:
$("[class^='mstrmojo-ListBox-item']","div:contains('Market Risk')")

However it returns all the nodes with this class, like it omits the second argument.
var a = $("[nm='Sel_Team_ListB']")
$(a).filter(function() {
  return $(this).text() === 'Market Risk';
})

It returns an empty string.
var a = $("[nm='Sel_Team_ListB']")
$(a).find("div:contains('Market Risk')", "[class^='mstrmojo-ListBox-item']")

This one is the closest, yet it returns all the parent nodes of the one I'm after as well.
How to do this properly? Thanks.
Comment: Assuming you're looking for the class and context of a single element, you need to combine the selectors: `$('div[class^="mstrmojo-ListBox-item"]:contains("Market Risk")');`
Answer: As of now, you are setting second argument as context
Where as you need to combine the selectors.
$("div:contains('Market Risk')[class^='mstrmojo-ListBox-item']")


Installing apache+mysql on primary hard drive or secondary?

Question: I'm installing a fresh copy of apache and mysql on a windows 2008 server with two hard drives
Primary one is naturally running the OS and more
The second drive is for the websites (php scripts)
Where should I install the Mysql and Apache for better performance.
Answer: You really won't notice a major performance difference unless you're getting a massive surge of traffic. If so, put it on the disk with the fastest RPM. However, you may want to put all this on the larger disk if you imagine it'll grow beyond the size of the smaller disk.
Answer: In general you want the database on a disk that does not have much in the way of other demands on it. with that in mind install Mysql and Apache on the primary and store the database files on the second drive along with the site content.


How to serialize a diff of two folders optimally in C++

Question: I'm trying to develop a file diff format for multiple files recursively in folders. Consider a source directory containing patched files and a destination directory containing original files. Write a size minimal diff file which expresses the difference between all files in the source and destination directory which can be applied to the original files in order to transform the original files into the patched files.
For this purpose I found the dtl library. Which algorithm or feature of the library should I use to write a file diff to the disk which I can then later read back and apply in order to patch the file?  Any example code for this? I tried writing the result of the shortest edit script (SES) to the disk but I realized that I needed to specify the character and operation for every single byte. This of course makes the output file bigger than the entire comparison file, making this diff format entirely redundant since storing the entire target file instead would've saved more storage.
As another reference, this is very similar to how version control systems like git or svn operate but I don't want to use those since I'm mainly dealing with binary files and the simple requirement of creating and applying patches.
Comment: [GDIFF](https://www.w3.org/TR/NOTE-gdiff-19970901)
Comment: afaik neither git nor svn actually care what is the filetypes, be it binaries or text or whatever
Comment: @eerorika: Thanks, that's a good link
idclev463035818: Right
Answer: After doing some more search, I found the HDiffPatch project.
It worked fine apparently but it seems to take long on bigger folder comparisons:
diff usage: hdiffz [options] oldPath newPath outDiffFile
patch usage: hpatchz [options] oldPath diffFile outNewPath

EDIT:
Another good option is open-vcdiff but it only supports individual files.
Answer: use HDiffPatch: you can run hdiffz with "-s-48" for up speed;
or try "-s-32" , "-s-1k", "-s-128k" ...


Disable Radio button if default value is "inactive"

Question: I need to disable other radio button(s) when [#default_value] => Inactive as in below code it is?
I tried with different ways but unsuccessful. Kindly let me know how to do that?
PHP CODE
foreach($form['field_complaint_status'] as $key=>$val)
{
    echo '
'; print_r($val['field_complaint_status']); exit;
}

Output
Array
(
    [#type] => container
    [#attributes] => Array
        (
            [class] => Array
                (
                    [0] => field-type-list-text
                    [1] => field-name-field-complaint-status
                    [2] => field-widget-options-buttons
                )

        )

    [#weight] => 13
    [#tree] => 1
    [#language] => und
    [und] => Array
        (
            [#entity] => stdClass Object
                (
                    [vid] => 544
                    [uid] => 754
                    [title] => Complaint/Feedback
                    [log] =>
                    [status] => 1
                    [comment] => 1
                    [promote] => 1
                    [sticky] => 0
                    [nid] => 544
                    [type] => complaint_or_feedback
                    [language] => en
                    [created] => 1492408487
                    [changed] => 1492587955
                    [tnid] => 0
                    [translate] => 0
                    [revision_timestamp] => 1492587955
                    [revision_uid] => 754
                    [field_type] => Array
                        (
                            [und] => Array
                                (
                                    [0] => Array
                                        (
                                            [value] => Complaint
                                        )

                                )

                        )

                    [field_complaint_status] => Array
                        (
                            [und] => Array
                                (
                                    [0] => Array
                                        (
                                            [value] => Inactive
                                        )

                                )

                        )
                    [cid] => 0
                    [last_comment_timestamp] => 1492408487
                    [last_comment_name] =>
                    [last_comment_uid] => 754
                    [comment_count] => 0
                    [menu_node_links] => Array
                        (
                        )
                    [picture] => 0
                )

            [#entity_type] => node
            [#bundle] => complaint_or_feedback
            [#field_name] => field_complaint_status
            [#language] => und
            [#field_parents] => Array
                (
                    [0] => field_complaint_status
                    [1] => 0
                )

            [#columns] => Array
                (
                    [0] => value
                )

            [#title] =>
            [#description] =>
            [#required] => 1
            [#delta] => 0
            [#type] => radios
            [#default_value] => Inactive
            [#options] => Array
                (
                    [Active] => active
                    [Inactive] => inactive
                )

            [#value_key] => value
            [#element_validate] => Array
                (
                    [0] => options_field_widget_validate
                )

            [#properties] => Array
                (
                    [filter_xss] => 1
                    [strip_tags] =>
                    [strip_tags_and_unescape] =>
                    [empty_option] =>
                    [optgroups] =>
                )

            [#after_build] => Array
                (
                    [0] => field_form_element_after_build
                )

        )

    [#access] => 1
)

Comment: Where is you radio button code?
Comment: I created it using manage field of a content type. I didn't code it.
Comment: what is the field name??
Comment: its name is field_complaint_status as I already mention in my question.
Answer: You can use the #states property to achieve that. The #states property can be applied to all Form API elements.
  $form['student_type'] = array(
    '#type' => 'radios',
    '#options' => array(
      'high_school' => t('High School'),
      'undergraduate' => t('Undergraduate'),
      'graduate' => t('Graduate'),
    ),
    '#title' => t('What type of student are you?'),
  );
  $form['high_school'] = array(
    '#type' => 'fieldset',
    '#title' => t('High School Information'),
    // This #states rule says that the "high school" fieldset should only
    // be shown if the "student_type" form element is set to "High School".
    '#states' => array(
      'visible' => array(
        ':input[name="student_type"]' => array('value' => 'high_school'),
      ),
    ),
  );

References :
states
form_example_states_form
Comment: Please re-read my question I asked about **disable** other values (radio buttons) of the same field as above mentioned **[#default_value]**. **[#default_value]** means the same field. Your answer is referring to show/hide fields as [Conditional Fields](https://www.drupal.org/project/conditional_fields) works.
Comment: Can you provide  image of the form?
Comment: I have figured out. See my answer below
Answer: I have done with JS, See code below
jQuery(".inactive input").each(function(index, element) {
    jQuery(this).attr("disabled",true);
});


Modify localstorage?

Question: I'm using simplecartjs to power an online store. It stores it's data in local storage, which looks like this:
{"SCI-1":{"quantity":1,"id":"SCI-1","price":20,"name":"Mattamusta -teippi","size":"Tyhjä"},"SCI-3":{"quantity":1,"id":"SCI-3","price":19,"name":"Mohawk .vaimennusmatto 48 x 39cm"},"SCI-5":{"quantity":2,"id":"SCI-5","price":8,"name":"Car Speaker -hajuste","color":"Green Tea"},"SCI-7":{"quantity":1,"id":"SCI-7","price":50,"name":"Asennuspaketti"},"SCI-9":{"quantity":1,"id":"SCI-9","price":30,"name":"Quartz-kalvot","color":"Yellow","size":"50cm x 30cm"},"SCI-11":{"quantity":1,"id":"SCI-11","price":30,"name":"Quartz-kalvot","color":"True Blue","size":"50cm x 30cm"}}

And I want to add this line before it's closed.
"SCI-12":{"quantity":1,"id":"SCI-12","price":5,"name":"Toimituskulut"}

However, the amount of products will depend on user, and so on SCI-12 must grow with the number of items.
EDIT Actually, it doens't have to use SCI-1, it can be anything, as long as it's after the items.
EDIT2
Here's what I'm trying... But without luck.
$("#matkahuolto").click(function(){
    var value_object = '"Toimituskulut":{"quantity":1,"id":"Toimituskulut","price":5,"name":"Toimituskulut"}';
    var json_object = JSON.parse(localStorage.your_json); // convert string to object

    json_object["simpleCart_items"] = value_object; // add value

    localStorage.your_json = JSON.stringify(json_object);  // store it again.

    });

    $("#posti").click(function(){
    var json_object = JSON.parse(localStorage.your_json); // convert string to object

    json_object["simpleCart_items"] = value_object; // add value

    localStorage.your_json = JSON.stringify(json_object);  // store it again.

    });

EDIT3 A screenshot of localstorage.
Comment: Oh, didn't notice that. Odd it is then, as I want it to be displayed as another product.
Comment: I'm not sure, but I would say after. The whole local storage is a mystery for me.
Answer: The first thing you need to understand is how items are stored in localStorage, which is basically like a hashmap/dictionary in that the items are stored in key value pairs.
For example to store a string localStorage you would do something like
localStorage["myKey"] = "some value";

To retrieve the value you would just to the reverse
var myValue = localStorage["myKey"];

The next thing to realize is that you can in fact only store strings in localStorage, so if you want to store a object you need to first convert it to a string representation. This is usually done by converting the object to JSON which is a compact notation used to represent an object as a string. To convert an object to JSON you just use the JSON.stringify method, and to parse an item you use the JSON.parse method
For example to convert an object to JSON
var someObject = {id: 1, name: 'Test'};

var jsonSomeObject = JSON.stringify(someObject);
// jsonSomeObject looks like "{"id":1,"name":"test"}"

And to read an object from JSON
someObject = JSON.parse(jsonSomeObject);

So now in your case assuming that your object contains the appropriate data all you need to do is stringify your object and add it to localStorage using some key,
var jsonData = JSON.stringify({"SCI-12":{"quantity":1,"id":"SCI-12","price":5,"name":"Toimituskulut"}});

localStorage["aKey"] = jsonData;

and when you want to access this data later (presumably after coming back to the page)
var mySCI = JSON.parse(localStorage["aKey"])

If you are trying to update a specific entry in localStorage then you would just read it in and then overwrite it, for example
var mySCI = JSON.parse(localStorage["aKey"]);
mySCI.SCI-12.quantity = 2;
localStorage["aKey"] = JSON.stringify(mySCI);

Keep in mind that while most browsers have built in support for JSON some older ones don't, if this is an issue you can include Douglass Crockfords JSON-js script to provide support.
Edit:
Based on the screenshot you just posted, you can see that the key under which the values are stored in localStorage is in fact simpleCart_items (and not your_json which are using in your code), and that the object that is being stored has a object stored under the key "SCI-1) (and probably others under "SCI's"). So what you would need to do is something like the following
 $("#matkahuolto").click(function(){
    var value_object = {quantity: 1, id: 1, name: "someName"} ;
    var jsonObject = JSON.parse(localStorage["simpleCart_items"]);
    json_object["SCI_1"] = value_object; // add value

 localStorage["simpleCart_items"] = JSON.stringify(json_object);  // store it again.

});

$("#posti").click(function(){
 // convert string to object
 var json_object = JSON.parse(localStorage["simpleCart_items"]);

json_object["SCI-1"] = value_object; // add value

 localStorage["simpleCart_items"] = JSON.stringify(json_object);  // store it again.

});

Comment: So, if I understand correcly, when I look at local storage, it has a key called `simpleCart_items` and a value of `{"SCI-1":{"quantity":1,"id":"SCI-1","price":20,"name":"Valkoinen hiilikuitu -teippi","size":"Tyhjä"}}`. So I have to retrieve the value before modifying it, and add the data I want?
Comment: Not quite, from the code you provided your accessing a key *your_json* and in that object there is a key *simpleCart_items*, I edited my answer based on this. If this isn't the right key you will need to modify your code accordingly.
Comment: your code has the right values, but the local storage looks the same.
Comment: I'm not sure I understand, are you sure you are accessing the right key in your localstorage?
Comment: I think you meant you updated your *question*. Anyway I updated my anwser based on your edit.
Comment: Oops, yeah, that's what I meant. I'll try this now.
Comment: Seems to be working, however this is a **bit** out of my understanding. Thanks!
Answer: LocalStorage stores all data as as string of text.  So it would be easiest to modify it before it has been converted to a string of text.
Otherwise you need to pull the json string into an object, add the property, convert it back to a string and store it.
Sample Code
var json_object = JSON.parse(localStorage.your_json); // convert string to object
json_object[key] = value_object; // add value
localStorage.your_json = JSON.stringify(json_object);  // store it again.

Note
This is what indexedDB is for.
One might want to consider this as a substitute.
Comment: @pure_code Why do you always delete your comments? All that does is confuse people because they can't see your conversation

Modify localstorage?