Drupal 7 Date - Is there a way to change field settings if there is data in it already?

Question: Currently I am using the date module for drupal 7 and I already have stored data in the existing date field. I want to make changes to the date field by adding "Repeating Dates", but obviously I cannot since I have data in there already. The options I came up with are:

Create a completely new date field for the content type with the additional "Repeating Dates" feature. Then copy all the old dates into the new field (im not sure how to do this easily)
Modify the existing Date field table via phpmyadmin or mysql console.

What is the suggested way to go about updating an existing field that already has data?
Comment: I think I inadvertently answered this on your [newer question](http://drupal.stackexchange.com/questions/80007/in-drupal-7-where-is-field-settings-data-stored-not-the-field-data)
Answer: I got this working by doing the following without having to write any code. Keep in mind im only doing this for the DATE type fields:
example:
my old field: field_eventdate
my new field: field_placeholder

create the same field type with a different name and the options you want.
open up phpmyadmin
goto the table: field_config
search for the new field you created (field_placeholder)
click on the data column blob and download that.
search and edit field_eventdate and upload the file you downloaded which contains the new settings.
do the same exact thing for the table: field_config_instance
now we have to update the table structures of the field to encompass these changes. I first inspected the strucuture of the new field i created and see what the old table was missing. Once you have that down, create the missing columns in the old field that exists in the new field.
Do #8 again but this time for the revisions table. In my case it would be: field_revision_eventdate
delete the field_placeholder via the content type page as you wont need it anymore.

let me know if this worked for anyone else too.
Comment: Just wanted to say this worked and I love you!!!!!!
Comment: i love you too, waffles... ^^
Comment: I'm surprised manually editing the data value by hand like that wouldn't cause problems, since it's serialized by PHP.
Answer: A more secure way than touching the database...

First create your new field with the repeating date, let's call it field_event_date
Then copy everything from the first field (field_date) to your new one

Code:
<code>$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', {your_content_type})
  ->addMetaData('account', user_load(1));

$result = $query->execute();
foreach($result['node'] as $nid => $n) {
  $node = node_load($nid);
  $node->field_event_date = $node->field_date;  // Copy one field to another
  node_save($node);
}
</code>
Comment: wouldn't this have issues if you have a large database and it exceeds the php script execution time limit?
Answer: I went about it by first capturing the original Date field with Features. Then, I created a field like I would like to target (similar to what you'd done with the placeholder) and Features-exported it. I compared the exported code and updated the original field's Feature export code, SQL-dumped the data from the field_data_field_.. table, deleted the original field by Manage Fields screen, feature-reverted to the modified Features export code, and then SQL-imported from my export.  voila!
Answer: You could take a look at this contrib module too
https://www.drupal.org/project/entity_recur


Probabilistically-weighted variance

Question: How do I calculate a statistic for one mixture component?
My samples are drawn from a distribution which is an additive mixture of two overlapping component distributions. Given a probabilistic estimate for the labelling of all the data-points (e.g. sample #13 has a 4% plausibility of having arisen from component-B), how do I estimate e.g. the standard deviation of component A?
Background
I considered a few potential approaches:

Deterministically round the probabilistic labels, to produce a non-fuzzy labelling (e.g. assign sample #13 to component-A because this is its most probable classification). Then apply the ordinary standard deviation formula to the identified subset. The downside is this labelling will create ubrupt boundaries that poorly represent the true shapes of either distribution.
A Monte Carlo approach: instantiate a non-fuzzy labelling via a random process (using the plausibilities as biases), calculate the standard deviation as before, repeat many times and take the mean. The downside is iterative computation.
Find a formula that weights samples according to their probability of belonging to the sub-population. Wikipedia contrasts "frequency weights" (positive integers representing duplicated datapoints) or "reliability weights" (which seems to quantify uncertainty/imprecision in the measured value, rather than the uncertainty about the measurement itself). Should the probabilistic classification be treated as fractional frequencies?
Apply a more robust estimator of dispersion (e.g. median absolute deviation), and if necessary convert this to standard deviation later.

This kind of scenario occurs in physics (e.g. proportional counters for radiation particle spectroscopy). Picture a detector for some phenomenon of interest, but the detector lacks specificity (additionally detecting events from an unrelated mechanism), resulting in a spurious background that confounds with the signal. Using prior knowledge, how much new information is it possible to infer about the phenomenon of interest (somehow separating out the background noise)?
Answer: As I understand you your data comes from the mixture of two distributions with density
$$ f(x_i) = \pi f_1(x_i) + (1 - \pi) f_2(x_i) $$
where $\pi$ is proportion of first class and $f_1,f_2$ are the two components. You have estimated probabilistic labels for the components and want to calculate the variance of your components.
First, recall that weighted variance is defined as
$$ \sigma^2 = \sum_{i=1}^n w_i (x_i - \bar x)^2 $$
where $w_i$ are non-negative weights such that $\sum_i w_i = 1$. In your case weights for $k$-th component is
$$ w_{ik} = \frac{ \gamma_{ik} }{\sum_{n=1}^N \gamma_{nk}} $$
where
$$ \gamma_{ik} = \frac{\pi_k f_k(x_i)}{\sum_{j=1}^K \pi_j f_j(x_n)} $$
As you noticed, $\gamma_{ik}$ can be thought as posterior probability that $i$-th observation belongs to $k$-th component.
If you wonder if this approach is valid, then you can read about EM algorithm (check also code example). For example, EM algorithm for estimating parameters of mixture of normal distributions would calculate variances of normal distributions in the M step exactly like described above.
Comment: I like that your answer cites EM (presumably "soft EM" as opposed to "hard EM"). It looks like you're suggesting a biased estimator for weighted variance; what would the unbiased estimator look like and when would either be appropriate? (Also, are you missing $\pi$ in the denominator of $w_{ki}$?)
Comment: @benjimin weighted estimators depend on the weights you provide and so will be biased. You cannot correct them allowing for arbitrary weights at the same time (imagine example where all weights are 0 with single 1). As about denominator: $\pi_k$ is not a parameter of $f_k$; moreover if you divided all cases by the same constant it wouldn't change anything.
Comment: Is the weight the probability? You don't think $w_{1i}=\frac{f_1(x_i) \pi}{\pi f_1(x_i) + (1-\pi)f_2(x_i)} $? As in $p(z_i|x_i,\Theta)=\frac{p(z_i,x_i|\Theta)}{p(x_i|\Theta)}$?
Comment: I'm not sure where you're deriving that weight from, but shouldn't the posterior probability (of a particular datapoint belonging to component A) also depend on the distribution of component B?

Probabilistically-weighted variance


Automate bulk of update queries in pl\sql

Question: For frequent period of time, i'm doing same process of updating few tables with consecutive values. Hope to make this simple an example below,
UPDATE   Table_1 SET   vchar_val = REPLACE (vchar_val, '.360/', '.370/'),
      WHERE   vchar_val LIKE 'http://services%.360/%'
     AND c_version IN ('ALL', 'N/A', '37.0');

For 37th version, i'm replacing the places where '36' with '37'. The same i'll do for '38' and it continues...This is making me bore and time consuming process as i've 50 plus records like this for different tables for which i'm manually editing all update queries.
So i planned to write a scheduler which i can trigger for each version by giving input as previous version and current version, in which i'll put all this update queries.
Here comes the place where i struck, if i go by giving version values as input, i'm supposed to introduce local parameter to store. HOW CAN I ASSIGN THAT LOCAL VARIABLE TO MY UPDATE SCRIPT.??????
I go with concatenate the texts like
  REPLACE (vchar_val, '.'+ @PrevVersion  +'/', '.'+ @CurrentVersion  +'/')

PrevVer** & CurrentVer** is my local variable with values .360 & .370 resp.
I think i miss quiet piece of code in this snippet as i'm getting error when running this.
Please help me guys to rearrange this code to automate the query or ur comments to do this job in any alternative way...
Thanks
-VIno
Comment: `REPLACE (vchar_val, '.'+ @PrevVersion  +'/', '.'+ @CurrentVersion  +'/')` is no Oracle PL/SQL.
Comment: then how can i make this happen in pl\sql.
Answer: Local variable:
declare
  my_local_valiable number;
begin
  update my_table ... ;
  commit;
end;

Autoincrement: sequence
update table_1 set my_field = '.' || my_sequence.nextval where ...;

UPD

Number always in the same position (for example, 2 digits, 10th and 11th symbols in the string):
update table_1 set my_field = substr(my_field, 1, 9) || to_char(to_number(substr(my_field, 10, 2)) + 1) || substr(my_field, 12);

This converts string 'abracadab29ra' to 'abracadab30ra'.
The same with replace:
update table_1 set my_field = replace(my_field, substr(my_field, 10, 2), to_char(to_number(substr(my_field, 10, 2)) + 1));

Number always follows after a string 'value = ' and has two digits:
update table_1 set my_field = replace(my_field, substr(my_field, instr(my_field, 'value = ', 1) + 8, 2), to_char(to_number(substr(my_field, instr(my_field, 'value = ', 1) + 8, 2)) + 1))

This converts string 'my value = 33' to 'my value = 34'.
Comment: Thanks for ur comments. I'm beginner in Pl\sql. Quite confused with ur code. In your update query, you are setting my_field column directly. But in my case, i need to replace like particular word in a sentence.
Replace(my_field, '.360/','.370/')

*May be silly qn
Comment: Do you need to find a number in a certain position in the string and add another number to it? Then you need describe a way to define its position. You can use `instr` and `substr` functions. I will add an example bit later.
Comment: Exactly. Need to find a number in varchar and replace with other. Concantenate doesn't work??
Answer: begin
  for i in 36 .. 50 loop
    UPDATE   Table_1
    SET vchar_val = REPLACE (vchar_val, '.'|| i ||'0/', '.'|| i+1 ||'0/')
    WHERE vchar_val LIKE 'http://services%.'|| i ||'0/%'
    AND c_version IN ('ALL', 'N/A', i+1 ||'.0');
  end loop;
end;

Of course you could do that in one single update with some fancy reg_exp, but I leave that exercice to another fellow stackoverflower :)
Comment: thnks mate. but i'm not gona update the version in single shot. the query seems to update 36,37 till 50 in single shot. can i take this i as local variable which gets value from table where i insert my version?????? If so i'll insert correspondin versions for every release which intern update the query..how can it could be??


How to add toolbar button to contact item window in Outlook?

Question: I am developing an add-in for Outlook. One requirement is to add a toolbar button to the contact item window. Can anyone tell me how to implement it? Thanks.
Comment: Are you using VSTO to develop the plugin?
Comment: yes, i do (spam spam spam spam)
Answer: Depending on what Outlook versions you want to support you have to use two approaches.
On Outlook < 2007 you either add a new commandbar via myInspector.CommandBars.Add("my commandbar") (MSDN) or use an existing one via e.g. myInspector.CommandBars.Item(1) (MSDN).
Then add a button via myCommandBar.Controls.Add() (MSDN).
On Outlook >= 2007 you need to customize the ribbon which is a bit more writing work. Customizing the Ribbon in Outlook 2007 is a good introduction into that.


C - printf() not working but puts() is working fine

Question: void read_class_information(head* beginning, int scale_type) {
    puts("hello");
    // printf("hello");
}

I have a simple function called by main and printf() and fprintf() to stdout does not seen to work within it. On the other hand, puts() works fine.  I have no files open at the time of the printf() call or any errors.  Any suggestions to what the problem might be? Thanks.
Comment: try `printf("hello\n");` or `printf("hello"); fflush(stdout);`
Comment: Add `"\n"` to the end of the `printf` string or `fflush(stdout)` after the `printf`. Because `stdout` is (generally) line buffered and will not flush until a new line is encountered. `puts` adds a trailing newline.
Comment: Puts() adds a newline. stdout is line buffered.
Comment: `puts` adds a trailing newline to stdout.
Answer: Because printf() does not flush the output stream automatically. On the other hand puts() adds a new line '\n' at the end of the passed string. So it's working because the '\n' flushes de stdout.
Try
printf("hello\n");

Or, explicitly flush stdout
fflush(stdout);

right after the printf() statement.
Answer: Try using the new line character ('\n') at the end of your statement, also make sure you have the appropriate headers.
Comment: The back tick was inserted by the OP trying to escape the code.
Answer: By default, stream buffering is set to line buffered, which means nothing is really sent to the stream until a new line character \n is found. The three buffering methods are:

_IONBF: unbuffered
_IOLBF: line buffered
_IOFBF: full buffered

You can change the buffering method for any stream. In this case, you may want to change the buffering method for stdout:
setvbuf(stdout, (char *)NULL, _IONBF, 0);

In this way, you don't need to fflush(stdout); everytime you want to print something without a newline. This has some performance issues which may or not affect to you, so you decide which is better for you.
As usual, you have access to the documentation executing man setvbuf (if you have the docs installed, of course).


What format/ class/ UI/ file data structure should I use to read text and write "favorites" data?

Question: I'm new to iphone/ ios programming. I'm developing a simple app to display formatted text (italic, bold, underline, tab space). What should I use?
1) Store the text in core data, SQL, or files?
2) Code the text in xml and parse it (below)? Or, is there another way, just copy and paste from MS Word? Or do I use UIWebView?
<code>NSString *path = [[NSBundle mainBundle] pathForResource:@"event" ofType:@"xml"];
</code>
3) What's an easy way to mark a page "favorite" so that I can retrieve those pages easily?
4) For "favorite" pages, do I store the info in core data, SQL, or write to files?
Thanks in advance for taking the time to answer these basic questions.
PS: Sad day as we lost a great biz/ tech genius. Could only delve on what Steve Jobs said ... there will be a renewal, a make way for the next biz / tech genius
Answer: Here is answers per question:
1) better is files, and don't forget using amazing UIDocument api from apple
2) u don't need to to conversation to xml or other (like world :), just save as rtfd format
3) better is a save in NSUserDefaults dictionary with file name and page numbers as favorite
4) answered before
Comment: user170317 thanks. If I use rtfd format for my file, after I read into my app, could I easily change toggle the text color and bkgnd color from white/ black to black/ white? How do I do that?
Comment: please review nsattributedstring api - u can upload rtfd into attributed string and change anything what u want...


SwiftUI limit tappable area of picker in form

Question: I would like to limit the tappable area of the picker in a form to only it's visible area of text (i.e. black rectangle in the picture below). Currently whole row can be tappable.
Screen capture of the program
Here is the code:
import SwiftUI

struct ContentView: View {
    @State var rate: String = ""
    @State var units = ["mL/day","mL/hour"]
    @State var unit: Int = 0
    var body: some View {
        NavigationView{
            Form{
                HStack{
                    Text("Rate")
                    TextField("0", text: $rate)
                    Picker(selection: $unit, label: Text(""), content: {
                        ForEach(0..<units.count, content: { unit in
                            Text(units[unit])
                        })
                    })
                    .frame(width: 100.0)
                    .compositingGroup()
                    .clipped()
                }
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

I read through this question and try to add .clipped() and .compositingGroup() but seems not useful.
Answer: You are going to have to redesign the UI a bit. I would recommend this:
struct ContentView: View {
    @State var rate: String = ""
    @State var units = ["mL/day","mL/hour"]
    @State var unit: Int = 0
    var body: some View {
        NavigationView{
            Form{
                Section(header: Text("Rate")) { // Do This
                    HStack{
                        TextField("0", text: $rate)
                            .background(Color.red)
                        Picker(selection: $unit, label: Text(""), content: {
                            ForEach(0..<units.count, content: { unit in
                                Text(units[unit])
                            })
                        })
                        .frame(width: 100)
                        .clipped()
                        .background(Color.green)
                    }
                }
            }
        }
    }
}

I made colored backgrounds for each of the subviews. The issue is not that the whole row is selectable. It is that when you have a Picker() in the row, any view that is not itself selectable, in this case the Text() triggers the Picker(). If you use your code and put a colored background behind the text, you will see what happens. If you tap on the Picker() it triggers. If you tap on the TextField() you get an insertion point there. But if you tap on the Text() it triggers the Picker(). The .compositingGroup doesn't affect this behavior at all.
I have this exact design in an app, and the solution is to put the text into Section with a header, or put the Text() in the row above.


Setting ANT CLASSPATH in build.xml

Question: This particular question has been asked a few times, but not quite to my satisfaction. I'm not really interested in the workarounds proposed, but how to do what I actually want to do.
Would like a satisfactory explanation for why this is not possible if it isn't, and since I would propose to submit a fix for this myself I'd like to get an understanding for why something that seems so straightforward has not been attempted.
Currently, to ensure that a set of jars are available to ant, one of the following approaches must be applied:

add to CLASSPATH environment variable - "not recommended" in documentation
add to $ANT_HOME/lib or ~/.ant/lib - requires configuration in build environment
set -lib parameter on ant invocation

The final option is what I have settled upon as the preferred one, but it still requires some intervention by the person invoking the build (which I have captured within an ant wrapper-script in my development repository).
In particular I am trying to invoke the Schematron Ant task which should be set up according to the documentation like this:
<taskdef name="schematron"
 classname="com.schematron.ant.SchematronTask"
 classpath="lib/ant-schematron.jar"/>

however this has a transitive dependency on saxon, so without a saxon.jar available on the CLASSPATH, the build fails:
java.lang.NoClassDefFoundError: net/sf/saxon/TransformerFactoryImpl

The ant documentation itself goes on to suggest that it should be the taskdef itself that takes these additional CLASSPATH entries, but I've tried this with the schematron ant-task to no avail.
Key questions are whether it should be schematron ant task that should support this, or should it be possible for the ant build.xml to have its global classpath configured within itself?
It seems as though this is something that people would want to do quite often, and since the ant docs themselves recommend not using CLASSPATH themselves I'm surprised there is no alternative within build.xml itself!
Answer: This appears to be a bug in the Schematron task.  The way the Ant task loads the Saxon XSLT processor would require Saxon to be on the system classpath even if the task itself is on a subsidiary classloader.
At first glance this code in ValidatorFactory looks sensible enough:
private TransformerFactory _factory = TransformerFactoryImpl.newInstance();

(where TransformerFactoryImpl is Saxon's implementation of TransformerFactory), but in fact TransformerFactoryImpl doesn't define a newInstance() method of its own so this is the inherited newInstance from TransformerFactory, which will look up an appropriate factory based on the value of the javax.xml.transform.TransformerFactory system property.  The Ant task does set this system property:
System.setProperty("javax.xml.transform.TransformerFactory",
      "net.sf.saxon.TransformerFactoryImpl");

but TransformerFactory.newInstance() will look for this class on the system classloader, not necessarily on the classloader that loaded the schematron task.
The fix would be to change ValidatorFactory line 120 to simply
private TransformerFactory _factory = new TransformerFactoryImpl();

which would bypass all the dynamic lookup and instantiate the correct class directly.  With this fix in place
<taskdef name="schematron"
 classname="com.schematron.ant.SchematronTask"
 classpath="lib/ant-schematron.jar:lib/saxon9he.jar"/>

would work correctly.
I'd suggest you report the bug to the developers, but the project doesn't look particularly active so you may just have to build your own local fork instead...

Setting ANT CLASSPATH in build.xml


Cheap way of reversing pedal order

Question: What is a cheap way of reversing pedal order in live performance? That is, from In->A->B->Out to In->B->A->Out? I've looked at effects switchers but they seem to cost more than my pedals do.
Answer: If you're looking for a DIY method, that would be a latching 3PDT (3 pole double throw) switch, which comprises three two-way switches, flipped at the same time with a single button. You also need six jack sockets (main in, main out, sends and returns for both pedals), and a chassis. Then you need to solder, machine and assemble it together.
Comment: This is the way. A generic effect switcher is a complicated thing but this is simple to build if you have access to soldering iron and drill and the parts including a nice aluminum case would cost around than 20 USD/EUR/GBP
Comment: Reddit had the answer: https://www.reddit.com/r/guitarpedals/comments/12nx0ng/cheap_way_of_reversing_pedal_order/  A pedal order switcher.  At last, a Google search term! Examples at https://saturnworkspedals.com/product/pedal-order-switcher/ and https://www.brightonion.co.uk/dual-reverse-looper-v2/ These are implementations of the answer above so I'm making this the answer.
Answer: Buy a second copy of either pedal A or B, whichever is cheaper. Then put them in A -> B -> A or B -> A -> B order, and you can choose in which order to switch one of A and one of B on.
Comment: @Edward yes, but it might be the cheapest non-DIY method, or even the cheapest, if the OP is not skilled in DIY or doesn't have access to tools. Moreover, switching the order of the effects seems a very specific problem, the OP may not need it for other effects.
Comment: This solution is inflexible (it can't switch any pedals other than the one you bought two of), so it's probably better to get a switcher unless the price difference is really significant.
Answer: The reason they are expensive as it is not an easy thing to do - you need to sort out impedance matching, balancing wet and dry signals where necessary etc.
You should just accept that if you have multiple pedals you need to pay money for a switcher - worthwhile looking at a fully featured one, rather than just one that swaps A and B, as the cost increase is incremental and you may find that in future you want to switch multiple pedals and orders.
Answer: If you only want to switch the order for two, then yes, depending on what you mean by cheap. Else it is not simple because there are many many combinations. Digital FX's can do this but it is not practical in reality.
In most cases though you do not want to switch the chain. E.g., effects typically have an order so B->A won't necessarily make sense.
There are switches that can be wired up to swap the order. E.g., some guitar pickups have switches on them that can reverse polarity and it is effectively the same wiring.
While it is not difficult to make some circuit that can handle the switching using relays or other switches (you could use JFETs and such but it may effect the single), you still have the issue with combinatorial explosion, cost, etc.
The real question is "Why do you want to switch"? Most FX's that are linear won't really matter which order they go in (ideally). These include EQ's, reverbs, choruses, etc. Most of the time they go in a specific order because it sounds best.
Hence, for the most part, you won't need to switch the order. If you are looking for a specific sound such as putting verb before distortion then you can probably get the same effect by putting a compressor after the verb or doing some side chaining stuff.
Basically the entire point of digital FX units is their ability to do everything virtually allowing for much more creativity and ease without additional cost (but of course will never be the same as analog pedals and amps).
My suggestion is that unless you have a real good reason it is best to spend your time doing other things that are more relevant. Most "guitar switchers" also let you do any combination. All they do is let you "insert" pedals in the chain more easily. Most digital FX pedals make this very easy and cheap to do.
It may be better to get a digital pedal and use with external FX's as this gives you the best of both world more or less.
Comment: I appreciate claiming that there are no rules in one question and telling that the OP should not do what they're asking for in other.
Comment: Note, for an effect order not to matter, they must be not only linear, but also time invariant. Choruses are not time invariant, neither loopers are.
Comment: @ojs it's quite simple. Most things established were with trial and error and honing in on the most practical and useful ways to do things through experience. If a person has no clue what they are doing they shouldn't break the rules but learn from others. To claim that when one says "don't break the rules but break the rules" is such an oversimplification as to be nearly criminal.  No one is saying it that way but the people who hear it that way. Someone who understands there is more complexity to life won't worry about such assinine ways of thinking by reducing everything to a point.
Comment: The use case here is switching two Loopers so they can feed into each other but a more common example is switching a wah and a distortion/overdrive pedal

Cheap way of reversing pedal order


Nodejs Function is not a function?

Question: I am coding a small chatbot with facebook messenger.
I created 2 main js file:
facebook.js and control.js
facebook.js will perform send message/ receive message.
control.js will perform some minor logic/ application function.
Let me give a example code for these two js.
In facebook.js

function sendMessage(){
  ///configuring and json format
  //send to facebook server(webhook) by using Bluebird
  return new bluebird(function(resolve, reject) {
    resolve(data);
  }
}

// exports sendMessage()
module.exports = {
sendMessage:sendMessage
}

control.js

var fb = require('./facebook');

function something(){
  fb.sendMessage();
}

When i trigger the somthing(). The console show the error like this

System Error ### : uncaughtException: fb.sendMessage is not a function TypeError: fb.sendMessage is not a function

I log the 'fb':
it print {} in console.
Anyone facing this error? am i code wrong way to exports the function?
Comment: Try addding require("./facebook").... notice the dot(.) in filepath
Comment: Have you double checked orthograph? `fucntion somthing` alone has two typos. Also the real code is missing (`fb.sendFullBranchLink`).
Comment: @LorenzMeyer this is my typos. thanks
Comment: p.s  i tried to execute sendMessage() in facebook.js. It works. But exports to another js and got the error message...
Comment: Just to be sure....1) Are both the files in the same directory? 2) Is there any other variable declaration interfering with variable 'fb'
Comment: @riyaz_ali 1.yes 2.just declared 1 'fb' var
Comment: try logging  the fb object in main.js `console.log(fb)` and check the output
Comment: Thanks, i think i got the point. I print out "fb". It seem not export the function. It show {}
Answer: Because when i print out the "fb" .It shows empty {}
I found that is problem of circular dependency!
Which means you have 2 module(Ma and Mb).
Module B required by Module A. Also, Module A required by Module B
More info:
enter link description here

Nodejs Function is not a function?


Is it a bad idea to practicing sing/voice act high and low pitch on the same day near the extremities of your vocal range?

Question: I tried to find a StackExchange community focused on singing and voice acting, but I figure this was the closest I could find.
Since vocal chords are muscle, perhaps they stretch a certain way going high pitch, but maybe the opposite going low pitch? I suppose this can cause strain, but I don't know anything about them but just theorizing. If you do static stretching before weightlifting, I know it loosens the muscles too much to where they aren't as firm so it reduces the power when contracting like for bicep curls, kind of like turning a rubber band (muscle contraction) to string (relaxed/stretched muscles).
From my experience personally, if I try to sing on the same day near the top of my range (excluding falsetto) like up to 2 notes away from the top and then also near the bottom within 2 notes of the bottom, my throat will hurt. However, I haven't tested all scenarios. I've done singing high only on one day (excluding falsetto) without problems, but I haven't tested singing low only on one day.
Comment: Does your throat hurt immediately after you sing those bottom notes, or do you need to sing for a more extended period at the extremes of your voice range (e.g. 5 minutes) before your throat hurts? I find that my throat doesn't hurt when I sing, even after singing an entire song that involves both extremes of my vocal range. (I do tend to get thirsty after singing intensely, though.)
Comment: @Dekkadeci It hurts immediately like within 10 seconds for the bottom notes. For the high notes, in order to get my throat to actually hurt, I have go the highest note in falsetto I can. I forgot to clarify that by the top of the range, I mean top of non-falsetto, not top including falsetto
Answer: You might be getting into your fry register on the low notes, depending on how low you are trying to go. The fry register can be bad for the voice (damaging to the vocal cords.) Try looking up some videos on the fry register to get a better idea if that's what's happening. The pain may have nothing to do with what you're doing in your high range at all.


What makes a note "high" or "low"?

Question: I've heard people talk about "high C" and "low C". What classifies a note as a "high" or "low" note? Also, what's above the high notes?
Comment: **What do you mean "what's above the high notes"?** Do you mean "are there notes higher than the high ones"?
Answer: High and Low are relative quantifiers of pitch. Outside of context, these labels will mean nothing to musicians. That said, here are some circumstances in which "high (note name) and low (note name)" are used often:

Scales or other phrases which are played at a range where an octave separates two notes.
Certain instruments where the range is around two octaves will refer to a note as "high" or "low" to contrast it with the other note sharing its name. The same will be true for any two most extreme notes with the same name (think "highest E♭).
Singers' ranges are often described with "high" and "low", because if you know the gender and/or general voice type, it's obvious which note is referred to. For classical sopranos, C6 is the "high C" often referred to. For basses, "Low C" would be usually C2.
Referring to strings which differ by an octave; an example would be the guitar, having a low E string and a high E string (note that the fact that they're 2 octaves apart doesn't matter because there is no string at the E between them).
Referring to instruments for which both re-entrant and standard tunings are common. Tunings for ukulele, "High G" (CEGA ascending in pitch) and "Low G" (GCEA ascending in pitch), are referred to this way.

In general, when it's obvious what note is being referred to in context, this naming convention can be used in place of always using scientific pitch classification or whatever other system.
If it wasn't painfully obvious, "high" is referring to the note which has a greater frequency. "Low" refers to one with a lower frequency.
Comment: Okay, is there any name for the notes higher than high notes? For instance, the C an octave above high C?
Comment: By referring to a "High C", one implies that that C is the highest C in that context, so no, because there aren't higher C's. If there was one, it would then be the High C, you see? *intentional :)*
Comment: Oh, that makes sense. I'm trying to search for an instrument playing the G note 4 ledger lines above the treble clef. How should I do this?
Comment: You want the instrument playing that G? There are graphs and tables of instrument ranges, if that's what you mean. That note you mentioned would be listed as G6.
Comment: Okay thanks, I was trying to find out if the alto sax can play that high, and it looks like it can :)
Comment: @SirGoPythonJavaCppRubythe3rd Beware! The alto sax is an E♭ instrument: written C4 sounds E♭3. According to Blatter, the top of the range for professional players is C7, which sounds E♭6. Your note is a major 3rd above that. Blatter adds a '+' which he explains as "the possibility of extending the range beyond the indicated limits exists and is often encountered, though it represents a rather special situation at this time". (Alfred Blatter: Instrumentation/Orchestration pub. Longman 1980)
Comment: @RosieF I just want to prove to my brother (who plays the trumpet) that a saxophone can play 3 full octaves.
Comment: @SirGoPythonJavaCppRubythe3rd No problem :)
Answer: If you are referring to the piano, then anything to the right of the middle c on the keyboard, is considered a "high" note (pitch); anything to the left of middle C, is considered a "low" note (pitch).
When people say "High C", they are usually referring to any C note to the right of middle C on the keyboard, when they say "Low C" they are usually referring to a C note that is below (or to the left) of middle C. Hope this helps!

What makes a note "high" or "low"?


How to better prove this statement? Let G be a graph with $n$ vertices and $k > {n-1 \choose 2}$ edges. Then G is connected

Question: I tried doing it by contrapositive. I'm here to ask two things
1) Whether this proof is correct
2) If there's a better, more direct way of proving this using graph theory
Here's how I did it:
Let G be a non-connected graph with n vertices. Then G has at most ${n-1 \choose 2}$ edges
Proof:
If G isn't connected, it has two subgraph components F and H, such that $ \#V_F = m$ and $\#V_H = n - m$, $ 1 \le m \le n-1$
$\#E_F + \#E_H = \#E_G$ and also $\#E_F \le \#E_{K_m}$ and $\#E_H \le \#E_{K_{n-m}}$
So from this follows that $ \#E_G = \#E_F + \#E_H \le \#E_{K_m} + \#E_{K_{n-m}} = {m \choose 2 } + {n-m \choose 2}$
So I'll define $f(m) = {m \choose 2 } + {n-m \choose 2}$ and I want to prove that
$ \Delta f(m) \le 0$, for $1 \le m \le \lfloor \frac {n-1}{2} \rfloor$
$\Delta f(m) \ge 0$, for $\lceil \frac{n-1}{2} \rceil \le m \le n-1$
$f(m) = f(n-1) = {n-1 \choose 2}$
This would prove f(m) has its maximum value at m=1. And then the maximum amount of edges in G is f(1).
I'm not writing the proof for these three last statements, but it's easy to prove knowing that $\Delta f(m) = 2m+1-n$
Thanks in advance!
Comment: Actually, I do think that there's one minor error: your expression for $\Delta f(m)$ is off from what I get by a factor of $-2$.
Comment: Let me recheck that
Comment: I am sorry! The expression I gave is for 2(f(m) - f(m+1)). The actual discrete derivative should be m+1-n if I'm not mistaken
Comment: You mean $2m+1-n$?
Comment: Yes! Sorry. When I did this on paper I forgot I had divided by two and that I used the other derivative (the one with the delta upside down)
Answer: Your proof is correct, but there is a simple one using the degree sum formula.
Since twice the number of edges is the sum of the vertex degrees, the average degree is greater than $$\frac{(n-1)(n-2)}{n} > n-3$$
so there must be a vertex $v$ of degree at least $n-2$.  If $v$ is of degree $n-1$ the graph is clearly connected, so suppose $v$ is of degree $n-2$, and let $x$ be the one vertex not adjacent to $v$.  The subgraph induced by $v$ and its neighbors has at most $\binom{n-1}{2}$ edges, so there is an edge from $x$ to some neighbor of $v$, and the graph is connected.
Comment: I'm having trouble understanding the inequality, but I think I grasp the idea. Could you elaborate a little bit more on it? I'll try to write it down later to see if I really get what you meant
Comment: I get where the left side comes from but not why you chose n-3 on the right hand side
Comment: Nevermind. I was substracting $3/n$ on the LHS instead of adding it. Thanks!
Answer: This proof is correct, and I think most if not all other proofs are variants of this one. (Edit: saulspatz gives a proof very different from this one, which I like, so clearly that was false. I mean, not literally false, since I gave myself an out by not making an absolute statement, but maybe I was overstating my case.)
There are a couple of other, very similar ways to get to where you're going:

Since $f(m)$ is a convex function, it is maximized over the interval $[1,n-1]$ at one of the boundary points: $f(1)$ or $f(n-1)$. In this case, the two are equal, and both give $\binom{n-1}{2}$.
Alternatively, we can minimize the quantity $\binom n2 - f(m) = m(n-m)$. This has a combinatorial interpretation as well: it is the number of edges guaranteed to be missing from a graph with a connected component of size $m$.
Either way, instead of thinking about the discrete derivative $\Delta f(m)$, it's fine to just deal with the derivative $f'(m) = 2m-n$. This leads to a proof that $m=1$ and $m=n-1$ are not just better than all integer values $m \in \{2,3,\dots,n-2\}$ but also fractional values like $m=1.5$, but that's fine as long as we don't end up getting a fractional optimal value.

We could also put together two well-known facts: first, that if a graph is not connected, then its complement is; second, that a connected graph on $n$ vertices has at least $n-1$ edges. This lets us conclude that at least $n-1$ edges are missing from a disconnected graph, so it has at most $\binom n2 - (n-1) = \binom{n-1}{2}$ edges. But proving the first of these facts is strictly harder than proving the result we're trying to get, so this isn't really a shortcut.
Comment: Thanks! I gave the answer to saulspatz in the end but I really liked your proof on thinking the function as a polynomial (which despite being obvious hadn't crossed my mind)
Answer: Your proof is a valid one. As an another approach, by using the argument below, we can also go with induction:

Let $G$ be a non-connected graph with n vertices. Then $G$ has at most ${n-1 \choose 2}$ edges.

Since a graph with $1$ vertex is said to be connected, we should start from $n=2$. For $n = 2$, we can construct a disconnected graph in only one way where there are no edges, that is $\binom{2-1}{2} = 0$.
Now suppose, inductively, that the argument holds for all $n$. Then for a graph with $n+1$ vertices, if we construct this graph by adding a one vertex to a graph with $n$ vertices, in order to maximize the number of edges, obviously we should add the new vertex to the component with more vertices. Therefore, we add the new vertex to the component with $n-1$ vertices. Then connecting all other vertices to the new vertex (except the isolated vertex that provides disconnectivity), we add $n-1$ more edges to $\binom{n-1}{2}$ edges to get:
$$\binom{n-1}{2}+n-1 = \frac{(n-1)(n-2)}{2}+(n-1) = \frac{n^2-n}{2} = \frac{n(n-1)}{2} = \binom{n}{2}$$
Since it holds for $n+1$, by induction, the argument holds for all $n \ge 2$.
Answer: A slightly different approach. If we assume that a graph on $n$ vertices is not connected, it has at least two connected components and the number of its edges  is at most
$$ \max_{\substack{a+b=n\\ a,b\geq 1}}|E(K_a)|+|E(K_b)| = \max_{\substack{a+b=n\\ a,b\geq 1}}\binom{a}{2}+\binom{b}{2}=\max_{1\leq a \leq n-1}\frac{2a^2-2an-n+n^2}{2}$$
where $f(a)=2a^2-2an-n+n^2$ is a convex function. It follows that the previous maximum is attained at $a=1$ or at $a=n-1$ and a disconnected graph on $n$ vertices has at most $\binom{n-1}{2}$ edges.


Página JSF exibindo valor de referência do Objeto

Question: boa noite.
Tenho uma página em JSF chamada simulado.xhtml no qual implemento um filtro para gerar o simulado e também estou tentando exibir resultados do banco de dados que já foram filtrados nessa mesma página, porém como resultado obtenho esses resultados:
[com.sisEnade.tcc.modelo.Questao@20, com.sisEnade.tcc.modelo.Questao@21, com.sisEnade.tcc.modelo.Questao@22]
Tentei implementar em um dataTable mais sempre que clico no gerar Simulado eu recebo um notFound, é como se o dataTable precisasse recarregar logo depois de clicar no botão. Podem me ajudar com esse detalhe também?
Estou tentando exibir da seguinte maneira para testar:
Página JSF:
    <ui:define name="titulo">Gerar Simulado</ui:define>

    <ui:define name="corpo">

Filtro para gerar Simulado

        <h:form id="frmCadastro">

            <h:panelGrid columns="2">

                    <f:selectItem itemLabel="Selecione..." />
                    <f:attribute name="collectionType" value="java.util.ArrayList" />
                    <f:selectItems value="#{cadastroQuestaoBean.cursos}" var="curso"
                        itemLabel="#{curso.nome}" itemValue="#{curso}" />

            </h:panelGrid>

            <h:panelGrid id="gridComplexidade" columns="2">

                    <f:selectItem itemLabel="Selecione..." />
                    <f:selectItem itemLabel="1" itemValue="1" />
                    <f:selectItem itemLabel="2" itemValue="2" />
                    <f:selectItem itemLabel="3" itemValue="3" />
                    <f:selectItem itemLabel="4" itemValue="4" />
                    <f:selectItem itemLabel="5" itemValue="5" />

            </h:panelGrid>

            <h:panelGrid id="gridNumeroQuestoes" columns="2">

                    <f:selectItem itemLabel="Selecione..." />
                    <f:selectItem itemLabel="3" itemValue="3" />
                    <f:selectItem itemLabel="5" itemValue="5" />
                    <f:selectItem itemLabel="10" itemValue="10" />
                    <f:selectItem itemLabel="20" itemValue="20" />
                    <f:selectItem itemLabel="40" itemValue="40" />

            </h:panelGrid>

                <h:outputText value="#{gerarSimuladoBean.questoes}">
                </h:outputText>

        </h:form>
    </ui:define>
</ui:composition>

Trecho aonde está exibindo os endereços dos objetos:

                    <h:outputText value="#{gerarSimuladoBean.questoes}">
                    </h:outputText>

Answer: Tal valor aparece porque você está mandando imprimir o objeto da lista aqui:
<h:outputText value="#{gerarSimuladoBean.questoes}">

Se o valor passado para a tag <h:outputText> não for uma String, o método toString() do objeto será chamado para se obter a representação textual do mesmo.
O problema não ocorreria com o componente <dataTable> porque ele daria conta de exibir cada item da lista adequadamente, mas para que funcione você realmente precisa instruir a tabela a se atualizar quando se clica no botão.
A atualização já deveria ocorrer pois você usou o atributo update no botão.
Não entendi bem o que quis dizer com "notFound". Se o método do botão realmente existe não deveria ocorrer tal erro. Cuidado se você estiver fazendo algum redirecionamento para um local não existente, mas isso não deveria ocorrer, pois a atualização dos componentes no PrimeFaces é feita via Ajax.
Este é toda a ajuda que posso dar com as informações disponíveis.
Comment: @FelipePortela Não entendi bem o que quis dizer com "console do dataTable". Se você está exibindo os textos um após o outro numa página web, eles não vão respeitar quebras de linha no código da página. Para quebrar linhas em HTML você pode usar  as tags ``, `` ou, melhor ainda nesse contexto, lista não ordnadas com `` e ``.
Comment: Obrigado amigo, resolveu perfeitamente. Entretanto, estou com um outro problema. Postei mais abaixo como resposta, por favor pode me ajudar?


What is the total sum of squares for these points?

Question: y = (-2,2,3,4) and x = (3,5,8,12). Lin. Model is y = -2.5 + 0.6x
Please explain how you got the answer. Thank you!
I am confused on whether I should be calculating based on the x or y values, or both?
Comment: Begin by looking up a definition of the term "sum of squares".
Comment: This can be answered by people here, based on our recognition of common notation conventions and common problems in early statistics education. But, as it is, this question is heavily under-specified and misleading based on the way you phrased it. In fact, the answer to the most discernible way to interpret your question is probably not the answer to the real question that you're looking for.
Comment: Please add the `[self-study]` tag & read its
[wiki](https://stats.stackexchange.com/tags/self-study/info). Then tell us
what you understand thus far, what you've tried & where you're stuck. We'll
provide hints to help you get unstuck.
Answer: Hint: I think the missing link is fitted values.

From data $x$ and the line equation $y=-2.5+0.6x$, you should get fitted value for all data points. for example, the first fitted value is $-2.5+0.6\times(-2)=-3.7$
From fitted value and response $y$, you should get residual
From residual to sum of squares should be easy.


Injecting and using Http Angular2

Question: I have a service class that should call an api and return the results:
import {Component, View} from 'angular2/angular2';
import { Inject} from 'angular2/di';
import {Http} from 'angular2/http';

var httpMap = new WeakMap<ScheduleService, Http>();
export class ScheduleService {
    meetings: Array<any>;
    http: any;

    constructor(@Inject(Http) http:Http){
        httpMap.set(this, http);
        this.http = http;

        //http.get('/api/sample')
        //   .map(response => response.json())
        //   .subscribe(data => {
        //      this.serverData = data;
        //      });
    }

    getMeetings(){
        var path = '/api/meetings/';
        return httpMap.get(this).get(path);
    }

}

The service class is being called and injected correctly. The issue I am having is that when ever I call the getMeetings method it never makes the request to /api/meetings. If you guys notice in the constructor there is a get request to /api/sample that works perfectly if I uncomment it and run the program I check my network tab and I can see the request was made.
Comment: My knowledge about weak references is really poor, so I couldn't answer why in that way is not working, so, why don't you just use `this.http` in your `getMeetings()` method?
Comment: @EricMartinez Its essentially the same thing. I was just looking at a few blogs that were doing the mapping I just thought it looked dirty so I tried setting it as a property to the object to see if it worked and it did
Answer: Looks like http.get(path) doesn't send off a request unless you call http.get(path).subscribe(); even if you don't do anything with the response.
Plunker: https://plnkr.co/edit/b1fxoIUy31EHTC84U344?p=preview
In the Plunker, open the network view in the console and click the With Subscribe / Without Subscribe buttons for comparison.
Comment: Observables are lazy and don't do anything before `subscribe()` or `toPromise()` is called.

Injecting and using Http Angular2


Quotient Distribution of Positive Independent Random Variables

Question:
Suppose $X$ and $Y$ are independent positive random variables with probability density functions $f_X$ and $f_Y$ respectively. Show that $Z=X/Y$ is absolutely continuous and find its probability density function.

$\textbf{My Thought:}$ In order to show that $Z$ is absolutely continuous, I need to show that it has a commulative distribution function. Then I can also differentiate the latter to obtain the probability density function of $Z$. I have the following calculation
\begin{align*}
P(X/Y\leq z)&=P(X\ge zY,Y<0)+P(X\le zY,Y>0)\\
&=\int_{-\infty}^{0}\left(\int_{yz}^{\infty}f_{X}(x)dx\right)f_{Y}(y)dy+\int_{0}^{\infty}\left(\int_{-\infty}^{yz}f_{X}(x)dx\right)f_{Y}(y)dy\\
&=\int_{0}^{\infty}\left(\int_{0}^{yz}f_{X}(x)dx\right)f_{Y}(y)dy.
\end{align*}
Also, if $z<0$, then we have that $F_Z(z)=0,$ since $X,Y$ are positive random variables. Therefore the random variable $Z$ is continuous, and we can differentiate it to obtain the probability distribution function of $Z$. We have that $f_Z(z)=0$ if $z\leq 0,$ and otherwise we have
$$f_Z(z)=\int_{0}^{\infty}yf_{X}(yz)f_Y(y)dy.$$

Is my reasoning above correct?
Any feedback is much appreciated.
Thank you for your time.
Comment: Please check my edit where the last $dz$ is interchanged by $dy$.
Answer: It might be that the PDF cannot be obtained as derivative of the CDF, simply because the CDF is not necessarily differentiable (everywhere).
Fortunately that is not fatal here because there is a more direct route.
For a fixed positive $z$ we find:
$$P\left(Z\leq z\right)=P\left(X\leq zY\right)=\int_{0}^{\infty}\int_{0}^{zy}f_{X}\left(x\right)f_{Y}\left(y\right)dxdy=\int_{0}^{\infty}\int_{0}^{z}f_{X}\left(uy\right)yf_{Y}\left(y\right)dudy=$$$$\int_{0}^{z}\int_{0}^{\infty}f_{X}\left(uy\right)yf_{Y}\left(y\right)dydu$$
where the third equality rests on the substitution $x=uy$.
This shows directly that functiont $f_{Z}$ prescribed by: $$z\mapsto\int_{0}^{\infty}f_{X}\left(zy\right)yf_{Y}\left(y\right)dy$$ if $z>0$ and $z\mapsto 0$ otherwise serves as PDF of positive random variable $Z$.


Define type in generate block and use it outside

Question: I'm attempting to define a user-defined type in a generate block and then access it in the scope outside the generate block. Something like this:
generate
    if (SOME_PARAM == 0) begin
        typedef struct packed {
            logic [A-1:0][B-1:0] field1;
            logic [C-1:0] field2;
        } struct_id_t;
    end
    else begin
        typedef struct packed {
            logic [SOME_PARAM-1:0] other_field;
            logic [A-1:0][B-1:0] field1;
            logic [C-1:0] field2;
        } struct_id_t;
    end
endgenerate
struct_id_t some_struct_instance;

The last line of code triggers an error indicating that struct_id_t is undefined. Apparently, generate blocks create a local scope, which would explain the error.
Is there another way to accomplish this?
Before discussing what I've considered/tried, I'll first say that I understand one solution to this is to place all uses of struct_id_t in the local scope created by the generate block. However, this would require quite a bit of code duplicated between the blocks that I'd really prefer to avoid.
Other things I've considered:
A compiler directive does not create a local scope like a generate block. Unfortunately, (System)Verilog does not have an ifeq compiler directive, so I don't think this will work.
I also tried to forward declare the type. Something like:
typedef struct struct_id_t;
generate
    if (SOME_PARAM == 0) begin
        typedef struct packed {
            logic [A-1:0][B-1:0] field1;
            logic [C-1:0] field2;
        } struct_id_t;
    end
    else begin
        typedef struct packed {
            logic [SOME_PARAM-1:0] other_field;
            logic [A-1:0][B-1:0] field1;
            logic [C-1:0] field2;
        } struct_id_t;
    end
endgenerate
struct_id_t some_struct_instance;

The resulting error complains about struct_id_t never being defined. Section 6.18 of the 1800-2012 standard explains the error:

The actual data type definition of a forward typedef declaration shall be resolved within the same local scope or generate block.

So, the definition needs to be in the same scope.
I tried to create a label for the generate blocks that includes the parameter definition. That way I believe I could access the type hierarchically. Something along the lines of gen_name[SOME_PARAM].struct_id_t. But it seems that's not a valid name for a generate block.
What are my options?
Comment: A couple of questions: Does this code need to be synthesizable? If not, there are a number of approaches using classes. If you don't use your first attempted solution, how would you prevent `other_field` from being referenced? Where is `SOME_PARAM` being set from?
Comment: It does need to be synthesizable. `SOME_PARAM` is a module parameter. 2nd question: I think what you're saying here is that I define the struct with `other_field` and then only use that field in cases where `SOME_PARAM!=0`. I could do that and seems like a reasonable solution. Having a 2-bit unused field in the struct isn't ideal, but the synthesis tool should throw it out if it isn't used, so I guess my preference is mostly "aesthetic".
Answer: There is no way to declare a type in a generate block this way. But, you can define a variable inside a block as the following and use it with a structural name:
 if (SOME_PARAM == 0) begin: def
        typedef struct packed {
            logic [A-1:0][B-1:0] field1;
            logic [C-1:0] field2;
        } struct_id_t;
    struct_id_t some_struct_instance;
    end
    else begin: def
        typedef struct packed {
            logic [SOME_PARAM-1:0] other_field;
            logic [A-1:0][B-1:0] field1;
            logic [C-1:0] field2;
        } struct_id_t;
      struct_id_t some_struct_instance;
    end

assign def.some_struct_instance = 1;

The other approach is to pass the type to the instance of your module (mod):
module top#(SOME_PARAM = 0, A=1, B=1, C=1)();
  typedef struct packed {
    logic [A-1:0][B-1:0] field1;
    logic [C-1:0] field2;
  } struct1_id_t;

  typedef struct packed {
    logic [SOME_PARAM-1:0] other_field;
    logic [A-1:0][B-1:0] field1;
    logic [C-1:0] field2;
  } struct2_d_t;

  mod #(.stuct_id_t(struct1_id_t)) mod1();
  mod #(.stuct_id_t(struct1_id_t)) mod2();
endmodule

module mod#(type struct_id_t = logic) ();
  struct_id_t some_struct_instance;
    // ...
endmodule

Comment: Oh, I hadn't realized it was permissible to give the generate blocks the same name. For anyone else coming across this, the relevant part of the 1800-2012 standard is in section 27.5 Conditional generate constructs: "Because at most one of the alternative generate blocks is instantiated, it is permissible for there to be more than one block with the same name within a single conditional generate construct." Option (1) works nicely. Though I'm curious why it's possible to reference a variable from the generate block but not a type.


Split-Path + Join-Path functionality

Question: I have a problem concerning the Split-Path and Join-Path cmdlets of MS PowerShell. I want to copy an entire directory from the folder (including all folder and files therein) C:\Testfolder to the folder C:\TestfolderToReceive.
For this task I use the following coding:
$sourcelist = Get-ChildItem $source -Recurse | % {
    $childpath = split-path "$_*" -leaf -resolve
    $totalpath = join-path -path C:\TestfolderToReceive -childpath $childpath
    Copy-Item -Path $_.FullName -Destination $totalpath
}

The problem arises with files which aren't directly in C:\Testfolder, but in subfolders of it (EXAMPLE: C:\Testfolder\TestSubfolder1\Testsub1txt1.txt). All these files which are not directly in C:\Testfolder return "null" via the $childpath variable.
For example for the file C:\Testfolder\TestSubfolder1\Testsub1txt1.txt I would like it to return TestSubfolder1\Testsub1txt1.txt so that a new path called C:\TestfolderToReceive will be created by the Join-Path functionality.
Could someone explain me what I am doing wrong and explain me the correct way for tackling such a problem?
Answer: I think you're overthinking this. Copy-Item can do this for you on its own:
Copy-Item C:\Testfolder\* C:\TestfolderToReceive\ -Recurse

The \* part is crucial here, otherwise Copy-Item will recreate TestFolder inside C:\TestfolderToReceive
In this scenario, you could use Join-Path to position the * correctly:
$SourceDir      = 'C:\Testfolder'
$DestinationDir = 'C:\TestfolderToReceive'

$SourceItems = Join-Path -Path $SourceDir -ChildPath '*'
Copy-Item -Path $SourceItems -Destination $DestinationDir -Recurse

If you want a list of files copied, you can use the -PassThru parameter with Copy-Item:
$NewFiles = Copy-Item -Path $SourceItems -Destination $DestinationDir -Recurse -PassThru

Split-Path + Join-Path functionality


How to identify that joined table row have been changed?

Question: I have following simplified table structure:
CREATE TABLE CustTrans
(
  CUSTACCOUNT VARCHAR(20),
  JOURNALID   BIGINT,
  VALUE       NUMERIC(28,12)
)
CREATE TABLE CustJour
(
  ID BIGINT
)

And the following query (also simplified):
DECLARE @LastJourId BIGINT

SELECT ct.CUSTACCOUNT ,
       SUM(ct.VALUE + CASE WHEN @LastJourId != ct.JOURNALID THEN dbo.fnGetAdditionalCharges(ct.JOURNALID) ELSE 0 END)),
       @LastJourId = ct.JOURNALID
FROM CustTrans      AS ct
INNER JOIN CustJour AS cj ON cj.ID = ct.JOURNALID
GROUP BY ct.CUSTACCOUNT
ORDER BY ct.CUSTACCOUNT

This gives the error message:
A SELECT statement that assigns a value to a variable must not be combined with
data-retrieval operations.

The function fnGetAdditionalCharges calculates additional charges that apply to the journal. Therefore it should be run once per journal.
Is there way to calculate sum of transaction and additional charges for journal in one query?
In example above I tried to solve it using local variable assigning it last value of journal id and that is how tried to know that journal line was changed.
There are a lot of similar queries. And preferable solution is to make small change to query. I'm aware of solution using 2 SELECT statements with different grouping - first by CUSTACCOUNT and JOURNALID) and second by CUSTACCOUNT and adding fnGetAdditionalCharges value on that step.
Sample data:
INSERT INTO CustJour ( ID ) VALUES (1);
INSERT INTO CustTrans ( CUSTACCOUNT, JOURNALID, VALUE ) VALUES ('1', 1, 1), ('1', 1, 1);

For simplification, assume that function fnGetAdditionalCharges returns 1 each time. And in SELECT statement you are free to replace function call with 1
Expected result in this case will be 3. 2 - for sum of CustTran.VALUE and additionally 1 as charge on 1 existing journal.
There can be lot of journals. Each journal may contain many transactions.
Comment: have you tried without the variable, just `ct.JOURNALID` and then group by the same column `... GROUP BY ct.CUSTACCOUNT, ct.JOURNALID`
Comment: I need grouping by CUSTACCOUNT. I do not need additional break down by JOURNALID in results. Groping by CUSTACCOUNT and JOURNALID will at least require enveloping the SELECT in additional SELECT with grouping by only CUSTACCOUNT
Comment: can you show us some sample data and expected results ?
Comment: do you want to always run the `dbo.fnGetAdditionalCharges(ct.JOURNALID)` for the most recent `journalID`?
Comment: I want to run `dbo.fnGetAdditionalCharges(ct.JOURNALID)` for each unique ct.JOURNALID.
Answer: There's nothing wrong with breaking up a query into smaller parts; optimizer does it all the time, so why can't we?
If I understood correctly, you need something like this:
with x as (
    SELECT
        ct.CUSTACCOUNT, ct.JOURNALID,
        SUM(ct.VALUE) AS Value
    FROM
        CustTrans AS ct
    INNER JOIN
        CustJour AS cj ON cj.ID = ct.JOURNALID
    GROUP BY ct.CUSTACCOUNT, ct.JOURNALID
)
select CustAccount, sum(Value + dbo.fnGetAdditionalCharges(x.JOURNALID))
from x
GROUP BY
    x.CUSTACCOUNT
ORDER BY
    x.CUSTACCOUNT

Untested, of course. Like the others said, please give us some sample data to verify it.
Comment: Could you pls elaborate on _"there is a lot of almost similar SELECTs"_ -- where?
Comment: Actually, your best course of action would most likely be to modify each of those SELECTs.
Comment: Yes something like this. The only thing is that there is a lot of almost similar SELECTs. And I want to make small modifications instead of enveloping in additional SELECT like Milen wrote in answers.
Comment: It's a part of big stored procedure. Depending on a parameter it runs appropriate SELECT from a set. Using IF ELSE.
Answer: Your problem is that a SELECT statement can either create a result set, or assign to variables, but not both at the same time.
I'd suggest splitting this into more than one part; firstly select the CUSTACCOUNT, VALUE and JOURNALID into a temporary table, then evaluate @LastJourId based upon the value of JOURNALID in your temporary table, and re-select from your temporary table combined with @LastJourId to get your final result set.
Comment: Transact SQL is quite restrictive in how you can get results from it - you can either have a results set, or assign to variables with a SELECT statement, but not both simultaneously. The way around this, if you do need both a results set AND a value in a variable, is to perform the operations that generate those values sequentially, either by selecting into a bunch of variables and re-selecting the columns you need into a table format, or vice-versa, by selecting a bunch of columns into a results set and then selecting the individual columns you need in variables from those results.
Comment: I'm not an MSSQL expert. But I assume there can be some trick that might help me to solve problem.
Answer: SELECT  CUSTACCOUNT, SUM(Value) + ISNULL(dbo.fnGetAdditionalCharges(journalid), 0) as Custaccvalue
FROM
(
     SELECT  distinct ct.CUSTACCOUNT, SUM(ct.VALUE) as Value, ct.JOURNALID as journalid
     FROM
         CustTrans AS ct
     INNER JOIN
              CustJour AS cj ON cj.ID = ct.JOURNALID
     GROUP BY
             ct.CUSTACCOUNT, ct.JOURNALID
    ) a
GROUP BY
    CUSTACCOUNT
ORDER BY
    CUSTACCOUNT

demo: http://sqlfiddle.com/#!3/d910d/14
Comment: Yes. This is what I meant by enveloping with additional SELECT. But only `dbo.fnGetAdditionalCharges(ct.JOURNALID)` should be placed not in the inner SELECT but in the TOP.
Comment: the top select is aggregated row - for `custaccount` you'll have a lot of `journalId`'s I presume? How do you pick the journalid? Is it the most recent one ?
Comment: Sure, there are lot of journal ids. The thing is that inner SELECT goes by each transaction line and function `dbo.fnGetAdditionalCharges` in your case will be run per each transaction. So `dbo.fnGetAdditionalCharges` have to be in the TOP select as it goes only by unique journal ids


add a form into pop up stage (Customize Stage content)

Question: I have a button called add new user by hitting that a pop up window should come out containing a add user form .
Here is my function for that button :
public void  btnAddeNewClicked(){

        final TextField name = new TextField() ;
        final TextField addr = new TextField() ;
        final TextField wp = new TextField() ;
        final TextField state = new TextField() ;
        final TextField loginName = new TextField() ;
        final Label labelUsername = new Label();
        final Label labelAddress = new Label();
        final Label labelWebPage = new Label();
        final Label labelState = new Label();
        final Label labelloginName = new Label();
        final Button btn = new Button("Add");

        Stage dialog = new Stage();
        dialog.initStyle(StageStyle.UTILITY);
        Scene scene = new Scene(btn);
        dialog.setScene(scene);
        dialog.show();

}

the problem is I don't know how to add my form into my Stage . Any help is strongly appreciated :)
Answer: Use any of the layout to add the content of your popup. Later, add this layout as the root of the scene.
In the following example, I have used a GridPane.
import javafx.application.Application;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.stage.StageStyle;

public class Main extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        Button button = new Button("Show Popup");
        button.setOnAction(e -> btnAddeNewClicked());
        Scene scene = new Scene(new StackPane(button), 200, 200);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public void  btnAddeNewClicked(){

        final TextField name = new TextField() ;
        final TextField addr = new TextField() ;
        final TextField wp = new TextField() ;
        final Label labelUsername = new Label("Username");
        final Label labelAddress = new Label("Address");
        final Label labelWebPage = new Label("Web Page");
        final Button btn = new Button("Add");

        GridPane gridPane = new GridPane();
        gridPane.setVgap(10);
        gridPane.setHgap(10);
        gridPane.setPadding(new Insets(10));

        gridPane.add(labelUsername, 0, 0);
        gridPane.add(name, 1, 0);
        gridPane.add(labelAddress, 0, 1);
        gridPane.add(addr, 1, 1);
        gridPane.add(labelWebPage, 0, 2);
        gridPane.add(wp, 1, 2);
        gridPane.add(btn, 0, 3, 2, 1);
        GridPane.setHalignment(btn, HPos.CENTER);

        Stage dialog = new Stage();
        dialog.initStyle(StageStyle.UTILITY);
        Scene scene = new Scene(gridPane);
        dialog.setScene(scene);
        dialog.show();
    }
}

OUTPUT
Answer: Choose a suitable layout Parent to add your Nodes to. There are a lot of possibilities, so I just demonstrate it with a very simple one: VBox, which just puts the places all children in a vertical row:
final TextField name = new TextField() ;
final TextField addr = new TextField() ;
final TextField wp = new TextField() ;
final TextField state = new TextField() ;
final TextField loginName = new TextField() ;
final Label labelUsername = new Label();
final Label labelAddress = new Label();
final Label labelWebPage = new Label();
final Label labelState = new Label();
final Label labelloginName = new Label();
final Button btn = new Button("Add");

VBox root = new VBox();
root.getChildren().addAll(name,
                          addr,
                          wp,
                          state,
                          loginName,
                          labelUsername,
                          labelAddress,
                          labelWebPage,
                          labelState,
                          labelloginName,
                          btn);

Stage dialog = new Stage();
dialog.initStyle(StageStyle.UTILITY);
Scene scene = new Scene(root);
dialog.setScene(scene);
dialog.show();

Note that these layouts could be used as children of other layouts too, if a more complex layout is needed. Using SceneBuilder may be easier for a beginner, but you should know how the layouts position the children regardless. It's easy to see the child-parent relationships in the resulting fxml file reproduce the same layout in java code.


Ho to fix Jumbled pages with rails calls?

Question: When I run this code, the data is entered into the table cells correctly from the tables I am pulling from, but the forms overlap themselves so they display the form over top of the form below it, they are also shifting left and right. I have also included my CSS code, I tried adding a div wrapper around it after the loop is intiated so that it would be placed in a wrapper for each itteration, but that has not solved the problem.
<% if @form.valid? %>

      <% if @form.items.any? %>
        <% @form.items.each do |w| %>
          <% if !w.hours.any? %>
            Error Message
          <% else %>
            <% w.hours.each do |l| %>

                        SECTION A – Information

                        Complete:

                        list:
                        <%= l.list.list_name %>

                        sublist name:
                        Blank

                        number:
                        <%= l.b_line_item.b_line_item %>
                        Paragraph number:

                        Main number:
                        Left in for now
                        Identifier:
                        <%= l.identifier.identifier %>

                        Start & end dates:
                        <%= l.description %>
                        Basic or option :
                        <%= l.year.year %>

                        category
                        <%= l.category.category %>
                        Effort:

                        e

                        b

                        c

                        Narrative description:

                        <%= l.item.description %>

                        Section C –  Estimating

            <% end %>

      <% end %>
    <% end %>
  <% end %>
<% end %>

CSS:
div#form{
    padding: 10px;
    align: center;
}
.tg {
    border-collapse:collapse;
    border-spacing:0;
}
.tg td{
    font-family:Arial, sans-serif;
    font-size:14px;
    color: #000;
    padding:10px 5px;
    overflow:hidden;
    word-break:normal;
    border: black;
    border-style: solid;
    border-width: 1px;
}
.tg th{
    font-family:Arial, sans-serif;
    font-size:14px;
    font-weight:normal;
    color: #000;
    padding:10px 5px;
    overflow:hidden;
    word-break:normal;
    border: black;
    border-style: solid;
    border-width: 1px;
}
.tg .tg-multirow{
    background-color:#c0c0c0;
    text-align:center;
}
.tg .tg-subtitle{
    background-color:#ffffc7
}
.tg .tg-title{
    font-weight:bold;
    font-size:16px;
    background-color:#bbdaff;
    text-align:center;
}
.tg .tg-celltitle{
    background-color:#c0c0c0
}
.tg .tg-datacell{
    text-align: center;
}

h1 {
    display: inline-block;
    padding: 0px,15px,0px,0px;
    min-width: 80px;
    font-size: large;
    color:#003366;
    font-weight: bold;
}

Answer: I'm not sure if I understood your question correctly, but right in the middle of your template you have 2 member rows with no colspans set. This part:

                    e

                    b

                    c

Edit: One more thing would be to put  s inside empty tds. Empty tds can collapse
Comment: It worked fine all the templates were in order on the page until I started loading data into cells with rails calls, when I did that is when the issue occured.


Mathematics in PHP

Question: I am a beginner here. I have two questions.
This is my query:
$result = mysql_query( "select SUM(achievenum) as achieve_rows from games" );
$row = mysql_fetch_object( $result );
$total_achieve = $row->achieve_rows;

$result = mysql_query( "select SUM(achieveget) as get_rows from games" );
$row = mysql_fetch_object( $result );
$get_achieve = $row->get_rows;

$completed_rate = $get_achieve * 100 / $total_achieve;

How can I make this code with one query instead of two?
When I display the percentage

it shows
Completion Rate : 32.3529411765%

I need it to show only the first three numbers.
32.3 %

Comment: Please stop writing new code with the ancient mysql_* functions. They are no longer maintained and community has begun the [deprecation process](http://news.php.net/php.internals/53799). Instead you should learn about prepared statements and use either [PDO](http://php.net/pdo) or [MySQLi](http://php.net/mysqli). If you care to learn, [here is a quite good PDO-related tutorial](http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers).
Comment: Ok Thanks For Posting This :) Iam Gonna Learn
Answer: To modify your sql use this:
select
    SUM(achievenum) as achieve_rows,
    select SUM(achievenum) as achieve_rows
from games

and to display the result, you want to format it first using round:
<?php
    echo round($completed_rate,1)."%";
?>

Answer: The query would be :
select ROUND(SUM(achieveget)*100/SUM(achievenum),1) as completion_rate from games

Comment: +1 for doing it all in MySQL ([as you should always do](http://www.onextrapixel.com/2010/06/23/mysql-has-functions-part-5-php-vs-mysql-performance/)) and in 1 SQL query

Mathematics in PHP


Javafx audit logging

Question: I have an assignment in Javafx to take a basic login application and have it produce an audit log that includes the entries the user put in the text boxes and the buttons pressed along with the date and time. I have searched high and low and I cannot find an example that I can make work with my application. Can someone provide me a basic example of how to implement the audit log or point me in the right direction?
Answer: For a professional application, many people use java.util.logging, or Apache Log4J. However, since this is an assignment, I assume your instructor wishes you to keep a log using your own File I/O.
I would suggest implementing a method called log(String message) which opens your audit file and appends a line to the end with the current timestamp and given message. Then, everywhere in your application you need to log something, you simply call your own log(message) function.
For more help with File IO, try reading through this tutorial, or searching google for a good one.
Comment: How is this implemented? I understand using BufferedWriter but how do I get log(message) to work?

Javafx audit logging


Verificar se existe parâmetro em URL javascript

Question: Tenho uma URL que poderá ou não conter parâmetros nela. Ex: www.site.com.br/?id=1 ou www.site.com.br.
Preciso verificar se existe algum parametro nesta URL e com isso poder acrescentar mais um no final. Por ex:

Se URL for www.site.com.br vira www.site.com.br/?id=1
Se URL for www.site.com.br/?utm=teste vira www.site.com.br/?utm=teste&id=1

Ou seja, a URL poderá ou não ter um parâmetro e esse parâmetro poderá ser aleatório, com isso não tenho como saber exatamente qual o parâmetro terei.
Preciso saber isso, pois preciso adicionar um parâmetro id=SC no fim da URL e em algumas vezes está dando erro, pois já existe um parâmetro anterior. Veja como estou fazendo:
//Pego a url anterior que o usuário estava e redireciono para a mesma url porém adicionando um parametro no final
window.location.href = document.referrer+'?id=CS';

Com o código acima, se a URL anterior for www.site.com.br/?utm=teste a nova URL ficará site.com.br/?utm=teste?id=CS e o usuário não conseguirá acessar a página.
Answer: Basta usar SearchParams.set().

var url="";

//COM parametro id na url, substitui o valor
url = new URL('http://www.site.com.br/?utm=teste&id=12');
   url.searchParams.set('id', 'SC');
    console.log(url.toString());

//SEM parametro id na url, acrescenta o parametro e respectivo valor
// já separado com &
url = new URL('http://www.site.com.br/?utm=teste');
    url.searchParams.set('id', 'SC');
    console.log(url.toString());

//SEM parametros na url acrescenta o parametro e respectivo valor
//com a interrogação (?)
url = new URL('http://www.site.com.br');
    url.searchParams.set('id', 'SC');
    console.log(url.toString());

 // com anchor
   url = new URL('http://www.site.com.br/?utm=teste&id=12#secao');
   url.searchParams.set('id', 'SC');
    console.log(url.toString());
Comment: @sam hahaha, só fazer assim: if(isIE == true){ use o do tio sam}else{use o do vô leo} :)
Comment: É uma solução também, mas não gosto dessas APIs porque não funciona no IEca.
Answer: Uma alternativa é usar new URL(endereco) para criar um objeto URL e depois usar um URLSearchParams para manipular os parâmetros da URL.
Através do método set é possível adicionar o novo parâmetro. Depois basta atualizá-lo na URL:

// URL sem parâmetros
var url = new URL('http://www.site.com.br');

var sp = new URLSearchParams(url.search);
sp.set('id', '1')
url.search = sp;

console.log(url.toString()); // http://www.site.com.br/?id=1

//--------------------------------------
// URL com parâmetro
url = new URL('http://site.com.br/teste/p?utm=teste');

sp = new URLSearchParams(url.search);
sp.set('id', '1')
url.search = sp;

console.log(url.toString()); // http://site.com.br/teste/p?utm=teste&id=1

O detalhe é que o endereço deve ter o protocolo (http://etc..., https://etc..., ftp://etc...), caso contrário new URL dá erro - ou seja, new URL('http://www.abc.com') e new URL('https://www.abc.com') funciona, mas new URL('www.abc.com') dá erro.

Para manipular a URL atual, você pode fazer var url = new URL(window.location). Depois você adiciona os parâmetros que precisa (usando set) e por fim faz window.location = url:
var url = new URL(window.location);

var sp = new URLSearchParams(url.search);
sp.set('id', '1')
url.search = sp;

window.location = url;

Obs: caso a URL já possua um parâmetro id, o set sobrescreverá seu valor:

// já tem id=2
var url = new URL('http://www.site.com.br/?id=2');

var sp = new URLSearchParams(url.search);
sp.set('id', '1')
url.search = sp;

// sobrescreve o valor de id para 1
console.log(url.toString()); // http://www.site.com.br/?id=1

Se for o caso, você pode verificar se já existe o parâmetro id usando if (sp.has('id'))

Usar regex e adicionar o parâmetro no final pode funcionar para a maioria dos casos, mas se a URL tiver anchor, não vai funcionar. Isso porque o anchor fica no final (ver aqui e aqui).
Por exemplo, se a URL for http://www.site.com/?teste=1#secao. Se eu simplesmente adicionar o parâmetro no final, a URL ficará http://www.site.com/?teste=1#secao&id=1, o que não é o desejado, já que neste caso o id=1 não faz parte da query string. Usando URLSearchParams você obtém o resultado correto, que é http://www.site.com/?teste=1&id=1#secao, veja:

// tem anchor "#secao"
var url = new URL('http://www.site.com/?teste=1#secao');

var sp = new URLSearchParams(url.search);
sp.set('id', '1')
url.search = sp;

// adiciona o id na posição correta (antes do anchor)
console.log(url.toString()); // http://www.site.com/?teste=1&id=1#secao

Apenas para deixar mais claro a diferença:

// tem anchor "#secao"
var url = new URL('http://www.site.com/?teste=1&id=1#secao');
var sp = new URLSearchParams(url.search);
// imprime teste=1 e id=1
for (var [nome, valor] of sp.entries()) {
    console.log(`${nome}=${valor}`);
}
console.log(url.hash); // #secao

console.log('----------------');
// se adicionar o parâmetro depois do anchor, não funciona
url = new URL('http://www.site.com/?teste=1#secao&id=1');
sp = new URLSearchParams(url.search);
// só vai imprimir teste=1
for (var [nome, valor] of sp.entries()) {
    console.log(`${nome}=${valor}`);
}
// tudo que está depois do # é o anchor
console.log(url.hash); // #secao&id=1

Repare que quando a URL é http://www.site.com/?teste=1#secao&id=1, somente o teste é reconhecido como parâmetro da query string. Já tudo que está depois do # (no caso, secao&id=1) faz parte do anchor (ou seja, se apenas concatenar &id=1 no final da string, este não é reconhecido como parâmetro).
Por isso que concatenar no final não é garantido que funcione em 100% dos casos.

Atualmente, esta API funciona bem no Firefox, Chrome, Edge e Safari, mas não no IE 11: https://caniuse.com/#search=URLSearchParams
Comment: Se quiser pegar o domínio dinamicamente também pode usar o `document.domain`, no caso de não querer algo fixo no `new URL`.
Answer: Acho que sua própria lógica já indica que o que você precisa fazer é um if. Ex:
if(document.referrer.contains("/?")){
window.location.href = document.referrer+'?id=CS'
}
else{
window.location.href = document.referrer+'&id=CS'
}

Comment: mas e se a url anterior for por ex: site.com.br/teste/p?utm=teste ou seja, não posso colocar uma regra fixa...poderia pesquisar apenas se existe a "?" na url, mas não sei se seria certo
Comment: Pq a url dessa pagina é amigavel, ou seja, cada uma é de um jeito. Vai que na url amigavel tenha "?" acho dificil, mas vai saber
Answer: Pode verificar com regex se no document.referrer possui o padrão:
?qualquer_coisa=

Se for verdadeiro, concatena &, se for falso, concatena ?:
var ref = document.referrer;
window.location.href = ref + (/\?.{1,}=/.test(ref) ? '&' : '?') + 'id=CS';

Comment: Por favor evitem longas discussões nos comentários; a conversa de vocês foi [movida para o chat](https://chat.stackexchange.com/rooms/83013/discussion-on-answer-by-sam-verificar-se-existe-parametro-em-url-javascript)


Form isn't sending POST parameters?

Question: I want to have a single email field form on my page to suscribe to a newsletter and when the user submit this form, to redirect to a complete form (with name, surname...)
The complete form is designed with Webforms module and this single field form with the Form API in a custom module.
I'm using Drupal 6.25.
The problem is when I submit this form; I feel it don't send any POST parameters. I get them in Webform by setting a default value for the E-mail field at %post[newsletter_mail] and it doesn't work.
This is my code.
function block_contact_newsletter_form() {
  $form['description'] = array(
    '#type' => 'item',
    '#title' => t('Suscribe to Newsletter !')
  );

  $form['newsletter_mail'] = array(
    '#type' => 'textfield',
    '#default_value' => t('Your E-mail')
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('OK'),
  );

  return $form;
}

function theme_block_contact_newsletter_form($form) {
  $output = '';
  $output .= drupal_render($form['description']);
  $output .= drupal_render($form['newsletter_mail']);
  $output .= drupal_render($form['submit']);
  $output .= drupal_render($form);

  return $output;
}

function block_contact_newsletter_form_theme() {
  $themes = array();

  $themes['newsletter_form'] = array(
    'arguments' => array(),
  );

  return $themes;
}

function block_contact_newsletter_form_submit($form, &$form_state) {
  $link_newsletter = drupal_get_path_alias('node/'.variable_get('webform_newsletter_default_nid', ''), $language->language);
  if (strstr($path_newsletter, 'node/') !== FALSE) {
    $link_newsletter = drupal_get_path_alias('node/'.variable_get('webform_newsletter_default_nid', ''), 'fr');
  }

  $form_state['redirect'] = $link_newsletter;
}

function block_contact_default() {
  $content = array();
  $content[] = '
My.Sitwe
';

  $items[] = array('class' => 'mail', 'data' => l(t("By mail"), 'node/'.variable_get('webform_contact_default_nid', FALSE)));
  $chat = variable_get('default_chat', "");
  if (!empty($chat)) {
    $items[] = array('class' => 'chat', 'data' => l(t("By chat"), variable_get('default_chat', "")));
  }

  $facebook = variable_get('default_facebook', "");
  if (!empty($facebook)) {
    $items[] = array('class' => 'facebook', 'data' => l("Facebook", $facebook));
  }

  $twitter = variable_get('default_twitter', "");
  if (!empty($twitter)) {
    $items[] = array('class' => 'twitter', 'data' => l("Twitter", 'http://twitter.com/'. $twitter));
  }

// The interesting part for this function begins here.
  $items[] = array('class' => 'newsletter_form', 'data' => drupal_get_form('block_contact_newsletter_form'));

  $content[] = theme('item_list', $items);

  return array(
    'subject' => t("Contacts"),
    'content' => implode('', $content),
    'classes' => array('block-ot-contact')
  );
}

Do you have any advice?
Answer: You're telling the form to submit via POST, and then once it's done submitting, to redirect to the webform. I think what you intended to do was to make the form submit its data straight to the webform, which you could do with the #action key in the $form array. See http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/6#action
However, this isn't really a very robust approach. A better approach would be to put together your own webform, and then put that webform into a block. If you need to do any custom processing on the webform, the webform module has its own API and hooks that you can use.
Comment: Thank you for your answer ! I now use $form['#action'] instead of $form_state['redirect'] and I check into Network traffic in Google Chrome and my POST parameter is sent but I can't retrieve it in my Webform. Do you have an idea other than create a new Webform ? Thank you again
Comment: That's a slightly different question! If you can see the POST is working properly, the original question has been answered. You should post a new question with a different title.
Comment: http://drupal.stackexchange.com/questions/31985/cant-retrieve-post-parameters-in-webform

Form isn't sending POST parameters?


Using constants defined in header file

Question: I'm trying to translate a X11/OpenGL demo into Java and I'm not sure how to use the constants OpenGL defines.  The only method I can think of is digging into the OpenGL headers and copying the constants to my program but is that the proper way to do it?  I imagine that there is no guarantee that those constants will be the same in a different environment.
Answer: If you use a library like LWJGL it defines those constants for you and you don't have to worry about their actual values.
Comment: What drew me to JNA is the ability to potentially use opengl with no native libraries.
Comment: I missed the JNA tag. Copying the constants would be the only method as there is no way to magically get at them as C/C++ has no reflection. BTW JNA also uses a native library.
Answer: I can't use this method to do what I want because I'm actually trying to get a preprocessor definition but it does answer my question.
You use the NativeLibrary class like so.
NativeLibrary library = NativeLibrary.getInstance("LIBRARY_NAME");
library.getGlobalVariableAddress("VARIABLE_NAME");
Edit: I feel like I should admit that it does not make sense to access a preprocessor definition, I ended up just copying the definitions into my program.

Using constants defined in header file


Random forest regression prediction for high dimensional data

Question: I am working on a project by using a high dimensional data set. Close to 50000 Obs. with 392 Variable.
I used lasso to reduce it to this point from a total of 1200 variables. And the whole data set is grouped into several clusters. The data is of a product and its specifications and other relevant details as covariates and time to get sold is the response.
I am trying to predict the time with the help of covariates and I am using randomForestSRC package.
<code>    library(randomForestSRC)
    options(rf.cores = 8)
    rfdata <- data.frame(time,factors,agewitinmy,exclusivity,specs,financial)
    obj <- rfsrc(time ~ ., data = rfdata[(1:500), ],nsplit = 10)
    pre <- predict(obj,rfdata[(500:550), ])
    results <- cbind(data.frame(time[500:550],pre$predicted))
</code>
But the accuracy is not good, am I doing something wrong here ? Can I adjust the accuracy by doing some changes. Or is it because of the high number of variables ?
Thanks for your time and response.
Comment: I'm not sure that the lasso procedure is useful here because the random forest model is implicitly interactive, while the lasso only looks at linear effects in the equation that you specify. So a feature that's not important on its own (in lasso) might be important in the presence of another (in random forest).
Answer: Pre-selecting with lasso may not be beneficial; can check both scenarios. RF was designed for thousands of predictors, so this should not in itself be an issue. Just need to make sure the number of trees is appropriate for the number of predictors (check error stabilization).
Several general possibilities for improvement include: removing worst predictors; removing correlated predictors; adjusting for predictors with a very wide range of classes; weighted RF if there is class imbalance (although improvement they report is rather small).
Comment: Thank you, I checked with out using lasso and it is giving better prediction. I think lasso removed/made the coefficient of some variables to zero which was important for prediction in RF.


I want to access my servers(private) using public domain names

Question: Ec2 gives a public hostname to each instance instead of assigning an ip. I want to do the same. I want to access my machines like that.
<code>machine1.mycompany.com >> 10.0.0.123
machine2.mycompany.com >> 10.0.0.234
</code>

Internet > proxy-server > (machine1, machine2)Intranet

What should I use as a proxy server and How can I configure that. Apache? nginx?
Example:
I just created an instance. It has private ip of 10.34.90.77 and it has public domain name ec2-50-17-23-238.compute-1.amazonaws.com.
Comment: Your question isn't clear.  Are you talking about something specific with EC2 or are you using that as an example.  Are you asking about DNS, or about a hosting solution / issue?
Answer: Amazon also gives you a public IP and a private IP, the difference is how those 2 resolve. If you resolve from inside AWS you get the private IP and from outside you get the valid public IP address. You can do the same, you just need 2 DNS servers (one external and one internal to your network) and any kind of firewall that does NAT (so you can assign 1-to-1 NAT mappings from a valid IP to an internal one).
Comment: I dont think aws assigns public ip to an each instance unless you manually do so.
Comment: Check the interface for Public DNS and Private DNS. Ping the Public DNS from outside AWS and you will get it as a valid IP. You can also assign a Elastic IP to the instance, the difference being that the Public and Private IPs will change when you reboot your image, but the Elastic IP never changes. The Public DNS is like `ec2-ip.compute-1.amazonaws.com`
Answer: If you want to access your machines using domain names, you have two options:

Setup and run an internal DNS server like bind and configure your server with the IPs you want.
Modify your hosts file on the machine you want to access these machines from.
Comment: +1 I think a basic DNS overview would be helpful too for the OP.
Comment: I want to access them from public Internet.


Nvidia NPP static link on windows

Question: Is there no static linking option for windows for nvidia's performance primitives libraries?
The guide for npp recommends static linking, and shows how for linux, but not windows.
http://docs.nvidia.com/cuda/npp/index.html
Comment: Only dynamic linking is possible on Windows.
Answer: It is not currently possible to statically link NPP on windows.

Nvidia NPP static link on windows


APC Smart-UPS 3000 turning off but passing own test

Question: I have APC Smart-UPS 3000 at home which I got hand and apparently when the power goes down it just shuts down instead of switching to backup.
Based on how it behaves I have reasons to believe is not the batteries. Apparently there is no service nearby and I am sure shipping it would too expensive.
Sadly it does not have a network card on it so the only way to debug its condition is via the front panel.
I recorded a video at https://www.youtube.com/watch?v=gIVx7s68rzs to exemplify better how it behaves.
Answer: The mainboard might be faulty.
Your only hope is a cold reset and watch after if it work better after.

The Cold start procedure is used to determine if a UPS is functional
  if it will not turn on when plugged into utility power. The Brain Dead
  procedure performs a hard reset of the Smart-Ups microprocessor. It
  does not however reset saved preferences.
Resolution:
Cold Start: This is a great way to establish if a UPS will not turn on
  due to bad input power. Never use a Cold Start to troubleshoot a bad
  battery LED as it will clear the light most every time even if the
  battery is actually bad. This is because the self-test is comparing
  the battery health compared to the load attached. If there is no load
  attached, the battery will appear healthy.   1) Turn off and unplug
  the Smart-UPS from wall. Remove any attached load. 2) Press and hold
  the power button (labeled ""I/TEST"" on legacy non-LCD screen units)
  on the front of the UPS until you hear a LONG beep. 3) Let go DURING
  the long beep. If you let go after the beep ends you will need to try
  again. 4) UPS should go through its' normal self test and end up on
  battery with 4 beeps every 30 seconds. This shows that the UPS is
  functioning correctly and can both pass a self test and function on
  battery. 5) You can now plug your UPS back into the wall. If the input
  power is acceptable the UPS will transfer back online.
Comment: Aparently cold-boot test end-up with "internal fault" and the middle (3/5) battery led on as on https://www.youtube.com/watch?v=ChBs_yHg5AY :(
Answer: You pinged me on my similar post here :
APC Smart-UPS turning off by itself?
Just wanted to let you know that a few days after I posted, the UPS suddenly went OFFLINE with no prior warning due to an "inverter fault" and will not turn back on. It's basically broken now.
So I would consider any suspicious behavior with this type of UPS as a sign of impending failure. Take action now if your UPS is serving anything without redundancy, that's my advice.
Hope this helps


Is it possible to represent set of rational numbers as the countable union of disjoint dense subsets?

Question: Let, Q is set of rational numbers with relative topology of natural topology on R. Is it possible to represent Q as the countable union of disjoint dense subsets?
P.S. According the famous book, "Counterexamples in topology" by Steen and Seebach, it is possible, (page 143. Definition of Roys Lattice space). But, I dont know the proof of this.
Comment: Try $x+D$, where $D$ are dyadic rationals, $x\in\mathbb Q$.
Comment: Yes, every LOTS is maximally resolvable (killing a mosquito with a shotgun..)
Answer: Sure, there are various ways to do this.
In my opinion, the nicest is to consider restrictions on denominators - for example, let $B_k$ be the set of rational numbers whose lowest-terms representation has denominator a power of $k$ (with the convention that the lowest-terms representation of $0$ is $0\over 1$). Then:

What can you say about each $B_k$ in terms of topology?
How do the different $B_k$s relate? In particular, can you find an infinite set $X\subseteq\mathbb{N}$ such that for distinct $a,b\in X$ we have $B_a\cap B_b=\emptyset$ (which will then give you the partition you want)? HINT: think about divisibility ...
Comment: Its clear that every Bk is dense in Q, because for any efsilion>0, there exist a and b from Bk, such that, |a-b|<efsilion.

X must be such set: X={x from N: x is not a any power of any natural number.}
Clear that, union of Bk, when runs over the X, is Q.

Am I wright?
Comment: Also X is infinite, because it contains the set of prime numbers.


Specify default filegroup for indices?

Question: This is puzzling me - in SQL Server 2005/2008, I can specify the default file group which is then used for all data tables. I can also specify another filegroup for all BLOB type fields.
But I cannot figure out if and how I can specify a default filegroup for indices.....
My setup usually is:
* primary filegroup - nothing but the system catalog - bare minimum
* DATA filegroup - which I make the default for my database
* INDEX filegroup for all indices
* BLOB filegroup (optional) for all BLOB data
* LOG (obviuosly)
Now if I create all by tables and indices manually by script, of course I can specify the appropriate file group for each. But is there a way / trick / hack to make it possible to specify where to put the indices? When I use SQL Server Mgmt Studio to e.g. designate a column as primary key on a table, it creates a PK_(tablename) index - but unfortunately, it sticks that into the DATA filegroup, and once it's there, it seems I cannot change it anymore (in the visual designer).
Am I missing something? Or has Microsoft just not provided such a setting??
Thanks for any hints, pointers, leads!
Marc
Answer: If there is a clustered index on a table, the data and the clustered index always reside in the same filegroup. You cannot place the base table and clustered index on separate Filegroups. This is because the clustered index is the actual table data.
You can of course place non-clustered indexes in a different Filegroup from the table they reference.
You cannot specify two default Filegroups i.e. one for data and one for indexes.
Hope this clears things up for you but please feel free to pose further questions.
Comment: Yes, obviously - clustered index *IS* the data - right, I should have known.....
I can change the filegroup for the other indices in the designer - too bad there's no option to specify a default for those....
Comment: Add a connect item requesting that be added in a future release.
Answer: You can create a clustered index on a filegroup other than where table resides,but the filegroup of table may automatically change to index's filegroup.
Comment: A clustered index IS THE ACTUAL TABLE, ignore this answer.

Specify default filegroup for indices?