Connection timed out and lock_may_be_available() on working site

Question: I'm hoping someone can point me to a fix. My drupal 7 app was running fine locally this a.m. while I was testing a way to insert a row using mysql tools for a non-Drupal function. My environment is Apache running virtual host on php 5.4.34 on a Ubuntu VM.
After not getting satisfaction using the mysql functions, I started a simple PDO function using Drupal's database settings from the settings.php file. I was able to insert a row successfully but when I returned to the local site I got this error after a long time:
drupal_log_error(Array ([%type] => PDOException,[!message] => SQLSTATE[HY000] [2002] Connection timed out,[%function] => lock_may_be_available(),[%file] => /media/psf/Home/apps/habitatnashville/includes/lock.inc,[%line] => 167, etc

[%type] => PDOException
    [!message] => SQLSTATE[HY000] [2002] Connection timed out
    [%function] => lock_may_be_available()
    [%file] => /media/psf/Home/apps/habitatnashville/includes/lock.inc
    [%line] => 167
    [severity_level] => 3

I've looked here and on Drupal's site. Because it's a connection error the likely suspects are that I've munged the credentials somehow.
When something like this happened months ago, I did a service mysql restart, did that again a few minutes ago, rebooted the ubuntu VM and rebooted entire computer to shake that lock.
I've removed that test file with the PDO just in case. Here's the output of my drush status:
Drupal version                  :  7.27
 Site URI                        :  http://default
 Database driver                 :  mysql
 Database username               :  admin
 Database name                   :  my_db
 Database                        :  Connected
 Drupal bootstrap                :  Successful
 Drupal user                     :  Anonymous
 Default theme                   :  My_theme
 Administration theme            :  rubik
 PHP executable                  :  /home/sam/.phpbrew/php/php-5.4.34/bin/php
 PHP configuration               :  /home/sam/.phpbrew/php/php-5.4.34/etc/php.i
                                    ni
 PHP OS                          :  Linux
 Drush version                   :  6.2.0

My database is running as "service mysql status" => mysql: start/running, process 1291.
What else could be affecting this?
Comment: "Connection timed out". My guess is there could be some DNS issues. Checkout [slides 64-72](https://docs.google.com/presentation/d/1AgnurTWsWdMAFjfFmSU7mk2zfJu8jG_KmVdZ7-o6Pok/edit#slide=id.g385c64257_0182) for some ideas on things to try.
Comment: Yes, that makes sense. I've changed the reference to the IP addy of the db server temporarily, but it doesn't seem to be the cause, at least in this case. The slides were very helpful for related things I need so that's a bonus.
Comment: Is it the port number?
Comment: I don't think so as it was working earlier in the day. My "fix" to get past it was to increase memory in PHP, Drupal from 128m to 150m. If you'd like, pls form it into an answer.
Comment: I noticed you've suggested to increase the memory, which I've written as last point in my answer.
Answer: There could be multiple reasons/thoughts:

Are you sure mysql is running?
Has your site got just too big for the resources allocated to mysql in the configuration?
Did you manually "emptied" all of the cache files via the database?
Low file system space on the database server
If you just moved the site to the other server and mysql is not set up to accept enough connections.
The user you are connecting with has SELECT permissions on mysql but not DELETE or UPDATE etc.
The host settings in sites/default/settings.php doesn't matche the one from the User in the database
MySQL 5.7 does not allow root user to access a database from client app. After switching to a normal user, it solves.
Sometimes tuning xampp like on php.ini (memory_limit=256M) and my.ini (max_allowed_packet = 32M) and disable devel by drush (drush dis -y devel) also works.
...


Rational morphism vs rational point over function field

Question: an homework question :
Let $X$ and $Y$ be two integral schemes of finite type over a field $k$. There is a rational morphism $X\longrightarrow Y$ if and only if the scheme $Y\times_k k(X)$ has a rational point ($k(X)$ denotes the function field of $X$).
Any idea on how to prove that?
Answer: To go from the rational map to the rational point, try answering these two questions: what (regular) maps are there from $K(X)$ to anything obvious; and if you have a rational map from $X$ to $Y$, what regular maps to $Y$ is it related to?
To go from the rational point to the rational map, first try doing it when $X$ and $Y$ are both affine, which will show you why finite type is necessary.  Then answer these questions: can $X$ be assumed to be affine; and can $Y$ be assumed to be affine?
Some further intuition might be helpful, though I don't know if it will actually aid in solving the problem.  A regular map $X \to Y$ is determined by its graph, an $X$-valued point of $X \times_k Y$.  This problem is asking you to show that a rational map is also determined by its "graph" in $K(X) \times_k Y$.  Figuring out what that means is, in some sense, the proof.
Comment: I'm sorry but i don't manage to get any further. Could you give me more details?


read int64 from fixed64 protobuf field in golang

Question: I have a field that is of type fixed64 in a .proto file.
I want to read it as an int64 field:
score := int64(pb_obj.Score)

When I try to compile the line agove I get the error message cannot convert pb_obj.Score (type *uint64) to type int64.  I tried converting the a uint64 as well, and got an almost identical message.
Comment: Yes, *pb_obj.Score is fine. And also don't make sense to change fixed64 to int64. If score is allways positive use uint64 and fixed64 in proto. If can be negative prefer int64 and sfixed64 in proto files.
Answer: pb_obj.Score's type seems to be *uint64 (pointer to uint64), not uint64. You just need to access to the value the pointer is referencing:
score := int64(*pb_obj.Score)

(See the * prefix as the difference)
Answer: Based on the compile error you're working with a uint64 pointer and not a uint64 value.  You may get what you want by referencing the value directly using the * operator. I've never worked with protobuf, so I could be off but that should get you moving.  Here's a nice reference that may help golang pointers


Como mudar de Activity ao clicar em uma opção no menu AlertDialog?

Question: Estou com o seguinte problema, tenho um metodo que é chamado, quando a pessoa clicar em um botão, E SEGURAR, (onLongClickListener) aparecerá um alert com várias opções.
1º Opção é Cancelar a Mesa, 2º Ver pedidos, e 3º Chamar outra activity.
Acontece, que dá erro quando eu clico na terceira opção, onde estaria o meu Intent, chamando outra Activity.
Obs:
A inicialização da outra activity nao tem erro, pois eu consigo acessar ela por outros botões usando o mesmo método Intent intent = new Intent();
private AlertDialog opcoes;
CharSequence op[] = new CharSequence[] {"Cancelar Mesa", "Ver Pedidos", "Acrescentar/Alterar Pedido", "Teste"};
private void opcoesMesas(final View v) {
    //Cria o gerador do AlertDialog
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    // define o titulo
    builder.setTitle("Escolha a Opção desejada: ");
    //define a mensagem
    //builder.setMessage("Deseja cancelar essa mesa?");
    //define um botão como positivo
    builder.setItems(op, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
                switch(i){
                    case 0:
                        ConfirmacaoDeCancelamento(v);
                        break;
                    case 1:
                        exibindoPedidosDasMesas(v);
                        break;

                    case 2:
                        openPedidos();
                        break;

                    case 3:
                        break;

                    default:
                }

        }
    });
    builder.show();
}

private void openPedidos(){
    startActivity(new Intent(getBaseContext(),pedidos.class));
}

No case 2:, eu já tentei colocar o Intent direto, também nao dá.
E ele reconhece que foi clicado na terceira opção, pois eu ja coloquei um Toat para me informar caso chegasse no Case 2, e deu certo.
Me ajudem, eu so preciso chamar outra tela, ao clicar no Case 2.
Comment: Poste o *logcat* com o erro.
Answer: Antes de ir para a próxima activity chame o método dismiss() do dialog e então chame o método openPedidos()
Comment: o que faz, pra que serve esse, dismiss() ?
Comment: fecha o  dialog. chame-o : dialogInterface.dismiss(); ou dialogInterface.getDialog().dismiss();


need more detail tying in Session_start() to a select statement

Question: Still banging my head, but I think an answer may help me see how things really work. I always sucked at languages, but I figure with your help I can brute force this.
So I am just going to post the whole code so as not to cause confusion.

<title>Change a player</title>

<?php
 include "inc.php";
 session_start();

 print 'Select week for season: ';
   print $this_season;
##the week drop down query#
$wquery=
"select week_num,week_name
from stats_week
where season=$this_season
order by week_num";
    $wresult=mysql_query($wquery);
print'<form action="changeplayer_2.php" method="post">';
    session_start();
        print"<select name='Week_select'>
";
        while ($wrow=mysql_fetch_array($wresult))
    {
    print '<option value="'.$wrow['week_num'].'">'.'week             '.$wrow['week_num'].'     '.$wrow['week_name'].'</option>
\n';
    }
print "</select>

";#
print'<button type="submit" >Next</button>';
$varWeek=$_POST['Week_select'];
    print"</form>";
$_SESSION['week'] = $varWeek;
?>

So, I don't know how to get 'Week_select' to be assigned to $_SESSION['week']. Above code was my last ditch effort.
Secondly, once I assign something to the Session, how do I clear it out later so it doesn't keep popping up?
Bonus question
print 'Select week for season: ';
   print $this_season;

Is the only way I can make the both the statement and the variable to display.
When I do
print 'Select week for season: '$this_season;

I don't get the variable displayed, also when I do
print 'Select week for season: $this_season';

I get Select week for season: $this_season displayed
Comment: you can only start a session once in a page.. so remove all other `session_start();` at the buttom of your code
Comment: @BillFlippen yes you need to
Comment: http://www.diffen.com/difference/Echo_%28PHP%29_vs_Print_%28PHP%29
Comment: @kaii great catch, I got to placing it in various places trying to get it to work, though i got rid of that one.
Comment: @DipeshParmar Will that answer the reason why I need two line?
Answer: When displaying (print/echo) a variable with a specific string, you must concatenate the two with " . " (dot)
print 'Select week for season: ' . $this_season;

Comment: thanks!!!!!!!! This is still all new to me and I am still learning the small stuff
Answer: Session unset and destroy: here
Or you could just unregister the one variable: session_unregister($week)
And yes you should only have once session_start per page ideally before anything is output.
And the correct way to print is to concatenate:
print "Select week for season: " . $this_season;

Comment: Thank you, I didn't realize I had the second session_start(), I was moving it to different parts of the code forgot I moved it without deleting
Answer: Place your session_start() at the top of the html. Remove the second session_start() in the page.
Try printing/echoing your $_SESSION['week'] to check if it has a value.
print $_SESSION['week'];

Comment: thank you for the time, my 2nd page does have that but fails to print (it does print other $_session['x'] that I was testing with (thus my question about unregistering them)
Comment: Come to find out, my pftp session ended, I reopened and didn't get the cd directory path quite right. I was uploading my changes to the wrong directory. Thanks for your patience!
Answer: Your first question:
Part 1
To set a session the code should be inserted before the HTML tags. Read code below:
<?php
session_start();
$_SESSION['week'] = $this_season;
?>

//your code here

//your code here

Part 2
If you want to remove a session completely you can use the following code, which will destroy the session:
<?php session_destroy(); ?>

Or if you only want to clear a session you can use the following code:
<?php unset($_SESSION['week']); ?>

It will clear the session value.
Your second question:
To merge both print syntax together you need to use a dot "." . In some other language "+" is used. The process is called concatenation
Your new code should be:
print 'Select week for season: ' . $this_season;

This means that you want to print the string 'Select week for season: ' followed by the variable $this_season.
Comment: Thank you, after a bit more clarification [here](http://stackoverflow.com/a/15963224/2227549) your answe makes perfect sense
Answer: session_start() should be placed before output or any $_SESSION interaction. And only once.
<?php
session_start();
?>

<title>Change a player</title>

<?php
 include "inc.php";
// etc...
?>

UPDv1:
if you need to remove something from session, then you can perform:
<?php unset($_SESSION['something']); ?>

UPDv2:
If you need tu put entire select into $_SESSION, you may do:
ob_start();

print "<select name='Week_select'>";

while ($wrow=mysql_fetch_array($wresult))
    { print '<option value="'.$wrow['week_num'].'">week '.$wrow['week_num'].' '.$wrow['week_name'].'</option>'.PHP_EOL; }

print "</select>";

$_SESSION['something'] = ob_get_clean();

// var_dump($_SESSION);

Comment: Removed second Session(). So how do I get the  print" "; to be assigned to $_SESSION('Week') ?
Comment: Read below. If you save something to $_SESSION, then output should show it via var_dump($_SESSION). Useful while debugging.
Comment: I understand (kinda of) how the $_SESSION works, just not how to get a $variable assigned from my  statement. Can I simply do a $_SESSION= ?
Comment: I guess I don;t know how to ask the question, let me try again and thank you for your patience.   From the drop down list, I want to select 1 item, then assign it to a variable to get it to $_SESSION
Comment: I will open this as another question thanks so much for all your help
Comment: Could you tell me what `var_dump($_POST['Week_select']);` shows to you? It should be working already. Do you destroy (`session_destroy()`) your session anywhere? If not, then it should be working.
Comment: I actually got it answered [HERE](http://stackoverflow.com/a/15963224/2227549). It was a combination not knowing the SUBMIT/POST operation and uploading to the wrong directory


What options are there for cheap synthesiser/synth modules to get for gigs?

Question: I have an electronic piano with nicely weighted keys and a midi out, but I want to play 80s music with my band and it doesn't have the right sounds.
I need a fairly cheap (sub £300) synth/synth module. It has to have a nice interface to be able to switch voices during gigs, and it has to have at least 10 voice polyphony.
Any suggestions?
Comment: If you could give us the model it would help, but seeing as it has midi output you can probably control a synth from it. Also, do you specifically want synth hardware or would computer software suffice?
Comment: I would prefer hardware, my laptop is very old.
Comment: I would look into rack style synth modules, they have a MIDI input you hook your keyboard into. For specifics, FM synthesis was pretty big in the 80s, so that's a good place to start. Look into it. A while back I got a used Yamaha TX81z rack-mounted synth for about $50 that does great 80s style sounds, probably because it came out in '87 (famous Lately Bass: http://bit.ly/1AF3w28). Look for used synths from that era, there are tons and they all usually accept MIDI input. The Roland Juno series might also fit the bill, and they have modern versions of it as well. They cost a bit more though.
Comment: What do you think of the Roland jv 1080?
Comment: If you are asking me, I don't have personal experience with the Roland, but it's got a great reputation (see link).  It will be a little more expensive than the FM type rack modules I mentioned, but will probably be a lot more flexible. http://www.vintagesynth.com/roland/jv1080.php
Answer: Yes you can control any synth with a MIDI input with your electronic piano. Don't worry about the range, the range of a synth (128 notes at the very least) is bigger than the keys in your keyboard (88 keys in the bigger ones).
If you want cheap 10 note polyphony, the cheapest option I can think of is the Novation MiniNova. In good quality synths you'll hardly find something cheaper, but it's still a robust system.
Another popular option from that price range is the microKorg, but it only has 4 note polyphony.
There are a lot of options from there on. Check synth listings like this one. You won't find cheap analog synths with that polyphony, so you want to search for analog modeling, virtual analog, or digital synths.
Comment: @KeirLewis Yes. It has 10 note polyphony, MIDI in, and you can carve an 80s sound with it (you can carve an 80s sound with pretty much any synth). If you are planning to buy it compare it first with other synths from its price range, make sure you are not missing something (a model with more oscillators, more routing options, maybe a vocoder, etc).
Answer: I am excluding from my answer new synths with built-in keyboards. That would broaden things too far into the area of product-recommendation. Suffice to say there are lots of MIDI keyboards on the market, and all of them will function as a MIDI sound module if you want to control them from a different keyboard.
Other than to say you want to play 80s music, you don't say much about what kind of sounds you want to produce -- and that's going to play the biggest part in what you want to buy. Bleepy analogue solo sounds? Warm analogue bass? Lush pads? Cheesy FM leads? Do you want high quality presets, or do you want to craft your own sounds? These are all factors that will influence your choice of synth.
In the words of a forum post I found somewhere, "software synths have pretty much taken over the low end world". £200 will get you a laptop that's more than capable of running most software synths. The cheapest Dell/etc will do. A second-hand laptop a couple of years old will also do the job.
In Windows, there is a wide range of software synths provided as VSTs - a standard plugin format. Many VSTs are free, or just a couple of pounds -- although there are also VSTs that cost hundreds of dollars.
You plug your VST into a program that can host it; and there are many. One such is VSTHost, again free, which takes a bare-bones approach to routing MIDI notes to VST sound sources.
There are similar tools for Macs.
This approach gives you lots of flexibility to try different types of synthesis. Unlike a hardware synth, which does what it does and nothing else, your laptop can be a twittery analogue synth one minute, an FM synth the next, a sampler the next, or all of them at once.
If your keyboard has a USB socket, then you're ready to go -- the sound will come out of your PC's sound card.
If your keyboard only has a DIN type MIDI out, then you'll need to buy a hardware MIDI interface, and now you have a choice -- a cheap one that just converts MIDI to USB? Or a posh sound card with MIDI as a bonus? See How necessary is an USB Audio Interface?
You can also hook up your MIDI keyboard to an iPad, in which case there's plenty of soft synth apps, including the bundled GarageBand and the excellent Sunrizer.
If you are dead set on using a hardware sound module, without a built in keyboard, you will probably find yourself restricted to high-end rackmounts that are out of your price range, or second-hand modules.
Answer: You don't actually need another keyboard. I use a Roland JV series,which is the 'brain' of a synth, without the keyboard part - much smaller, easier to store/carry. There are cards available which fit in, to give an extra 200+ sounds each. MIDI in/out, so controllable with your existing keyboard - and cheaper, as no keys.
Comment: What do you think of the jv 1080?
Comment: I sometimes use XPs for gigs - love them, but need a piano feel as well, so take another board, but MIDI into JV-1080 and use its sounds too. Love the cards, don't often make my own sounds. It works well, and is rack-mountable.A few about on Ebay for around £100.
Comment: Forgot to mention, my electronic keyboard already has a nice piano sound, as well as a couple other basic ones like e. piano and strings, so I'll look into xps
Comment: XPs have been at £300-£400 for last few years. Great tools, organ type action, so I basically use decent Roland pno for well, pno, and MIDI it to XPs. Better for playing Hammond type stuff on XP, although you can put in whatever sound you like, of course.


fast approximation of degree of normality, given order statistics

Question: In a software application, I have access to the order statistics (without any extra computational cost) of a collection of $N$ samples (where $N$ can vary and is often quite large, usually on the order of $10^4$). I would like to quickly determine a rough and approximate degree of normality for the samples, without incurring a huge computational overhead. Note that I do not need a formal boolean test of normality; quantitative confidence or p-values are not important here. I only need some metric or test statistic that will approximately vary along with the degree of normality of the current collection of samples.
I have looked at some options in the literature and fear they may incur too much processing time (and be overkill for my needs, as I only need something loosely approximate). For example, the Anderson–Darling test statistic involves repeated ln() and erf() calls (please correct me if I'm wrong), which are not very cheap for large $N$. The Shapiro–Wilk test statistic seems somewhat promising, but I am unclear on how much is involved in calculating the coefficients $\alpha_i$. It looks like it could be complex (or involve a very large lookup table?)--and would these coefficients need to be recalculated completely if $N$ changes (which can happen frequently in my application)?
The Shapiro-Francia test seems powerful and simple, but there is no closed-form analytic expression for the values of $m_{i:n}$ required by the test. Is there a good, computationally cheap approximation for the $i^{th}$ mean of the order statistics for large $N$?
Maybe the Kolmogorov-Smirnov test statistic is my best bet, because the only "expensive" function needed is erf() and there may be ways to cheaply scale/interpolate these normal CDF values for changing $N$. For example, maybe I can precompute it for a very large $N$ and then downscale/interpolate quickly to any smaller $N$.
Is there any computationally cheap test statistic I can calculate, maybe even just using empirical z-scores or something? Any help is appreciated.
Comment: Given the discussion on [this page](https://stats.stackexchange.com/q/2492/28500), what are you trying to accomplish with this normality testing?
Comment: I am not doing normality *testing*. No true/false formal statement ever needs to be made on if the samples are objectively normal with any certain degree of confidence. Instead I need a metric (or "statistic" or "feature") that will approximately vary along with how well the dataset approximately fits a normal distribution. It could be considered a realtime feature over a constantly changing set of samples. New samples will arrive and old ones will drop off. For example, the value could increase as the set better fit a normal distribution and the value can decrease the less this is the case.
Comment: $10^4$ is not large, computationally speaking, for functions like $\ln$.   For example, I just computed 100,000 logs of exponential variates in 0.004 seconds on my home PC.
Comment: Yes, the `ln()` call in itself is not a problem. But the `erf()` is expensive if called repeatedly.
Answer: Here is a sketch of a possible methodology.

Set up $2k+1$ bins of equal probability from inverse cumulative normal distribution.

Estimate the mean $\hat{\mu}$ and variance $\hat{\sigma}$.

Standardize the sample points, $z_i = \frac{x_i-\hat{\mu}}{\hat{\sigma}}$

Count the number of standardized sample points $z_i$ in each bin $j$ to get empirical probability distribution by bin, accumulate bin probability $P_j$ with $\frac{1}{N}$ increment per data point in bin $j$.

Use the discrete KL-divergence measure as your statistic. KL-divergence is asymmetric, use empirical distribution for $P_j$, $\frac{1}{2k+1}$ for $Q_j$.

$D_\text{KL}(P \parallel Q)  = \sum\limits_{j=1}^{2k+1} P_j \log\left(\frac{P_j}{Q_j}\right) ~.$

You can set up the bins once (small constant overhead), the other operations are proportional to the number of data points, so your $O(N)$ requirement should be realized. I would not worry about computational costs of functions like log() for $2k+1$ bins.
Comment: This is an interesting proposition. By fixing the number of bins, the calculation dependency on the particular current value of $N$ is greatly reduced. Do you have any estimate or heuristic to use for the total number of bins? It seems like it cannot be too high (due to too few samples per bin). But maybe being too low decreases the power of the test? Any ideas on a formula to maybe guide the number of bins, given an estimated average $N$ value?
Comment: This is a quick and dirty proposal. OP mentioned 10^4 sample size. So 101 bins gives nearly 100 expected per bin if near normal. Using 0 = 0 ln(0), zeroes aren't really a problem.  I'd have to code it up to get better intuition.
Comment: I would not categorize the proposed method as a _test_, its more of a metric useful for _ranking_ a standardized empirical distribution's closeness to the standard normal distribution. Given the proposed method's only intent is to rank, I don't think the exact number of bins will change the output rankings much.
Comment: I misspoke when I said "decreases the power of the test". I meant to say "decreases the discrimination of the metric". I will be running some experimental tests with this metric and should have results in a few days. So far, this answer seems very appealing.
Comment: Based on your application needs, you can certainly construct a "test" by specifying an ad hoc threshold for $D_{\textrm{KL}}\left(P||Q\right)$.
Comment: Thanks for the excellent suggestion. I posted the results of my experiments below. The solution works great and has low computational complexity across a very wide range of $N$. And the optimal number of bins for my discrimination purposes is only ~10, regardless of $N$.
Answer: I have found the Kullback–Leibler divergence (a measure of statistical distance) suggested by @krkeane in the accepted answer to be an effective and computationally cheap solution. This implementation does not actually require the order statistics, and in fact it requires less computation to compute it on the unordered sample set. Pre-sorting the samples requires $O(N*log(N))$ for the total computation, but computing this measure on the unordered samples requires only $O(N*log(B))$ in total, where $B$ is the number of bins and the optimal $B \ll N$ (as I show below). $O(N*log(B))$ is due to performing a $log(B)$ binary search over the bins for each unordered point in $N$. I've also found that $B$ need not be an odd value, as originally proposed; even values also work fine.
I have performed a series of experiments to determine the optimal $B$ value for discriminating between random normal samples ($\mathcal{N}$), random uniform samples ($\mathcal{U}$), and a 50%-50% mixture of the two distributions ($\mathcal{N}\mathcal{U}$). I performed these experiments for $N=1k$, $N=10k$, and $N=100k$ sample points. I averaged the results over 500 trials for each tested number of bins ($B$).
Somewhat unexpectedly, I found that optimal $B$ does not appear to depend on $N$, and always seems to be around 10 or 11 (at least for discriminating $\mathcal{N}$ vs. $\mathcal{U}$ vs. $\mathcal{N}\mathcal{U}$, with $N = [1k, 100k]$). I optimized $B$ against a certain measure of discrimination: $\displaystyle \operatorname*{argmax}_B min(ratio, 1-ratio)$, where $ratio = \left.\frac{(D_\text{KL}(\mathcal{N}\mathcal{U} \parallel Q) - D_\text{KL}(\mathcal{N} \parallel Q))}{(D_\text{KL}(\mathcal{U} \parallel Q) - D_\text{KL}(\mathcal{N} \parallel Q))}\right|_{bins=B, D_\text{KL}(\mathcal{U} \parallel Q) \ge D_\text{KL}(\mathcal{N}\mathcal{U} \parallel Q) \ge D_\text{KL}(\mathcal{N} \parallel Q)}$ and $ratio = 0$ was assigned if the expected ranking of the three $D_\text{KL}$ values was violated.
A $min(ratio, 1-ratio) = 0.0$ represents the worst possible discrimination between the three sample distributions, and $min(ratio, 1-ratio) = 0.5$ represents the best possible discrimination. I found that higher $N$ lowered the variance of the results and increased the maximum possible discrimination $min(ratio, 1-ratio)$, but did not affect the optimal $B$ at all. Please see the charts below for a summary of the results. Having optimal $B \approx 10$ means that this measure can be computed very efficiently over an unordered sample set for a huge range of $N$, which was precisely the objective.
A typical result with $N=100k$ and $B=10\\ D_\text{KL}(\mathcal{N} \parallel Q) = 0.000036\\ D_\text{KL}(\mathcal{N}\mathcal{U} \parallel Q) = 0.015816\\ D_\text{KL}(\mathcal{U} \parallel Q) = 0.028814$

UPDATE
After further testing, I have learned that the optimal $B$ actually depends on exactly how the two differing distributions overlap. For example:
$\mathcal{N}(\mu=0,\,\sigma^{2}=1), \mathcal{U}[-1, 1]$: gives optimal $B=10$ (and the charts given above).
$\mathcal{N}(\mu=0,\,\sigma^{2}=1), \mathcal{U}[-2, 2]$: gives optimal $B=36$ (and a skewed appearance to the charts).
However, in all cases tested so far, the $B$ "sweet spot" has been between 10 and ≈40, and does not appear to depend on $N$. And $B=10$ still performs well, across the board, even if it is not always the exact optimal value for the two given differing distributions.


ip6tables rules are completely ignored inside OpenVZ container

Question: We have set up IPv6 networking on openvz using bridged veth devices.
The IPv6 traffic to and from the VEs works fine.
ip6tables works on the HN and iptables work on the VE.
Inside the VE we can set up ip6tables rules without any error messages.
They are completely ignored however.
What additional configuration options are necessary for ip6tables to work?
Comment: Might be worth doing a `ip6tables -I INPUT -j LOG` and seeing if packets are actually hitting the filters. If they are, try adding similar lines throughout the filters (particularly after any expected drops) and see what gets logged to syslog.
Comment: Make sure the iptables features you require are in the vz.conf file.
Comment: Is the service started?  Does it need to be restarted for the changes to take effect?
Comment: Did you verify that the iface you are using is seeing traffic in the old IPv4 iptables? Obscure abstraction layers can leave several "wrong" NICs in the system that seemingly do nothing. Gone are the days when you simply had eth0 for internet and eth1 for your internal LAN.
Answer: Seems you are using the containers under proxmox, right?
You should then check from the graphical interface in proxmox that the networkd addresses are fine and known by PVE
In some cases, pve prevents to use some iptables modules, eg:
 FATAL: Could not load /lib/modules/4.15.18-1-pve/modules.dep: No such file or directory
Note: On proxmox 5, OpenVZ containers will be converted to LXC, this might introduce some bias
Answer: Make sure you are applying the rules to the venet0 interface by explicitly.
Comment: Nope. OP said explicitly that he uses veth. No venet0 here
Answer: OpenVZ containers inherit the kernel and modules from the host node.  Because of this you cant load new kernel modules in an OpenVZ/LXC container. I would ensure that the hostnode has the ip6_tables kernel module either compiled into the kernel or loaded as a module.
This is a problem because OpenVZ is Paravirtualization, meaning that it shares the same kernel with the host node.  Because you share the same kernel as the other OpenVZ containers, you can't load modules into the kernel.  With Hardware virtual machines you get to run your own kernel and can then load/unload kernel modules, or compile your own kernel to use. The question linked below covers the differences in more detail.
What is the difference between Full, Para and Hardware assisted virtualization?
Sadly when you only have access to the Guest OpenVZ environment determining if the IPv6 IPtables module is loaded can be a bit hard as lsmod, /proc/modules, and /proc/config.gz often do not exist inside OpenVZ.
Because of this, you might just have to contact your provider as someone with root access on the host node will have to load this kernel module for you.
Comment: This is all true, but completely irrelevant: he _is_ the provider and the relevant modules are _already_ loaded.


Contador de horas progressivas e cumulativas com dias

Question: Tenho um projeto onde devo acumular horas trabalhadas de um serviço em um projeto, ele deve armazenar no banco as horas/dias.
Então quando iniciado, se não houver tempo anterior começa do zero, mas se já houve uma etapa anteriormente ele deve contar a partir daquele e tempo e acumular, salvando depois no banco.
Até então o script está funcionando, porém preciso agora deixá-lo dinâmico para que o relatório apareça mais de um projeto mostrando o tempo de execução.
JS

PHP
<?php
    var_dump($_POST);
    $data1 = '0,1,59,55';
    $data2 = '0,7,59,55';
?>

HTML

<form action="" method="POST" enctype="multipart/form-data" role="form" name="form1">
    <input type="text" id="campo1" name="tempo" value="">

    <input type="submit" value="Enviar" class="btn btn-primary" />

Não entendo de js, mas creio que seja a melhor solução, achei um script interessante de timer, já adaptei algumas das necessidades, mas não consigo aplicar mais de um input fazendo o código reagir dinamicamente.
Comment: Achoq ue ficaria legal utilizando ajax, ai nem precisa do timer.
Tambem aconselho você a utilizar a lib momentJs, facilita muito calculos com data.
Comment: Se resolveu o problema, pode fechar a pergunta.
Comment: Foi mal, na verdade eu usei o plugin errado. O que ele usou chama `Flipclock`. Agora você já conhece dois :)
Comment: Cara como faço isso? srsrsrsrsrrs
Comment: Manja trabalhar com ajax?
Comment: n.
Demorei 2 dias pra fazer uma junção de 4 scripts pra fazer isso rssrsr
Comment: Você conseguiu resolver?
Comment: ainda não consegui
Comment: Usa um plugin chamado [Final Countdown](http://hilios.github.io/jQuery.countdown/). Meu colega precisou fazer exatamente a mesma coisa. Eu ensinei ele a fazer com o `LocalStorage` para armazenar onde o tempo "parou" para prosseguir posteriormente do mesmo ponto.
Comment: vou testar, vlw
Comment: Resolveu seu problema?
Answer: Bem pessoal. Para fazer cálculos com horas, é preciso transformar a hora em um número que corresponde à menor unidade significativa com a qual vai trabalhar. Por exemplo, se precisar dos segundos, transforme-a em segundos: horaEmSegundos = horas*3600 + minutos*60 + segundos.
Aí calcule o tempo fazendo o cáculo tempoTotal = hrEmSegFinal - hrEmSegInicial.
Bem, desculpem, eu não entendo nada de PHP, eu comecei com Java e agora trabalho com NodeJS. Eu tenho, aqui, dois métodos em javascript, que no Java, logicamente, com pequenas adaptações, também funcionam. Acredito que seja possível também no PHP.
O primeiro pega a hora UNIX (todos os milissegundos desde 01/01/1970 somados) e calcula o intervalo de tempo. E só iniciar só ficar clicando nos botões parar/continuar que os intervalos de tempo vão sendo somados na variável tempo1Acumulado.
O Segundo, o cálculo e é feito a partir da hora digitada em campos de texto e estes intervalos vão sendo acumulados na variável tempo2Acumulado, em minutos. Ah, não esqueça, que este método visa ser simples e didático. Caso esse intervalo envolva a meia-noite(mudança de data), deve ser somado 24 horas à hora final(pode ser feito colocando um if se a hora de início é maior que a de término). Ah, por serem no javascript, podem apresentar problemas, se a hora da máquina cliente não estiver correta. Espero que possa ser adaptado ao PHP, mas no Nodejs funciona porque esta é a sua linguagem de programação.
HTML + JavaScript
<!DOCTYPE html>

       <title>Contador acumulativo de tempo</title>
       <meta charset="UTF-8">

Contagem de Tempo

        <fieldset>
            <legend>Método 1- A partir da hora do Sistema </legend>

Total Acumulado: 0

Clique no botão iniciar: 0

                  <input id="btnIniciar1" type="button" value="Iniciar" onclick="getHoraInicio()" title="Iniciar neste momento"/>
                  <input id="btnFim1" type="button" value="Parar" onclick="paraContador()" title="Terminar agora" disabled="disabled"/>
        </fieldset>
        <fieldset>
            <legend>Método 2- Apartir da hora digitada</legend>

Total Acumulado: 0

                  Hora Início
                  <input type="text" id="hIni" value="14:17" />

                  Hora Término
                  <input type="text" id="hTerm" value="17:30" />

                  <input id="btnCalc" type="button" value="Adicionar o Intervalo de Tempo" onclick="addTempo()" title="Terminar agora"/>
        </fieldset>


Algebra vs field extension. Examples of finite dimensional algebras without primitive generators.

Question: Could someone clarify the difference, if any, between an algebra over a field $K$ and a field extension of $K$? Also, can someone provide an example of a finite dimensional algebra over $K$ that has no primitive generator?
About the above question, I know that a finite extension of a field $K$ has a primitive generator, as long as the field is finite or of characteristic zero. Does the same property hold for algebras? (if so, I guess the example must be an infinite field with finite characteristic).
Also, I know that a reduced finite dimensional algebra over a field $K$ of zero characteristic has a primitive generator. What happens when instead $K$ is finite? Could someone provide an example of such an algebra which has no primitive generator?
Comment: What does the notation $(x,y)^2$ mean? Is that the product of the ideal generated by $x$ and $y$ with itself? Also, could you provide a bit more details on its zero dimension over $K$? (It's the first time when I encounter it, I think).
Answer: I can't answer all of your questions, but I can tell you this much: A $K$ algebra is a ring $R$ with a ring homomorphism $\varphi : K \to R$. Thus you can multiply each element of $R$ by any element of $K$ via $k\cdot r = \varphi(k) r$.
Generally, one might not actually assume that an algebra is a ring, in which case a $K$ algebra is simply a $K$-vector space with a bilinear multiplication map satisfying no additional assumptions.
By contrast, a field extension $L$ of $K$ is a field which contains $K$ as a subfield. Thus, it is a very special case of an algebra.
Yes, the notation $(x, y)^2$ means the product ideal $(x, y) \cdot (x, y)$. It's generated by the elements $x^2, xy, yx, y^2$.


Computing double integral $\ \iint \sqrt{4-r^2}r \ dr d\theta $

Question: I am trying to solve the following integral:
$$\ 2 \int_0^\pi \int_0^{2\sin\theta} \sqrt{4-r^2} \ r \ dr d\theta $$
My attempt:
$$\ 2 \int_0^\pi \int_0^{2\sin\theta} \sqrt{4-r^2} \ r \ dr \ d\theta \stackrel{t = 4-r^2}{=} -\int_0^\pi \int t^{\frac{1}{2}} \ dt d\theta = -\frac{2}{3} \int_0^\pi t^{\frac{3}{2}} \ d\theta = -\frac{2}{3} \int_0^\pi \left[(4-r^2)^{3/2}\right]_0^{2\sin\theta} \ d \theta= -\frac{2}{3} \int_0^\pi (4 - 4 \sin^2\theta)^{3/2} - 8 \ d\theta = - \frac{2}{3}\int_0^\pi 8(1-\sin^2\theta)^{3/2} - 8 \ d \theta $$
because $\ (1-\sin^2\theta) = \cos^2\theta$ and $\ (\cos^2\theta)^{3/2} = \cos^3\theta $
$$\ = -\frac{16}{3} \int_0^\pi \cos^3\theta - 1 \ d\theta = \frac{16\pi}{3}  $$
but I'm wrong somewhere along the way because the answer should be $\ \frac{16}{9} (3\pi -4) $ and with the limits I set I get the right answer using Wolfram integral calculator.
Comment: just the cosine. Note that the integrand is positive while cosine takes on also negative values in the required range.
Comment: Shouldn't there be an absolute value in the last integral?
Comment: you mean like $\ | \cos^3\theta -1 | $ ?
Answer: The error is due to assuming $(x^2)^{3/2}=x^3$ as opposed to $|x^3|$. This can be solved by noticing that $\cos^3x=|\cos^3x|$ for $x\in[0,\pi/2]$ and $-\cos^3x=|\cos^3x|$ for $x\in[\pi/2,\pi]$. Thus the integral should become $$2\times\left(-\frac{16}{3} \int_0^{\pi/2} \cos^3\theta - 1 \ d\theta\right)=\frac{16(3\pi-4)}9.$$
Comment: oops.. thanks for clarifying!! :)


Functional equation with two variables: $ f(x) - f(y) = (x+y)(x-y) $

Question:
Find all functions that, for all real numbers $ x $ and $ y $, satisfy the following functional equation:
$$ f(x) - f(y) = (x+y)(x-y) $$
Answer: Hint: $f(x) - x^2 = f(y) - y^2$, so this must be ...
Comment: I'm not sure could you factorise that maybe?
Comment: $f(x) - f(0) = x^2$ and hence $f(x) = f(0) + x^2$. The function is of the form $f(x) = k+x^2$ for any constant $k$. There are infinitely many functions satisfying the given condition.
Comment: Sorry could you please explain why $f(x) - f(0) = x^2$ ?
Comment: Added an answer with explanation.
Comment: The point is that the right side doesn't depend on $x$ (or, if you prefer, the left side doesn't depend on $y$), so $f(x) - x^2$ is constant.
Answer: Putting $y=0$, we get $f(x)−f(0)= (x+0)(x-0) = x^2$ and hence $f(x)=f(0)+x^2$. The function is of the form $f(x)=k+x^2$ for any constant $k$. There are infinitely many functions satisfying the given condition.
Comment: No. We have already got the function expression.
Comment: Oh I get it now, thanks for the clarification. I also tried the inverse (subbing in y = 0) and that also worked. Just to be clear, would I need to substitute in any other values to prove the validity of my argument?
Answer: $$f(x)-f(y)=(x+y)(x-y)$$
so:
$$f(x)-f(y)=x^2-y^2$$
and:
$$f(x)-x^2=f(y)-y^2$$
Left Side has only $x$ and Right Side has $y$ argument and each side is equal to another, so both sides must be equal to a Constant, like $K^2$.
so:
$$f(x)-x^2=f(y)-y^2 = K^2$$
and:
$$
f(x)=x^2 + K^2\\
f(y)=y^2 + K^2
$$


Typescript Open File Dialog to Upload File from an Angular Service without using an input element

Question: I have an Angular keystroke service that I am listening to keyboard keystrokes & performing actions based on the keystroke pressed.
I have a keyboard shortcut that I would like for it to open the file dialog, & the user should select a specific JSON file to upload, & then use this JSON data & convert to an object to use in the system.
The normal way of uploading a file is trough a HTML: <input type="file" />. However I am in a service and I don't need an input element, nor do I have where to put it. as I don't think a service should contain HTML.
How can I accomplish to trigger the file dialog box to open in a function & get the data of the selected JSON file that without an input and without downloading any external npm packages.
Comment: A common practice would be to dynamically add an input file field to the page and logically click it.
Comment: I don't think a service should deal with html, I would do so in a component but I want to avoid it in a service.
Comment: I don't think a service should deal with UI at all, and therefore should not be concerned with things like file dialog boxes, or keystrokes for that matter...
Answer: Unfortunately, <input type="file"> is a little bit special in HTML. You cannot generate such an event in JavaScript that would correspond clicking this input.
The only way to trigger this programmatically is to have a hidden UI component where this input is added and then the click triggered.


DELPHI - help need with a ClientDataSet

Question: I have a ClientDataSet with the following data
IDX   EVENT BRANCH_ID   BRANCH
1     E1     7  B7
2     E2     5  B5
3     E3     7  B7
4     E4     1  B1
5     E5     2  B2
6     E6     7  B7
7     E7     1  B1

I need to transform this data into
IDX   EVENT BRANCH_ID   BRANCH
1     E1     7  B7
2     E2     5  B5
4     E4     1  B1
5     E5     2  B2

The only fields of importance are the BRANCH_ID and BRANCH
and BRANCH_ID must be unique
As there is a lot of data I do not what two have copies of it.
QUESTION:
Can you suggest a way to transfrom the data using a Cloned version of the original data ?
Comment: Can you describe the intended transformation more fully?  There are multiple potential interpretations possible from an example like that.
Answer: Cloning won't allow you to actually change data in a clone and not have same change reflected in the original, so if that's what you want you might rethink the cloning idea.
Cloning does give you a separate cursor into the clone and allows you to filter and index (i.e. order) it independently of the master clientdataset.  From the data you've provided it looks like you want to filter some branch data and order by branch_id.  You can accomplish that by setting up a new filter and index on the clone.  Here's a good article that includes examples of how to do that:
http://edn.embarcadero.com/article/29416
Taking a second look at your question, seems like all you'd need to do would be to set up a unique index on branch_id on the cloned dataset.  Linked article above has info on how to set up index; check docs on clientdataset.addindex function for more details and info on setting the index to show only unique values, if I recall it may just mean you set branch_id as the primary key.
Answer: I can't think of a slick way to do this, but you could index on BRANCH_ID, add an fkInternalCalc boolean field to your dataset, then initialize that field to True on the first row of each branch (using group state or manually) and then filter the clone on the value of the field. You'd have to update the field on data changes though.
I have a feeling that a better solution would be to have a master dataset with a row for each branch.
Answer: You don't provide many details about your use case so I'll try to give you some hints:

"A lot of data" suggests that you might have it from a SQL backend. Using a 'SELECT DISTINCT...' or 'SELECT ... GROUP BY BRANCH_ID' (or similar syntax depending on what SQL backend do you) will give the desired result with ease and speed. Please confirm and I'll give you more details.
As the others said a simple 'clone' wouldn't work. The most simpler (and perhaps quicker) sollution, assuming that ussually the brances are few in number WRT to data is to have an index outside of your dataset. If really you want to filter your original data then add a status field (eg boolean) on your data and put a flag (eg. 'True') on the first occurence.

PseudoCode:
(Let's asume that:
 your ClientDataSet is cds1
 your cds1 have a status field cds1Status (boolean) - this is optional, needed only if you want to sort/filter/search the cds1
 you have a lIndex which is a TStringList)
lIndex.Clear;
lIndex.Sorted:=True;

with cds1 do
try
  DisableControls;
  First;
  while not Eof do //scan the dataset
  begin
    cVal:=cds1Branch_ID.AsString;
    Edit; //we anyway update the Status field
    if lIndex.Find(cVal, nDummy) then //nDummy - we don't use it.
    begin //already in index
      cds1Status.AsBoolean:=False; //we say here "No, isn't the 1st occurence"
    end
    else
    begin //Not found! - Well, let's add it...
      lIndex.Append(cVal); //update the index
      cds1Status.AsBoolean:=True; //mark the first occurence
    end;
    Post; //save the changes in the status field
    Next;
  end; //scan
finally
  EnableControls; //housekeeping
end;

//WARNING! - NOT tested. I wrote it from my head but I think that you got the idea...
...Depending on what you try to accomplish (which would be the best thing that you might share with us) and what selectivity do you have on BRANCH_ID perhaps the Status engine isn't needed at all. If you have a very low selectivity on that field (selectivity = no. of unique values / no. of records) perhaps it's much faster to have a new dataset and copy there only the unique values rather than putting each record of the original cds in Edit + Post states. (Changing dataset states are costly operations. Especially if your cds is linked to a remote data storage - ie. a server).
hth,
PS: My sollution is intended to be mostly simple. Also you can test with lIndex.Sorted:=False and use lIndex.IndexOf instead of Find. In some (rare) cases is better. Depends on your data. If you want to complicate the things and the speed is really a concern you can implement a full-blown BTree index to do your searces (libraries available). Also you can use the index engine of CDS and index the BRANCH_ID and do many 'Locate' on a clone but because your selectivity is clearly < 1 scaning the cds's entire index theorethically should be slower that a scan on a unique index, especially if your custom-made index is tailored to your data type, structure, distribuition etc.
just my2c

DELPHI - help need with a ClientDataSet


Cannot SVN checkout when anon-access = none

Question: When I have
anon-access = write

Everything works fine. When I change svnserve.conf to:
anon-access = none
auth-access = write

And uncomment password-db and authz-db AND add user in authz with rw AND put username/password in passwd, nothing works. Eclipse keeps giving me a "Cannot map the project with svn provider" error.
I have given all the files under conf 777.
Any ideas what's wrong?
Comment: Could you try the commandline svn client? The errors from the commandline client are far more "googleable". Example:

    svn checkout http://full.path.to/your/svn/repository dir
Answer: I commented out
authz-db

in svnserve.conf. Everything OK now.


Value cannot be null, parameter name key

Question: Anyone have a way to solve this sql error when trying to automate schedule a custom filtered processing screen in acumatica?
Value Cannot be null, parameter name key.
Below is the stack trace. My ID field does have IsKey = true in the DAC and is a Primary Key in the sql script
12/20/2022 11:09:19 AM Error:
Value cannot be null.
Parameter name: key

   at System.ThrowHelper.ThrowArgumentNullException(ExceptionArgument argument)
   at System.Collections.Generic.Dictionary`2.FindEntry(TKey key)
   at PX.Data.PXViewCollection.TryGetOrCreateValue(String key, PXView& value)
   at PX.Data.PXViewCollection.get_Item(String key)
   at PX.SM.AUScheduleMaint.OnScreenIdChanged(PXCache sender, AUSchedule schedule)
   at PX.Data.PXCache.OnRowInserted(Object item, Object pending, Boolean externalCall)
   at PX.Data.PXCache`1.Insert(Object data, Boolean bypassinterceptor)
   at PX.Data.PXCache`1.Insert(Object data)
   at PX.Data.PXSelectBase`1.Insert(Table item)
   at PX.Data.PXFilteredProcessing`2._ScheduleAdd_(PXAdapter adapter)
   at PX.Data.PXAction`1.RunHandler(PXAdapter adapter)
   at PX.Data.PXAction`1.d__28.MoveNext()
   at PX.Data.PXAction`1.d__28.MoveNext()
   at PX.Data.PXAction`1.d__28.MoveNext()
   at PX.Data.PXAction`1.d__28.MoveNext()
   at PX.Web.UI.PXBaseDataSource.tryExecutePendingCommand(String viewName, String[] sortcolumns, Boolean[] descendings, Object[] searches, Object[] parameters, PXFilterRow[] filters, DataSourceSelectArguments arguments, Boolean& closeWindowRequired, Int32& adapterStartRow, Int32& adapterTotalRows) in C:\Users\svc-builder\AppData\Local\Temp\~PX.Web..1\PX.Web.UI.dll.il:line 110930
   at PX.Web.UI.PXBaseDataSource.ExecuteSelect(String viewName, DataSourceSelectArguments arguments, PXDSSelectArguments pxarguments) in C:\Users\svc-builder\AppData\Local\Temp\~PX.Web..1\PX.Web.UI.dll.il:line 108573

My ID field does have IsKey = true in the DAC and is a Primary Key in the sql script
enter image description here
Filter DAC:
public class NGZoomProcessingFilter : IBqlTable
{
    #region OperationID

    [PXInt(IsKey = true)]
    [PXUIField(DisplayName = "Operation ID")]
    [OperationIDEntityType]
    public virtual int? OperationID { get; set; }

    public abstract class operationID :
PX.Data.BQL.BqlInt.Field<operationID>
    {
    }

    #endregion

    #region OverrideLastRunDate

    [PXDate()]
    [PXUIField(DisplayName = "Override Last Run")]
    public virtual DateTime? OverrideLastRunDate { get; set; }

    public abstract class overrideLastRunDate :
PX.Data.BQL.BqlDateTime.Field<overrideLastRunDate>
    {
    }

    #endregion

Main DAC:
{
[Serializable]
[PXCacheName("Zoom Processing Routine")]
public class NGZoomProcessingRoutine : IBqlTable
{
    public class PK :
PrimaryKeyOf<NGZoomProcessingRoutine>.By<operationID>
    {
        public static NGZoomProcessingRoutine Find(
            PXGraph graph, int? operationID)
            => FindBy(graph, operationID);
    }

    #region Selected

    [PXBool]
    [PXUnboundDefault(false)]
    [PXUIField(DisplayName = "Selected")]
    public virtual bool? Selected { get; set; }

    public abstract class selected : BqlBool.Field<selected>
    {
    }

    #endregion

    #region OperationID

    [PXDBInt(IsKey = true)]
    [PXUIField(DisplayName = "Operation ID")]
    [OperationIDEntityType]
    public virtual int? OperationID { get; set; }

    public abstract class operationID :
PX.Data.BQL.BqlInt.Field<operationID>
    {
    }

    #endregion

    #region LastRun

    [PXDBDate()]
    [PXUIField(DisplayName = "Last Run")]
    public virtual DateTime? LastRun { get; set; }

    public abstract class lastRun :
PX.Data.BQL.BqlDateTime.Field<lastRun>
    {
    }

    #endregion

Graph:
{
//PrepareDataScreen
public class NGZoomProcessing : PXGraph<NGZoomProcessing>
{
    public PXCancel<NGZoomProcessingFilter> Cancel;

    public PXFilter<NGZoomProcessingFilter>
Filter;
    public PXFilteredProcessing<NGZoomProcessingRoutine,
NGZoomProcessingFilter> ProcessingRoutine;

    public PXSetup<NGZoomProcessingSettings> Settings;

    public SelectFrom<NGPgtAIntroWebinarParticipant>.View
Participants;

    public SelectFrom<NGPgtAIntroWebinarInstance>.View Webinars;

    protected void _(Events.RowSelected<NGZoomProcessingFilter>
e)
    {
        if (e.Row is null) return;
        DateTime? lastRunDate = null;
        if (e.Row.OverrideLastRunDate is not null)
        {
            lastRunDate = e.Row.OverrideLastRunDate;
        }

        ProcessingRoutine.SetProcessDelegate((list) =>
SyncWebinars(list, lastRunDate));
    }

Answer: I took a look at this, and its because you have IsKey=true on your filter DAC, remove it and your problem will go away


Enviar id em um campo hidden ao clicar em um item do autocomplete.js

Question: Preciso que seja enviado o id do cliente para um campo hidden ao clicar no nome dele que é trazido pelo autocomplete do jquery.
O autocomplete já esta funcionando ok.. o que eu preciso mesmo é que ao clicar seja enviado o ID para o campo hidden.

html

<form class="form-horizontal" action="cadastroAdm.php" method="post" name="clientForm">

                  Nome do cliente
                  <input type="text" name="clienteNome" id="clientes"  class="form-control" placeholder="Nome do cliente">

                  <input type="hidden" name="clienteId" id="clienteId" >
      </form>

jquery

$(document).ready(function() {
// Captura o retorno do retornaCliente.php
    $.getJSON('php/retornar_cliente.php', function(data){
    var dados = [];
    // Armazena na array capturando somente o nome do EC
    $(data).each(function(key, value) {
        dados.push(value.clienteNome);
    });
    // Chamo o Auto complete do JQuery ui setando o id do input, array com os dados e o mínimo de caracteres para disparar o AutoComplete
    $('#clientes').autocomplete({ source: dados, minLength: 3});
    });
});// JavaScript Document

retornar_cliente.php

<?php
$hostname = "";
$user = "";
$pass = "";
$basedados = "";
$pdo = new PDO("mysql:host=localhost; dbname=adv; charset=utf8;",'root','');
$dados = $pdo->prepare("SELECT clienteNome, clienteId FROM cliente ORDER BY clienteNome");
$dados->execute();
echo json_encode($dados->fetchAll(PDO::FETCH_ASSOC));
?>

Answer: Utilize a função select, ela é chamada toda vez que um item do menu é selecionado.
$('#clientes').autocomplete({
  select: function(event, ui) {
    $('#clienteId').val(ui.item.id);
    console.log('Objeto selecionado: ' + ui.item);
  }
  source: dados,
  minLength: 3
});

Comment: desta forma ele envia o nome para o input.. mas eu preciso do ID daquele nome
Comment: Coloquei errado, basta trocar pela propriedade que desejar. O item é o seu elemento. Veja a resposta editada.
Comment: troquei mas nao aconteceu nada :|
Comment: ta certo a minha função .each?
Comment: no  console só aparece "undefined"
Comment: Tente ver o que tem no `ui` apenas. E navegue entre as propriedades. Por padrão o `item` irá trazer o `objeto` selecionado da lista que você adicionou no `source`.


How to put collection name in mongoose model

Question: mY model,
<code>       var CategorySchema = new Schema({
      categoryname: {
        type: String
      },
     topictitle: {
        type: String
      },
       topicdescription: {
        type: String
      },
      tag: {
        type: String
      },
      topicid: {
        type: Schema.ObjectId
      },
      user: {
        type: Schema.ObjectId,
        ref: 'User'
      }
   });
    mongoose.model('topics', CategorySchema);
</code>
Here topics is the name of my model but where can i keep my collection name?Can anyone suggest me help.
Answer: In the below model definition

mongoose.model('topics', CategorySchema);

<code>var topics = mongoose.model('topics', CategorySchema,'topics' );
var tags = mongoose.model('tags', TagSchema, 'topics');
</code>
'topics' (last parameter) is the collection name & CategorySchema is the structure of a particular document
Check Mongoose documentation
Comment: ok,how can i call the model i.e where can i keep my model name
Comment: i have 5 models but only 1 collection,in that case i cant keep all name as same ,since it throws error ,collection is already registered
Comment: finally, the collection name and model name are same?
Comment: i have 2 models 1.tags 2.topics but both should go to same collection i.e topics
Comment: In this case my 2 models have like this  mongoose.model('topics', CategorySchema); ---for tags  and  mongoose.model('topics', CategorySchema);----for topics but if i run my code ,it shows error 'schema topics already registered same cannot be done twice'.So how to solve this.
Comment: Thank you so much,it helped me.


Principal part of Laurent series when there's multiple singularities

Question: I'm taking a complex variable class and I've recently been introduced to the Laurent series as
$$f(z)=\sum_{-\infty}^{\infty}a_n(z-z_0)^n$$
where $z_0$ is the singularity point and the expression holds for $z \in D^*= \{ z\in \mathbb{C} : |z|<r \} - \{z_0 \} $.
However, further in the subject, I've come across the following theorem:
Given $f(z)=1/Q(z)$ with $Q(z)$ a polinomial of roots $\alpha_1,...,\alpha_r$, then you can rewrite $f$ as the sum of polinomials in $1/(z-\alpha_i)$
Now, the proof starts by considering the principal parts $P_1,...,P_r$ of the function $f$ in each singularity $\alpha_i$.
My problem is that I don't fully understand what it means for a function to have different principal parts for different singularities. As far as I was concerned, the Laurent series was only developed for a single singularity.
I also fail to understand the meaning behind defining a new function as the original one minus all the principal parts, i get that this has to do with "removing singularities" but I can't see why it works (mainly because I don't really understand the mathematical expression for the Laurent series of a function with multiple singularities).
Just to make sure, it's not the theorem itself I'm having trouble with but more with the fact that I don't understand the Laurent series for a function with more than one singularity.
I'd appreciate if someone could help me with this issue.
Thanks in advance and sorry for my poor English.
Answer: Let's recap the proof in bite-sized bits. Feel free to comment on the parts that are unclear.
(1) At each isolated singularity $a_k$,  your function $f$  has a Laurent expansion $f(z)=\sum_{j} c_j (z- a_k)^k$ that converges near  that point.
(2) Each  singularity is a pole (of some finite order $m_k\geq 1$).
(3) We can toss out the terms with positive powers to create a rational function $R_k(z)= \sum_{j=1}^{m_k} c_j (z- a_k)^{-j}$ that decays to zero as $z\to  \infty$. This is called the principal part of the singularity at that pole.
(4) Because  your function $f(z)$ decays at infinity and has only finitely many poles, $g(z)=f(z)-\sum_k R_k(z)$  also decays at infinity and by construction has only removable singularities.
(5) Thus $g(z)$ is entire and bounded  hence constant, and that constant can be evaluated by letting $z$ tend to infinity. Thus $g(z)$ is identically zero by Liouville's Theorem.
Comment: Thank you so much, it's way more clear this way :)


Drupal 8 variable_get

Question: I have some code in Drupal 7 what are using variable_get. Now I would like to write the code in Drupal 8. So I was reading this but its didn't help me a lot.
How to write this code in Drupal 8 from code in Drupal 7?
$types = array_values(variable_get('test_content_types', array()));

or this
'#default_value' => variable_get('test_content_types', array()),

Some suggestion.
Answer: In Drupal 7
 $data =  variable_get('test_content_types');

In Drupal 8
 $data = \Drupal::state()->get('test_content_types');

For more information about about "get", "set", "delete" visit - Step 5: How to upgrade D7 variables to D8's state system.
Comment: Be aware that in D8 there is a difference between state and config. As noted on https://www.drupal.org/developing/api/8/configuration: "Configuration is a place to store information that you would want to synchronize from development to production. This information is often created during site building and is not typically generated by regular users during normal site operation.

You should use the State API, not configuration, for storing local variables that shouldn't travel between instances. Use state for hidden system values, and if you never want to deploy it between environments."
Comment: Thank you @darol100 .. The link is nice.. Now I understend. So I can write  $data = \Drupal::state()->get('test_content_types', array());
Answer: The accepted answer is half the answer.  As marcvangend notes, there are two options in Drupal 8 for what used to be stored in the variables table and was stored and retrieved with variable_set() and variable_get().  The first, documented in darol100's answer, is the State API.
The second is the Configuration API and should be used in most cases where you have a configuration form.  It requires at minimum in your module a configuration installation file, for example config/install/example.settings.yml.  For a single piece of configuration (with multiple potential values), that file could just contain for example:

test_content_types:
  - article

And then use the value with:
$types = \Drupal::config('example.settings')->get('test_content_types');

Or change the stored values with:
\Drupal::service('config.factory')
  ->getEditable('example.settings')
  ->set('test_content_types', ['article', 'page'])
  ->save();

See also the the Drupal 8 documentation for D7 to D8 configuration upgrades and using configuration in modules.
Comment: For me, this is the correct answer to the question. I'm currently making the transition from Drupal 7 and it helped me a lot.

Drupal 8 variable_get


Por que é obrigatório implementar "public static void main (String [] args)"?

Question: Por que é obrigatório implementar esse método em uma aplicação Java?
Comment: Possível duplicata de [O que significa public static void main(String\[\] args)?](http://pt.stackoverflow.com/questions/93048/o-que-significa-public-static-void-mainstring-args)
Comment: Basta uma leitura nas duas e dá para ver que o assunto é o mesmo, mas a pergunta não é a mesma, portando não é duplicata. Não podemos fechar perguntas só porque o assunto é o mesmo, isso impediria a maioria das perguntas já feitas. Na verdade olhando as respostas que tem lá não respondem o que foi perguntado aqui, então não faz sentido fechar essa.
Comment: Não responde sua pergunta por completo, mas pode te ajudar a entender mais sobre este ponto de entrada: http://pt.stackoverflow.com/a/93051/41056
Comment: Esse inicio do Java Significa.
O Método que deve ser iniciado primeiro é publico, estático, não retorna nada é o usuário pode passar argumentos como string "Conjunto de caracteres"
Answer: É obrigatório porque toda aplicação precisa de um ponto de entrada. Normalmente o sistema operacional precisa saber onde começa o código, no Java na verdade é o ambiente operacional dele, é o JRE que vai iniciar a aplicação e precisa saber o que chamar primeiro. convencionou-se que seria esse método chamado main(), já que outras linguagens usavam algo assim.
Na verdade também precisa especificar qual classe será a principal já que o método main() pode existir em outras classes.
O corpo pode ser tão simples quanto apenas chamar um outro método. Não vejo utilidade nisso, a não ser para algum fim muito específico, as outras pessoas faem sem saber porque.
Nem sempre é obrigatório
Existem algumas situações onde ele não é obrigatório. É o caso de aplicações web que já iniciam por algum outro lugar do framework usado e depois vão chamando o que você programou. Na prática há um main(), mas não no seu código.
Também é possível funcionar com apenas um método estático dentro de uma classe considerada principal. Também não vejo vantagem geral nisso, mas é possível segundo uma resposta no SO.
class JavaAppWithoutMain {
    static {
        System.out.println("Hello World!");
    }
}

Coloquei no GitHub para referência futura.
Assinatura
Na assinatura do método foi convencionado o uso de String[] args para receber argumentos de linha de comando - como podem ser vários e pode conter qualquer tipo de informação o ideal seria um array de string. Também se optou por retornar nada para o sistema operacional, ao contrário de outras linguagens que o fazem. Você pode ignorar essa variável.
Ao contrário de outras linguagens Java preferiu não dar opções e essa é a única assinatura possível. A filosofia da linguagem é simplificar, ainda que seja discutível se isso é uma simplificação de fato.
Há mais detalhes sobre cada componente em O que significa public static void main(String[] args)?.
Comment: Olha a resposta está excelente, só que fiquei confuso se o AP quer saber do `main` apenas ou também quer saber dos argumentos (apesar dele não ter citado isto). Todavia já deixo o +1
Comment: Ótima resposta, mas qual a finalidade de passar o "String[] args" como parâmetro ?
Comment: @JoseVieiraNeto a finalidade é que "args" é um array de string que contém os parametros passados no momento da execucao. Veja exemplo: http://www.devmedia.com.br/entendendo-o-parametro-string-args-em-java/29245
Answer: Geralmente, em qualquer linguagens de programação, esse parâmetro representa os dados de entradas que serão passados para seu programa.
Eu não possuo muito entendimento sobre Java, embora já tenha testado isso, e sei como funciona.
Se você por exemplo tem uma classe chamada Hello que tem esse String args[] como parâmetros, ao você executar o comando java Hello world
O resultado dessa String args[] será ["Hello", "world"].
Eu não sei se em todas as linguagens são assim, mas em todas que eu trabalhei até hoje (Python, PHP e afins), o primeiro argumento que se trata do nome do programa (no meu exemplo é "Hello") sempre está presente.
Isso é muito útil para você passar argumentos para sua aplicação.
Answer: Basicamente esse método significa que na você está tornando a classe que você está implementando como principal.
É ele que faz a execução de todo o código que você construir ou chama-ló.
Comment: @CypherPotato, neste caso não é nem pro compilador, mas sim pra hora da execução que você precisa informar qual será a classe a ser executada. O compilador vive bem sem esse método em nenhuma classe
Comment: O que seria uma classe principal? Acredito que está a se referir ao método de entrada apenas. A classe não desempenha papel pro compilador, e sim o método de entrada.


Remove access to drive "Properties" in My Computer

Question: I'm attempting to lock down a Windows 7 build but I've noticed that users (In this case, students) can highlight a drive and get to the properties menu. I'd like to disable this if possible.
I normally use the following GPO:

User Configuration\Administrative Templates\Windows Components\Windows
Explorer\Remove Windows Explorer's default context menu

Which also disables the "Properties" button, but occasionally customers ask for this to be left enabled. So, is there a way to do both?
Answer: Why bother with hiding things? I don't feel like hiding things, typically, accomplishes much of anything useful and usually creates "make work".
Make sure that the NTFS and/or share permissions on the shared folder are such that the student users can't actually make any changes to permissions and let them look at the "Properties" sheets all they want.
Comment: I don't *disagree*, and this question was really more out of curiosity as I couldn't find anything else on the net. But, in my experience, kids will click and play with anything they can find - so it's in my interest to provide the customer with a solution that contains minimal fuss!


Delphi + Firemonkey: parent dinâmico em componente criado em tempo de execução

Question: Tenho um TForm que permite que o usuário do sistema crie componentes em tempo de execução (TButton, TRadioButton, TLabel, TPanel, entre outros).
Essa funcionalidade está funcionando, porém agora surgiu a necessidade de que o usuário crie esses componentes levando em consideração um outro componente previamente selecionado no TForm, ou seja, ele pode criar um TPanel, selecionar ele, e sem seguida criar um botão dentro deste TPanel.
Até agora eu usava a propriedade Parent do Form principal e definia isso em tempo design usando o mesmo, mas de forma dinâmica não estou conseguindo fazer. Já tentei usando o Focused.GetObject que pega o objeto selecionado, mas obviamente ele pega sempre o TButton que eu cliquei para criar o componente e não o componente que estava em foco anterior.
Tentei usando o FindComponent pelo nome do componente anterior mas também não consegui.
Tela da Aplicação:
Answer: Existem algumas formas de lidar com essa questão. Vou explicar como eu fiz a última vez que precisei de algo similar.
Primeiro você vai precisar de uma variável que guardará o valor do último, vamos chamar, container clicado, que no seu caso ao que parece pode ser um TPanel. Quando a pessoa adicionar um component ao form, você vai ver qual o último TPanel que foi clicado, e se utilizar disso para definir a propriedade Parent do component adicionado.
A lógica seria essa. Recomendo também, afim de facilitar o entendimento do usuário, você pintar as bordas do último TPanel clicado, de azul por exemplo, para que o usuário saiba qual está selecionado. Se eu não me engano no Firemonkey o TPanel não dispõe de bordas, mas o TRectangle possuí. Se você adicionar um dentro do TPanel com a proprieade Align setada para Client dentro nele, você pode pintar as bordas.
Vamos realizar um exemplo prático:
type
  TfrmExemplo = class(TForm)
    Panel1: TPanel;
    Button1: TButton;
    procedure Panel1Click(Sender: TObject);
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    ObjetoSelecionado: TFmxObject;
  end;

Repare que no form eu tenho declarado em public uma variável ObjetoSelecionado que como eu havia dito, ficará responsável por armazenar o último painel selecionado pelo usuário. Vejamos agora o conteúdo da procedure Panel1Click:
procedure TfrmExemplo.Panel1Click(Sender: TObject);
begin
  ObjetoSelecionado := TFmxObject(Panel1);
end;

Após isso temos o último painel clicado pelo usuário, e como eu disse nessa mesma procedure você poderia pintar as bordas para ficar mais claro. Agora vamos olhar o conteúdo da procedure Button1Click:
procedure TfrmExemplo.Button1Click(Sender: TObject);
var
  btnAux: TButton;
begin
  btnAux := TButton.Create(ObjetoSelecionado);
  btnAux.Parent := ObjetoSelecionado;
end;

Ao realizar essa ação, você criará um botão dentro do painel previamente selecionado, resolvendo assim a sua questão.
Comment: Sobre pintar as bordas, sim, você tem razão, no meu caso, eu coloco um tselector sobre ele e ele assume as propriedades do mesmo, podendo redimensionar da forma que eu desejar, isso já esta ok. Sobre criar a variavel para armazenar, sim, também tem razão, já até fiz isso, porém, minha duvida é esta mesmo, como usar o nome do componente clicado anteriormente e transforma-lo em FMObject para que eu possa usa-lo como Parent do outro?
Comment: Coloquei uma imagem na pergunta original, acima, de uma pequena parte do meu software, exemplificando como esta agora. Eu já adiciono os componentes, pego as propriedades, etc. Só preciso mesmo inserir um componente dentro do outro que já esta selecionado.
Comment: Modifiquei a resposta colocando um exemplo mais prático da lógica proposta. Da uma olhada por favor e vê se te atende.
Comment: Legal, antes de mais nada agradeço as formatações e melhorias na pergunta e resposta, vou passar para o projeto suas dicas e volto para pontuar sua resposta. Obrigado.
Comment: Resposta precisa e perfeita, pensei em muita coisa mas a resposta era muito simples. Agradeço pelo tempo que desprendeu para ajudar;
Comment: Maravilha, fico feliz que tenha lhe ajudado. Boa sorte!
Answer: Somente para quem estiver com o mesmo problema, a solução é simples, da forma que o Pedro explicou acima também funciona, mas, para mim, o exemplo a seguir funcionou mais adequadamente à minha necessidade.
ComponenteCriadoRuntime.Parent := TFmxObject(FindComponent(edtName.Text));

Onde ComponenteCriadoRuntime é do tipo TControl e instancio nele qualquer classe que eu desejar. edtName é um componente do tipo TEditque contém a propriedade Name do elemento que esta selecionado em meu form usando a resposta do Pedro acima.
Assim funciona perfeitamente.


global variables not parsing as parameters

Question: I am having troubles with global variables not parsing when passed as parameters.
{exp:channel:entries
    disable="categories|category_fields|member_data|pagination|trackbacks"
    dynamic="no"
    entry_id="{structure:child_ids_for:21}"
}

(0.012500 / 3.36MB) Tag: {exp:channel:entries disable="categories|category_fields|member_data|pagination|trackbacks" dynamic="no" entry_id="{structure:child_ids_for:21}" }
The same result is produced with and without parse="inward"
However this works fine and grabs the data I need
{exp:channel:entries
    disable="categories|category_fields|member_data|pagination|trackbacks"
    dynamic="no"
    entry_id="{exp:query sql='SELECT exp_structure.entry_id,
            exp_structure.parent_id,
            exp_structure.lft
            FROM exp_structure
            WHERE parent_id = 21
            ORDER BY exp_structure.lft ASC'}{entry_id}|{/exp:query}"
    parse="inward"
}

But, then if I add in a global variable author_id="{logged_in_member_id}" it fails to work, if I hard code that value as 1 then it functions.
Any thoughts as to what could be happening here?
Answer: You can avoid the overhead of embeds by using Stash for this sort of thing. It has the insanely useful ability to let you explicitly state your preferred parse order for different chunks of code. In this case the first thing you'd do is store the two variables via {exp:stash:set}, then you can retrieve them in the second chunk of code via {exp:stash:get}. The magic bit is the parse priority tag; because the first item has a priority of 10 it will be executed first, which ensures the vars are available for use as channel entries parameters in the second {exp:stash:parse} tag.
{exp:stash:parse priority="10" process="end"}
    {exp:stash:set}
        {stash:structure_ids}{structure:sibling_ids}{/stash:structure_ids}
        {stash:logged_in_member}{logged_in_member_id}{/stash:logged_in_member}
    {/exp:stash:set}
{/exp:stash:parse}

{exp:stash:parse priority="20" process="end"}
    {exp:channel:entries
        disable="categories|category_fields|member_data|pagination|trackbacks"
        dynamic="no"
        entry_id="{exp:stash:get name='structure_ids'}"
        author_id="{exp:stash:get name='logged_in_member'}"
        parse="inward"
    }
    ...
    {/exp:channel:entries}
{/exp:stash:parse}

Answer: I can't speak for Structure's global variables, but {logged_in_member_id} is a late-parsed global variable, meaning you can't use it in a module tag parameter. I can only only assume that the same goes for the Structure variables.
You can use the CURRENT_USER constant in the author_id parameter though (docs).
Unfortunately, the solution for your {structure:child_ids_for:21} issue is to pass that as an embed variable, and put your Channel Entries loop in an embed. (I say unfortunately because embeds do incur some overhead.)
One note: parse="inward" has no effect on module tag pairs - they always parse inward. It only affects plugin tag pairs.
Comment: Thanks Derek, trying to avoid embeds but that appears to the be the solution here. Thank you for your input, much appreciated.


Creating jupyter notebook with Python code

Question: I am creating a jupyter notebook programatically with Python. Using the nbformat library.
Once I create the file:
fname = f'{filename}.ipynb'

with open(fname, 'w') as notebook:
   nbf.write(nb, notebook)

I open the file with Jupyter Lab and get the following error in the terminal console:
Fatal Python error: init_import_size: Failed to import the site module
Python runtime state: initialized
Traceback (most recent call last):
  File "/Users/sota/anaconda3/lib/python3.8/site.py", line 580, in <module>
    main()
  File "/Users/sota/anaconda3/lib/python3.8/site.py", line 567, in main
    known_paths = addsitepackages(known_paths)
  File "/Users/sota/anaconda3/lib/python3.8/site.py", line 350, in addsitepackages
    addsitedir(sitedir, known_paths)
  File "/Users/sota/anaconda3/lib/python3.8/site.py", line 208, in addsitedir
    addpackage(sitedir, name, known_paths)
  File "/Users/sota/anaconda3/lib/python3.8/site.py", line 169, in addpackage
    exec(line)
  File "<string>", line 1, in <module>
  File "/Users/sota/anaconda3/lib/python3.8/importlib/util.py", line 14, in <module>
    from contextlib import contextmanager
  File "/Users/sota/anaconda3/lib/python3.8/contextlib.py", line 5, in <module>
    from collections import deque
  File "/Users/sota/anaconda3/lib/python3.8/collections/__init__.py", line 24, in <module>
    import heapq as _heapq
  File "/Users/sota/anaconda3/lib/python3.8/heapq.py", line 581, in <module>
    from _heapq import *
KeyboardInterrupt

I have been researching a lot, but I don't get to find the error... some guidance on why this is happening?
PD: the only solution I've found so far is openinig the notebook with vscode and somehow, the notebook gets fixed.
Comment: Try to specify version in according a documentation:

https://nbformat.readthedocs.io/en/latest/api.html
Comment: You need to use ```notebook``` at ```nbf.write()```
Answer: It was actually a very newbie error. I had written the names of the folders with accented characters. Therefore, Jupyter Lab couldn't recognize correctly the files.


PHP 7 - Usuário logado(AD) e nome da máquina

Question: Já pesquisei no Stackoverflow En e PT, google e só encontrei coisas como getenv(), $_SERVER['user'],shell_exec() ou qualquer coisa que me retorne dados do servidor Web, nada do usuário logado no sistema.
Outra solução, nada viável, foi utilizar o ActiveX, que só funcionaria no IE, sem chance.
A solução até o momento que eu encontrei foi criar um Webservice em .Net, que só me retorna o usuário local, nada muito difícil, mas chato por ter q utilizar outra app alem da default em php, em outro servidor.
Quanto ao nome da máquina, eu já tenho o ip local via $_SERVER, mas preciso do name da máquina local mesmo rodando o dig com shell_exec não rola.
Então, das 2 perguntas, buscar o usuário(ad) pelo PHP imagino que realmente não tenho saida, mas e quanto a buscar o nome da máquina local?
Comment: Você quer obter o nome da máquina do cliente no lado do servidor?
Comment: N entendi.. a aplicação roda no servidor.
Answer: Tente fazer executando o seguinte comando.
<?php
$hostname = gethostbyaddr($_SERVER['REMOTE_ADDR']);
echo $hostname;
?>

Testando ele aquifuncionou perfeitamente, pelo entendi o que entendi o que tu quer
Fonte
Comment: ah... se vc está rodando o servidor web local, provavelmente vai retornar tudo, até o usuário da rede rodando o shell_exec('echo %username%'), mas como o servidor é a parte, provavelmente deve ser por isso que não rola.
Comment: Se você colocar o ip dentro do gethostbyaddr? O que rola?
Comment: echo(gethostbyaddr($_SERVER['REMOTE_ADDR']));   --me.u.i.p
echo(gethostbyname($_SERVER['REMOTE_ADDR'])); --me.u.i.p
Comment: gethostbyaddr me retorna o IP, se eu utilizar gethostbyname tb..
Comment: Tente com echo getenv("USERNAME");


Parsing selected value in drop down to next page

Question: I'm trying to parse the current selected value of a drop-down to the next page via a http request - so the value selected is parsed via the url to the next page.
The form drop-down looks like this:
<form name="sortby">
    <select id="order_by" name="order_by" onchange="sortBy()">
        <option<?php if(isset($_GET['order_by']) && $_GET['order_by'] == 'choose') echo ' selected="selected"'; ?> value="choose">Sort By</option>
        <option<?php if(isset($_GET['order_by']) && $_GET['order_by'] == 'OVERALL_VALUE') echo ' selected="selected"'; ?> value="OVERALL_VALUE">Most Popular</option>
        <option<?php if(isset($_GET['order_by']) && $_GET['order_by'] == 'PRICE') echo ' selected="selected"'; ?> value="PRICE">Price (low to high)</option>
        <option<?php if(isset($_GET['order_by']) && $_GET['order_by'] == 'PRICE_REVERSE') echo ' selected="selected"'; ?> value="PRICE_REVERSE">Price (high to low)</option>
        <option<?php if(isset($_GET['order_by']) && $_GET['order_by'] == 'QUALITY') echo ' selected="selected"'; ?> value="QUALITY">Rating</option>
    </select>
</form>

Here is where I want to post the selected value to the next page - via button:
echo " <button>Next >></button>";

So where it says &order_by=" . $_GET['order_by'] . is where I want to parse the current selected value to the next page. But I don't get the value in the url with this Get method - what am I doing wrong ?
Comment: It looks like you're trying to pass variables to construct an `SQL` statement through the URL ?!?!
Comment: it seems that you need to use Javascript, if you want this to change without you using forms .. However if you want to use forms, then use hidden inputs for your data.
Answer: use http_build_query() to clean that up. Use it like this:
$data = array('foo'=>'bar',
              'baz'=>'boom',
              'cow'=>'milk',
              'php'=>'hypertext processor');

echo http_build_query($data) . "\n";
//OUTPUT: foo=bar&baz=boom&cow=milk&php=hypertext+processor

echo http_build_query($data, '', '&');
//OUTPUT: foo=bar&baz=boom&cow=milk&php=hypertext+processor

Alternatively, with JS you can do this:
function getCurrentParams() {
    var url = document.URL;
    var url_split = url.split("?");
    var params = url_split[1];
    return params;
}

function urlToObj(url) {
    var obj = {};
    var pairs = url.split('&');
    for (i in pairs) {
        var split = pairs[i].split('=');
        obj[decodeURIComponent(split[0])] = decodeURIComponent(split[1]);
    }
    return obj;
}

function getQuery(e){ // will fire on button click
    var value = $("#order_by").val();
    var params_string = getCurrentParams();
    var get_params_obj = urlToObj(params_string);
    get_params_obj.orderBy= value;
    var params = $.param(get_params_obj);
    alert(params);
    location.href = "http://youbaseurl.com?"+params;
    return false;
}

HTML:
<button onclick="return getQuery(this)"></button>

Comment: Have a hard time understanding how to use your JS example. How do I get  the value retrieved with the JS into the url call in the button ? @CodeGodie
Comment: it does work to the extend that I get alerted the value from the sort by drop down. But it does not go to the url I get fra the Alert. How do I get the function getQuery to actually go to the url created ?
Comment: you have to force a `location.href`. i updated the code
Answer: just put a submit button instead of  tag and click on it . it will send the selected value via get method. and make sure u define action attribute in form element
        <form action="">
        <select>
       .....................
       </select>
        <input type="submit" name="submit">
        </form>

Comment: This will not work, because he needs all the other data in his query. To make it work without JS, he would need to use many hidden inputs.


How to generate a Commerce order from a CSV?

Question: I'm using Drupal 7 with commerce. Is there a way to generate an order from a csv or similar? the idea is that users could upload a csv (sku and quantity for now) with the items they want and the system generate an order with that.
i'm trying with feeds and the entity processor but i can't import the line items and create de order in the some process (they have to be related with an order). If this is the way, it's not clear to me how to do that.
Comment: Good question! I don't think such a module exists to do that. Doing it would not be hard though and it maybe a good idea for a contib module. Use feeds for the csv processing.
Comment: Please, be more concrete. Paste your csv file structure and example. I think it should be possible, but first we need to take a look at your data structure.
Comment: Ok, just the basic info for now: product id (sku probably) and quantity.
Comment: I should try to implement this solution. Existing modules does not provide this functionality. At least you need: hook_feeds_before_import and create new order manually to retrieve its id. Use this id and current user (as owner)  during import (mb some hooks can help).
Comment: This might actually be an interesting feature request for the [Commerce Feeds](https://www.drupal.org/project/commerce_feeds) module that allows you to import products and product displays.
Answer: Im not sure how to make csv directly to order, but this should work:

create a node type, called "csv order"
use Feeds module to fetch the data from csv to this node type
install module hook_post_action
write a custom module, which after saving node "csv order" would take data from this node, and create commerce order with line items
remove the csv order node if neccesary


Property of homology

Question: I have this proposition, and I have two questions:
1) Why $H_k=\text{Im} i_*\oplus \ker r_*$ ?
2) Why $j_*: \ker r_*\rightarrow H_k(X,A)$ ?

Edit:
For the second, I try the 1th theorem of isomorphism, and I found that there is an isomorphism between $H_k(X)/\ker j∗$ and $H_k(X,A)$, and I don't know how to appear $\ker r∗$ in the place of $H_k(X)/\ker j∗$.
Answer: The trick to do (1) goes like this. If you have $x \in H_k(X)$, you apply $ir$ to get $ir(x) \in im i_*$. The cool thing is than you can then just check that $x - irx$ is in the kernel of $r$, and so $x = irx + (x - irx)$ is your decomposition. To show it's direct, you take $0 = iy + z$. Then applying $r$, we get $0 = riy = y$, and so the sum is direct. The same idea lets you write things in split short exact sequences as sums.
For (2), using your observation from the first isomorphism theorem you put in the edit:
\begin{align*}
H_k(X,A) &\cong H_k(X)/(\ker j_*) \\
&= (\ker r_* \oplus im i_*)/(\ker j_*) \\
&= (\ker r_* \oplus \ker j_*)/(\ker j_*) \\
&= \ker r_* \end{align*} Note where we used the exactness condition $im i_* = \ker j_*$.
Comment: I dont understand "The same idea lets you write things in split short exact sequences as sums" ? please need your help
Comment: please how to do to obtain this short exacte sequence
Comment: There's a theorem in homological algebra that says a short exact sequence $0 \rightarrow A \rightarrow B \rightarrow C \rightarrow 0$ of abelian groups that has a map $r:B \rightarrow A$ which, when composed with $A \rightarrow B$, gives the identity on $A$ induces a direct sum decomposition of $B$ as $B \cong A \oplus C$. The way that you prove this is similar to the arguments I gave. You could, in fact, directly apply this to obtain the proposition in your question.
Answer: This is an application of a result of homological algebra which is:
If  $0\to N\stackrel{i}{\to} M\stackrel{j}\to P\to 0$ is an exact sequence and $r:M\to N$  such that $r\circ i=id_{N}$ then $\ker r\simeq P$ and $\text{Im}(i)\simeq N$, and $M=\text{Im}(i)\oplus \ker r \simeq N\oplus P$.
Proof:
Because $i$ is injective we have $\text{Im}(i)\simeq N$.
For $\ker r \simeq P$ it suffice to show that $j:\ker r\to P$ is an isomorphism: if $x\in \ker r$ such that $j(x)=0$ then $x\text{Im}(i)$ hence there exists $y\in N$ such that $x=i(y)$, but $y=r(i(y))=r(x)=0$. for the surjectivity, let $z\in P$, there exists $x\in M$ such that $y=j(x)$ set $x'=i(r(x))$, we have $r(x-x')=r(x)-r(i(r(x)))=r(x)-r(x)=0$, hence $x-x'\in \ker r$ and $j(x-x')=j(x)-j(i(r(x)))=j(x)=z$.
For $M=\text{Im}(i)\oplus \ker r$: let $y\in \text{Im}(i)\cap \ker r$ then there exists $x\in N$ such that $y=i(x)$ , sa $0=r(y)=r(i(x))=x$ we have $y=i(x)=i(0)=0$.
Let $y\in M$, and set $x=r(y)$, we have $x=i(r(y))\in \text{Im}(i)$ we have
$r(y-x)=r(y)-r(i(r(y)))=r(y)-r(y)=0$, then $z=y-x\in \ker r$, now we get
$yx+z$ with $x\in \text{Im}(i)$ and $z\in \ker r$.
Comment: Merci @Hamou, svp pour quoi on ne peut pas dire directement que $H_k(X)=\text{Im} r_*\oplus \ker r_*$ ?
Comment: Normalement on peut dire n'importe quoi, mais c'est la façon de dire qui compte: c-a-d on peut le dire intuitivement ou d'après un autre résultat bien connue , ou sans dimenstrasion .........
Comment: Est que c'est vrai que $H_k(X)=\text{Im} r_*\oplus \ker r_*$ ou c'est faux ? Merci beaucoup
Comment: yes it is true.
Comment: Ok, c'est une autre méthode et svp toute fonction $f: X\rightarrow Y$ injective verifie $\text{Im}~f=X$ ? merci
Comment: Attention, l'image de $f$ est une partie de $Y$ et non pas de $X$!
Comment: oui et donc pourquoi $\text{im}~i_*=H_k(A)$?
Comment: Si $f:N\to M $ est injective alors $N\simeq \text{Im(f)}$. en effet c'est un isomorphism.
Comment: je pense que ceci est vrai uniquement si $N\subset M$ ?
Comment: Sauf si je dit que $N=\text{Im}~f\oplus \ker f$ comme $f$ est injective $\ker f=\lbrace 0\rbrace$ et donc $N=\text{Im}~f$ qu'on dite vous ?
Comment: $N$ et $M$ deux modules, et $f:N\to M$ une application linéaire injective. $N'=\text{Im}(f)$ est un sous mudule de $M$, alors les deux modules $N$ et $N'$ sont isomoephe. mais il n y a aucune hypothèse que $N$ soit un sous module de $M$. mais on écrit $N\simeq N'$.
Comment: ou est ce que je peux trouver cette propriété je ne la connait pas
Comment: Je suis bete sorry on utilise le premier theorem d'isomorphisme that's all, $N/\ker f \simeq \text{Im}~f $ $f$ est injective donc $\ker f=\lbrace 0\rbrace $
Comment: Mais svp j'ai oublier $i_*$ est injective parce que cette une inclusion ?
Comment: je suis désolé, mais j'ai lu la réponse donné par Zach pouvez vous m'expliquer cette phrase "The same idea lets you write things in split short exact sequences as sums"
Comment: un coup d'oeil: [Suites exactes courtes scindées](http://fr.wikipedia.org/wiki/Suite_exacte)
Comment: Oui mais que veut il dire ? il faut rendre tout les espaces en somme directe ? et la suite exacte courte vient uniquement du fait que $i_*$ est injective ?merci
Comment: rendre l'espace situé au milieux (de la suite) en somme direct. Mais a condition que la suite court soit **exacte et scindée**
Comment: s'il vous plait etes vous sure que $i_*$ est injective prcequ'elle est induite par une inclusion ? merci
Comment: Si $f\circ g=id$ alors $g$ est injective. Dans votre cas vous avez $r_*\circ i_*=id_{H_k(A)}$ donc $i_*$ est injective.
Comment: pouvez vous me dire pourquoi $f\circ g =id $ alors g est injective, je ne vois pas comment faire merci
Comment: Avce cette hypothèse cad $f\circ g=id$, si $g(x)=g(y)$ alors $f(g(x))=f(g(y))$ donc $x=f(g(x))=f(g(y))=y$ i.e $x=y$.
Comment: merci donc le fait que i soit une inclusion n'a rien a avoir avec l'injectivité
Comment: Oui, mais inclusion+retraction= ca marche.
Comment: comment ? s'il vous plait ?
Comment: Si $r$ est une retraction alors $r\circ i=id$ donc $r_*\circ i_*=id$ ansi $i_*$ est injective.
Comment: S'il vous plait, vous pouvez m'aider  ici, http://math.stackexchange.com/questions/913379/question-about-property-of-homology  d'ou viens la somme directe j'ai pas d'idée svp svp
Comment: please svp aidez moi

Property of homology


Como resetar CSS de vários arquivos HTML incluídos por require

Question: Por sugestão desta resposta, estou tentando utilizar o normalize.css pra zerar os estilos entre um require e outro, mas não tem jeito, a CSS do arquivo posterior interfere completamente no layout do arquivo anterior. Isso não altera o resto da página, o problema é apenas entre eles.
Se coloco apenas um arquivo tudo bem, fica perfeito, mas quando incluo outro dá problema entre eles.
O HTML com o PHP:

            <?php
                require "arquivo1.html";
            ?>

           <?php
                if ($var1 == "incluiarq");
                require "arquivo2.html";
            ?>

    </div

O arquivo1.html (o arquivo2 é basicamente igual, mas com as CSS diferentes):
<link rel="stylesheet" href="_css/normalize.css">

    Loren

    .

    Loren ipsumLoren ipsumLoren ipsumLoren ipsumLoren ipsum Loren ipsum

    Loren ipsumLoren ipsumLoren ipsumLoren ipsum

    Loren ipsum, data venia,
    Loren ipsumLoren ipsumLoren ipsum
    Loren ipsumLoren ipsumLoren ipsum

Estes arquivos eram originalmente docs feitos no google drive, e foram convertidos pra HTML pelo próprio google drive, então ele gera este monte de css, mas de forma surpreendente fica perfeito :-) quando incluo apenas um.
Este que postei acima (arquivo1.html) é o arquivo inteiro que estou incluindo, eu retirei todo o cabeçalho e as tags de fechamento pra que não interferisse, e se coloco apenas um tudo bem, mas quando coloco o segundo  dá problema. Alguma ideia?
Comment: remove o css inline das páginas e cria uma arquivo pra cada `style`, na hora de incluir inclua o css referente à cada arquivo
Comment: @ErlonCharles Você diz criar um arquivo CSS com a formatação que vem no arquivo HTML? Tentei isso mas não funcionou, ele continua sobrepondo as CSS's.  Ou vc diz criar um arquivo css só e aplicar em todos de acordo com as classes? O problema, se for isso, é que ele cria atributos diferentes para as classes... Por exemplo .c1 num arquivo é `.c1{
    font-size:14pt;
    font-family:"Times New Roman";
    font-weight:bold}` enquanto no outro é `.c1{
    widows:2;
    orphans:2;
    text-indent:86pt;
    text-align:justify;
    direction:ltr`
Comment: Em tempo: testei utilizando arquivos externos com e sem o normalizecss... Com normalize usei assim no início do arquivo ` `
Comment: Só pra constar, até encontrei uma forma gambiarra pra contornar isso, que foi usando um plugin do google drive pra mesclar todos os arquivos em um só, e depois gerei apenas um arquivo HTML. Daí poderia usar esta CSS pra todos os arquivos individuais (depois de separar de novo o arquivo mesclado), mas quer saber, achei que ia ficar uma bela porcaria, e decidi reescrever  tudo, usando poucas tags, e pouco CSS, afinal, é só um arquivo de texto, não tem sentido usar todo esse CSS e esse HTML doido que o google drive gera.
Answer: Isso possivelmente se da por conta de especifidade do seu arquivo .css sobrescrevendo seletores de tipo. Aconselharia linkar no arquivo .html principal o normalize .css (apenas para reset) e outro .css para gerir responsabilidades de estilo Ex: (main.css) e nesse arquivo fazer um import de dois .css com responsabilidades diferentes de estilização tipo: (doc-1.css e doc-2.css)
Arquivo .html
...

<link rel="stylesheet" type="text/css" href="css/base/normalize.css">
<link rel="stylesheet/less" type="text/css" href="css/main.css">

Arquivo .css...
@import "../doc-1.css";
@import "../doc-2.css";

Comment: @gustavox Apenas um adendo lembre-se que os **.css dos docs** não podem ter as **mesmas classes** se não realmente sempre vai sobrescrecer e o que vai **prevalecer** é a **especifidade do seletor** . Uma saida é definir um prefixo para classe de cada doc. Ex: `.doc-c1, .doc2-c1`...  E injetar isso via javascript. Abs.
Comment: Valeu pela resposta, quando tiver um tempo vou testar e retorno aqui. +1