webform contact form gives access denied for anonymous users

Question: I have a few webforms on my D9 site. They all work for anonymous site visitors except for the contact form, which gives an "access denied" error.
The permissions under the form's Settings->Access tab are the same as for other forms that do work.
The form's access permissions are set to allow anonymous / authenticated / admin users to create and view/ update own submissions:

I did search for the solution but what I found didn't help. I tried the debugging code from https://drupal.stackexchange.com/a/315766 and get the following messages:
The website encountered an unexpected error. Please try again later.
Exception: ACCESS DENIED: in Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException->__construct() (line 28 of /path/to/vendor/symfony/http-kernel/Exception/AccessDeniedHttpException.php).
<code>Drupal\Core\Http\Exception\CacheableAccessDeniedHttpException->__construct() (Line: 118)
Drupal\Core\Routing\AccessAwareRouter->checkAccess() (Line: 95)
Drupal\Core\Routing\AccessAwareRouter->matchRequest() (Line: 112)
Symfony\Component\HttpKernel\EventListener\RouterListener->onKernelRequest()
call_user_func() (Line: 142)
Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher->dispatch() (Line: 145)
Symfony\Component\HttpKernel\HttpKernel->handleRaw() (Line: 81)
Symfony\Component\HttpKernel\HttpKernel->handle() (Line: 58)
Drupal\Core\StackMiddleware\Session->handle() (Line: 48)
Drupal\Core\StackMiddleware\KernelPreHandle->handle() (Line: 191)
Drupal\page_cache\StackMiddleware\PageCache->fetch() (Line: 128)
Drupal\page_cache\StackMiddleware\PageCache->lookup() (Line: 82)
Drupal\page_cache\StackMiddleware\PageCache->handle() (Line: 48)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle() (Line: 51)
Drupal\Core\StackMiddleware\NegotiationMiddleware->handle() (Line: 23)
Stack\StackedHttpKernel->handle() (Line: 718)
Drupal\Core\DrupalKernel->handle() (Line: 19)
</code>
I don't know what this all means. Where do I go from here? Thank you.
Comment: Is this relevant? https://www.drupal.org/project/webform/issues/3157367
Comment: Unfortunately, no. I don't have anything set in the submission limit settings. Thanks tho
Comment: Unfortunately the Drupal 8 version of Webform is no longer supported, and neither is Drupal 8 for that matter. You could install a new site on your own dev platform or with simplytest.me, export the configurations of the forms and diff the exports. That is what I would do, faced with this issue.
Comment: I'm in the process of updating the site to D9 and so far I'm still seeing the same problem. I will try what you suggest. Thanks.
Comment: Updated with D9 info. Confirmed the problem is still happening. I will try the config exports next.
Comment: So I made a mistake earlier. @cilefen's link (first comment) actually does turn out to be the problem. Thank you for that. The debug suggestions were good / useful as well.
Answer: This is probably due to submission limits, as laid out by the module maintainer.

You need to uncheck 'Limit total to one submission per webform/source
entity' (/admin/structure/webform/manage/contact/settings/submissions)
and set [the] submission limit to 1.


8 quarter notes in 4/4 time?! And how do I insert this into Guitar Pro?

Question: Look at the below graphic and please tell me how is this possible.
This is supposed to be in 4/4 time but it has 7 quarter notes??! (and an 8th note as well as a "8th note rest" - not sure if thats what it's called)
How is this possible? If I try to copy the below into Guitar Pro it gives me an error.
(There are two half notes (E and A) as well, those I am guessing are on the 2nd track and GP won't even let me put them in the same place thats shown in the graphic)
Comment: Ryan,  your questions are fundamentally reasonable, but seeing as you've posted rather a lot of Guitar-Pro questions,  perhaps you'd be better off reading the manual and experimenting a bit so you know how to use the tool.
Comment: The thing is, I am very very rusty on notation and starting out on GP as well. I get what you are saying but I think I will keep posting here because when I post and people answer they sometimes go into a little more details which has taught me a LOT more compared to even had I found the answer myself. I may not be getting much input on using GP but I have gotten loads of new information about music that is pretty much invaluable.
Comment: Looks like the middle voice is syncopating.
Answer: There are 3 separate voices.  Voice 1 is the high D-F#-A-G, voice 2 is the middle [eighth rest]-D-A-E-A, and voice 3 is the half notes.
Comment: This is a pretty strange measure of music, I will grant you that. I would have notated this differently, but it is playable if you can decipher it. The notes in the middle voice should be written as single eighth notes and tied eighth notes. "Staggering" the three syncopated notes in the middle voice by writing them as quarter notes is against the conventions of proper notation.
Comment: Three voices!!! Ok, makes sense now :) Just got introduced to voices yesterday so didn't think beyond two :p Thanks! Picked your answer.
Answer: This is a pretty strange measure of music, I will grant you that. I would have notated this differently, but it is playable if you can decipher it. The notes in the middle voice should be written as single eighth notes and tied eighth notes. "Staggering" the three syncopated notes in the middle voice by writing them as quarter notes is against the conventions of proper notation.
I would have notated it like this:
Comment: The point is that you should clearly show where the beats are. Using those "staggered" syncopated quarter notes obscures where the beats are.
Comment: Those staggered crochets are standard notation in multivoice keyboard music. That is such a standard rhythm, and so commonly occurring, that it is easier and cleaner to notate and _read_ the rhythm without the ties. (If one or more the crochets are divided, that's a different thing - we only use this for very simple syncopations.) It is very much like the crochet-minim-crochet rhythm in that regard. I would be very surprised if Daniel disallows it altogether in the Steinberg product - he knows better.
Comment: Sadly more and more music is seen without the tie across the middle of a 4/4 bar. May be something in the software of these computer generated progs? S'pose it's called progress...   Yours looks better, though!
Comment: There's a company called Steinberg that is working on a music notation software competitor to Sibelius and Finale. I follow the development, and there was recently a video blog by the lead developer who said that the new Steinberg product would, by default, prevent people notating things like what was done in Voice 2 in the example provided by the questioner, and would default to the kind of notation I use in my example.
Comment: I always do! Don't think the programmers are as fastidious, though. But at the end of the day, there's only four beats to get mixed up in. Bit like key sigs. We don't really need them at the beginning of each line, but they still get put in. Why stop there? Put the time sig in as well!!
Comment: @Patrx2, You can watch Daniel Spreadbury discussing this issue right here. https://youtu.be/VBhPyTNkXKI?t=24m
Comment: OK, so he is in effect saying that we can set the default rules. That makes more sense.
Answer: I'd just like to emphasise (for those that are still confused by this layout) just how the voices work and interleave with each other.
Following is the bar re-created with MuseScore with each of the voices in a different colour - Blue (primary), Green (Secondary) and Gold (Tertiary).  The same colours are duplicated in the guitar tabulature to emphasise how they are transcribed from score to tabulature notation.

You can clearly see in this image how each of the three voices has its own timebase to work from.  The primary voice is played on the beat (1-2-3-4).  The secondary is played on the half-beat (and-1-and-2-and-three-and-four) offset by the quaver rest at the start (also in green).  The tertiary voice is notation more normally seen for multi-voice layouts, and has the more obvious beat 1-3.
While this format is frowned upon by music purists it does make for a cleaner layout.  It is though, as you have seen, slightly more cryptic than the more explicit (and correct) notation shown by @WheatWilliams, but once you have got used to looking for this style (and especially noticing that elusive rest at the start of the secondary voice) it becomes just as readable as the more strict layouts.
Personally I don't know which method is better - the strict (though maybe overwhelming to the beginner with all those ties) notation or the loose (which makes it clearer what the length of the notes are if not the timing) notation.  Suffice it to say, though, that with the loose notation becoming more and more common it's important to get used to reading both of them and translating, in your head, between the two.


Taking screenshot with Win32 API (C# pInvoke) not working in IIS

Question: I want to take a screenshot of an external website.
Currently my workflow is to start a Firefox instance with the specified URL and take a screenshot using PrintWindow in the Win32 API
When I run this application in IISExpress it works fine but when I run the same application in IIS on a windows VPS it is not working (screenshot is blank).
I don't know what I'm doing wrong?
My code:
<code>using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security;
using System.Threading;
using System.Web;

namespace WebTools.Web
{
    public class RemoteScreenshot
    {
        public static Bitmap TakeScreenshot(Process process)
        {
            // may need a process Refresh before
            return TakeScreenshot(process.MainWindowHandle);
        }

        public static Bitmap TakeScreenshot(IntPtr handle)
        {
            RECT rc = new RECT();
            GetWindowRect(handle, ref rc);

            Bitmap bitmap = new Bitmap(rc.right - rc.left, rc.bottom - rc.top);

            using (Graphics graphics = Graphics.FromImage(bitmap))
            {
                PrintWindow(handle, graphics.GetHdc(), 0);
            }

            return bitmap;
        }

        [DllImport("user32.dll")]
        private static extern bool GetWindowRect(IntPtr hWnd, ref RECT rect);

        [DllImport("user32.dll")]
        private static extern bool PrintWindow(IntPtr hWnd, IntPtr hDC, int flags);

        [StructLayout(LayoutKind.Sequential)]
        private struct RECT
        {
            public int left;
            public int top;
            public int right;
            public int bottom;
        }

        public static void Save(string url, string file, int timeout = 0)
        {
            var proc = Process.Start(new ProcessStartInfo("C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe", url)
            {
                CreateNoWindow = false,
                WindowStyle = ProcessWindowStyle.Maximized
            });

            Thread.Sleep(timeout);

            var bitmap = TakeScreenshot(proc);

            bitmap.Save(file, ImageFormat.Png);
            bitmap.Dispose();

            proc.Kill();
        }
    }
}
</code>
EDIT: Running Firefox works fine because the AppPool is under another account that has the rights to execute firefox.
Comment: How is it not working? Does it throw an exception? Chances are you're hitting a code access boundary and it's throwing an UnauthorizedException
Comment: @SimonWhitehead I run the apppool with a user-identity. I'm eventualy getting a ArgumentException on the Bitmap constructor part because the width and height of the screen can't be calculated but when I set this to 1600x900 it is also not working.
Comment: You'll need to add some logging. Log the values you're passing into the bitmap constructor.
Comment: I know what values are passed, 0 and 0 because the 'GetWindowRect' function returns that. But when I pass 1600x900 to the constructor I get a blank image.
Comment: Are you sure that the user account that you run the IIs pool with has been initialized properly, with a proper user profile (think %USERPROFILE%) and such? I would imagine that Firefox needs a user profile to work properly.
Comment: If you're getting 0,0 from `GetWindowRect`, then your window handle is wrong.
Comment: @Magnus I think so, when I check the task manager then I see that the process is created.
Comment: @SimonWhitehead That's weird because 'GetLastError' in the Win32 API returns '0' ..
Comment: @DillenMeijboom just because the process is created doesn't mean that Firefox actually does what you expect. Imagine what happens when you first run Firefox as a new user, does it a) start a first time use wizard/import wizard or b) immediately show you a blank browser ready to use?
Comment: @Magnus Hmm, I guess your right. But still if the 'new-user-screen' is shown then the Screenshot application should still take a screen shot right?
Answer: Using IIS you can't take Screen Shot as It works under NetworkService Account in Windows server
Comment: I had similar problem with windows server, When I couldn't find a proper solution within time, I ended up writing a WCF Service Hosted on a console application as it was not working even in windows service.
Comment: I can because I'm using the 'user-identity' settings in IIS to run the AppPool under another account than the NetworkService account.
Comment: The IIS service is likely non-interactive and child processes will inherit that.
Answer: What screen are you taking a screenshot of?
If an application is running on a laptop it will paint to a physical display adaptor.  If it is running on a machine at the end of an RDP session it will paint to a virtual display adaptor, and the image will be sent over the wire.
But if an application is running in a non-interactive session then there is no display.  The application won't receive WM_PAINT messages so nothing gets painted.
There is no screen bitmap to capture.
Comment: Hmmm, the application is running on a virtual private server from CloudVPS. But is there a way to make a session interactive or something?
Comment: @DillenMeijboom If you're on XP you might get away with it but Vista and later try to avoid interactivity as much as possible: http://msdn.microsoft.com/en-us/library/windows/desktop/ms683502(v=vs.85).aspx
Comment: @ta.speot.is I shall take a look at it, I'm currently running Windows 8 server on my VPS.
Answer: IIS service donot have the access to the server desktop. The code of ASP.NET in IIS is running on the server side. And it will be trying to capture the screen of the server, which is denied.
You will need to use the silverlight which runs the code on the client machine.
Following link might help:
Capturing a Silverlight Screen
User using the webpage in the browser might need to provide permissions due to security reasons.
Comment: I don't want to use Silverlight and since it works local I'm sure with some help I can make it work online ;)
Comment: There will not be anyway to capture the screen of client from the server side.
Please see my edited answer.
Comment: I'm 100% sure that I can make it work, the user I've created has permissions to open Firefox and I can capture the screen using the Win32 API to make a screenshot of the Firefox browser.


when click button move to another html and show layer

Question: Is it possible that when click the button from a.html then move to b.html and show a layer(b.html) ?
I searched some similar example like active tab specific from another HTML.
Using javascript event like hash.location....
Anyone know how to make it and some examples? Thank you
Comment: By "move to another HTML", do you mean changing the page ? If so, just use `window.location`. `layer(div)` does not mean anything. Does "open another HTML" means a popup or a modal ? You need to be clearer and more precise
Answer: You need 2 HTML files. Let's say you have a.html and b.html in the same folder.
If I understand correctly, you want to change the page when clicking on a button.
You now have 2 solutions :

listening to a click on the button
using a little trick, by having a button element inside a link tag .

Listening to a click on a button
Let's say you have this button in your a.html file :
<button id="pageChanger">Change Page</button>

Then you need to add this JS :
document.getElementById('pageChanger').addEventListener('click', () => {
    window.location = 'b.html';
})

(Don't forget that it has to be added at the end of your document, or else it will not load properly
Having a button inside a link
You just need to add this HTML code :
<button>Change page</button>

Answer: For example, suppose two html pages are as follows:
page1.html:
<!DOCTYPE HTML>

    <title>Page 1</title>

    <button type="button" onclick="window.location.href = 'page2.html#myDiv'">Goto Div in Page 2</button>

page2.html:
<!DOCTYPE HTML>

    <title>Page 1</title>

        This is my div

When you click on the Button in the first page, window redirects to the layer in the second page.
In this example, anchor part is used. The anchor part is the part of the URL after the hash sign (#).
Example:

<button type="button" onclick="window.location.href = 'https://stackoverflow.com/jobs?med=site-ui&ref=jobs-tab#profile-summary'">Go!</button>


How do people play fast tremolo on guitar (with a plectrum)?

Question: I've noticed that to play good, consistent sounding tremolo, especially on short, thick strings, you can't just move the pick back and forth because the sound is inconsistent - the string doesn't respond fast enough. What I've found is you either have to tilt the pick side ways so you need less force to pluck the string, although this creates a scraping sound on the strings, which could sometimes be a disadvantage, or you have to move your hand in a semicircle motion, which is difficult to do fast. You could also tilt the pick with each stroke so that it comes at the string at an acute angle and slides on the string rather than getting caught on it.
What technique do players typically use?
Two bits I'm trying to play:
Comment: Comment, not answer, because it points away, but picking is a big, wide question, and [Troy Grady's _Cracking the Code_](https://troygrady.com/) is the most complete exploration on all things pick control. You should have _some_ angle on your pick wrt the strings, and _some_ angle wrt the plane of the strings to allow movement between strings. [Troy's videos](https://youtube.com/user/troygrady) will walk you through it.
Comment: Is it considered tremolo picking when they're playing metered rhythms, as in the linked videos?
Comment: I wouldn't call either example "tremolo" - the first maybe could be considered measured tremolo but notating it with explicit 16ths makes sense, as is shown in the video. The second example is not very fast at all. For me the quintessential fast tremolo that I never got fast enough for is the segment in "Eruption" by Van Halen. The main thing you need to play faster is more slow practice. Also use as little of the pick as possible.
Comment: Neither of the videos shows what I call *tremolo*. Not even particcularly fast picking. Tremolo playing is sounding rather like a mandolin - think Lara's Theme.
Comment: A low-e string that vibrates at around 82 Hz on an open E **does** respond fast enough; it does a complete cycle (hither, back, tither, back) in 1/80th of a second.
Answer: Here is an interesting interview with Jeff Waters, at the beginning he speaks a lot about picking hand technique:

To summarize:

Practice a lot
Vary the tempo
Analyze your technique
Avoid excessive, unnecessary movements
Employ your arm in the movement (rather than just wrist or fingers) – this actually varies between guitarists, and typically the movement is some combination of wrist, but my impression is that that the best rhythm guitarists use the arm a lot
Comment: Awesome video. To add some more summary points: he moves the pick the absolute minimum (just a few millimetres) and uses muscle tremors (he calls them spasms) to create the movement. A lot like some video gamers use "hypertapping" (https://www.youtube.com/watch?v=9WLoLhOdkjI)
Answer: The Kubi example you posted isn't tremolo picking - I only hear metered 16th notes.  Tremolo is more of a continuous sound.
There are two factors: first, the pick is angled to allow the point to "skate" across the string, lowering resistance.  Second, the wrist is tighter, which brings the muscles of the forearm into play - larger muscles don't tire as quickly.
In your first example video he's using the wrist rather than the forearm... but it looks like he's anchoring the heel of his palm on the bridge, which can help with the fatigue.  I tend to avoid that technique, because it limits the timbre (you're forced to pick close to the bridge), but for a specific tune that can also be a workable technique.
Comment: I'm not sure what your point is with the forearm muscles - IMO, the aim should be to keep the movement as small as possible, and to work from the wrist as far as possible. Also, with that style of playing, you have to keep the hand close to the bridge - first, the string has too much wiggle room farther away from the bridge, and second, palm muting only really works right at the bridge. So it's not really a specific tune that requires this - it's the vast majority of metal.
Comment: Richard, it really isn't. For any really fast picking, the majority of metal guitarists use the forearm. And a lot of metal shifts continuously from right hand palm muting to left hand muting, using whatever is right at that time. But in any case, the two videos posted by the OP are not very fast.
Answer: There's a jazz guitar instructor called Peter Farrell (who studied with George Benson) who has a take on this. He refers to it as "bee picking", presumably a reference to Flight of the Bumblebee.
The preamble is that the pick should be slightly angled to the string to allow it to roll on and off smoothly. He then says to concentrate on "keeping the pick in contact with the string" i.e. when playing, aim to produce the smallest picking movement possible with the aim of feeling like the pick never leaves the string.
Obviously, the pick does in fact leave the string (otherwise no sound would come out) but by aiming for that feeling of contact it does make it a lot easier to play fast.
Reference:
Answer: I see no evidence for anything you have said in your question.  Just moving the pick back and forth does lead to consistent sound.  It sounds to me that you are not putting in any practice effort and looking for a quick fix.  The tilting phenomenon may make it easier to develop a sloppy tremolo that, in your own words, sounds scratchy.  But slow, steady, practice every day with the metronome will lead you to develop a fast consistent tremolo over time with good techniques and tone.
I would recommend exercises in a book called "Speed Mechanics for Lead Guitar" by Troy Stetina.  The basic exercises are not style specific and work well for ANY and ALL plectrum style playing.  You need to put in the time to see the dividends.


Newbie Python: Print Function that Outputs NULL bytes

Question: I don't program in Python at all, so please forgive my code. I am trying to write a print function that terminates after a certain number of bytes. This is what I have done so far:
   def print_stuff(stuff, size):
    i = 0
    data = ""
    while i < size:
            if stuff[i]=='\0':
                    data += " "
            else:
                    data += stuff[i]
    print data

But when I tried to do printf_stuff(data, 5050) Python doesn't print anything and seems to freeze. What am I doing wrong?
Answer: You're not incrementing the value in i.
Answer: You can do this with a string slice and a replace.
def print_stuff(stuff, size):
    data = stuff[:size]             # Slice it up to the size that you want.
    data = data.replace('\0', ' ')  # Replace all occurrences of \0 with a space.
    print data

Answer: Yeah, you need to put i += 1 in there probably after your condition statements:
def print_stuff(stuff, size):
  i = 0
  data = ""
  while i < size:
    if stuff[i]=='\0':
      data += " "
    else:
      data += stuff[i]
    i += 1                        # Here's your missing line.
  print data

Answer: You are not incrementing i variable


How to remove fields from big query table?

Question: I updated schema of one production bq table and added record type of field with few repeated fields inside another record type field. Now I have to drop this column. I can't delete whole table as it already has more than 30 TB data. Is there any way to drop particular column in big query table?
Comment: Possible duplicate of [BigQuery - remove unused column from schema](https://stackoverflow.com/questions/35406494/bigquery-remove-unused-column-from-schema)
Answer: See:

https://cloud.google.com/bigquery/docs/manually-changing-schemas#deleting_a_column_from_a_table_schema

There are two ways to manually delete a column:

Using a SQL query — Choose this option if you are more concerned about simplicity and ease of use, and you are less concerned about costs.
Recreating the table — Choose this option if you are more concerned about costs, and you are less concerned about simplicity and ease of use.


Selecting taxonomy term in article and showing all articles titles associated with this term

Question: I have a content type article and when editing an article there should be a field where you can select a taxonomy term of a specific vocabulary.
When viewing the article it should show a list of titles of all articles associated with the selected taxonomy term. I know how to make a select field and also a view to show the titles. But how do I send the selected term to the view and how do I display the view in the article?
Answer: 1) Create a View block, when you create it use Show: Content.
2) Under Advanced Contextual Filters add Has taxonomy term ID
3) Select provide default value Type: Taxonomy term ID from URL (this will automatically grabs the term from your node) If you want, you can limit the terms by vocab.
Even if your tax term reference field is limited to 1, maybe you should set it up as if it was unlimited, in case your client later wants to allow more than 1 value.
Change the multiple-value handling option to the 2nd one, share any term.
Scroll down to MORE and check mark allow multiple values.

Click Apply, to save the settings.

Now you want to exclude the current Article (node) from the list. No point in showing the Article the visitor is already viewing/reading.
4) Add another contextual filter of ID
5) Provide default value Type: Content ID from url (automatically grabs the ID from your node).
6) Scroll all the way down, and click on MORE, and check mark Exclude.

So your Advanced section should look like this:

To place the block in your article, there are several ways.
Go to admin/structure/block and click on Place Block, search for your View Block and click on Place Block.
In the configuration, under Visibility settings, select Content Types and check mark your content type.

Site Note: There are other ways to insert/place your view:

Through a template file.
Using Panels and or Display Suite (Note: I am not 100% sure on this as I have not played much with these modules in D8, in D7 I know you can).
Comment: Ok, I found my mistake: I was adding the block within the taxonomy term view instead of creating a new view. Thank you for your effort!
Comment: Wow, this is amazing thank you! What would have to be changed if there was the possibility to select more than one taxonomy term on the content edit page?
Comment: I am on mobile ATM. I'll update the answer later. In step 3, you sroll down and click MORE and check mark Allow multiple values.
Comment: It doesn't work, now it doesn't show any titles
Comment: In step 3, change the **multiple-value handling** option to the 2nd one, share any term.
Comment: Still doesn't show anything :(
Comment: `Still doesn't show anything :(` Are u referring to in the View preview? Because it is normal for your preview to be blank since the edit View URL has no terms. Just place the View block in your article, when you go to/read your article, the titles will show up then.
Comment: No, I already placed the block. When I select one taxonomy term it shows the titles correctly, when I select two, nothing appears.
Comment: ok, give me a few mins to test.
Comment: You must of gone wrong somewhere, I tested here https://rgr9h.ply.st/node/3 and works as expected. Feel free to login: `admin2` and pass: `admin2` See the Orange Juice (/node/3) as the main example.
Answer: Regarding the placement of the block, I found another interesting thread:
How to create a field that references a Views Block display in D8?
So I tried using the modules
1) "Views Reference Fields", so you can add a field to a node to insert a specific view, especially in conjunction with Paragraphs. Unfortunately it didn't show anything on my test site. Also with Paragraphs you have to save the node and reopen before you can select a display of the selected view.
2) "Block field", so you an add a field to a node to insert a block, which can also be a block of a view. It worked for me with and without paragraphs.


Dúvida em como utilizar o Shift em Java

Question: Bom, eu estou com uma dúvida em como utilizar o Shift Left em java. Eu possuo uma String representando um valor em hexadecimal. Só que eu preciso passar esse valor para binário. Para isso eu uso uma variável inteira para transformar essa String em um número decimal:
int primeiroOperando = Integer.parseInt(addR2, 16);

E para transformar em binário, eu utilizo o toBinaryString:
String addR1 = Integer.toBinaryString(primeiroOperando);

Mas, como eu preciso fazer o Shift, pois tenho que tirar os bits menos significativos, eu não posso usar essa String pois tem que usar um número inteiro para isso.
Como posso fazer essa conversão de binário para guardar em uma variável inteira e assim poder fazer o Shift?
Answer: O binário é apenas uma representação. Você pode usar o shift com decimal, hexadecimal, etc, como mostra o exemplo abaixo:
    int i = 7;
    int x = i >> 1;
    int y = i << 2;
    System.out.println(String.format("i=%d, x=%d, y=%d", i, x, y)); // i=7, x=3, y=28

Comment: Igor, o `shift` é uma operação a nível de bits, então é totalmente independente do esquema de exibição do número. Tente transformar o exemplo aqui do Murillo em binário, pode facilitar o entendimento da operação.
Comment: Agora entendi, muito obrigado!

Dúvida em como utilizar o Shift em Java


How to create a view showing content linked with an entity reference field?

Question: I have 2 content types: Developments and Carousel Images. Carousel Images has an entity reference field to select the Developments page it is linked to.
I simply want to create a view which will display on all Development pages, but only show the images which are linked to it. So the Development page called 'London' will display a view with all Carousel images where 'London' is selected in the entity reference field.
I have tried using contextual filters and relationships but not been able to get this working.
Any ideas?
Comment: This may be helpful: http://drupal.stackexchange.com/questions/32510/how-to-use-entity-reference-and-views - in short it's possible, it's just a little complex.
Comment: Thanks for the reply. I did look at this, but it seems to be more to do with showing content in a view from linked content types. I'll check again in case I missed something but what I want is to dynamically link the content of a view to display in a block in a different content type based on.a link through possibly an entity reference fiield.
Comment: OK, finally worked out how to do it. Thanks to this video which explains it all: https://www.youtube.com/watch?v=4Pdii7aFIvc&t=392s
However, in case anyone else is stuck you need to first create a relationship based on your entity reference field, sthen create a contextual filter using node:id based on url. This is all you need to do.
Answer: OK, finally worked out how to do it. Thanks to this video which explains it all: https://www.youtube.com/watch?v=4Pdii7aFIvc&t=392s
However, in case anyone else is stuck you need to first create a relationship based on your entity reference field, sthen create a contextual filter using node:id based on url. This is all you need to do.


Buying same product simultaneously in drupal commerce

Question: Case: There is a product in stock with 1 quantity. Now two or more buyers try to buy that product simultaneously.
I want to restrict any one from buying that product on first come first serve basis.
Is there any hook available ?
Please help.
Answer: Check out Commerce Stock - https://www.drupal.org/project/commerce_stock. The module itself will expose hooks for controlling stock. Or there are sub modules it provides - Simple Stock and Simple Stock Rules - which add an integer field and use Rules to validate purchases.
This runs on Add to Cart, Can Checkout, and prior to purchase.
Answer: Create a custom module. like

custom_module.info
custom_module.module

and write this code in module file.
<code>// form alter
function custom_module_form_alter(&$form, $form_state, $form_id) {
    if($form_id == 'commerce_checkout_form_checkout'){
        $form['buttons']['continue']['#submit'][] = 'paypal_check_handler';
    }
}
// form handler
function paypal_check_handler(&$form, $form_state){
    $order_number = $form_state['order']->order_number;
    $return = _get_current_stock($order_number);
    if($return=='goto_paypal'){
        db_query("UPDATE commerce_order SET status = 'checkout_payment' where order_id='$order_number'");
     }else{
       db_query("UPDATE commerce_order SET status = 'checkout_checkout' where order_id='$order_number'");
       drupal_set_message("Stock not available");
       drupal_goto('cart');
    }
}

/* To show items in cart on paypal window closed*/
function custom_module_commerce_checkout_page_info_alter(&$checkout_pages) {
  $checkout_pages['payment']['status_cart'] = TRUE;
}
/**
 * This function check current stock.
 */
function _get_current_stock($order_id) {

    global $user;
    $order = commerce_cart_order_load($user->uid); // get user order details

    // get all product id of current order
    $results = db_query("SELECT cp.product_id AS product_id, cli.quantity AS order_qty,fcs.commerce_stock_value AS stock_qty FROM commerce_line_item AS cli LEFT JOIN commerce_product AS cp ON cli.line_item_label=cp.sku LEFT JOIN field_data_commerce_stock AS fcs ON cp.product_id=fcs.entity_id WHERE cli.order_id='$order_id' AND cli.type ='product' ")->fetchAll();

    $product_ids = $qty = $stock_qty = array();
    /*
     * @var $product_ids            : Product ID array.
     * @var $qty[$product_ids]      : get each Product order quantity.
     * @var $stock_qty[$product_ids]: get each Product stock quantity.
     */
    foreach($results As $value){
        if(!empty($value->product_id)){
            $product_ids[] = $value->product_id;
            $qty[$value->product_id] = (int)$value->order_qty;
            $stock_qty[$value->product_id] = (int)$value->stock_qty;
        }
    }
    // product id array convert in string forn sql.
    $product_ids_query = implode($product_ids, ',');
    /*
     * Here get product remaining stock
     * @stock   : Stock
     * @order   : Order qty in order table ( status is checkout_payment).
     * @avail   : available qty
     * @stock - @order = @avail
     */
    $results2 = db_query("SELECT cli.line_item_label AS line_item, cp.product_id AS product_id,cli.quantity AS order_qty, FORMAT(SUM(cli.quantity),0) total_order_qty,  FORMAT(fcs.commerce_stock_value,0) AS total_stock_qty, FORMAT((fcs.commerce_stock_value - SUM(cli.quantity)),0) As available_qty FROM commerce_line_item AS cli LEFT JOIN commerce_product AS cp ON cli.line_item_label=cp.sku LEFT JOIN field_data_commerce_stock AS fcs ON cp.product_id=fcs.entity_id LEFT JOIN commerce_order AS co ON co.order_id=cli.order_id WHERE co.`status`='checkout_payment' AND fcs.commerce_stock_value!=0 AND cp.product_id IN ($product_ids_query) GROUP BY cp.product_id")->fetchAll();

    $available_qty = array();
    foreach($results2 As $value2){
        $available_qty[$value2->product_id] = $value2->available_qty;
    }
    $redirection_var = 'goto_paypal';
    foreach($product_ids AS $product_chk){
        if(!empty($available_qty[$product_chk])){
            $current_stock_qty = (int)$available_qty[$product_chk];
        } else {
            $current_stock_qty = (int)$stock_qty[$product_chk];
        }

        $ordered_qty = $qty[$product_chk];

        if($current_stock_qty > 0){
            // go to paypal
             $redirection_var;
        } else {
            return $redirection_var = 'not_goto_paypal';
        }
    }
    return $redirection_var;
}
</code>
Comment: Thank you...exactly what I was looking for. This will surely help others.
Comment: This code isn't using sanitized query variables. At least update your code to use placeholders  - https://www.drupal.org/node/310072


RRULE google-rfc-2445 with hour and seconds

Question: I'm working with the implementation google-rfc-2445 (https://code.google.com/p/google-rfc-2445/) to generate the date which should be repeated following an event, not as a rule indicate (RRULE) that the repetition is done taking also note the time, ie the date is calculated next time I throw too.
example:
Start Date: 17/04/2013 8:30 a.m.
Rule: "RRULE: FREQ = DAILY; UNTIL = 20130430T083000Z, INTERVAL = 1"
Expected Result, Next Repetition: 4/18/2013 8:30 a.m.
Result Obtained, Next Repetition: 4/18/2013 00 00 00

This is the code I'm using
 LocalDate start = new LocalDate(System.currentTimeMillis());

            String ical = "RRULE:FREQ=DAILY;"
                    + "UNTIL=20130430T083000Z;"
                    + "INTERVAL=1;";

            //Next Notification
            Date f = null;

            for (LocalDate date
                    : LocalDateIteratorFactory.createLocalDateIterable(ical, start, false)) {
                 f  = date.toDateTimeAtCurrentTime().toLocalDate().toDate();
                break;
            }

            System.out.println("Next = " + f);

The printing result is
Next = Wed Apr 17 00:00:00 COT 2013
It is the existence of "BYHOUR = 8; BYMINUTE = 05; BYSECOND = 10" but not how to use it, if I can lend a hand, thank you.
Comment: Your RRULE seems to be malformed.  It contains commas where there should be a semicolon and extraneous spaces.  What is the exact rule you're using?
Comment: RRULE: FREQ = DAILY; UNTIL = 20130430T083000Z, INTERVAL = 1
Comment: I see `String ical` in your code sample which includes the correct punctuation.
Answer: LocalDateIteratorFactory produces dates without a corresponding time, but it sounds like you want DateTimes.  Use DateTimeIteratorFactory instead.
Also,
LocalDate start = new LocalDate(System.currentTimeMillis());

is probably not equivalent to
Start Date: 17/04/2013 8:30 a.m.

You probably want to use DateTime
DateTime start = new DateTime(2013, 4, 17, 8, 30, 0);

Finally, there's no reason to use the Joda time compatibility layer if what you want at the end is
Date f = null;

Just use the java.util compatibility layer instead.
I would suggest sticking to Joda time though, since java.util dates are a mess.
Comment: One more question, is it possible to indicate the start time in the RRULE? , For no DateTime start, but from the current date.
Comment: @GustavoSalgado, No.  RFC-2445 requires both to specify the behavior of an RRULE, and doesn't specify a syntax for combining them.
Comment: For serves then "BYHOUR = 8; BYMINUTE = 05; BYSECOND = 10" ?


ANT_HOME is set incorrectly or ant could not be located

Question: I'm trying to build a project in Ant, using BuildFile (build.xml).
Although ANT_HOME environment variable clearly exists and is set to the path where "ant.bat" is located, it always displays this error message.
How to configure Ant properly to compile builds in Windows?
Thanks
Comment: I was appending a ";" after ANT_HOME just like how we do for PATH. Because of this it was not working. Adding it here, someone may find it useful..
Answer: Actually ANT_HOME should NOT be set where ant.bat is located.
It should be set to the ant.bat parent directory.
E.g.
C:\apache-ant-1.8.1 <-- ANT_HOME
  |
  bin <-- this is where ant.bat lives.

As duffymo correctly pointed out the ANT_HOME/bin still must be on your PATH.
Comment: Note too that changing an environment variable like ANT_HOME won't be picked up by any command-prompt windows already open. If (like me) you had ANT_HOME pointing at the \bin directory where ant.bat lives, you also need to close your command-prompt window and open a new one.
Comment: @Roger_S just cost me a few hours...
Answer: ANT_HOME might be set, but that doesn't mean the path to /bin is in your PATH so the OS can find it.
Add ANT_HOME/bin to your PATH and the OS will be able to find ant.bat.
Comment: if this doesn't work, go download the latest version. (not even sure what version i had...) +1
Answer: Just sharing my experience, using cd %ANT_HOME% can point out errors in setting the variable correctly.

ANT_HOME should point to the parent directory, not the bin.
Path should include %ANT_HOME%\bin
The ant.bat file under bin is editable, it can be altered to print the current value for ANT_HOME for troubleshooting.
A system reboot is probably required for the system variables to get updated.
Comment: Thank you a lot about (3)! Adding a log sentence to the ant.bat, and checking the current ant version helps a lot!
Answer: The ANT_HOME variable has to be a reference to the directory where the bin folder is found such as C:\Apps\apache-ant-1.8.4-bin\apache-ant-1.8.4\
The PATH reference can than be a reference to the ANT_HOME variable and the bin folder such as %ANT_HOME%\bin
example:
SET ANT_HOME=C:\Apps\apache-ant-1.8.4-bin\apache-ant-1.8.4\
SET PATH=%ANT_HOME%\bin

Answer: ANT_HOME should be set to the directory where ant is installed. e.g.
If your ant installation is located at: C:\tools\apache-ant
Your ANT_HOME should be set: set ANT_HOME=C:\tools\apache-ant at the System Environment settings and not User Environment Settings
Answer: I've had the same problem, and this is how I resolved it:
Open your ANT directory and check that all the ANT files exist (like directories for bin,lib,etc...)
I found my ANT directory was abnormal, just bin was there, the others like lib were missing. (I'm not sure what caused this)
If you have missing files/directories, unzip the apache-ant-1.9.4-bin.zip again, and make sure all the files exist.
Comment: Follow link works for me..http://stackoverflow.com/questions/5607664/error-installing-ant-ant-home-is-set-incorrectly/32183652#32183652
Comment: thanks.This resolved the issue for me.I didn have the lib folder inside ant home.
Answer: If you are using Bamboo, make sure that the ant path in Bamboo setting is the same as your ANT_HOME.
Answer: I had the same problem and none of these solutions worked, so i simply deleted my ANT_HOME from enviroment variables, restarted my PC and I was all set to go
Answer: Check your existing PATH that may already included. Ant will not work if path is duplicated.


I can't move my image using the css selectors?

Question: I'm trying to move the icons or images to the center of the css circles which I'm using as background (which I called blocks). They appear at the corner of the circle, so I try to position it to the center. There seems to be something wrong with my selector code, or something else maybe. It isn't changing the position of the icons whether I try margin or anything.

html,
body {
  font-family: Bahnschrift;
  font-size: 13;
}

h1,h2,h3{margin: auto; text-align:center;}

.wrap {
  max-width: 1100px;
  margin: 0 auto;
}

header {
  width: 100%;
  height: 108px;
  background-color: #001e22;
}

header .wrap > img {
  margin-top: 17px;
}

nav {
  float: right;
  margin-top: 35px;
}

li {
  font-size: 18px;
  display: inline-block;
  margin-left: 48px;
}

a {
  color: white;
  text-decoration: none;
}

.banner > img {
width: 100%;
}

.wrap .block-row {
background: white;

}

.wrap #block1{
margin-left:80px;
margin-right:80px;
margin-top:80px;
width:100px;
height:100px;
background-color:#2fcbe0;
border-radius:100px;
display:inline-block;
}

.wrap #block2{
margin-left:80px;
margin-right:80px;
margin-top:80px;
width:100px;
height:100px;
background-color:#2fcbe0;
border-radius:100px;
display:inline-block;

}

.wrap #block3{
margin-top:80px;
margin-left:80px;
margin-right:80px;
width:100px;
height:100px;
background-color:#2fcbe0;
border-radius:100px;
display:inline-block;
}

.wrap #block4{
margin-top:80px;
margin-left:80px;
margin-right:80px;
width:100px;
height:100px;
background-color:#2fcbe0;
border-radius:100px;
display:inline-block;
}

h1{margin-top:80px; font-size:48px;}

.wrap #block1,
.wrap #block2,
.wrap #block3,
.wrap #block4 {
    position: relative;

}
.wrap #block1 span,
.wrap #block2 span,
.wrap #block3 span,
.wrap #block4 span {
    position: absolute;
    top: 120px;
    font-size: 26px;
}

.wrap #block1 p,
.wrap #block2 p,
.wrap #block3 p,
.wrap #block4 p{
position: absolute;
top:150px;
width:230px;
text-align:center;
left:-60px;
font-size:15px;
}

.wrap #block1 span{
left:10px;}

.wrap #block2 span,
.wrap #block3 span,
.wrap #block4 span {
    left:-10px;

.block-row .wrap > img{position:relative; top:-30px;}

CONTACT US

SOFTWARE USED

PROJECT

ABOUT US

HOME

SOME ICONS

  ABOUT
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.

  COMPANY
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.

  SERVICES
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.

 CONTACT
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.

Comment: Did you try `text-align: center`?
Comment: @ManojKumar yes
Answer: Give margin to the image to position it. Try the code below.

html,
body {
  font-family: Bahnschrift;
  font-size: 13;
}

h1,h2,h3{margin: auto; text-align:center;}

.wrap {
  max-width: 1100px;
  margin: 0 auto;
}

header {
  width: 100%;
  height: 108px;
  background-color: #001e22;
}

header .wrap > img {
  margin-top: 17px;
}

nav {
  float: right;
  margin-top: 35px;
}

li {
  font-size: 18px;
  display: inline-block;
  margin-left: 48px;
}

a {
  color: white;
  text-decoration: none;
}

.banner > img {
width: 100%;
}

.wrap .block-row {
background: white;

}

.wrap #block1{
margin-left:80px;
margin-right:80px;
margin-top:80px;
width:100px;
height:100px;
background-color:#2fcbe0;
border-radius:100px;
display:inline-block;
}

.wrap #block2{
margin-left:80px;
margin-right:80px;
margin-top:80px;
width:100px;
height:100px;
background-color:#2fcbe0;
border-radius:100px;
display:inline-block;

}

.wrap #block3{
margin-top:80px;
margin-left:80px;
margin-right:80px;
width:100px;
height:100px;
background-color:#2fcbe0;
border-radius:100px;
display:inline-block;
}

.wrap #block4{
margin-top:80px;
margin-left:80px;
margin-right:80px;
width:100px;
height:100px;
background-color:#2fcbe0;
border-radius:100px;
display:inline-block;
}

h1{margin-top:80px; font-size:48px;}

.wrap #block1,
.wrap #block2,
.wrap #block3,
.wrap #block4 {
    position: relative;

}
.wrap #block1 span,
.wrap #block2 span,
.wrap #block3 span,
.wrap #block4 span {
    position: absolute;
    top: 120px;
    font-size: 26px;
}

.wrap #block1 img,
.wrap #block2 img,
.wrap #block3 img,
.wrap #block4 img {
  margin:40px;
}

.wrap #block1 p,
.wrap #block2 p,
.wrap #block3 p,
.wrap #block4 p{
position: absolute;
top:150px;
width:230px;
text-align:center;
left:-60px;
font-size:15px;
}

.wrap #block1 span{
left:10px;}

.wrap #block2 span,
.wrap #block3 span,
.wrap #block4 span {
    left:-10px;

.block-row .wrap > img{position:relative; top:-30px;}

CONTACT US

SOFTWARE USED

PROJECT

ABOUT US

HOME

SOME ICONS

  ABOUT
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.

  COMPANY
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.

  SERVICES
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.

 CONTACT
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.

Added this extra code. Change margin value according to your need.
.wrap #block1 img,
.wrap #block2 img,
.wrap #block3 img,
.wrap #block4 img {
  margin:40px;
}


How to get key (index) value of a textbox in array textboxes

Question: I want a jQuery function or javascript that alert the index and the value of array textboxes : e.g.
<input type="text" name="textbox[]" value="1" onblur="javascriptfunction(this.value,this.index)" />
<input type="text" name="textbox[]" value="foo" onblur="javascriptfunction(this.value,this.index)" />

<input type="text" name="textbox[]" value="banana" onblur="javascriptfunction(this.value,this.index)" />

Whenever mouse moves for example from the first input I have this alerted (1,0) and second is (foo,1) and so on. I couldn't find the function that does that. Please help.
Comment: yes i want to navigate the index of the current textbox
Comment: im just giving an example of what i want to do ! how to get the index or the key of that selected textbox
Answer: You can use jQuery index() and val() like

$('input').blur(function(){
  alert($(this).val() + ',' + ($(this).index()-1));
  });

<input type="text" name="textbox[]" value="1" />
<input type="text" name="textbox[]" value="foo" />

<input type="text" name="textbox[]" value="banana" />

Update
To target certain elements or have this in a named function, first, put identifiers on your elements such as a class my-class. Then, make a named function and pass it to the jQuery blur function

$('.my-class').blur( alertIndexAndVal );

function alertIndexAndVal(){
  alert($(this).val() + ',' + ($(this).index()-1));
}

<input class="my-class" type="text" name="textbox[]" value="1" />
<input class="my-class" type="text" name="textbox[]" value="foo" />

<input class="my-class" type="text" name="textbox[]" value="banana" />
Comment: How to make a function for that ? its not necessary that all textboxes send values and indexes ! thank you for your great contribution
Comment: @kallokallo, do you mean you want to have only certain inputs do this? Or do you just want to use a named function like function getValAndIndex(){...}?
Comment: Thank you Ammar ! the problem is im using jquery clone to duplicate rows that have array input fields ! your code only works on the first input and doesnt work on the rest of the input text fields that have the same name ! so i decided to try to broadcast the index for each element (textbox) using a function that i should call every time i generate a new input text field .. like this  is that possible ?
Comment: @kallokallo, can you create a fiddle?
Comment: @kallokallo, but note the fiddle above uses a newer version of jquery. Let me know if you cannot use a newer version
Comment: try to add 5 rows ! click on any in the middle you have indexx of (-1) !!
Comment: Please change it if you that would give the needed output im a lil noob in javascript and jquery
Comment: Thank yo Ammar ! got what im looking for !
Answer:

var textboxes = $('input[name="textbox[]"]');

textboxes.on('blur', function() {
    var index = textboxes.index( this );
    alert( this.value + ', ' + index );
});

<input type="text" name="textbox[]" value="1"  />
<input type="text" name="textbox[]" value="foo"  />
<input type="text" name="textbox[]" value="banana"  />
Comment: Thank you Peter, but still the code works for only first text box but not the rest ! im using this code to clone the table tr :
Comment:
Comment: maybe that what caused the problem ?
Comment: It might be helpful if you created a jsfiddle ..... which would be much easier to troubleshoot. What do you think?
Comment: You are genius Man !! thank you from the bottom of my heart !!
Comment: How do i make a function for that purpose on your last fiddle example ? so i dont have to see its execution all the time ! i need to use in some special cases
Comment: You probably need to add a class to the input elements you want to target. Then you'll use that class in your code.
Answer: I figured I'd post a javascript solution which to be honest attempts to do something like the index function of jquery although i think jquery function might be better.

var getIndexValue = function (e) {
    var children = e.parentElement.children;
    for (var i = 0; i < children.length; i++) {
        if (children[i] == e) {
            alert("Index: " + (i+1) + ", Value: " + e.value);
        }
    }
}

    <input type="text" name="textbox[]" value="one" onblur="getIndexValue(this)">
    <input type="text" name="textbox[]" value="two" onblur="getIndexValue(this)">
    <input type="text" name="textbox[]" value="three" onblur="getIndexValue(this)">

Index: (i+1)
Value: (e.value);


Get raw node id value in views template without errors

Question: I need to get the raw node id value in a views template, but the debug comments are interfering. Based on this issue I am using the following:
<code>{{ row.columns.nid |render|striptags|trim }}
</code>
Which actually works, but I am also getting errors in the dblog relating the render method:
<code>User error: "0" is an invalid render array key
User error: "wrapper_element" is an invalid render array key
User error: "attributes" is an invalid render array key
User error: "default_classes" is an invalid render array key
</code>
Is there a better way to access the raw nid in a views template?
Answer: I assume this is about a views table template, then this topic might help How to access raw data in twig template using views table format.
Otherwise you could simply use
<code>{{ row._entity.id }}
</code>


How do I let my users create organic groups?

Question: [n00b apologies] I have installed Organic Groups but am apparently too dumb to understand it.
How do I let me users create and administer their own groups? What do I need to do on the admin pages, and how do I add something on the main page to let them administer & join groups.
Sorry if this sounds dumb

Update: if they can't, and I have to - how do I add a "groups" item to the man menu and a sub-menu for each group?
Answer: see documentation for Drupal 6 http://drupal.org/documentation/modules/og or Drupal 7 http://drupal.org/node/1114852.
Answer: once you have enabled a "content type" as "group type" you can just let your users add new content of that type and it will create new groups.
It's explained very well in this screen cast.
Comment: Thanks, I normally hate podcasts & screen casts, but this was wonderful. I am working my way through all 14 videos now.


Content in Lightbox dialog

Question: Is this possible to pass some content (cck fields values) to Lightbox dialog when image belongs to the same content type is opened?
Answer: Lightbox is specifically design to preview images. For General purpose overlay preview for images, videos, iframe and any custom html/text I recommend to use Fancybox. Fancybox module is available for integration in druapl.
<code>$.fancybox("Your HTML");
</code>
Comment: Thanks. What about image attributes: title, alt, is this possible to output them on dialog?
Comment: yes title works as caption on the dialogue.
Answer: You can also use the Colorbox module which allows to load inline content and url content.

Colorbox is a light-weight, customizable lightbox plugin for jQuery 1.3 through 1.6. This module allows for integration of Colorbox into Drupal.
Images, iframed or inline content etc. can be displayed in a overlay above the current page.

Content in Lightbox dialog


Show the conditional probability

Question: Let $\theta, U_1, U_2,\ldots$ be independent and uniform on $(0,1)$. Let $X_i = 1$ if $U_i\le\theta$ ,$X_i=−1$, if  $ U_i >\theta$, and let $S_n = X_1 + \cdots+ X_n$. In words, we first pick $\theta$ according to the
uniform distribution and then flip a coin with probability θ of heads to generate a
random walk. Compute $\mathbb{P}(X_{n+1} = 1\mid X_1, \ldots,X_n).$
Let $i_1,\ldots,i_{n}\in \left\{-1,1\right\}$ and $N= \text{the cardinality of} \left\{1\le i\le n:X_i=1 \right\}$.$$\mathbb{P}(X_1=i_1,\ldots,X_n=i_n)=\theta^{N}(1-\theta)^{n-N},$$$$\mathbb{P}(X_{n+1} = 1,X_1=i_1,\ldots,X_n=i_n)=\theta^{N+1}(1-\theta)^{n-N},$$ $$\mathbb{P}(X_{n+1} = 1\mid X_1=i_1, \ldots,X_n=i_n)=\theta.$$
However, I have a sense that it may not be correct.
Comment: Shouldnt the first line be conditioned on $\theta$ since $\mathbb{P}(X_1=1)=1/2$ and $\mathbb{P}(X_1=i_1,...,X_n=i_n)=1/2^n$?
Answer: We have by the definition for conditional probability,
$$P(X_{n+1}|X_n,\ldots,X_1)=\frac{P(X_{n+1},\ldots,X_1)}{P(X_n,\ldots,X_1)}$$
and by the definitions for marginal probability and conditional independence,
$$P(X_k,\ldots,X_1)=\int_0^1\Big(\prod_{i=1}^kP(X_i|\theta)\Big)P(\theta)d\theta$$
can you take it from here?
Answer: The $\sigma$-algebra generated by $X_1,\dots,X_n$ is generated by the partition $\left\{\bigcap_{i=1}^n\{U_i\leqslant \theta\}^{\varepsilon_i},\varepsilon_i\in\{0,1\}\right\}$, where $A^1$ denotes $A$ and $A^0$ the complement of $A$. For $\varepsilon=(\varepsilon_i)_{i=1}^n\in\{0,1\}^n$, write $A_\varepsilon=\bigcap_{i=1}^n\{U_i\leqslant \theta\}^{\varepsilon_i}$. Then by the formula giving the conditional expectation of a random variable with respect to a $\sigma$-algebra generated by a partition, one has
$$
\mathbb P(X_{n+1}=1\mid X_1,\dots,X_n)=\sum_{\varepsilon\in\{0,1\}^n}
\frac{\mathbb P\left( X_{n+1}=1\}\cap A_\varepsilon\right)}{\mathbb P(A_\varepsilon)}\mathbb 1_{A_\varepsilon}.
$$
In order to compute the involved probabilities, one can condition on $\theta$ and deduced that these terms depend only on the number of coordinates $i$ for which $\varepsilon_i=1$; we write $c(\varepsilon)$ this number. If $c(\varepsilon)=k$, then using the fomula
$$
\mathbb E\left[g(X,Y)\right]=\int \mathbb E\left[g(X,y)\right]d\mathbb P_{Y}(y),
$$
valid for independent random vectors $X$ and $Y$, one gets
\begin{align}
\mathbb P\left( X_{n+1}=1\}\cap A_\varepsilon\right)&=\int_0^1\mathbb P\left( \{U_{n+1}\leqslant  t\}\cap \bigcap_{i=1}^k\{U_i\leqslant t\}\cap\bigcap_{i=k+1}^n \{U_i> t\}\right)dt\\
&=\int_0^1t^{k+1}(1-t)^{n-k}dt
\end{align}
and similarly, $\mathbb P(A_\varepsilon)=\int_0^1t^k(1-t)^{n-k}dt$. The formula mentioned by Gerard Letac allows to simplify the ratio $\mathbb P\left(\{ X_{n+1}=1\}\cap A_\varepsilon\right)/\mathbb P\left(   A_\varepsilon\right)$. Finally, letting $B_k:=\bigcup_{\varepsilon: c(\varepsilon)=k}A_\varepsilon$ gives an answer expressed as a linear combination of indicators of $B_k$.
Comment: I agree with the first line (if $\mathcal{I}_ \left\{X_{n+1\quad}=1 \right\}(X_{n+1})$ is replaced by $\mathcal{I}_ \left\{X_{n+1\quad}=1 \right\} $ but in the second line, you seem to have used independence between the $X_i$, which does not hold. Moreover, the last equal sign is not correct: you have the probability  $\mathbb P(U \leq V)$, where $U$ and $V$ have a uniform distribution on $[0,1]$ hence the probability is $1/2$.
Comment: You can have a look at $P(X_2=1,X_1=0)$ for example. $\{X_2=1\}$ and $\{X_1=1\}$ have both probability $1/2$.
Comment: @user250236 I have added a bit more details.
Comment: But I think it maybe like this:
$$\mathbb{P}(X_{n+1}=1\mid X_1,...,X_n):=\mathbb{P}(X_{n+1}=1\mid\sigma(X_1,...,X_n))$$$$=\mathbb{E}\left[\mathcal{I}_ \left\{X_{n+1\quad}=1 \right\}(X_{n+1})\mid \sigma(X_1,...,X_n)\right]$$$$=\mathbb{E}\left [ \mathcal{I}_ \left\{X_{n+1\quad}=1 \right\}(X_{n+1}) \right ]=\mathbb{P}(X_{n+1}=1)=\mathbb{P}(U_{n+1}\le\theta)=\theta.a.s.$$Where have I made errors?
Comment: Oh, thanks a lot ! I am sorry to say that I mistakenly took $\theta$ to be a constant.But why  $X_{n+1}$ is not independence with $\sigma(X_1,...,X_n)$?
Comment: Could you please clarify that $\mathbb P\left( X_{n+1}=1\}\cap A_\varepsilon\right)=\int_0^1\mathbb P\left( \{U_{n+1}\leqslant  t\}\cap \bigcap_{i=1}^k\{U_i\leqslant t\}\cap\bigcap_{i=k+1}^n \{U_i> t\}\right)dt ? $
Comment: Perhaps a slight typo, $\mathbb{P}(X_1=1,X_2=0)$ should be $\mathbb{P}(X_1=1,X_2=1)$.Then $\mathbb{P}(X_1=1,X_2=1)=\int_{0}^{1}\mathbb{P}(U_1\le t)\cdot\mathbb{P}(U_2\le t)dt=\int_{0}^{1}t^2dt=1/3\ne1/4=\mathbb{P}(X_1=1)\cdot\mathbb{P}(X_2=1).$Thanks for the additional hint you provided earlier.
Answer: Of course your answer should not depend on $\theta.$ Actually with your good notations
$$\frac{\Pr(X_{n+1}=1, X_n=i_n,\ldots, X_1=i_1)}{\Pr( X_n=i_n,\ldots, X_1=i_1)}=\frac{\int_0^1\theta^{N+1}(1-\theta)^{n-N}d\theta}{\int_0^1\theta^{N}(1-\theta)^{n-N}d\theta}=\frac{N+1}{n+2}$$ using $$B(a,b)=\int_0^{1}x^{a-1}(1-x)^{b-1}dx=
\frac{\Gamma(a)\Gamma(b)}{\Gamma(a+b)}.$$

Show the conditional probability


How to get accuracy precision, recall and ROC from cross validation in Spark ml lib?

Question: I am using Spark 2.0.2. I am also using the "ml" library for Machine Learning with Datasets. What I want to do is run algorithms with cross validation and extract the mentioned metrics (accuracy, precision, recall, ROC, confusion matrix). My data labels are binary.
By using the MulticlassClassificationEvaluator I can only get the accuracy of the algorithm by accessing "avgMetrics". Also, by using the BinaryClassificationEvaluator I can get the area under ROC. But I cannot use them both.
So, is there a way that I can extract all of the wanted metrics?
Answer: Have tried to use MLlib to evaluate your result.
I've transformed the dataset to RDD, then used MulticlassMetrics in MLlib
You can see a demo here: Spark DecisionTreeExample.scala
<code>private[ml] def evaluateClassificationModel(
      model: Transformer,
      data: DataFrame,
      labelColName: String): Unit = {
    val fullPredictions = model.transform(data).cache()
    val predictions = fullPredictions.select("prediction").rdd.map(_.getDouble(0))
    val labels = fullPredictions.select(labelColName).rdd.map(_.getDouble(0))
    // Print number of classes for reference.
    val numClasses = MetadataUtils.getNumClasses(fullPredictions.schema(labelColName)) match {
      case Some(n) => n
      case None => throw new RuntimeException(
        "Unknown failure when indexing labels for classification.")
    }
    val accuracy = new MulticlassMetrics(predictions.zip(labels)).accuracy
    println(s"  Accuracy ($numClasses classes): $accuracy")
  }
</code>
Answer: You can follow the official Evaluation Metrics guide provided by Apache Spark.
The document has provided all the Evaluation Metrics including

Precision (Positive Predictive Value), Recall (True Positive Rate),
F-measure, Receiver Operating Characteristic (ROC), Area Under ROC
Curve, Area Under Precision-Recall Curve.

Here is the link : https://spark.apache.org/docs/latest/mllib-evaluation-metrics.html
Comment: thank you, but this is RDD-Based and it uses "mllib" library. I work with dataframes and datasets and "ml" lib.
Comment: Oh Sorry for that. Check this [link](https://www.mapr.com/blog/predicting-breast-cancer-using-apache-spark-machine-learning-logistic-regression) maybe you get something. I'm not much familiar with ml.


How do I make on Domain Controller be used more to logon than another Domain controller on the same network?

Question: I am currently working in an environment where there are 2 DC's running and another DC that is a backup but is currently running as well so that if the other 2 fail, the backup has everything needed to be ran successfully.
The problem that I am currently encountering (really isn't too much of a problem, just the client would like it to run a certain way)is that when some users login, they are getting their group policies from the Disaster Recovery DC. The reason this is happening is because they are all on the same network with same subnet mask etc.
My question is, is there a way so that when a user logs in, the computer will be more inclined to go to the 2 main DC's rather than the Disaster Recovery DC?
Would it be with the metrics of the routing, or is there a certain part of the server that I can turn on and make it the more "Dominant" server.
The servers are Windows 2k8 servers running as VM's. Any more info needed I can get.
Thanks!
Comment: I think smithian has given a good answer, but I'm going to have to ask where this notion that another DC in the domain is a "Disaster Recovery" domain controller. It will obviosly help if the other DC fails (and this isn't "disaster recoverery", it's multimaster domain controllers behaving as designed), but if someone deletes something important from AD then... oops it's replicated to the "disaster recovery DC". Have you explained to your client that Microsoft doesn't describe additional DCs in a domain as "disaster recovery DCs" for a very good reason?
Comment: Can you please define *exactly* what you mean by "backup domain controller"?
Answer: Your client is doing it wrong. There's no such thing as a "disaster recovery" DC. for all intents and purposes all DC's are equal. You're allowing your client's lack of understanding to drive this scenario when you should be educating them instead. Without getting into the vagaries of FSMO role holders, global catalogs, AD authentication and authorization, Site coverage, replication, etc., etc. and all of the other minute details of AD function and operation I'll simply say that you don't need a "disaster recovery" DC; that the term "disaster recovery DC" is anathema to people who do understand the workings of AD; and that you should stop immediately and educate yourself on the finer points of Active Directory before moving forward with making any modifications.
Answer: If you are truly using the second DC as a 'disaster recovery' DC, then you should move it to a second site in AD Sites and Services.  This will cause the clients to authenticate to the 'closest' DC.  I typically setup two DC's for disaster recovery, but I allow the clients to use them both.
If you are pulling different GPO's from the DR server, then something is very wrong with your setup.  GPO's should be synced across all servers within minutes of being changed.
Answer: You can change the weights of the entries in _msdcs.yourdomain.com to make the Disaster Recovery DC less preferred.  By default they will have the same weight and clients will round-robin between them.
I don't recommend manually futzing with your domain controller DNS entries however.  It would be cleaner to move the DR DC into a separate site in ADSS.


Count data with continuous variables

Question: Let's assume one has looked at the occurence of a plant species at different altitude, different temperature and environment. Here are its data:
               Temperature    environment   altitude
    plant1        18.1           mud         812
    plant2        15.3          field        754
    plant3        17.4           mud         213
    plant4        15.2          forest       678
    plant5        16.6          field        1023
    etc...

This guy wants to know if the abondance of plants (number of plants) that one can find is dependent on the three variables. He could run a GLM with poisson distributed errors for the environment variable with these data:
Number of plants     environment
     311               forest
     102                mud
      71               field
     etc...

How could he do in order to evaluate the effect of continuous variables on the abondance of plants without having to cut the variable into chunks (Temperature: [10.1:13], [13.1:16], [16.1:19])? What type of model can incorporates continuous and categorial variables in order to makes sense of count data?
Would it make sense to run two Kolmogorov-Smirnov tests on Temperature and altitude to check if these variables are uniformly distributed and a test GLM, poisson distributed errors for environment? But then what happen if it tends to have more mud in high altitude? He would need one model with all variables.
Answer: A Poisson GLM can incorporate both continuous and categorical variables (like any regression-type model). Why do you think it could not?
Comment: So I don't quite understand how I could express my data in the model. The response variable should be a count of the number of plants observed in a each category, isn't it? So, we're obliged to express the explanatory variables into categories. Thanks for your help
Comment: No more so then with any other regression model. E.g. if the response was weight and explanatory was height, you would only observe weight at certain specific heights (the ones in the data set). That's how regression works.
Comment: Ok, so my response variable should be made of 0 and 1 only. presence-absence. Correct?
Comment: Now I am confused as to what data you have. Does each plant have a different altitude? If so, you probably want logistic regression. Or do many plants have the same altitude? Then it would be some form of count model.
Comment: Each plant has a different altitude (and different temperature). Many plants live in the same environment.
Comment: OK, sorry for being confused. I think you want some form of logistic; quite likely a multilevel model with nesting on "environment".
Comment: Ok. Sorry to extend discussion but it really helps me! And the response variable should be made of 0 and 1, is it correct?  If I had only the environment variable. Should I use a logistic model with 0 and 1 in response variable or should I count the number of plants in each environment and run a Poisson GLM?
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/11818/discussion-between-peter-flom-and-remi-b)

Count data with continuous variables


Convert Inner Join to Subquery in PostgreSQL

Question: I am joining two tables with the student table using the inner join below:
select (first_name || ' ' ||last_name) as "Student Name", gender, race from student
inner join gender on student.gender_id = gender.gender_id
inner join race on student.race_id = race.race_id

I want to know how I can get the same result using a subquery instead of using inner join on PostgreSQL?
Below are my code for the three tables (Student, Gender, Race) that I have created:
create table Student(Student_ID int primary key, first_name varchar(30), last_name varchar(30), gender_id int, race_id int, constraint gender_id_fk foreign key(gender_id) references gender(gender_id), constraint race_id_fk foreign key(race_id) references race(race_id));
create table Gender(Gender_ID int primary key, Gender varchar(30));
create table Race(Race_ID int primary key, Race varchar(30));
insert into Gender values(1, 'Male');
insert into Gender values(2, 'Female');
insert into Gender values(3, 'Other');
insert into Race values(1, 'White');
insert into Race values(2, 'Black');
insert into Race values(3, 'Asian');
insert into Race values(4, 'Native American');
insert into Race values(5, 'Other');
insert into Student values(1, 'John', 'Smith', 1, 1);
insert into Student values(2, 'Sara', 'Lee', 2, 3);
insert into Student values(3, 'Sam', 'Crawford', 3, 5);
insert into Student values(4, 'Cindy', 'Williams', 2, 2);

Below is the ERD relationship diagram in case if you need to take a look:
ERD Diagram
**Desired Output using subquery below: **
Output from Subquery
How can I get the same result using a subquery instead of using inner join?
Comment: What's wrong with joins?
Comment: So your current query returns the correct result? Why change it? What advantage do you expect?
Comment: Please don't post textual data, such as query results, as images. Why do you want to use subqueries instead of joins? In many cases, perhaps most, joins perform better than subqueries.
Comment: The big question is why would you move away from an industry standard? I don't see any benefits, only downsides in readability and maintenance. Everyone understands a JOIN.  And if they don't, they should not come even close to your code.
Answer: Heres the query without JOINS:
SELECT
  (first_name || ' ' || last_name) AS "Student Name",
  (SELECT gender FROM gender WHERE gender_id = student.gender_id) AS gender,
  (SELECT race FROM race WHERE race_id = student.race_id) AS race
FROM
  student;

Output:

Note: Its better to use JOINS, as they are faster as compared to SUBQUERIES for indexed data.
Comment: This query is not functionally equivalent to the original query with inner joins: it would be equivalent to the original query with outer joins to `gender` and `race`.
Answer: Your original query is the most straight-forward way. Because what you are trying to achieve is to create a joint view of multiple tables fully stitched together using a common key, which is exactly what JOIN is for. Also, subquery is usually used when there are more layers to the question rather than a case of just fully stitching tables together.
If you just don't want to use INNER JOIN, but achieve the result as INNER JOIN, using a CROSS JOIN with WHERE clause does the job as well. But I think it is unnecessary.
SELECT
  (s.first_name || ' ' ||s.last_name) AS Student_Name,
  g.Gender AS Gender,
  r.Race AS Race
FROM Student AS s, Gender AS g, Race AS r
WHERE g.Gender_ID = s.gender_id AND r.Race_ID = s.race_id;

There are usually 4 types of subquery

WITH: this is used when you'd like to pseudo-create a temporary
table from an existing table and place it at the top of the larger
query
Nested: it is used when you'd like the temporary table to act as a
filter within the larger query, and it often sits within the WHERE
clause
Inline: it is used in the same way as the WITH. Instead of the
temporary table sitting on top of the larger query, it's embedded
within the FROM clause.
Scalar: it is used when you want to generate a scalar value to be
used as a benchmark

None of above is really needed in this case.
On a side note, looking at the ERD, you are indicating that student table has one-to-many relationship with gender table and race table, so one student can have multiple different genders or races? or should it be one race or gender can correspond to multiple students? or are you better off just combining all into one table, race and gender are attributes about a student, then you don't even have to do a join? These are interesting questions to consider.


Installing Sharepoint 2007 on Windows Server 2008 R2

Question: we are using in our lab a clean installation of Windows Server 2008 R2 which is running as Hyper-V instance. Today we wanted to install a clean installation of Sharepoint 2007 with SP1 on this machine and we explorer an error that we are not able to install it. The setup is comes up with an error which is described here: http://support.microsoft.com/kb/962935 but this is not our szenario. A printscreen of this message can be found here: http://www.ronischuetz.com/images/SP_2007SP1_Inst_Error.png
@Microsoft,
my personal point of view is that it cannot be that we need to install first 2008, then Sharepoint 2007 with SP1, then SP2 and upgrade to 2008 R2. Nobody is going be happy with this solution and I hope we find a fast way how customers can install Sharepoint direclty on 2008 R2.
Anyway, thanks in advance for any further information how we should go on with this issue.
The issue is listed here: http://social.msdn.microsoft.com/Forums/en-US/sharepointadmin/thread/91a6be50-9009-43c8-a37c-66cfb83d738f
Answer: You can install SharePoint on Windows Server 2008 R2. You don't need to install it on Windows Server 2008 and then upgrade to Windows Server 2008 R2.
The issue is that Windows Server 2008 R2 is only compatible with Office SharePoint Server 2007 SP2.
Unfortunately, Microsoft have not released a version of SharePoint with SP2 built in, however it is fairly easy to do this yourself. You can create your own slip-streamed installation of SharePoint with SP 2 included and then install this directly onto Windows Server 2008 R2 (no upgrade required).
To slip-stream SharePoint see:

Create an installation source that includes software updates (Office SharePoint Server 2007)

I've done this with Office SharePoint Server 2007 SP2 and it installs fine on Windows Server 2008 R2.
Comment: @Hirvox - you shouldn't have to rename setup.exe. Are you sure that SP2 was slipstreamed correctly?
Comment: I tried to do this with Sharepoint 2007 RTM (with SP2 slipstreamed) and Windows Server 2008, but the Program Compability Assistant still complained about setup.exe. However, renaming setup.exe allowed the installation to continue.


Am I overusing Spring singletons?

Question: I have read many bad things about Singleton design pattern, but from what I gather, Spring singleton is not the same thing and it's perfectly fine to use it.
However recently I started wondering if I am not overusing that in the new application I am working on. Almost all of my classes in this application are Spring singleton beans. It's a Jersey web service with few service classes that would have business objects classes injected (IoC) that would contain all the business logic and communicate with DAO classes, which are also injected by Spring.
I thought that because I can make all my classes stateless easily, so there is no thread safety issues and because Spring has the instance of the class cached, performance-wise this would be reasonable solution.
I have since seen an application developed for my company by third party supplier, which is software house and they have all their Spring beans defined as "singleton=false", even though most of them dont hold any state. I started wondering, would that be a best practice approach to Spring beans and if I am in fact overusing singletons?
Would anyone have any comments on the matter in terms of best practices? Should I use Spring singleton whenever I can or should I stay away?
Comment: I don't think there's such a thing as "overusing." Just make sure that you're using them appropriately (i.e. scope your beans properly). For more information, see [Bean scopes](http://docs.spring.io/spring/docs/3.0.0.M3/reference/html/ch04s04.html).
Comment: I think you're fine.  I'm not so sure about the third party supplier.  If they have no intention of ever creating multiple instances of a bean, then labeling it `singleton=false` is misleading to the reader of the config file.
Answer: Your approach is fine. The usual problem with singletons (aside from global mutable state, which it sounds like is not an issue here) is that the singleton manages its own single-ness (meaning things like static getInstance methods), making it difficult to test. In Spring that's handled by having the factory control the scope of the singletons.
Another troublesome aspect to singletons is how anything can get called from anywhere. You can handle this with a disciplined approach to layering.
Comment: The usual problem with singletons is that they get overused and the application data becomes fragmented and incoherent.
Comment: @Hot: agreed, if my edit doesn't cover that I'm open to suggestions.

Am I overusing Spring singletons?


Javascript Code fails in Mozilla Firefox

Question: function getSelectedRadio(seeker_provider) {
  var sign;
  for (var i=0; i<seeker_provider.length; i++) {
    if (seeker_provider[i].checked)
    {
      sign=i;
    }
  }
  if(sign==0)
  {
    alert(sign);
    window.location='updatcty.php';
  }
  if(sign==1)
  {
    alert(sign);
    window.location='../registration_provider.php?proid=2222221 & pagname=select';
  }
  // alert(document.all.seeker_provider.value);
}

I wrote this JavaScript function for getting the selected radio button value and redirect accordingly, but it supports all browsers except Firefox 3.0.6. What can I do?
Comment: What you can do is tell us what happens when you run that code in Firefox 3.0.6.
Comment: 1. Is it possible to see how you get seeker_provider?
2. You must define default value for sign.
Comment: Firefox has a handy javascript console: ctrl+shift+j. What error are you getting?
Answer: Try changing this line:
window.location='../registration_provider.php?proid=2222221 & pagname=select';

to this:
window.location='../registration_provider.php?proid=2222221&pagname=select';

Comment: Why would that work? The url path doesn't use & for escaping. If anything it should be %26, but that's not what he's trying to do either...
Comment: He's obviously trying to pass parameters in the querystring, which should be separated by &, which should be encoded as &.

Regarding the answer, I'm making a best-effort guess considering the dearth of information. If the actual problem/solution is different I will "terminate" this answer.
Comment: When you want to pass the string, you need to encode: `name=Ben%26Jerry`. When you want a second parameter you shouldn't encode: `id=1&title=hello%20world`. Either way, `&` is for HTML, not for url. Feel free to test it.


PYTHON - Como passar um parâmetro?

Question: Eu estou tentando montar o jogo da cobrinha usando python, porém eu me deparei com um problema que travou completamente meu código.
Eu utilizei a biblioteca tkinter e todas as suas funções para criar o jogo, segue o código:
import tkinter
import random
from time import sleep

window = tkinter.Tk()

width = 800
height = 600

#FUNÇÃO QUE CRIA O MAPA

def Create_map(width, height):
    mapa = tkinter.Canvas(width= width, height= height, bg='black')
    mapa.pack()
    coordenadas = [10,10]
    Create_snake(coordenadas, mapa)
    Create_fruits(coordenadas, mapa, width, height)

#FUNÇÃO QUE CRIA A COBRA
def Create_snake(coordenadas, mapa):
    coordenadas = coordenadas
    snake = mapa.create_rectangle(coordenadas, 30, 30, fill='white')
    window.bind("<Up>", Move_Up)
    window.bind("<Down>", Move_Down)
    window.bind("<Left>", Move_Left)
    window.bind("<Right>", Move_Right)

#FUNÇÃO QUE CRIA AS FRUTAS
def Create_fruits(coordenadas, mapa, width, height):
    newcoord = [random.randint(10, width - 30), random.randint(10, height - 30)]
    fruits = mapa.create_rectangle(newcoord, newcoord[0] + 20, newcoord[1] + 20, fill='pink')

#FUNÇÃO QUE MOVE A COBRA
def Move_Up(key):
    print(key)

def Move_Down(key):
    print(key)

def Move_Left(key):
    print(key)

def Move_Right(key):
    print(key)

Create_map(width, height)

window.mainloop()

Eu estou usando as funções Move_Up, _Down, _Left  e _Right para atualizar a posição da cobra, porém ao utilizar o bind() eu não consigo passar nenhum parâmetro para as funções, ou seja, eu não tenho acesso ao widget snake para atualizar a coordenada e, logo, atualizar a posição da cobra. Alguém tem ideia do que fazer para passar o parâmetro nas funções que tem Move??
Comment: Ao usar funções, você pode deixar o objeto `snake` como global, já que precisará atualizá-lo de diversas funções; mas pode gerenciar esse escopo também utilizando uma classe.
Comment: Gerenciar o escopo utilizando uma classe? Alguma referência ou link de como fazer isso? Obrigado!!!
Comment: Para executar funções você deve escreve-las da forma `foo()`, do contrário a função não executará. Tente:

```
def foo(s):
    return (s)
print(foo)
print(foo(s))
```
Answer: Uma solução é criar uma função que chama a sua outra função; assim o parâmetro que você quer passar será capturado pelo escopo da função (conhecido como closure):
snake = mapa.create_rectangle(coordenadas, 30, 30, fill='white')
def chama_move_up()
    Move_Up(snake)
window.bind("<Up>", chama_move_up)

def Move_Up(s):
    # .... s é a snake ....

Uma outra solução é usar classes, e colocar esses objetos como atributos de instância self; assim eles são acessíveis em qualquer método da classe:
class Jogo:
    # ....
    def create_snake(self, coordenadas, mapa):
        self.snake = mapa.create_rectangle(coordenadas, 30, 30, fill='white')
        window.bind("<Up>", self.move_up)
        ...

    def move_up(self):
        # aqui pode usar self.snake

Answer: Então, sei que já tem muito tempo, mas vou deixar a explicação, pois pode ajudar outras pessoas...
Você consegue passar as parâmetros utilizando o lambda:
# Função que executa o .bind
def Executa_a_funcao(event, parametro): #event é o evento automático
    print(f'O evento foi {event}')
    print(f'O parâmetro foi {parametro}')

#chamada da função:
widget.bind("<Up>", lambda event, parametro = 'seu parâmetro':  Executa_a_funcao(event, parametro))

Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).

PYTHON - Como passar um parâmetro?


How to divide trigonometric ratios using identities?

Question: $$\frac{1-\tan^2x}{1+\tan^2x}$$
We know:
$$\frac{1-\frac{\sin^2x}{\cos^2x}}{1+\frac{\sin^2x}{\cos^2x}}$$
Now what? Flip denominator and times numerator?
Which equals ???
Please help - Thanks
Answer: $$
\tan^2 x + 1 = \sec^2 x
$$
Thus
$$
\frac{1-\tan^2 x}{\sec^2 x} = \cos^2x - \sin^2x
$$
But going from your point of view
$$
\frac{1-\frac{\sin^2x}{\cos^2x}}{1+\frac{\sin^2x}{\cos^2x}}= \frac{\frac{1}{\cos^2x}}{\frac{1}{\cos^2x}}\frac{\cos^2-\sin^2x}{\cos^2x+\sin^2x}=\\
\frac{\cos^2-\sin^2x}{\cos^2x+\sin^2x}
$$
then use the fact
$$
\cos^2x+\sin^2x=1
$$
Dividing through by $\cos^2x$ and knowing that $\frac{1}{\cos x} =\sec x$ will lead to the first identity.
Comment: You can simplify with `$=\cos 2x$`.
Comment: Thank you for quick response but can you "dumb it down" a little and not skip any steps.  How do we know tan^2x+1=sec^2x? Thanks
Comment: @bernard yup. But I wasn't sure how far he wanted to take it. I just wanted to show him the removal of the denominator.
Comment: that is a standard identity but I will update.
Comment: Thanks but I'm still confused - must need more coffee!


How to achieve strictly positive forecasts?

Question: I am working on a time series whose values are strictly positive. Working with various models including AR, MA, ARMA, etc, I couldn't find an easy way to achieve strictly positive forecasts.
I'm using R for doing my forecasts, and all that I could find was forecast.hts {hts} that has a positive parameter described here:
Forecast a hierarchical or grouped time series, package hts
## S3 method for class 'gts':
forecast((object, h,
  method = c("comb", "bu", "mo", "tdgsf", "tdgsa", "tdfp", "all"),
  fmethod = c("ets", "rw", "arima"), level, positive = FALSE,
    xreg = NULL, newxreg = NULL, ...))

positive
    If TRUE, forecasts are forced to be strictly positive

http://www.inside-r.org/packages/cran/hts/docs/forecast.gts
Any suggestions for non-hierarchical time series? What about generalization on using other constraints like minimum, maximum, etc?
Even if not implemented in R, suggestions on articles, models or helpful general variable transformations would be appreciated.
Comment: One of the easiest, but not always correct thing to do in such case is simply forecast the log of the variable.
Comment: To partly echo @mpiktas one approach is to work on the log-scale. In practice this often improves several aspects of the model at once. While prediction intervals transform back just fine, you have to take care with mean forecasts (if normality is reasonable on the logs, you can get an estimate for the mean of the lognormal that is usually reasonable if sample sizes are large). An alternative that can sometimes work for some simple time series models is to use a Gamma model.
Answer: With the forecast package for R, simply set lambda=0 when fitting a model. For example:
fit <- auto.arima(x, lambda=0)
forecast(fit)

Many of the functions in the package allow the lambda argument. When the lambda argument is specified, a Box-Cox transformation is used. The value $\lambda=0$ specifies a log transformation. So setting lambda=0 means the logged data are modelled, and when forecasts are produced, they are back-transformed to the original space.
See http://www.otexts.org/fpp/2/4 for further discussion.
Comment: Please ask the min/max question separately. Yes, the prediction intervals are correct when back-transformed.
Comment: @Ho1 Applied Time Series Analysis For Managerial Forecasting by NELSON ; Holden-Day 1973 pp162-165 discusses this in detail ... with a diverse opinion
Comment: Thanks Prof. Hyndman for your kind help. I think I should reread that chapter seriously! Do you think mentioning this in chapter 2-4 can help? I think so! :-) Some questions remain for me: Can some kind of transformation be used for minimum (or maximum) possible values? I'm trying to do this with a log based function, but  after all is the resulting confidence interval mathematically correct?
Comment: Unfortunately it did not work as expected, as it changed the method, and instead of a nice expected y variation on predictions, it just made a flat line around the average


how to calculate surface area of rectangular prism with given volume

Question: I am doing a math project on optimisation and have a rectangular prism with a volume of 100cm3 but no other information. I am supposed to analyse whether the manufacturer of that product has designed the optimal package to hold that volume. Any help?
Comment: You have two unknown but related variables, the length of a side of the square base and the height of the prism. You need the volume $V$ expressed as a function of those two variables and the surface area $S$ also expressed as a function of those two variables. Assuming that the manufacturer wants to minimize the surface area, use the formula for $V$ to express one of the two variables in terms of the other and substitute that into the equation for $S$ and use the method you learned in class for minimizing a functions $S$ defined in terms of a single variable.
Comment: p.s. You should attempt to work this problem for yourself using the outline which I gave in my previous comment.
Comment: @JohnWaylandBales How do you know the base is square?
Comment: @JohnWaylandBales thank you but it's a cuboid not a square-based prism
Comment: @EthanBolker Ah, thanks for pointing that out. Evidently I misread the problem. The volume and surface area will be functions of three variables, length, width and height, one of which can be expressed in terms of the other two. So one must optimize a function of two variables subject to a constraint, suggesting Lagrange multipliers.
Comment: @JohnWaylandBales I'm stuck with two variables in the equation for surface area once I made one of the sides equal 100/the other two sides and plugged that in.
Comment: @d.white You might gain some insight by solving the two dimensional problem first. What dimensions minimize the perimeter of a rectangle with fixed volume?
Comment: @EthanBolker okay thanks
Comment: Amending my earlier comment: Express both $S$ and $V$ as function of three variables and use the method of Lagrange multipliers with the constraint $LWH=100$. You should immediately find that $W=H=L$.
Comment: If the question has well-defined answer, then the optimum cannot be a rectangular prism (because we couldn't tell which one) ! So with closed eyes, the optimum is a cube and the answer is no (whatever the volume).
Answer: Volume:
$$ V=LWH=100 $$
Surface area:
$$ S=2LW+2LH+2WH $$
Using Lagrange multipliers:
$$ \nabla S=\lambda\nabla V $$
$$ \nabla S =(2W+2H,2L+2H,2L+2W) $$
$$ \nabla V=(WH,LH,LW) $$
\begin{eqnarray}
2W+2H&=&WH\lambda\\
2L+2H&=&LH\lambda\\
2L+2W&=&LW\lambda
\end{eqnarray}
Resulting in
\begin{eqnarray}
\lambda&=&\frac{2}{H}+\frac{2}{W}\\
&=&\frac{2}{H}+\frac{2}{L}\\
&=&\frac{2}{W}+\frac{2}{L}
\end{eqnarray}
So $L=W=H$. Therefore $LWH=100$ gives $L^3=100$, so $L=W=H=10^{2/3}$.
Comment: okay thank you so much! I still haven't done Lagrange multipliers but I will do some research, thank you again.
Answer: We know that $wlh=v$ and we can use this relation to eliminate $h$.
Then the (half) area is
$$wl+lh+hw=wl+\frac vw+\frac vl.$$
We minimize it by canceling the gradient,
$$\begin{cases}l-\dfrac v{w^2}=0,\\w-\dfrac v{l^2}=0\end{cases},$$ obviously giving $l=w=h$.


C# function that return instance with unknown generic type

Question: I am now implementing a function Register() which invoking other function ApiReturnFactory() inside.
    public ???? Register(string username)
    {
        var result = new AccountProcess().CreateAccount(username);
        return ApiReturnFactory.CreateInstance(result);
    }

new AccountProcess().CreateAccount(username) returns me an object like obj<WhateverType>.
ApiReturnFactory.CreateInstance(obj) returns me an object like obj2<SameTypeWithWhateverType>.
My question is the compiler have already know what type I will return in ApiReturnFactory.CreateInstance(obj) (IntelliSense do), but what should I state in the return type ???? of Register(string username)?
I don't want to specific a generic type for obj like obj<string>, this is not reasonable since the generic type may not always be a string. What I want is something like obj<T>.
Thanks in advance.
Comment: "since the generic type may not always be a string" - either this is wrong or your code sample is missing something. `result` must have a clearly defined type that is known at compile time. If it *does* then the type is fixed and can be inserted. If it *doesn't* then there must be some other use of generics within the function that you're not showing.
Comment: have you looked at the `dynamic` return type?
Comment: Could you provide exact signatures of `CreateAccount` and `CreateInstance` methods?
Comment: @Mauro I don't want to do it in such way as the object returned from `Register()` loss its type.
Comment: @Damien_The_Unbeliever Yes you are right, actually it is always returning the same type, but is there any way to make the return object auto detect the generic type?   If I want to modify `CreateAccount()` to return other generic type in the future, then I should change the return type of `Register` too?
Comment: @mannok you dont have to change the type if it implements an interface and your return type is that interfacetype see Ehsans answer
Comment: @Mauro Thanks!    I will try to understand and run it later. If it works I will mark it as acceptable ans.
Comment: But the only way that would work *close* to what your code currently does is if `CreateAccount()` were to be changed to be generic - at which point you'd just make this method generic too `public obj2 Register(string username)` and `var result = new AccountProcess().CreateAccount(username);`.
Comment: @Damien_The_Unbeliever I get what you mean, but is it reasonable for me to state the generic type of the return object again when I know the generic type of the return object `ApiReturnFactory.CreateInstance(result)` in advance?
Comment: It sounds like what you want is for type-inference to work for method return types. That's not currently available and I would guess is unlikely to appear in a future version of the C# language since I don't see a *compelling* use-case for it.
Comment: @Damien_The_Unbeliever Thanks, May I know is there any alternative way to do this?   Or any better practices in my case?
Answer: Create an interface and inherit your generic types from that interface and return that interface object back or a base class whatever is suitable in your use-case:
public interface IObject
{

}

public class GenericClass<SomeType> : IObject
{

}

and then you can return the interface object :
public IObject Register(string username)
{
    var obj = new AccountProcess().CreateAccount(username);
    return ApiReturnFactory.CreateInstance(obj);
}

Comment: I have tried this method but seems the returned object do not have the GenericClass properties in ItelliSense list
Comment: you would need to define the common members of your generic type in interface to be accessible via reference of interface type
Comment: @Ehasn Saijad Sorry I thought I don't get what you mean. Please take a look of `ApiReturn` and `IApiReturn` at [http://imgur.com/a/PAcxX](http://imgur.com/a/PAcxX). Am I doing it your way?
Comment: from the code you have shown, you don't need interface as your whole class is generic already.
Answer: public obj2<T> Register<T>(string username)
{
    var result = new AccountProcess().CreateAccount(username);
    return (obj2<T>)ApiReturnFactory.CreateInstance(result);
}