Are there any composer instructions on how to play a melody?

Question: In modern times (after recording a melody/song was possible) we have a fair idea on how the original composer imagined his composition to be played (most often he would be the one recording/mastering it).
What about in older times when no recording was possible, were there any notations or instructions on music sheets, or accompanying material, where the composer would describe the approach his music should have when played?
I understand there are multiple musical notations on intensity, speed, sustain etc but my question is more about "sentimental" instructions. Like Wagner e.g describing the intended way for "Ride of the Valkyries" to be played is as "all hell broke loose and coming to get you" or Beethoven noting that "Moonlight Sonata" should be interpreted as the "sadness embracing you while watching something beautiful and calm"...
EDIT: Do we know of any such original composer notes/material?
I can see an example here

 in the video description ""effect that matches the performance instructions, which are to play each piece "painfully", "sadly" or "gravely".""
Comment: Not only olden times. Last week my instruction for playing an introduction was 'play it like you're making love with a French lady'. I'm searching for exactly the right inspiration...
Comment: You mention Beethoven's "Moonlight" sonata, and its first movement is a good example of a piece whose composer gave a lengthy instruction on how to play it. Beethoven marks its first movement "Adagio sostenuto" and gives the instruction "Si deve suonare tutto questo pezzo delicatissimamente e senza sordino" ("Play all of this piece very delicately and without the soft pedal").
Comment: sometimes the title tell's as so: *prelude*, *nocturno* or *french kiss* 3Y8w2W1uy2A
Comment: @Rosie *senza sordino* doesn't mean without the soft pedal, it means without dampers, i.e., hold the damper pedal down for the whole movement.  Seriously.
Comment: @CamilleGoudeseune Ah, my mistake. Must've got my *con sordino* mixed up with my *una corda*.
Comment: @AlbrechtHügli Ah, the subtle discreetness.
Comment: Satie in particular played around with this sort of thing.  Though most of his instructions are somewhat whimsical and open for interpretation, e.g. "*With great benevolence*", "*With clairvoyance*", "*Alone for a moment*", "*On the tongue*", etc.  He was a bit of an oddball.
Answer: This practice as you describe it became more popular in the Romantic period, with Beethoven essentially serving as the bridge from Classic to Romantic. During this age the image of the artistic composer-genius began to be intertwined with mysticism around inspiration and the creative process. Belief in the supernatural was also hugely popular at this time.
Composers in prior periods gave less or hardly any expressive indications in their music. They relied on standard performance practice of the time and for performers to embellish their music (as was common practice). Modern editions of many baroque pieces include ornaments that wouldn't have been written in during the time period, as both composers and performers would have known what to do.
As technology (over the last century in particular) has given birth to "equality of voice" pedagogical and aesthetic zeitgeist has fractured and widened to a point where for the contemporary composer, it is absolutely necessary to include many details in a given piece.
So how did older performers know? They were taught. Performance practice became an oral tradition, and techniques were passed down. How do we know what they knew? A mix of oral / practice tradition and scholarly research finding old treatises and journals.
Answer: If my dictionary gets it correctly, this is called expressive mark (in German Vortragsbezeichnung).
Examples of those not relating to speed or dynamics are:

giocoso
dolce
animato
grave

Robert Schuman was aware of the deficiencies deriving from those terse words and frequently gave lengthy instructions as

Nicht schnell, immer sehr leise (not fast, and throughout quiet).

Another example by Debussy can be found in this question.
Answer: Programm music (19th century) was in itself a program (MOLDAU, PICTURES OF AN EXHIBITION) how the music should be performed. In earlier compositions where compositions were illustrating the lyrics actually the text or the title tells as how to play it:
e.g.:
dances of  suites
madrigals (pastorales)
cantatas (symbolism)
operas (underlying sound track to lyrics and action)
so it was not a reason for the composer to tell the musicians how to play a piece, it was the theme that told the composer how to write the music. The way was leading in the opposite direction.
example:
madrigal
https://study.com/academy/lesson/madrigal-definition-history-quiz.html
"To increase the dramatic impact of a story, madrigal composers came up with a technique called word painting, or text painting, is an attempt to musically represent the lyrics of a song." ...
Answer: Very often in early music, this kind of information was encompassed by the title and/or tempo markings (or lyrics, when present). However, I can think of two examples of more explicit instructions from the Baroque; one well known, and one not-so-much.
In Vivaldi's famous "The Four Seasons" concertos, there are notes in the various movements explicitly indicating certain effects such as "the birds", "the barking dog", "languor caused by the heat", "the drunkards have fallen asleep", and "the storm".
A less well-known example is Heinrich Biber's Battalia à 10 (1673), a suite of movements representing a battle, with events preceding and following it (there are movements named "The March" and "Lament of the Wounded Musketeer"). The 2nd Movement, titled "Die liederliche Gesellschaft von allerley Humor" ("the dissolute company of all sorts of humor"), is a polytonal mish-mash of various common songs written one on top of another without thought for creating polyphony. The bass part -- which normally would indicate the continuo harmonies -- has the instruction "hic dissonat ubique nam ebrii sic diversis cantilenis clamare solent." ("Here it is dissonant everywhere, for thus are the drunks accustomed to bellow with different songs.")


Statistics version of "What is..." columns in Notices

Question: Each issue of the AMS monthly magazine Notices contains a "What is..." column. This column is an expository article on a given topic, e.g. "What is...Noncommutative Topology". Do statisticians have something similar?
Answer: These days you often find such stuff in blogs! Here are two favourites of mine:
andrewgelman.com
normaldeviate.wordpress.com/


Cannot bind to multicast address (Windows)

Question: I am trying to write an application that listens to a number of multicast groups using Windows sockets.
The problem I'm running in to is that when I go to bind the socket, if I try to bind to the multicast group address and port this fails with WSAEADDRNOTAVAIL.  If I instead bind to INADDR_ANY and the port, then I can still receive other unrelated traffic destined for the same port.
When I implemented the same thing in Linux, I didn't have any issues binding to the multicast address (in fact, I saw it recommended several places to avoid getting unrelated traffic for the port).
Is this just not available with Windows sockets?  I assume I could filter traffic myself by using WSARecvFrom and peeking at the headers, but I'd rather a simple solution if one exists.
Also, this is running on Windows Server 2008.
Comment: I'm having the very same issue with Windows sockets. It looks like Windows sockets don't accept bindings on multicast IPs, which makes it imposible to prevent the socket from receiving unrelated trafic from other IP on the same port.
Comment: I'm here to concur with what others have said, after a decent amount of investigation, I haven't found any way to bind to the multicast address and prevent other traffic on the port from coming through.
Answer: While the doc for bind() does not say that this unsupported, it does say in the remarks:

For multicast operations, the
  preferred method is to call the bind
  function to associate a socket with a
  local IP address and then join the
  multicast group....

Maybe this scheme will yield better results?
Comment: Yes, as I mentioned in the original question, you can do this, however it does not prevent a recv on that socket from getting unicast data for the port.  I so for have not found a solution, other than to do a WSARecvMsg and examine the packet info to see the real destination address.
Comment: Sorry I thought setsockopt() with IP_ADD_MEMBERSHIP was supposed to filter out non-group traffic for the socket regardless of the address specifiedin bind().


Trying to push new object into array (should be very simple, new to javascript)

Question: Very new to javascript - basically I have a simple HTML form wherein one can enter their first name, last name, and number, and I want to add that to the array contactList but I'm running my head into a wall! My console.log command is showing an empty array.
var contactList = [];

function Contact(f, l, n) {
    this.fname=fname;
    this.lname=lname;
    this.num=num;
}

    var submit = document.getElementById("submit");
    submit.onclick = function(){
        var firstname = document.getElementById("fname").value;
        var lastname = document.getElementById("lname").value;
        var number = document.getElementById("num").value;

        contactList.push(new Contact(firstname, lastname, number));
    }

console.log(contactList);

Answer: you are using undefined variable inside Concat constructor. you pass (f,l,n) and assign fname,lname,num
edit it to be:
var contactList = [];

function Contact(f, l, n) {
this.fname=f;
this.lname=l;
this.num=n;
}

var submit = document.getElementById("submit");
submit.onclick = function(){
    var firstname = document.getElementById("fname").value;
    var lastname = document.getElementById("lname").value;
    var number = document.getElementById("num").value;

    contactList.push(new Contact(firstname, lastname, number));
}

console.log(contactList);

Answer: There are two reasons why you don't see new value in the contactList array:

If you use input or button elements with type submit inside of the form element, click on it will trigger the HTTP request to the URL specified in form's action attribute - this will reload your page, so you will lose the page context and you will see an empty contactList
Your last console.log statement is outside of your click handler, so it will be executed with (at that moment) empty contactList right after registering click handler.

To fix the second issue just move console.log inside of your click handler. The first issue could be fixed in different ways:

Don't use control of type submit. This will not trigger page reload
At the very beginning of your click handler use preventDefault method on event, which is passed as argument to click handler function. This will have prevent the default action of clicking on control of type submit. For example:
submit.onclick = function(e){
    e.preventDefault();
    // ...
}
Don't use the form element at all if you need just collect some values from inputs and process them somehow.

Also, as @Omar Elawady mentioned in another answer - you have wrong assignments inside of your constructor. You pass (f,l,n) and assign fname, lname and num
Comment: Tried this and it didn't work. Something weird actually happens, something briefly flashes on my console and then it disappears, leaving an empty console window. Perplexed.
Comment: @vikram add `e.preventDefault();` at the beginning of you submit handler. It seems like you use regular form so click on submit will reload your page and will clean your page context. `e` is a parameter passed to `submit` handler. Check out @adeneo's answer for it
Comment: @vikram or just use  or any other element styled as button instead of  and `onclick` handler.


Convergence of error term

Question: I was deriving the ratio of a Laplace approximation with the true quantity and I got this:
$$
\left(n\bar{x} + \alpha - \frac{1}{2}\right)\log\left(\frac{\bar{x}+(a-1)/n}{\bar{x}+\alpha/n}\right) + n\log\left(\frac{1+(\alpha+\beta-1)/n}{1+(\alpha+\beta-2)/n}\right),
$$
where $\bar{x}$ is the sample mean of an i.i.d. Binomial($1$, $\theta$) random sample of size $n$,  and $\alpha,\beta>0$.
I'm having trouble seeing if this thing converges to $0$. Can anyone please help? A gentle hint would be greatly appreciated.
Comment: Two popular ways of showing the limiting quantity of a function in statistics is: a) use L'Hospital's Rule and b) find a bounding function above or below who's limit is 0 or $\infty$ respectively. It seems pretty straightforward albeit detailed to do a), my hunch is that the quantity, as written, does *not* go to 0 as $n \rightarrow \infty$.
Comment: @AdamO Thanks for the help. Although, I don't think L'Hospital directly applies here since (after absorbing the multiplicative term into the log) the numerator and the denominator don't go to $0$ or $\infty$ simultaneously. I might be wrong...
Comment: Then look for a bounding function and make it easier on yourself
Answer: Set
$$z_n \equiv n\bar x +\alpha, \;\;\; \alpha + \beta -2 \equiv \gamma,\;\;\; x_n \equiv n+\gamma$$
The the expression can be re-written as
$$(z_n - 1/2)\cdot\ln\left(\frac{z_n -1}{z_n}\right) + (x_n -\gamma) \cdot \ln\left(\frac{x_n +1}{x_n}\right) $$
$$=\ln\left(1-\frac{1}{z_n}\right)^{z_n} - \ln\left(1-\frac{1}{z_n}\right)^{1/2} + \ln\left(1+\frac{1}{x_n}\right)^{x_n} - \ln\left(1+\frac{1}{x_n}\right)^{\gamma}  $$
Do you see where this approach is going?
Comment: $\exp(1)+\exp(-1)$! Wow this transformation is neat! Thanks a million!
Comment: @mkmlp  You're welcome. I guess this means that the expression does go to zero (due to logarithms)?
Comment: yes you're right. Sorry when I wrote $\exp(1)$ and $\exp(-1)$ I meant those are the limits of the terms inside the logarithms...got too excited

Convergence of error term


controlling length of the line of best fit in R

Question: I have plotted a graph which has a line of best fit. However, I want to make sure the line isn't touching the y- or x-axis. Is there a way to control its length?
I am currently using the code:
plot(Perimeter~Average.tortuosity, data=T.R,xlim=c(0,5), xlab="Path tortuosity", ylab="Territory perimeter", pch=19)
abline(lm(Perimeter~Average.tortuosity, data=T.R))

Thanks
Comment: Probably not using `abline`. You'll probably have to use `segments` or something equivalent.
Answer: If you only want to plot part of the regression line, you'll have to extract the points yourself. Abline draws a "line" which extends infinitely in both directions. But you can use the predict function to get a y for any x.
#sample data
dd<-data.frame(x=1:10, y=cumsum(runif(10)))

plot(y~x, dd)
mm<-lm(y~x, dd)

#lines from 4 to 8
nx<-c(4,8)
ny<-predict(mm, newdata=data.frame(x=nx))
lines(nx,ny, col="red")

And that results in


Get text from multiple cells of another sheet into 1 cell

Question: I know how to get text from 1 cell on another sheet into another sheets' cell.
But I can't seem to find a way to get text from 2 cells of another sheet into another sheets' cell.
I use the current formula to get 1 text from 1 cell:
<code>=HLOOKUP($C$1;Rooster!$1:29;27;FALSE)
</code>
The cell on the other sheet (Rooster) are below each other.
An example sheet (editable):
https://docs.google.com/spreadsheets/d/1-Eyb9C-O9d-Fjd5jbdGb1T23lWRyCDu0tUY9dGC63UU/edit
Clarifying issue
We have schedule (unfortunately I can't share the original one), but in that schedule, there are 2 fields, in 2 rows.
I can get the value from one of the fields using the above function (field is coming from index 27). Now what I want to do is getting values from both fields (indexes 27 and 28) and add them to a single field (separated by a comma).
I tried the following codes, but they do not work:
<code>=HLOOKUP($C$1;Rooster!$1:29;{27,28};FALSE)
</code>
Or:
<code>=ARRAYFORMULA(HLOOKUP($C$1;Rooster!$1:29;{27,28};FALSE))
</code>
Or even:
<code>={HLOOKUP($C$1;Rooster!$1:29;27;FALSE),=HLOOKUP($C$1;Rooster!$1:29;28;FALSE)}
</code>
Is this even possible?
Comment: please share a [sample sheet](https://docs.google.com/forms/d/e/1FAIpQLScf4e8rJpjbDx-SQOH2c2xIaUP-ewnNJoqv9uRAXIrenUvZ_Q/viewform) with example of your data and desired result.
Comment: @udarts, cell C1 is empty so we have no data to work with.
Comment: Please ensure that your question has well-defined inputs, desired outputs, and the requirements that explain their relations. A text-based example, such as sharing an editable example sheet could be a good start.
Comment: @z.. hereby a sample link: https://docs.google.com/spreadsheets/d/1-Eyb9C-O9d-Fjd5jbdGb1T23lWRyCDu0tUY9dGC63UU/edit
Answer: I managed to figure it out, using the ARRAYFORMULA works, but I was using a comma instead of a semicolon.
I am now using it as followed (comma separated the values):
<code>=ARRAYFORMULA(JOIN(", ";HLOOKUP($C$1;Rooster!$1:29;{27;28};FALSE)))
</code>


Backdrop color behind background Android app

Question: Having trouble identifying what this is actually called. In most apps you see this portion blend with the color of the toolbar. Which is what I would like to do in this case. (The area in question is the blueish segment above the toolbar)
Answer: It's called a status bar (the blue thing)


How to install Chosen using Drush Make?

Question: From Chosen module page:

This module comes with a Drush make file, which will automatically download the jQuery plugin if you use Drush make to set up your website.

I have Drush Make, but commands like..
 drush dl chosen
 drush en chosen

..don't help.
Should I use drush make ... command instead? Maybe there are other commands for quick libraries download.
P.S. I'm working on already installed copy of Drupal.
Answer: I found a way:
# cd to Drupal root folder
drush dl chosen
drush make sites/all/modules/chosen/chosen.make.example --no-core
drush en chosen -y

Update 04/29/2014: Chosen now provides Drush command chosenplugin.
This answer is still useful for other projects with *.make.example files but without custom Drush installation commands.
Answer: for the latest version of chosen I usually do the following
drush dl chosen
drush chosenplugin
drush en chosen -y
You not only need to download the drupal module (drush dl chosen) but also the chosen jQuery library (drush chosenplugin) in order for the module to work.
Comment: Thanks @Jen for your answer! Good to know. For projects with Drush Make files (usually `modulename.make.example`) but without custom Drush commands (like `chosenplugin` or `colorbox-plugin`) it is still possible to download external libraries and other dependencies with trick in my answer.

How to install Chosen using Drush Make?


Wait for uninstaller to finish using batch

Question: I would like to uninstall a few programs using batch and wait for each program to finish uninstalling before doing the other. The problem is that some of these uninstallers don't call other programs and aren't in the task manager, so START /WAIT wouldn't work. Any ideas would be helpful.
Comment: If those programs were installed internally through an .msi package then maybe it'll be possible to use `start /wait MsiExec.exe /X{5481F163-B9E5-30A8-8441-4DBBB87D6AA2}` for example. The exact product code can be found using `reg query`.
Comment: they aren't. They are custom uninstallers, where the the uninstaller isn't even in the task manager during the uninstall. I'm not sure what programs it is calling.
Comment: 1. The uninstall string should be present in `HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall` or `HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall`. 2. The process should be visible on the `processes` tab in the task manager.
Answer: Assuming you are using Windows and that the programs were installed with .msi packages,
Uninstalling a program in a batch file is as easy as using MSIEXEC. Full documentation on using MSIEXEC can be found on Microsoft Technet
To find the GUID of the installation that you would like to Uninstall, just use wmic in Command prompt:
wmic product get > C:\InstalledProgramsList.txt

Then navigate to C:\InstalledProgramsList.txt and use ctrl + F to find the desired product and associated GUID
Comment: Thanks for your quick reply. 2 things: I don't see in the link provided where I can wait until the install is done before continuing. Also, my programs are 64 bit using an installer that doesn't register with the WMIC.
Comment: @Wajo357 If you create a batch script for Windows with msiexec, each command will be run sequentially when the previous command has finished. Additionally, `wmic product get` should work for all x64 & x86 applications that are installed as `.msi packages`
Comment: @Wajo357 Ah I see that you are working with a custom installer. Try searching through: `HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall` OR `HKEY_CLASSES_ROOT\Installer\Products`
Answer: Ok. I think I got it. This is the code I'm using, where I created a subroutine that waits for the task to finish.
:waitforuninstallation
timeout /T 1 /NOBREAK >nul
tasklist /FI "IMAGENAME eq %1" 2>NUL | find /I /N "%1">NUL
if %ERRORLEVEL% EQU 0 goto waitforuninstallation
exit /b

This can be called using:
call :waitforuninstallation PROGRAMNAME.exe

Where PROGRAMNAME is the task running in the task manager.
Edit: made the subroutine carry an argument
Answer: There's a really annoying trend with free installers made by NSIS:  Cisco Amp, Folding@Home, PsychoPy, Anaconda, PyCharm.  The uninstaller exe quits, and something called Un_A.exe takes over and does the rest.  In this case, you'd have to wait for that process to finish instead.
powershell while (! (get-process Un_a -ea 0)) { sleep 1 }; 'waiting'; wait-process Un_a

Or if you want the exit code of un_a:
powershell while (! ($proc = get-process Un_A -ea 0)) { sleep 1 }; $handle = $proc.handle; 'waiting'; wait-process Un_A; exit $proc.exitcode

Comment: _The NSIS uninstaller copies itself to the temporary directory, runs the temporary uninstaller created and then exits. This is done so it will be able to delete itself._ (c) [When I use ExecWait uninstaller.exe it doesn't wait for the uninstaller?](https://nsis.sourceforge.io/When_I_use_ExecWait_uninstaller.exe_it_doesn't_wait_for_the_uninstaller)
Comment: @AntonK This is a bad design from an administrator's point of view.  You don't normally know when the uninstall completes, and what the error code is.  Plus uninstalling one version, and upgrading to a newer version becomes tricky, since both the uninstaller and the installer can run at the same time.


Dynamic - Automated multiplication - Pandas dataframes

Question: after spending quite a while search and reading on Stackoverflow and around the web, I am desperate...
I have a Pandas DataFrame with some imported data (spectra). The first column is the wavelength while the others are the various spectra (the data). The names of the columns are imported from a list that reads the filenames from a path and keeps just the names.
What I would like to achieve and I can't quite seem to get how is to multiply each of the columns with the wavelength column and either overwrite the existing ones or create a new dataframe (doesn't matter that much).
This is the code I have so far that does the job (even if not the most elegant, it get's the job done):
path = r'"thePathToData\PL_calc\Data_NIR'
idx = 0

#Create the DataFrame with all the data from the path above, use the filenames as column names
all_files = glob.glob(os.path.join(path, "*.asc"))
df = pd.concat((pd.read_csv(f, usecols=[1],  sep='\t') for f in all_files), axis=1) #usecol=1 for the spectrum only

fileNames = [] # create a list for the filenames
for i in range(0,len(all_files)):
    fileNames.append(all_files[i][71:-4])

df.columns = fileNames # assign the filenames as columns
wavelengths = pd.read_csv(all_files[0], usecols=[0],  sep='\t') # add the wavelength column as first column of the dataframe
df.insert(loc=idx, column='Wavelength', value=wavelengths)

If I plot just the head of the DF it looks like this:
Wavelength  F8BT_Pure_Batch1_px1_spectra_4V  \ ...
0    478.0708                        -3.384101
1    478.3917                        -1.580399
2    478.7126                        -0.323580
3    479.0334                        -1.131425
4    479.3542                         1.202728

The complete DF is:
1599 rows × 46 columns

Question 1:
I can't quite find an automated (dynamic) way of multiplying each col with the first one, essentially this:
for i in range(1, len(df.columns)):
    df[[i]] = df[[0]] * df[[i]]

Question 2:
Why does this work:
df['F8BT_Pure_Batch1_px1_spectra_4V'] = df['Wavelength']*df['F8BT_Pure_Batch1_px1_spectra_4V']

while this doesn't and gives me an "IndexError: indices are out-of-bounds"
df[[1]] = df[[0]]*df[[1]]

But when I print(df[['Wavelength']]) Name: Wavelength, dtype: float64 and print(df[[0]]) [1599 rows x 1 columns] I get the same numbers..
Question 3:
Why does this df[fileNames] = df[fileNames].multiply(df.Wavelength) give me a ValueError: Columns must be same length as key? All the columns are of the same length (1599 rows long, 0-1598 and a total of 46 columns in this case). fileNames contains the names of the imported files and the names of the columns of the dataframe.
Many many thanks in advance for your help...
Alex
Answer: Question 1
To multiply your wavelength column by every other column in your DataFrame, you can use:
df.iloc[:, 1:] = df.iloc[:, 1:].mul(df['Wavelength'], axis=0)

This assumes your wavelength column is the first column.
Question 2
Selecting columns like that using an integer is asking for columns of your DataFrame that are named 0, 1, etc., as ints. There are none in your DataFrame. To select columns by index number look into the documentation for pandas' iloc method.
Question 3
When you call df[fileNames], you are getting a a DataFrame with the same number of columns as the length of your list fileNames. Your code df[fileNames].multiply(df.Wavelength) is not giving you a DataFrame with the same number of columns as df[fileNames], hence you cannot assign the values. Using the axis=0 parameter in the multiply function is working for me.
Comment: Fantastic... Thank you so much for your help! I will study a bit on the iloc methods...


Quartz 2D -Drawing a point

Question: I know that drawing a point by using drawing a line method in Quartz 2D is
CGContextMoveToPoint(context,x,y-0.5f);
CGContextAddLineToPoint(context,x,y+0.5f);

Is there any other possible way to draw a point using Quartz?
I meant, some direct way of doing so?
Comment: What do you mean by "point"? A pixel? A rectangle of one by one point dimension? The presented code draws a diagonal line, not a point.
Comment: @NikolaiRuhe oops added wrong code.Sorry,edited.I am mentioning about a pixel
Answer: CGContextFillRect(context, CGRectMake(x,y,1,1));

Answer: if you want it to look like a circular point try this:
CGContextStrokeEllipseInRect(context, CGRectMake(x, y, 4, 4));

it will draw for you you a an ellipse inside a rectangle (above case is apparently a square). i prefer you to choose a square as it will look like a real circle and not oval one. however, this circle will be empty from the inside, you can fill it by a stroke. (but it looks cool like a donut!) :)

Quartz 2D -Drawing a point


What are some examples of filter Correct faulty and chopped off HTML?

Question: In Drupal one of the text filters that is enabled by default is the filter Correct faulty and chopped off HTML. As I understand it must fix HTML bugs.
Can anybody please give some example(s) of situations, where it can help?
I am confused, because if I do not close some tag (for example DIV), and save the result, then I get the same result in both cases (= it doesn't matter if that filter is turned on or off).
Answer: In Drupal, there is rule that a text filter should never change anything that the user saves.  The "Correct faulty and chopped off HTML" follows this rule. That is why you don't see any changes in the body field when you edit.
However, the filter will fix your HTML when the text in the body field is rendered (i.e. displayed to the user).
For instance, if you use the Drupal 6 or 7 "Filtered HTML" text type (which makes use this filter) and put the following faulty and chopped off HTML in the body (this is all you put in the body of a node):

xyzzy

and examine the rendered HTML in your browser (for instance using Ctrl-U or Firebug in Firefox), you'll see that it is corrected to:

xyzzy

Screen shots
Text in editor:

Rendered text, as displayed by Firebug:
Comment: I know about this rule. May be you do not understand me.
I see the result in firebug . And any different when  the filter is turned on and when off - I do not see.

Even if I use your exapmle. You can try it too, and see.

May be in drupal render function this filter is present to?
Otherwise how to explain it?
Comment: "You can try it too, and see." I did. I've now added screenshots from the editor and from Firebug to the answer to illustrate what I see.  What I observe on my test site (a clean install of Drupal 7) is clearly different from what you see.  (I've no idea why you're unable to see it, but I am pretty confident that this text filter works the way I've described it.)
Comment: Yes, but if you go to the admin/config/content/formats/filtered_html and disable filter "Correct faulty and chopped off HTML"  - You will see the same result. Nothing will change.

 The question is, why did this filter need? and why if it disabled we get the correct html in output?
I don not understand. Thank you for you time and answer.
Comment: Sorry, please. You were write. I do not understand why I see the same result in both cases.  May be it was the browher cache.
I check many time, before I write here. When I  clear cache site and browser and test again, I see the result of filter.

I asked this question here, because I really could not understand how this could be.
But now everything is clear.  Thank  you.
Comment: @bigferumdron Depending on what browser you use, and how you're inspecting the source, you might be getting fooled. Chrome, for example, will correct your faulty HTML in the inspector for you. So `xyzzy` will appear as `xyzzy`, unless you actually view the raw source of the page. It's worth remembering, that's caught me out a few times before. Always right click, view source to get the full picture
Answer: Refer to these 3 issues that contain a reference to that "Correct faulty and chopped off HTML" filter.
In these cases it has to do with the usage of some 3rd party library that generates something (like SVGs), which occasionally may produce xHTML that is not 100 % correct. Refer to this issue comment for an illustration of how I ever got in XML parsing errors, because of such HTML filter issues ...
So if you're a module (co-)maintainer using a 3rd party library that has such issues, then this faulty-work around is about the only thing you can do to address that somehow.


Como acessar uma Rota de um projeto (URL) escrito em Laravel de um outro projeto (URL) que não usa Laravel?

Question: Digamos que eu tenha myApp1.com e myApp2.com, e que somente o segundo projeto está escrito em Laravel.
A minha pergunta é:
Levando em consideração que myApp2.com possui autenticação de login, seria possível criar um link em myApp1.com que iria direcionar para uma rota em myApp2.com ?
//myApp1.com
Faça algo em myApp2.com

//myApp2.com
Route::get('/fazerAlgo', 'outConttroler@fazerendoAlgo')

Answer: Completamente,
Ficaria assim:
myApp1.com
Faça algo em myApp2.com

myApp2.com
Route
 Route::get('do-something', 'DoSomethingController@do_something');

Controller
public function do_something()
{
    echo "Hello World";
}

Acabei de testar funcionou perfeito aqui.
OBS: É claro que sua sessão de autenticação não seria passada para o myApp2.com
Espero ter ajudado.
Comment: ok... se vc já testou então está beleza. Mas não parece estranho?  De que serve então os filtros de autentição? Como o laravel permite isso? Entáo poderíamos criar um form em um outro servidor para ter acesso a controllers dentro do myApp2.com?
Comment: Por isso você deve usar token nos formulários, para evitar esse tipo de acesso indesejado.
Comment: Veja aqui https://laravel.com/docs/5.2/routing#form-method-spoofing


How can I perform arithmetic on integers of arbitrary size?

Question: My original codes here..
function AddNumStrings(Str1, Str2: string): string;
var
  i: integer;
  carryStr: string;
  worker: integer;
  workerStr: string;
begin
  Result:= inttostr(length(Str1));
  Result:= '';
  carryStr:= '0';

  // make numbers the same length
  while length(Str1) < length(Str2) do Str1:= '0' + Str1;
  while length(Str1) > length(Str2) do Str2:= '0' + Str2;

  i:= 0;
  while i < length(Str1) do begin
    worker:= strtoint(copy(Str1, length(Str1) - i, 1)) + strtoint(copy(Str2, length(Str2) - i, 1)) + strtoint(carryStr);
    if worker > 9 then begin
      workerStr:= inttostr(worker);
      carryStr:= copy(workerStr, 1, 1);
      Result:= copy(workerStr, 2, 1) + Result;
    end else begin
      Result:= inttostr(worker) + Result;
      carryStr:= '0';
    end;

    inc(i);
  end; { while }
  if carryStr <> '0' then Result:= carryStr + Result;
  Application.ProcessMessages;
end;

function yeni(s1, s2: string): string;
var
  j, i, k: integer;
  c: char;
  s: string;
begin
  k:= length(s2);
  j:= length(s1) - length(s2);
  for i:= j downto 1 do begin
    c:= s1[i];
    k:= k + 1;
    if (c <> '9') and (c <> '0') then begin
      s:= copy(s1, i, k);
      s:= AddNumStrings(s, s2);
      Setlength(s1, i - 1);
      Result:= s1 + s;
      break;
    end;

    Application.ProcessMessages;
  end;

  procedure TForm1.Button13Click(Sender: TObject);
  var
    i, k: integer;
    s: Ansistring;
  begin
    s:= '1111';
    for i:= 1 to 1000000 do begin
      for k:= 1 to 120 do begin
        s:= yeni(s, '4');
      end;
    end;
  end;

end.

Finally my string s has to be 1,000,000,000 length. But it takes me 68 days I think.
How can I speed up this code?
Comment: @DavidHeffernan: It's not that difficult to tell what he's trying to do, and seriously, is all this really necessary?  If you put half the effort you've put into insulting and belittling this poster into actually trying to help him, you'd have come up with an answer by now...
Comment: possible duplicate of [Delphi 7 working fast string?](http://stackoverflow.com/questions/19530665/delphi-7-working-fast-string)
Comment: Do not post the same question again under a different account. Instead, edit your [original question](http://stackoverflow.com/q/19530665/62576) and improve it, so we can tell what you're asking.
Comment: @mason It's easy to answer this question. The string can be evaluated at compile time! It's just not the right question. The asker has said that the real problem is different. Ken already gave the same answer as yours, essentially when he asked the same question. He'll keep asking the same question unless we tell him to ask the **right** question.
Comment: Allocate the entire string up front, and then fill out the contents. It might help if you learnt how to indent code. It would also help if you didn't ask how to do stupid pointless tasks quickly and instead told us the real problem.
Comment: Yes ı understand what you say. I did. but my program is tooks 1 hour.ıs it good choise using Strbuilder?
Comment: David Hefferman can you contact me? I see u 15-20 times. We can chat? My English is not well.
Comment: Why don't you just ask a real question with the real problem? No string builder in d7. One call to SetLength is all you need here. One single heap alloc. But so what, this is not the real problem. What's the point in making this code quick. Quickest solution is a string literal! Answer is known at compile time.
Comment: Yes u are right. It is part of my codes. Actually, my codes are tooks 68 day for real working time? How can I solve my problem? I dont know anything. Im searching everyday it. But result is false. Delphi and programmings are hobby for me. I like them.
Comment: Can anybody convert my codes to asm. Asm is a good choise?
Comment: You need to be able to ask the question. This one, and your previous one won't get you anywhere. Describe the real problem. In a new question. We'll help you make it a good question. The questions you've asked so far are no good.
Comment: I have a dream. And ı learnt delphi for my dream and ı learnt Php, Html,Css. They are my hobbies. But ı cant solve this problem. This problem is last walla between ı and my dream. Ha?
Comment: Please help me, ı can pay you money. Just ı have to solve it. I dont know what can ı do? Everpeople says same thing. But ı have same problem still.
Comment: I wrote my progrem for 2 years. Everything ı learn and write my program. My teacher is google. This program takes from 2 years.
Comment: @mason take a look at the comment to Johan's answer, and tell me I was wide of the mark. :-)
Comment: OK, that's better. Could you give us a high level view of the goal of this code?
Comment: @user2912813, can you please stop using `ı` for `I`. I in english is uppercase. It is not written using the symbol that you're using.
Comment: Ok Johan.and David Hefferman I dont say it. I said its my dream.
Comment: @Dimsak I understand you're frustrated to get this issue of yours solved. However you must understand this is a Q/A site for enthusiast and professional programmers. There's a certain way you need to ask your questions to be reasonably answerable. Not only that, but you're expected to have at least a basic understanding of what you're trying to do, and make sure that we can clearly understand what you're trying to do. We're not here to teach you how to do things, and we're also not here to write code for you, and we're certainly not here for you to recruit your own coder.
Answer: Your code is choking on a variant of Shlemiel The Painter's Algorithm.  Every time you add two strings together like that, the Delphi RTL has to increase the size of the string, which possibly involves allocating a new, larger string and copying the old string over, then freeing the old string.  When you do this 10 million times, all that memory copying and reallocation is going to add up.
What you need to do to get this to run quickly is figure out up-front how long the finished string will be, then call SetLength on s and allocate your large string from the beginning. After that, keep track of the index of the highest char that hasn't been "filled in" yet. Each of your IntToStr calls will yield a new string; insert the | character and then copy the IntToStr results over, updating the index as you go.  That should dramatically cut down the time it takes for this code to run.
Comment: Much better will be to get rid of the calls to IntToStr which involve heap alloc. Make those calls stack based.
Comment: @DavidHeffernan: Interesting idea, but where are we going to find a stack-based `IntToStr`?
Comment: Well, sprintf will do nicely. I expect there's something native in the Delphi RTL in sysutils too.
Comment: FormatBuf looks like our guy
Answer: You are trying to do arbitrary precision arithmetic using strings.
This is a bad idea.
Use a bigint library instead.
It uses arrays of integer to do the job.
A nice one is downloadable at: http://www.delphiforfun.org/Programs/Library/big_integers.htm
Or at LURD's suggestion: https://code.google.com/p/gmp-wrapper-for-delphi/
Comment: This library will do the job, [`http://gmplib.org/`](http://gmplib.org/). A delphi wrapper can be found here, [`The GNU Multiple Precision Arithmetic Library Wrapper For Delphi`](https://code.google.com/p/gmp-wrapper-for-delphi/).
Comment: Yes ı used it but it doesnt work for me.It says limited 500.000 digis for time consideration. But my sring's length is 1.000.000.000
Comment: So remove the limitation from the code. It's much much faster than your code. I've worked with this code and know of no such limitation though.
Comment: OK, is that it? You want arbitrary precision arithmetic? Use a bigint library indeed. My advice, switch to Python, and use one of the excellent big int libraries there.
Comment: But I dont know Python.
Comment: So what? You don't know Delphi either. Or how to write a big int code. In Python you only need to learn the language and it is much easier.
Comment: Johan but when Im using this, It takes more time for me. What seconds takes for you for 123456789^123456789? I  run it but program was locked. Not responfing my laptop. And I close it from Taskmanager.
Comment: David u are right but I dont have enough time. I finished University and I m working now as Mechanical Engineering. I dont enough time. So my web site is waiting for 6 mounths. I couldnt finish it yet. Please I need it for Delphi. May be after I will learn Python.
Comment: LU RD I downloaded it but I couldunt understand. How it help me?
Comment: This is why I suggest a more approachable solution. There are good big int libs for Delphi but they are hard to get into for less advanced devs.
Comment: There is a demo in the delphi wrapper download.
Comment: David Hefferman you want to see my original codes. Thare is my original codes that I wrote. Well, why dont you help me? Why did you want to see my original codes? Will anybody help me? ı m waiting here.
Comment: Yes LU RD but it is a game. What will ı do? I couldnt understand.
Comment: You've got your answer already. Use a big int lib. You've had the help that you need. Why won't you just heed the advice?
Comment: David I couldnt understand. But Bigint doesnt calculate 1.000.000.000 digit number. I couldnt understand. you say gmp lib or bigint lib. ?
Comment: @Dimsak, you are trying to do arithmetic with numbers around 1.000.000.000 digits. Doing this with strings and slow concatenation is not the correct solution. We are pointing to a solution, use this advice.
Comment: Kind of crazy you reject Python. You are not a skilled programmer, so it's too hard for you to write you own library. It's also too hard for you to install and use third party library. In Python you write x = y + z and built in have arbitrary precision arithmetic.
Comment: LU RD yes I see and hank you so so much. But I coulndt have eny result. And big problem is my English is bad. So I couldnt understand clearly. What will I do. Can you write an exmaple?
Comment: Well, Is there any limitation Length of integer or string in Python?
Comment: Bigint test is not calculate 987654321^123456 "Not Responding" program is locked.
Comment: Your English is good. You need to slow down and ask a simple question. For example, "How can I perform arithmetic on integers of arbitrary size?"
Comment: @Dimsak Please don't be a help vampire: http://meta.stackexchange.com/questions/19665/the-help-vampire-problem  It's bad form.
Comment: David thank you. And david I ask you: How can I perform arithmetic on integers of arbitrary size?
Answer: Obviously this is a silly example but there's a few things you can do:

Know what happens when you call a Delphi function
Know your data
Move stuff outside the loop
Don't jump unless its predictable

Let me elaborate
Know what happens when you call a Delphi function
When you call an RTL function, like string:= string + someotherstring
Delphi will perform a concat operation. This involves resizing the string allocation (if needed) and moving the string (if needed) to a new location in memory.
If you do this many times all of the storage allocation will start to add up. In fact it you double the function to 20,000,000 runs you'll find that the runtime more than doubles.
So you avoid this nonsense and move those costly functions out of the loop.
Know your data
As soon as s[index] = 0, any multiplication will be 0. You can use this knowledge to speeds things up a lot. Some people call this cheating; in this case that may be true, but in a more complex case knowing what your data will do can get you very nice speeds ups.
Furthermore you know that multiplying a single digit times nine can never yield a result > 81 so you need not check more than 2 chars.
Move stuff out of the loop
Once you know your data you can move stuff out of the loop, so instead of doing them many times, you only do them once.
Even if the stuff outside the loop takes 10,000 times longer than the stuff inside the loop. It's still a good deal.
Don't jump unless its predictable
In this case this doesn't apply because the function will quickly stabilize on outputting a steady stream of zeros, but I put it in for demonstration purposes anyway.
In fact an if here will be faster than no if because the jump breaks a dependency chain.
Code example
procedure TForm1.Button4Click(Sender: TObject);
const
  NumberOfCharsForKToSettleTo0 = 10;
  ManyTimes = 10 * 1000 * 1000
var
  i,j,k,l:integer;
  s:string;
begin
  //preallocate the length of the string
  SetLength(s, 4 + (ManyTimes * length('|1')) + NumberOfCharsForKToSettleTo0);
  s:='1369';
  l:= 4;
  for i:=1 to ManyTimes do begin
    j:=i mod 9;
    //k:=strtoint(s[Length(s)])*j; don't use strtoint
    k:= ord(s[l]) - ord('0');
    k:= k*j;
    //s:=s+'|'+inttostr(k);
    inc(l);
    s[l]:= '|';
    inc(l);
    s[l]:= chr(k div 10+ord('0'));
    inc(l,integer(k>9));  //avoid jumps/ifs that are hard to predict.
    s[l]:= chr(k+ord('0'));
  end;
end;

Comment: Thank you Johan and Mason Wheeler. Can you help me for my real codes?If u can ı will share below. This codes is part of my codes.
Comment: @Johan The string can be evaluated at compile time
Comment: @DavidHeffernan, I know. That's what I said when noting that it will quickly stabilize into a long line of zeros (separated by `|`).


returning pointer to a pointer in c

Question: I'm trying to return a pointer to a pointer from a function.
I have the following function
char **foo() {
 const char **bar;
 ...
 return bar;
}

and I get the following warning:
warning: return from incompatible pointer type [enabled by default]

what am I missing?
Comment: You need to decide, is it `const`, or is it not `const`. Can't have both...
Answer: You can't jsut cast away the const qualifier like that. It points to pointers to const chars. You can however:
 const char **foo() {
   const char **bar;
   ...
   return bar;
  }

Answer: bar is declared as const char ** but you are returning char **
Answer: That's because the function foo returns char **, while bar is of type const char **.

returning pointer to a pointer in c


Integrating Impress.js

Question: I'm trying to integrate Impress.js into a Drupal 7 instance, so that I can define a new content type (ie. keynote) for which I use a specific page.tpl.php template.
I build a small module to load impress.js files (both .css and .js) only when I have a node of that content type displaying in full view mode. I'm using preprocess_node_view.
But for some reason, though impress.js is being loaded, the browser returns the fallback message as it wasn't loading correctly.
May it be a problem with jQuery? May it be that the file is not properly loaded?
To test if it is a collision problem between jquery and impress I'd like to unset jquery for that page load, but I'm being unable to do it. (during preprocess_node_view it is too late, but I'm not finding how to do it in preprocess_page).
Do you have any idea?
Also, If anyone has already tried this integration (I dont like the Impress 3D module approximation) and may offer a pointer on where the real problem resides, it would be very appreciated, as I'm starting to get mad.
PS. I didn't find a solution yet. Here is the code i'm using:

Module that loads JavaScript and CSS through hook_node_view():
<?php
/**
 * Implements hook_node_view()
 */
function impressintegrator_node_view($node, $view_mode, $langcode) {
  // if node is a presentation, and we're looking at a full node view
  if ($node->type == 'presentacion' && $view_mode == 'full') {
    drupal_add_js(drupal_get_path('module', 'impressintegrator') .'/js/impress.js');
    // and add this css file
    drupal_add_css(drupal_get_path('module', 'impressintegrator') .'/css/impress.css');
  }
}

Node body (with PHP Code filter):

Tu navegador no soporta las funciones requeridas por impress.js. Por eso, lo que ves es una versión simplificada de la presentación.

Para una mejor experiencia, recomendamos usar la última versión de Firefox, Chrome o Safari. La incipiente versión 10 de Internet Explorer también debería ser compatible con impress.js.

Slides para la web

Hacer presentaciones se parece más a crear cómics que a redactar informes. Necesita una dosis extra de creatividad.

With Firebug I can see 2 errors: "body is null" (in impress.js) and "impress() is not defined" (in page body), though impress.js is loaded (and even giving errors, he he).
This is the hook I had implemented before posting here:
function impressintegrator_node_view($node, $view_mode, $langcode) {
  // if node is a presentation, and we're looking at a full page view
  if ($node->type == 'presentacion' && $view_mode == 'full') {
    drupal_add_js(drupal_get_path('module', 'impressintegrator') .'/js/jmpress.js');
    drupal_add_js(drupal_get_path('module', 'impressintegrator') .'/js/ejecutarjmpress.js');
    // and add this css file
    drupal_add_css(drupal_get_path('module', 'impressintegrator') .'/css/jmpress.css');
  }
}

Thanks for your feedback. The existing module for impress doesn't fit my needs, as I need to create many presentations and managed them as content, no as a view.
Right now i'm trying to use jmpress (as even the creator of that module says the demo is built using jmpress)
For some reason, my function is loading every file (from js to css), but it isn't working. The code to run jmpress is as simple as follows:
jQuery(function() {
    jQuery('#simple').jmpress();
});

But, even with all scritps being loaded, it is not working. As you see, I was using the function you recommend (drupal_add_js) but I don't know how to specify weight of each script, and I don't know how to implement Drupal.behavior (I did a couple of attempts but I think I'm not getting it...
I tried the following code, but have no experience with behaviors and i don't know if I'm missing some dependencies or anything else :)
(function ($) {
  Drupal.behaviors.impressintegrator = {
    attach: function (context, settings) {
      $('#simple').jmpress();
    }
  };
}(jQuery));

From what I understood, I can just call "diapos" even though I'm not declared it previously, and it will even run, but I didn't get anything running so I've probably missed something.
Comment: what is the fallback message ? how does your .js code look - are you using a behavoir ?, maybe try http://shama.github.com/jmpress.js/
Comment: the fallback message is that my browser doesn't support impress.js. That's not true: I am able to run impress.js in a demo .html file. The same html and the same javascript are not working when the js is loaded through the drupal module and the html is included as body of the node.
Comment: I modified my module to add jmpress.js to $styles, instead of impress.js. I changed also the line to effectively launch jmpress. And I'm getting the same kind of error, as if the js wasn't loaded when it really is loaded. So the problem must be elsewhere. The node has the "PHP Code" filter active, just to be sure that i'm not stripping any code. I'm loading jmpress.js in the header. I'm not using behaviour.
Comment: so - how does your javascript code look ?
Answer: First off, you should add the javascript and css includes in a preprocess function: yourmodule_preprocess_node()
Also, you never mentioned where/how you are calling impress().init();?
Ideally, you should either add it inline using drupal_add_js() and make sure it has a weight that is higher than the impress.js include or you could wrap it in a Drupal.behaviors in your own custom js (make sure its loaded after).
In case you are thinking about it, you should really avoid putting any css and js in node bodies, its just terrible practice and will likely get shredded by filters.
Also, this is unlikely to collide in any way with jQuery, try adding jQuery in your static demo page to find out.
EDIT
Your behavior code is almost there, it should look like this:
(function ($) {
  Drupal.behaviors.impressintegrator = {
    attach: function (context, settings) {
      $('#simple', context).jmpress(); // notice passing context variable to optimize selector
    }
  };
}(jQuery));

One thing though, you specify $('#simple") in your example, but I don't see it anywhere in your markup.  Also the code example from the library link suggests an entirely different approach than you are taking.
However, the main problem is that the "impress-not-supported" class should be added to the body element!
In your behavior, before anything else, do this:
$('body', context).addClass('impress-not-supported');

Also, I've never heard of jmpress, I've been working with impress.js, so you should try including it and using the impress.init() function call as in the project's example.
Finally, to add weights to your javascript includes:
drupal_add_js('path/to/impress', array('group' => JS_LIBRARY, 'every_page' => TRUE, 'weight' => 0'));

You should add the JS_LIBRARY group to the impress.js file and JS_THEME to your custom script.  Weight = 0 should be fine for both as libraries get added before theme scripts.
Do read up on the drupal_add_js() documentation it explains all of this stuff in detail! :)
Comment: Thanks, Alex! I've given it a try. What you suggest is what i've been trying, but I'm starting to think I'm missing some basic lesson here... as I dont get it working :) I've added extra info to my question.
Comment: I've complemented the answer :)
Comment: Thanks again! I've improved the code of my Behavior :) The mess with #simple and #impress is due to my migration from impress.js to jmpress.js (=jquery-like syntaxis). I wanted to use impress.js (gpl), but i didn't manage to get it running :( While I guess how to build a behavior that launches impress.js (to take js away from node->body), I'll be using jmpress.js, whose only problem is that it requieres jquery >= 1.7.0, while Drupal7Core bundles with jQuery 1.4 (used _js_alter to replace the bundled with 1.7.1 and it loaded OK). Thanks again! Any ideas on launching impress.js with behavior?
Comment: It's trivial, just call it! :)  Replace the line "$('#simple', context).jmpress();" with "impress.init();" as long as the impress-not-supported has been added to the body and the library has been loaded before, it should work fine!
Answer: Plan B: Try and use the existing Impress.js module!
Comment: It is a nice module, but doesn't fit my needs. I opened an issue at drupal.org a couple of days ago... And even exchanged a couple of mails with the developer, but his solution (building a multi-view with views) still doesn't fit my project. It is a really cool (easy to install) module that does only one thing but does it really well :)

Integrating Impress.js


Android(4.4+) WebView not showing iframe page content second time load

Question: i'm tring to show in webview page from local storage, it looks ok when page loaded first time, but when i remove webview and add it again it looks like on the picture (for 4.4+, on previous android versions just black screen):

webview adding progrommatcaly each time (using app context), switch off cache,cookies, and remove it in on destroy.
here is my code:
<code>    mLayout = (LinearLayout)  view.findViewById(R.id.linear_main);
    mWebView = new WebView(getActivity().getApplicationContext());
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.getSettings().setSaveFormData(false);
    mWebView.setInitialScale(1);
    mWebView.getSettings().setLoadWithOverviewMode(true);
    mWebView.getSettings().setUseWideViewPort(true);
    mWebView.getSettings().setAppCacheEnabled(false);
    mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
    mWebView.getSettings().setDatabaseEnabled(false);
    mWebView.getSettings().setDomStorageEnabled(false);
    mWebView.getSettings().setGeolocationEnabled(false);
    mWebView.getSettings().setSaveFormData(false);
    mWebView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
            LayoutParams.MATCH_PARENT));
    mWebView.setWebChromeClient(new WebChromeClient());

    if (Build.VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN) {
        mWebView.getSettings().setAllowUniversalAccessFromFileURLs(true);
    }

    mWebView.getSettings().setPluginState(WebSettings.PluginState.ON);
    mWebView.getSettings().setPluginState(WebSettings.PluginState.ON_DEMAND);

    mLayout.addView(mWebView,0);

    /// then display page by call
    public void display(String path){

    Map<String, String> noCacheHeaders = new HashMap<String, String>(2);
        noCacheHeaders.put("Pragma", "no-cache");
        noCacheHeaders.put("Cache-Control", "no-cache");
    mWebView.loadUrl(path, noCacheHeaders);

}

    /// after display destroy fragment  with the WebView
@Override
public void onDestroy() {
    super.onDestroy();
    CookieSyncManager.createInstance(getActivity().getApplicationContext());
    CookieManager cookieManager = CookieManager.getInstance();
    cookieManager.removeAllCookie();
    mWebView.removeAllViews();
    mWebView.destroyDrawingCache();
    mWebView.clearDisappearingChildren();
    mWebView.clearFormData();
    mWebView.clearHistory();
    mWebView.clearCache(true);
    mWebView.loadUrl("about:blank");
    mWebView.pauseTimers();

    mLayout.removeAllViews();

    mWebView.destroy();
    mWebView = null;
    getActivity().getApplicationContext().deleteDatabase("webview.db");
    getActivity().getApplicationContext().deleteDatabase("webviewCache.db");
}
</code>
could you please advice what else i need to try =)
Comment: are trying to load videos ?
Comment: no, one frame is google map, one for webpage, and 2 for images
Comment: wen add it again are you loading it with url ?
Comment: no, forgot to mention, i'm loading it from local file (every time), like file:///page.html
Comment: getActivity().getApplicationContext() use activity context and check
Comment: just now tried, unfortunately the same result =( also i'm wondering about webview memory leak, one of advice was to use app context.
Answer: looks that
<code>mWebView.pauseTimers();
</code>
save data in some static variable... so, it doesen't matter that i've destroy webview and create new one, playing iframes were stopped.
so, i've remove this line and it working now
be careful by using this flag
btw, guess it can related to memory leak issues.. but it's another story


Restricting node access for nodes that are associated with other nodes which have user reference

Question: I have one content type Jobs. These include a user reference field which is the contact.
I have another content type called Job Applications. The include a node reference field that links to Jobs.
How can I make so that public if someone attempts to read a URL for a job application, they won't be able to access that node unless they are contained in the user reference in the job node associated with that job application node.
I know that nodeaccess modules offers restrictions for content types containing user reference. I could add a contact user reference field in the job application content type BUT how do I keep it hidden (I think there is a module for hidding fields) AND more importantly how do I automate things so that when a job is selected (or used through node reference auto url) the hidden contact user reference field will automatically adjust based on that job node's user reference field.
Note: I don't want to restrict access by roles.
Update:
Job
Contact (user reference)
Job Applications
Job (node reference)
Contact (user reference) <-------- I need this to be copied automatically from the job (that is referenced in the node reference) contact user reference
Comment: Hello and welcome to Drupal Answers. By "public" do you mean available to the particular logged-in user? The contact is a Drupal user? Are you able to keep the field hidden by simply excluding it from the content type display options?
Comment: Hi Wtower. By public I mean anyone else anonymous or logged in user. Basically only the user in the Job contact user reference field should be able to see the applications associated with that job. The field at Job nodes should be visible. At job apps it should not be visible at input or display.
Answer: I don't have enough rep to comment, however, if you are referring to an authenticated user (logged in). You can set the Access Control rules for the logged in user per node. If the user is not logged in, then it is not possible as anybody with a valid URL can view the node.
If you want to hide fields in a content type node. Go to Structure->Pages->View Node (you will have to enable this first in case it isn't). Then create a new variant for that content type and then manually add fields you want the authenticated/anonymous user to see. Make sure you have Context and Selection rules enabled and that admin roles are excepted from viewing that variant. In other words, admin will see everything.
Answer: To add on, you can also consider the Access by Term module:

Provides very flexible, hierarchical node access control (content access control), for D7.
Supports following flags: View, Update, Delete
Grants are based on the relationship between the user->term<-node.
Comment: That could work but I would need to have a reference field for that content type. Is there any way that I can use rules that upon clicking node reference it will automatically read a job's user reference and copy it to the job application?
Comment: I would do that with a bit of coding. I believe this is subject of a different question though.


How to extract multiple numbers from a string and assign to individual variables

Question: Lets say I have the string "first=53 second=65 third=82". How do I assign each value to variables x, y, z?
Edit: The words must match as well. With the + signs and exact number of spaces.
Comment: regexes need a pattern to look for. What is the pattern you're establishing here? first -> x, second -> y, third -> z?
Comment: @JonathanMee yes. I believe the regex is this:

/^first=\d+\ssecond=\d+\sthird=\d+/ But not sure how to extract
Comment: The edit made your question incomprehensible.
Answer: str = "first=53 second=65 third=82"
x, y, z = str.scan(/\d+/).map(&:to_i)

Comment: Thank you. However, not what I'm looking for. The words must match as well. With the + signs and exact number of spaces. I forgot to mention it in the question.
Comment: Can't think of any intelligent use for that. Anyway, if you already know where everything is in the string, just get it off the string index. `x, y, z = [str[6..7], str[16..17], str[25..26]].map(&:to_i)`


How to manually add a root view controller arrow after new a storyboard?

Question: I was just created a new storyboard for test, rather than bother the main storyboard.
so when if I was testing, I would like to use the new storyboard I can managed add some view controllers, and I can start the storyboard as well as one of the controller in source code, but how to make a view controller in the storyboard, as there isn't the arrow as the main one!
Answer: Do you mean how can you designate a view controller as the storyboard's root view controller? Select the view controller, open the Attributes Inspector, and select Is Initial View Controller.
Answer: Select the view controller and in the Attributes Inspector, check the "Is Initial View Controller" checkbox.
Answer:
by clicker on is initial view controller at attribute Inspector it will give connection to that viewcontroller


Unique character of order 2

Question: "The multiplicative group $(\mathbb{Z}/p\mathbb{Z})^{\times}$of reduced residue classes modulo an odd prime p is a cyclic group of (even) order p − 1. Thus it has
a unique character of order 2."
Why we only have one character of order 2? What has this to do with the first statement above?
Answer: Characters of finite abelian groups are in 1-1 correspondence with the groups themselves. See this question for more details.
Comment: Honestly: Never heard of that fact. I mean with that my question is obviously answered but its not really obvious that your assumption is correct.
Comment: @FabianSchneider: not an assumption, it's proved at the link. Please read the answers there.
Answer: If $\chi:G\to\Bbb{C}^*$, $G$ a finite abelian group, is a character of order two, it follows that $1=\chi(g)^2=\chi(g^2)$ for all $g\in G$. This implies that

the kernel of $\chi$ contains all the squares in $G$, and
$\chi(g)=\pm1$ for all $g\in G$.

If we furthermore know that $G$ is cyclic of an even order $n=2m$, then

the squares form a subgroup $Q\le G$ of order $m$ and index two, and therefore
the coset $gQ=G\setminus Q$ for any non-square element $g$. Implying that the product of two non-squares is a square, and that the product of a square and a non-square is a non-square.

So if $\chi$ has order two, then

$\chi(q)=1$ for all $q\in Q$,
$\chi(x)\neq1$ for some $x\in G$. By the above observations $x\notin Q$, and $\chi(x)=-1$.
If $y\notin Q$, then $yQ=xQ$ implying that $y=xq$ for some square $q\in Q$.
So $\chi(y)=\chi(xq)=\chi(x)\chi(q)=(-1)\cdot1=-1$.
Items 1 and 4 imply that $\chi$ is the unique function taking the value $+1$ in $Q$, and the value $-1$ elsewhere.
It easily follows that the function defined in the previous bullet is actually a character of $G$.

As Hempelicious pointed out, the character group of an abelian group is isomorphic to the group itself. But, the isomorphism is not natural. In other words, it relies on our ability to write a finite abelian group as a direct product of cyclic groups. Such a decomposition is not unique, and this leads to complications similar to the well known result that the dual of a f.d. vector space is isomorphic to the vector space itself, but to write down the isomorphism you need to specify a basis. In sharp contrast to the simpler fact that the double dual is naturally isomorphic to the vector space we started with.
Comment: @Hempelicious Cyclicity is also essential. If $G=C_2\times C_2$ then it has three characters of order two. The generators of the two factors can both be mapped to $\mapsto\pm1$. We get a character of order two unless we make the trivial selection. Similarly, that group has three subgroups of index two, and each can serve as the kernel of a character of order two.
Comment: Yes, sorry, I left that part out, but I meant once we know they're homomorphisms, they can be counted by the index 2 subgroups. This wouldn't be true if the image had more than one element of order 2.
Comment: I guess another way of saying this is that in the abelian case, the character is actually a homomorphism. Since there is only one subgroup of order $2$ in $\mathbb{C}^\ast$, there's still most one such character.
Comment: Ok, @Hempelicious. We seem to agree :-)

Unique character of order 2


How to convert to Audio a MIDI recording routed to E-Drum module in Cubase 11

Question: Well, I'm kind of confused here and I don't know what else to do.
Let me explain because I think is kind of particular.
I have an EF-Note 5x, whose module allows you to record MIDI and audio directly from USB. The audio tracks exported are pretty good (but not good enough), but there MIDI ones are exactly what I hear when I play from my kit.
In order to do this, I had to create a MIDI track (not Instrument one) and route the output to the module as you can see on the following image.

What I need, is a way to convert what I hear when I hit play to an audio track so I can edit better the final result and the waveform.
A few disclaimers:

Since I really like the sound that comes from the module itself, I don't want to create an Instrument track using a VST like Superior Drummer, EZ Drummer, etc. I want to get an audio track of what I hear coming from the module but as it is when I'm using the MIDI option, because as I said, the 8-ch audio recording is good, but not enough at least based on what I hear.
The option for render in place doesn't work for MIDI tracks but for Instrument Tracks. There is a way to get the module sound on a instrument track otherwise?
I tried to export the MIDI track as Audio Mixdown but I only get a flat audio file with no sound on it.

Probably I'm confusing concepts here, but there must be a way to convert your MIDI recording as it sounds when the module is plugged and routed. Can you help me on this? It will be really appreciated because is what I need to record my E-Drum as I want.
Thanks in advance.
Comment: I use Cubasis on iPad, not full Cubase, so I don't know exact buttons to press, but you can absolutely route the midi output from your midi track to the instrument and then route the instrument back to a separate audio track to record back the sound your instrument makes in response to the midi track.  There should be countless youtube tutorials on this.
Comment: Yes Affe, thanks. I spoke today with a friend and he suggested exactly the same as you say. I will check it out and I'll let you know how it goes :)
Answer: I'm going to take a wild swing at this, based on guesswork.
I think the root of your issue is that your kit is sampled in stereo, yet only has 4 stereo output buses, switchable to 8 mono. You are splitting your individual sounds into 8 mono recordings, in effect, whereas what I think you want are 8 stereo.
You can't render in place for 'pure' Midi. Midi contains no sound, only note data. As you don't wish to route this to a VST, then you just can't use your Midi track this way.
If you record your performance in Midi, which also gives you the opportunity to 'fix' things, timing, velocities etc, then you need to route that midi back out to the drum unit & re-record the result.
Once you have your routing set up to achieve this, then you can make your recording in two passes.
Set kick, snare, hats, ride each to a stereo bus 1/2, 3/4, 5/6, 7/8 [with the others to the Main bus] Record only the separate buses. Then switch all the outputs over - your remaining instruments to the stereo buses & the ones you already recorded to the Main. Again, record just the separate buses.
I'm basing this on images from the Note 5 page, showing the bus setup…

That will give you 8 stereo tracks.
Actually, looking again at the bus setup picture, maybe you can do the cymbals separately if you need to.
As a precaution, check what comes over the Main bus if all instruments are routed to individual channels - just on the off-chance that the device sends ambience separately, which you'd also need to capture [or replace with plugin ambience/verb.
Anecdotally, this reminds me of how we used to record drum samples back in the days we could only play one sample at a time [early 80s] ;)
Comment: Yup. Just record the Midi performance initially, do any fixes needed in the midi while you have it right there, then play back the midi to the module & record the resulting audio in as many passes as it needs to capture all the instruments in stereo.
Comment: Let me see if I followed you. You said that I can record the midi DATA this way in order to work with that, but then I should create 4 stereo tracks to re-record the audio from my previous recording, am I right? I followed the logic on your explanation, but I'm having trouble on the "how-to". Could you please share a document/video to see the practical steps on this. Thanks a lot for your help, this at least gives me the answer that this is possible to do.
Comment: I'm working entirely from the page you linked - I've added the bus setup picture, which looks like how you could rig this up. You'd have to go through it all twice, of course, unless it has memory saves for setups.
Comment: Right, this image represents the routing that you want from the module. This helped me when I did the audio recording directly (not the MIDI one), I mean, creating audio 8-mono tracks or 4-stereo tracks. What I don't understand and I'm trying is, do you suggest to send the MIDI track to the module again and re-record it as audio in those new audio tracks suggested by the image? I will give it a shot if that's the case


Is there a heuristic for determining the size of a fully connected layer at the end of a CNN?

Question: For example, in VGG/OxfordNet, the fully connected (dense) layers that precede the final classification layer are of size 4096.

Similarly, in an AlexNet

... the number of neurons in the network's remaining layers is given by
  253,440–186,624–64,896–64,896–43,264–4096–4096–1000.

My question is what is the rationale for using this particular number of neurons in the dense layers?
I haven't found a satisfactory explanation, given that each of the above examples use different resolution images and different number of kernels and kernel sizes, thereby generating different number of parameters—but regardless use similar dense layers.
Even if this is purely empirical, I'd be interested in hearing your thoughts on how this is decided.
Answer: Choosing a network architecture is a bit of a "black art".
They might have tried multiple different parameters and chose one that worked well (evaluating each using cross-validation).  Also, you can inform your choice by what has been reported in the research literature to work well on similar tasks, and use that as a starting point for experimentation.
One consideration here is the number of weights that can be set independently: the more of those you have, the greater the risk of overfitting, and the greater the training time.  So, increasing this number makes training take longer and runs a higher risk of overfitting, but potentially increases the expressiveness of your neural network.  You probably want the number to be as small as possible, without sacrificing accuracy.  So, you might try something small and increase it until you stop getting improvements in accuracy (measuring using cross-validation).
Comment: @user3125, that's a separate question, which is probably worth asking separately. This is a question-and-answer site, not a discussion forum, so it's often best to ask follow-up questions by posting a new question rather than by leaving comments.  Comments are short and explaining the answer and why will take a bit longer than I can fit in a comment.
Comment: Is cross-validation heavily used during training deep learning model, which usually requires a lot of time to train?


fgets and sscanf

Question: This code is supposed to get integers from a file which is finput and sort it and gets the first integer in the file which is the number of integers to be sorted and the integers that follow are the integers to be sorted. I don't get how fgets and sscanf work together. Can someone explain how fgets and sscanf work in this code?
FILE *finput;
int *array_int, c1, no_elem;
char numlines[500];

fgets(numlines, 500, finput);
array_int = (int *)malloc(sizeof(int)*no_elem);
if ((sscanf(numlines, "%d", &no_elem) == 1) &&  array_int!= NULL)
{
    for(c1=0; fgets(numlines, 500, finput) != NULL; )
    {
        if (sscanf(numlines, "%d", &array_int[c1])==1)
        {
            ++c1;
        }
    }
}

Answer: fgets gets a string (i.e. a line of text) from the file.
sscanf parses a string based on the format string. It is reverse to sprintf. the <x>printf and matching <x>scanf functions allow formatted output and input accordingly, with a standard format string. For example, "%d" means "signed integer value", and in context of <x>scanf it means "read it into the next parameter in the following list of parameters" (your array member in your case).
You can parse directly from the file using fscanf, but using fgets + sscanf instead allows for more flexibility and might be safer.
Comment: Could you add an example of why `fscanf` might be unsafe?
Comment: @galymzhan can't think of any off the top of my head. Why?
Comment: So fgets gets the integer and sscanf assigns that integer to array_int? Am I right? Why is there a ==1 in sscanf?
Comment: @John, did you read the first sentence in my answer? How did you reach this conclusion? You're reading a text string, and then you parse the text string. These are two, distinct and unrelated actions. There's a function that does them both at once, or you can do them separately.
Comment: @littleadv Just curious, I've been using `fscanf` directly most of the time.
Comment: @littleadv I'm referring to my code. What I'm asking is, the fgets function in the code which is fgets(numlines, 500, finput) gets the string which contains the integers. And the sscanf function numlines, "%d", &array_int[c1] gets the string which is the number and extracts that value and the array_int will get that value as an integer. Is that right?
Comment: @John I think so... I'm not sure I followed you, but it seems you've followed me. fgets reads the string from the file. It doesn't care whats in it, as long as its less than 500 chars. sscanf reads an int from the string. It **does** care whats in it, will ignore everything until it can parse a number, and then ignore everything else. If it ended up ignoring the whole string - it will return 0 to mark you that it didn't find a number in there.
Comment: Oh I see, so sscanf will return 1 as long as it finds a string in numlines? Thank you very much! :D

fgets and sscanf


Force apache to server different directories on different ports?

Question: For example, say I have my htdocs in:
<code>~/public_html
</code>
and those documents are being served on port 80.  Is there any way to make apache server documents in:
<code>~/public_html/something
</code>
on a different port?  Or does that require a separate instance of apache?
Answer: It requires a different virtual host.
Just set up two virtual hosts that listen on different ports, let the second have a different document root and forbid access to 'something' within the first.
Comment: 2013 comment!!!
Comment: Thanks!  I'd vote up, but need 15 reputation before I can.
Comment: +1 correct - you just need a new vhost with a different docroot
Answer: Sure, first you'll have to set apache to listen on two ports. So in your httpd.conf set
Listen 80
Listen 8080
Then create two vhost configurations (/etc/apache/sites-enabled/000-default). The first can be *:80 and the second *:8080. Set the respective DocumentRoots.
<VirtualHost *:80>
DocumentRoot ~/public_html
Blah Blah....
</VirtualHost>
and...
<VirtualHost *:8080>
DocumentRoot ~/public_html/something
Blah Blah....
</VirtualHost>
Comment: Wow, you took Manni's answer a step further.  Thanks for the example config stuff, it's very helpful.  Sorry I can't upvote, but I will when I get 15 reputation!


Unable to connect to docker container to container

Question: I have created couple of docker ubuntu images in my Debian host.
1. app01 - sudo docker run --name app01  -P -id ubuntu-control-container-bkup
2. control - sudo docker run --name control  -p 22:22 -id ubuntu-control-container-bkup

Now, from control container im trying to ssh connect to app01 container but I get connection refused error.
root@5ffdec48995f:/# ssh 172.17.0.2
ssh: connect to host 172.17.0.2 port 22: Connection refused

Comment: Check the IP of app01 to confirm that you has the correct one: `docker inspect app01`. Then check whether it has the 22 port open: `docker exec app01 ss -ltn`
Answer: ssh isn't installed or enabled by default. if you really need it, you'll need to install it via your Dockerfile.
https://docs.docker.com/engine/examples/running_ssh_service/
but you might want to consider these things:
https://jpetazzo.github.io/2014/06/23/docker-ssh-considered-evil/
Comment: Thanks.Im lil bit confused after reading the article as im from traditional background..We generally use a ansible control machine to ssh to different boxes and install multiple packages..How do I install different packages(tons of linux/python packages) if I can't ssh..
Comment: each different type of target machine would be a separate Dockerfile and image to build... php app? Dockerfile and image. rails app? Dockerfile and image. nginx? Dockerfile and image. etc etc. instead of deploying configuration to a server, you build the configuration into the image and deploy images - all configuration already done and handled. no more configuration drift, no more dynamic configuration of servers for a specific app. just deploy the image and run containers from it.
Comment: that's not to say ansible isn't still useful. lots of good docs and aricles on using them together, out there... but if you're replacing ansible deployed apps with docker, then this is the general approach you would take.


Peavey XXX amp - weak / overly loud clean channel

Question: Problem
I own a Peavey triple X (XXX) amp. I like most of the amp, but its clean channel is just to clear and clean for me. I mainly play metal/rock and I need the clean sound warmer, compressed and have a bit bite.
The clean channel has only one knob for gain/volume - both the red and orange channels have separate gain/volume knobs. So when I have enough gain and body on the clean channel it becomes much louder than the others - especially when playing chords (because there's nothing to compress the transients on clean)... This became worse with my active pickup guitar.
Currently I use the amp with minimal master volume (around 9 o'clock), the volume on both distorted channels set to almost max and clean around halfway.
Questions

What can I do to compress and warm up the clean channel in the meantime not affecting the  distorted channels? Modding the amp? Use a funky control that can switch on/off a pedal for only the clean channel?
I tried to search for mods for the clean channels, but I only get vague descriptions. Sending the amp from middle of Europe to a guy in America is not an option :). So can anyone suggest how to mod it? (Or a forum where I can ask for proper knowledge?)
Answer: The traditional solution would be to crank up the master volume to get more power amp overdrive, the only stage common to all channels. So it will of course affect the distortion channels as well, but probably not in a harmful way. However, it of course means you'll be much louder overall1.
Really, that Clean channel seems to be meant to have such a sound that does not make anything "warm", doesn't smooth out any transients, but preserves any details of the sound you give it as much as possible. If you need a more bluesy sound, then this channel is just not the right choice – unless you happen to have a pedal which offers just the right sound, and you don't want the amp to change it in any way.
Otherwise, the natural thing to do is to just use the Rhythm channel instead, in a clean-ish setting: perhaps achieved by attenuating the signal before the amp (guitar volume pot or some rather turned-down pedal). If you also need higher gain scenes on that channel and can't cope with the volume difference, you might even use the lead channel for this, with very much turned-down input. In both cases you can of course also use extra distortion pedals to make up for a bit of the amp's distortion.
But if you want to keep the Rhythm and Lead channels as they are, and are determined to "abuse" the Clean channel as a crunch channel, then you'll have to get that overdrive from somewhere else. Generic tube preamps2 like the ART TubeMP make a good permanent gentle / warm overdrive without altering the frequency response. Again this will affect the other channels as well, but probably not even noticable – only, the signal will have a much higher level into the amp. Just turning down the gain pots (volume in the clean channel) might give exactly the right sound. An opto/tube compressor might be even better.
If you actually want to mod only the clean channel, probably the most effective thing would be to hard-wire such an entire tube preamp into it. You don't really need to know anything about the specs, basically just trace the signal coming from the guitar jack and route it through this extra tube stage. Without an extra tube, I doubt any modification will give you the crunch you're asking for: again, that clean channel was specifically designed to not have any crunch whatsoever!

1It's possible if somewhat ridiculous to "burn away" that extra power with special resistor modules before the cabinets.
2You'll typically find the sold as mic preamps, but they work fine with instrument signals too.
Comment: Thanks for the detailed answer! Actually, the crunch channel has some much gain, that turning down itself usually means it is either silent or still have too much crunch. But it can be easily tested with turning down a volume pot on the guitar.
Comment: @atoth: well, you have plenty of headroom in the master section, so I don't think it should be a problem to get the Rhythm channel loud enough when used only slightly crunchy.
Answer: I agree with @leftaroundabout's answer but if you add pedals you can compress and warm up the clean channel. I do this all the time. An all-in-one pedalboard that will allow you to tweak the clean amp to your heart's delight is the Boss ME-80:

. I'm not a Boss sponsor in any way, but this pedalboard has worked for me in live gigs.
If you don't want jump between pedals then the standard way to "warm up" and compress a clean tone is to use a tube preamp.  You could leave this on all the time. There are quite a number of tube preamp pedals on the market such as the EHX Black Finger as well as pedals that model tube preamps such as the Tech 21 Sans Amp
Comment: Thanks for the suggestion, but I'm looking to a solution that does not alter the Crunch/Ultra channels, and I don't require performing well-timed acrobatics (like jumping on a footswitch AND a pedal at the same time).


"File not found error" when installing using composer

Question: I'm running Docker on Ubuntu 18 with a container for MariaDB, Nginx and php-fpm (7.3).
The PHP container has composer installed, and I used it to create a Drupal Commerce project. I can start the Drupal install process using a browser, but after I input the DB settings, the process fails and I get the following error.

An AJAX HTTP error occurred.
  HTTP Result Code: 404
  Debugging information follows.
  Path: /core/install.php?profile=commerce_base&langcode=en&id=1&op=do_nojs&op=do
  StatusText: Not Found
  ResponseText: File not found.

Increasing the execution time, post time, memory limit, post and upload sizes in the php.ini file, as recommended by another user, didn't solve the problem.
Nginx error log contains the following message.

[error] 6#6: *46 FastCGI sent in stderr: "Primary script unknown" while reading response header from upstream'.

The database has tables and data in it, so I know the database credentials are correct.
What am I doing wrong?
Comment: I think this is Nginx related, look here https://serverfault.com/questions/517190/nginx-1-fastcgi-sent-in-stderr-primary-script-unknown
Answer: Yes, it turns out it was an Nginx configuration problem. In my docker-compose.yml file i have:
web:
  volumes:
    - '/server/path/to/html:/usr/share/nginx/html'

php:
  volumes:
    - '/server/path/to/html:/var/www/html'

In my site.conf file, i had:
fastcgi_param SCRIPT_FILENAME project/$fastcgi_script_name;

Not sure why this worked for the initial php files i tested but then failed during the installation. Changing this line to the full path as follows solved the problem for me:
fastcgi_param SCRIPT_FILENAME /var/www/html/project/$fastcgi_script_name;


Hot Module Replacement enabled but not working http://localhost:3000/__webpack_hmr

Question: My problem is, no matter what I do I get a 404 on the wepack_hmr and I can't for the life of me work out why its not available.
Full Webpack Config
var url = 'http://localhost:3000';

module.exports = {

    resolve: {
        extensions: ['', '.js']
    },

    entry: ['webpack-hot-middleware/client','./src/client/js/Kindred'],

    devtool: 'cheap-module-source-map',

    module: {
        loaders:[
            {
                test: /\.js$/,
                exclude: /node_modules/,
                loader: 'babel',
                query: {presets: ['es2015', 'react', 'react-hmre', 'stage-0']}
            },
            {test: /\.png$/, loader: "url-loader?limit=100000"},
            // Images
            {test: /\.jpg$/, loader: "file-loader"},
            {
                test: /\.(eot|svg|ttf|woff|woff2)$/,
                loader: 'file?name=./font/[name].[ext]'
            },
            // Stylesheets
            { test: /\.scss$/, loader: ExtractTextPlugin.extract('style',
                [
                    'css?sourceMap&modules&importLoaders=1',
                    'sass?sourceMap&modules',
                ]
            ) },
            // Font Definitions
            { test: /\.svg$/, loader: 'url?limit=65000&mimetype=image/svg+xml&name=public/font/[name].[ext]' },
            { test: /\.woff$/, loader: 'url?limit=65000&mimetype=application/font-woff&name=public/font/[name].[ext]' },
            { test: /\.woff2$/, loader: 'url?limit=65000&mimetype=application/font-woff2&name=public/font/[name].[ext]' },
            { test: /\.[ot]tf$/, loader: 'url?limit=65000&mimetype=application/octet-stream&name=public/font/[name].[ext]' },
            { test: /\.eot$/, loader: 'url?limit=65000&mimetype=application/vnd.ms-fontobject&name=public/font/[name].[ext]' }
        ]
    },

    sassLoader: {
        includePaths: [ 'src/client/scss' ]
    },

    plugins: process.env.NODE_ENV === 'production' ? [
        new ExtractTextPlugin ('app.css', {allChunks: true}),
        new webpack.optimize.DedupePlugin (),
        new webpack.optimize.OccurrenceOrderPlugin (),
        new webpack.optimize.UglifyJsPlugin ()
    ] :  [
        new webpack.HotModuleReplacementPlugin(),
        new webpack.NoErrorsPlugin(),
        new ExtractTextPlugin("style.css")
    ],

    devServer: {
        hot: true,
        contentBase: './public'
    },

    output: {
        path: path.join(__dirname),
        publicPath: '/',
        filename: 'bundle.js'
    }

};

Node cmd to run
webpack-dev-server --inline --history-api-fallback --port 3000

When loading up the page
[HMR] Waiting for update signal from WDS...
home:1 GET http://localhost:3000/__webpack_hmr
client:22 [WDS] Hot Module Replacement enabled.

It takes me its running but its not :/
Comment: Webpack hmr is a tricky devil to get working properly. It is not enjoyable enough that I would be able to do it for you. I recommend you review one of the available react boilerplate's that include it, and look for differences between your config. https://github.com/gaearon/react-transform-boilerplate
Comment: Coming from grunt -> gulp -> webpack. I must say webpack seems the most black box to me. But thats almost certainly because I've not read the documentation like the others. :)
Comment: webpack-hot-middleware - I believe this one works only with express, you are using webpack dev server here. Also HMR doesn't work with ExtractTextPlugin.
Comment: Haha cheers john :) I appreciate the help and also insight that this might get ugly.
Comment: Yeah sorry heh, I usually enjoy helping people solve react related problems and don't mind jumping in writing code but webpack config is the worst.. lol
Comment: Yeah it's just got a lot it can do so that entails a lot of config and a lot of docs; plus you only really set it up at the beginning of your project so it's not something that you're really doing day in day out
Comment: By the looks of it you are missing certain client entry. Hence the error. You could try running the dev server in inline mode to avoid problems with entries.
Answer: Ok just so its easy for people to see what I did to get it working here it is:
I think it was easier for me to completely remove scss and just go with css modules out of the box. This seemed to help a lot.
I used firstname.lastname@example.com:christianalfoni/webpack-express-boilerplate.git to help me guide myself through. Knowing I had a working thing actually taught me a hell of a lot more than I have most likely learnt before hand in webpack. As you can guess that wasn't very much :D
Also the one main change that really helped was changing the paths not surprisingly. But these were relative to the path sex in output.path I had read this before but thought that was relative to the wepack.config.js not that from there on everything would count as document root, even for the html and css.
**KEY PART :) **
I also have to update my express set up, as I hadn't given it a express.static path... Oh my folly, how could I miss such a basic thing.. So:
Express
app.use(express.static(__dirname + '/public/')); //Don't forget me :(

Final CSS
/* Webfont: Lato-Black */@font-face {
    font-family: 'LatoBlack';
    src: url('/font/Lato-Black.eot'); /* IE9 Compat Modes */
    src: url('/font/Lato-Black.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
         url('/font/Lato-Black.woff2') format('woff2'), /* Modern Browsers */
         url('/font/Lato-Black.woff') format('woff'), /* Modern Browsers */
         url('/font/Lato-Black.ttf') format('truetype');
    font-style: normal;
    font-weight: normal;
    text-rendering: optimizeLegibility;
}

Wekpack.config
'use strict';
var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var qs = require('querystring');
var precss = require('precss');
var autoprefixer = require('autoprefixer');
var stripInlineComments = require('postcss-strip-inline-comments');

module.exports = {
    devtool: 'eval-source-map',
    // resolve: { modulesDirectories: ['node_modules'], extension: ['', '.js', '.css'] },
    entry: [
        'webpack-hot-middleware/client?reload=true',
        path.join(__dirname, 'src/client/js/Kindred')
        // path.join(__dirname, 'app/main')
    ],
    output: {
        path: path.join(__dirname, '/public/'),
        filename: '[name].js',
        publicPath: '/'
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: 'public/index.tpl.html',
            inject: 'body',
            filename: 'index.html'
        }),
        new webpack.optimize.OccurenceOrderPlugin(),
        new webpack.HotModuleReplacementPlugin(),
        new webpack.NoErrorsPlugin(),
        new webpack.DefinePlugin({
            'process.env.NODE_ENV': JSON.stringify('development')
        })
    ],
    module: {
        loaders: [
            {
                test: /\.jsx?$/,
                exclude: /node_modules/,
                loader: 'babel',
                query: {"presets": ["react", "es2015", "stage-0", "react-hmre"]}
            }, {
                test: /\.json?$/,
                loader: 'json'
            },
            {
                test: /\.jpg$/, loader: "file-loader"
            },
            {
                test: /\.css$/,
                loaders: [
                    'style-loader',
                    'css-loader?importLoaders&' + qs.stringify({
                        modules: true,
                        importLoaders: 1,
                        localIdentName: '[path][name]-[local]'
                    }),
                    'postcss-loader?parser=postcss-scss'
                ]
            },
            // Font Definitions
            { test: /\.svg$/, loader: 'url?limit=65000&mimetype=image/svg+xml&name=font/[name].[ext]' },
            { test: /\.woff$/, loader: 'url?limit=65000&mimetype=application/font-woff&name=font/[name].[ext]' },
            { test: /\.woff2$/, loader: 'url?limit=65000&mimetype=application/font-woff2&name=font/[name].[ext]' },
            { test: /\.[ot]tf$/, loader: 'url?limit=65000&mimetype=application/octet-stream&name=font/[name].[ext]' },
            { test: /\.eot$/, loader: 'url?limit=65000&mimetype=application/vnd.ms-fontobject&name=font/[name].[ext]' }
        ]
    },
    postcss: function (webpack) {
        return [
            stripInlineComments
            , precss
            , autoprefixer
            , require('postcss-simple-vars')
            , require('postcss-nested'
            , autoprefixer({browsers: ['last 2 versions']}))
        ];
    }
};

I have actually posted the same answer twice. But they are both related. Sadly :(


How to Track Mobile Device Rotation in Unity

Question: I am trying to make a 2D mobile game where the game's gravity changes as the device is rotated.  However, the only relevant input that I can find in the Unity Docs is DeviceOrientation, which doesn't help me because it is an enum with only 7 possible values.  Is there any way to capture continuous changes in rotation, using Unity's scripting engine?
Your help is much appreciated!
Answer: I asked this same question on the UnityAnswers forum.  To future Googlers that land here, you can check out the answer I got there.