All the TCP connection b/w DataStax driver to the Cassandra Remain in Active close state . i.e TIME_WAIT state.

Question: The setup:
Web server
Apache Tomcat
RestFull web services
Using DataStax java driver 2.0
Database
-2-node Cassandra 22.214.171.124 cluster
-replicas=1
Problem
After sending set of 1500 request more than three times. I got error at the tomcat log
<code>     com.datastax.driver.core.exceptions.NoHostAvailableException: All host(s) tried for query failed (tried: /10.181.13.239 ([/10.181.13.239] Unexpected exception triggered))
                at com.datastax.driver.core.exceptions.NoHostAvailableException.copy(NoHostAvailableException.java:64)
                at com.datastax.driver.core.ResultSetFuture.extractCauseFromExecutionException(ResultSetFuture.java:214)
                at com.datastax.driver.core.ResultSetFuture.getUninterruptibly(ResultSetFuture.java:169)
                at com.jpmc.es.rtm.storage.impl.EventExtract.main(EventExtract.java:36)
                at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
                at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
                at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
                at java.lang.reflect.Method.invoke(Method.java:601)
                at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
    Caused by: com.datastax.driver.core.exceptions.NoHostAvailableException: All host(s) tried for query failed (tried: /10.181.13.239 ([/10.181.13.239] Unexpected exception triggered))
                at com.datastax.driver.core.RequestHandler.sendRequest(RequestHandler.java:98)
                at com.datastax.driver.core.RequestHandler$1.run(RequestHandler.java:165)
                at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
                at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
</code>
Observation
After this state of tomcat. All the further request attaining the same fate. That is  drivers are not able to send my insert request to cassandra.
After executing net stat command i find that the all the TCP connection b/w web server and the Cassandra are in TIMED_WAIT state.
What could be the reason ? why Datastax driver is not able to take back the connection back to the pool? or why does the Cassandra is engaging all the connection form its client.
Thanks in Advance
Answer: The connection was increasing Due to calling creating multiple session for each request. Now it is working Fine.
<code>         builder = new Cluster.Builder().
                addContactPoints("192.168.114.42");

        builder.withPoolingOptions(new PoolingOptions().setCoreConnectionsPerHost(
                HostDistance.LOCAL, new PoolingOptions().getMaxConnectionsPerHost(HostDistance.LOCAL)));

        cluster = builder
                .withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE)
                .withReconnectionPolicy(new ConstantReconnectionPolicy(100L))
                .build();
        session = cluster.connect("demodb");
</code>
Now Driver is maintain 17-26 number of connection irrespective of number of transaction.


How to create image gallery and integrate it to lightbox2

Question: I have a content type Product with a field Images. There are 4 photos. When i go to the product-node page i want to click on one of the photos (1 of 4) and open a popup/modal window where i would like to see all 4 photos (not only 1, as  Lightbox does). How can i do that?
Answer: You can do this by using Colorbox module.

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

How to use ?


How to get the type of a method member of a class without creating an instance?

Question: Assume we have:
template <typename T>
void foo(std::vector<T> &t) {
    auto var = T();
    std::vector<decltype(var.Get())> array;
}

In the above code, an array is created. The type of this array is whatever the return value of Get() is. We find this value by creating a dummy variable of type T and then infering the return type of Get by using decltype.
This works, however it requires the creation of a dummy variable that serves no purpose.
Instead we could do:
template <typename T>
void foo(std::vector<T> &t) {
    auto var = t[0];
    std::vector<decltype(var.Get())> array;
}

Which doesn't create any dummies, but this will potentially crash, given that we have no guarantee that the array contains at least on element.
Is there a way to infer the type of .Get() without creating a dummy?
Answer: std::vector<decltype(t[0].Get())>

t[0] will not be invoked as decltype is an unevaluated context.
Alternatives:
std::vector<decltype(T().Get())>
std::vector<decltype(std::declval<T&>().Get())>


Can I assume $R$ is a local ring?

Question: I should prove this statement:
Let $R$ be a ring, $M$ be a $R$-module and $P$ a projective $R$-module of finite type. If $x=\sum_i m_i\otimes p_i$ is an element in $M\otimes_R P$ such that $\sum_i m_i\phi(p_i)=0 \quad \forall\phi\in P^*$, then $x=0$.
Well, I've proved it in the case $R$ is a local ring. Can I assume $R$ is a local ring without loss of generality?
Answer: The statement is true For some finitely generated $R$- module $Q$ you have  $P \oplus Q \simeq R^n$. From this deduce:       a)  that there is an injective morphism of $R$-modules $M\otimes P \to M\otimes R^n $ and b) that every linear form on $P$ is the restriction of one on $R^n$. Since your result is true for
$M\otimes R^n $ because of the isomorphism $M\otimes R^n\simeq M^n$, it will also be true for the original $M\otimes P$ by using a) and b).
Your actual question Since the result is true it is impossible to say that it can't be proved by reducing to the case where $R$ a local ring. However in that case $P$ will be free and I suspect that you'll have to do something close to the above. Moreover you'll have to check one or two  little facts to ensure that you can go back and forth between the global case and the local case, in particular that your hypothesis   on linear forms in $P^\ast$ can be localized. So personally, I wouldn't go for the reduction to local rings since the general case is so simple.

Can I assume $R$ is a local ring?


Dimension of irreducible affine variety is same as any open subset

Question: Let $X$ be an irreducible affine variety. Let $U \subset X$ be a nonempty open subset. Show that dim $U=$ dim $X$.
Since $U \subset X$, dim $U \leq$ dim $X$ is immediate. I also know that the result is not true if $X$ is any irreducible topological space, so somehow the properties of an affine variety have to come in. I have tried assuming $U=X$ \ $V(f_1,...,f_k)$ but I don't know how to continue on.
Any help is appreciated!
Comment: What definition of dimension are you using?  Max length of chains of subvarieties?  Transcendence degree of function field?
Comment: Max length of chain of subvarieties, but I know that the transcendence degree is the same thing
Answer: Let $X=\operatorname{Spec} A$, and pick some nonzero $f\in A$ with $\operatorname{Spec} A_f = D(f) \subset U$.  Then we can lift chains of closed sets to see that $\dim D(f) \leq \dim U
\leq \dim X$.
But as shown here, we have $\dim D(f) = \dim A_f = \dim A = \dim X$.  We can also see this quite quickly by noting that $A$ and $A_f$ have the same fraction fields, and therefore the same transcendence degree over $k$.

Note that this is false for general rings $A$, even if $A$ is assumed to be a noetherian domain.  In fact, any DVR is a counterexample.
Answer: You should note that any nonempty open subset of an irreducible variety (or topological space) is dense : https://en.wikipedia.org/wiki/Hyperconnected_space.
Then you can use the definition of the dimension to conclude.
Comment: This does in no way answer the question because there exist examples of  irreducible topological spaces (even a two-point example!) for which an open subset has dimension smaller than that of the space.
Comment: But isn't the whole question about the correct way to "use the definition of dimension"?  As pointed out in the post, this is false for irreducible spaces in general.
Comment: To utilize the assumption that $X$ is an irreducible affine variety, we could relate the function fields of $U$ and $X$ or - using the "chains of subvarieties" definition - we could note that the first in a chain of subvarieties for $U$ must be special.


Group collection by created_at and file relation

Question: I have this relation:
Each user has gallery and gallery hasMany files.
Two users can have a gallery of the same date.
This is the output JSON response:
User1 {
 galleries: {
  created_at: 23.04.2019.
  files: [
    {
     path: "path/to/file.jpg"
    },
    {
     path: "path/to/file2.jpg"
    },
  ]
 }
},
User2 {
 galleries: {
  created_at: 23.04.2019.
  files: [
    {
     path: "path/to/file3.jpg"
    },
    {
     path: "path/to/file4.jpg"
    },
  ]
 }
}

I need somehow to group galleries by created_at value, but to keep all files in same JSON response, for the groupped galleries object. Like this:
Users {
 galleries: {
  created_at: 23.04.2019.
  files: [
    {
     path: "path/to/file.jpg"
    },
    {
     path: "path/to/file2.jpg"
    },
    {
     path: "path/to/file3.jpg"
    },
    {
     path: "path/to/file4.jpg"
    },
  ]
 }
},

I tried to use ->groupBy('galleries.created_at'), but that I get this - first file from the first gallery, first file from the second gallery
Users {
 galleries: {
  created_at: 23.04.2019.
  files: [
    {
     path: "path/to/file.jpg"
    },
    {
     path: "path/to/file3.jpg"
    },
  ]
 }
},

Comment: Can you show, how do you build your Collection?
Comment: I use fractal transformers with

`return $this->collection($user->galleries, new GalleryTransformer());` if you mean that
Comment: Probably better to look at the package documentation. Might be not pure Laravel question. I can't guess what's inside `GalleryTransformer` :)
Answer: Before passing data into a Fractal Transformer, it's a matter of getting the right data.
 Your desired output looks to be a listing of Files organized by the Gallery date.  It doesn't really have anything to do with Users (unless you plan to later scope the returned data).  That being said, Eloquent relationships won't really help here since we're not dealing with a single model's relationships, and we can just use the Laravel query builder and use the groupBy Collection helper function to organize the results.
It's up to you where to put this method; it could easily go into a controller method, but if you are planning on scoping the results (e.g. to certain Users, or for certain dates as below), you might have it live in the model.
// Gallery.php

public static function filesByGalleryDate($date = null) {
    $query = DB::table('gallery')
        ->leftJoin('files', 'galleries.id', '=', 'files.gallery_id')
        ->select('galleries.created_at', 'files.*')
        ->orderBy('galleries.created_at');

    $result = $date == null
        ? $query->get()
        : $query->where('galleries.created_at', $date)->get();

    return $result->groupBy('created_at')

        // for each date, convert inner stdClasses to arrays
        ->map(function($date) {
            return $date->map(function($file) {
                return (array) $file;
            });
        });
}


Calculating Power for ANOVA for unequal sample size

Question: I want to be able to calculate power for ANOVA with unequal sample sizes. I'm able to calculate one-way ANOVA (does not assume equal sample sizes) & effect size.  Now just need to calculate power.  I notice the pwr.anova.test() seems to assume equal sample size:
pwr.anova.test(k = NULL, n = NULL, f = NULL, sig.level = 0.05, power = NULL)
Arguments:
k Number of groups
n Number of observations (per group).
f Effect size
sig.level Significance level (Type I error probability)
power Power of test (1 minus Type II error probability)
Is there an R code for Anova POWER for unequal sample sizes?
Comment: Asking for code is generally off topic here.  Your post seems to imply that you have already run an ANOVA & now want to calculate power.  That doesn't make sense.  Once a test has been conducted, power plays no role.  This sounds like bad old practices around 'post-hoc power'.  FWIW, the easiest way to do this is to simulate.  Search the site, the topic has been covered many times already.
Comment: As noted above, you shouldn't be conducting post-hoc power analysis. However, if you're planning a study, you can absolutely use the `pwr` package for finding power for a range of pre-established scenarios (unequal vs. equal sample sizes). For the `n` parameter you give the average number of observations in each group, and very importanly, for the parameter `f`, you calculate *correctly* the effect size `f`, which is different if the group sample sizes will be balanced or unbalanced. I explain how to calculate correctly the effect size here: https://stats.stackexchange.com/a/637646/164936 .
Answer: The 'power and sample size' procedures for one-way ANOVAs usually give answers for models in which the number of
replications at each level of the factor is equal. I suppose this is for simplicity and because the most efficient use of
resources (to pay for replications) is usually a 'balanced' design with equal number of replications per level.
However, in some circumstances it is appropriate or necessary
to have unequal numbers of replications for various levels.
Examples: (a) You may be testing three new drugs against a current standard drug and want more replications for the standard drug for better power in ad hoc tests of each new drug against the standard.
(b) Replications at some levels of the factor may be much
more expensive than other levels.
When choosing numbers of replications for an ANOVA, it
is worthwhile to anticipate that one may find that some differences are significant. Then it is a good idea to have sufficient power for useful ad hoc tests.
If you go sufficiently deeply into the formulas for power against different patterns of alternatives, you may be able
to get exact results for power with differing numbers of replications. Perhaps more simply, you can get reasonably
accurate power values by simulation based on unbalanced designs; I show one such simulation below.
Suppose you have an experiment with normal samples with population means $50, 54, 57,$ standard deviations $4, 6, 7$ and sample sizes $20, 15, 15.$ Then we show the R procedure oneway.test, which does not assume equal variances for the levels. You might
have a dataset similar to the fictitious one below.
set.seed(1225)
x1 = rnorm(20, 50, 4)
x2 = rnorm(15, 54, 6)
x3 = rnorm(15, 57, 7)
x = c(x1, x2, x3)
g = rep(1:3, c(20,15,15))
oneway.test(x ~ g)

        One-way analysis of means
        (not assuming equal variances)

data:  x and g
F = 11.774, num df = 2.000, denom df = 27.597, p-value = 0.0002009

So, this particular dataset to the specifications above shows significance at below the 1%. A simulation of 100,000 datasets
will give a good idea of the power of such a design. [Notice that denom df < 47 above, because the three sample variances differ.]
set.seed(2021)
m = 10^5;  pv = numeric(m)
g = rep(1:3, c(20,15,15))
for (i in 1:m) {
 x1 = rnorm(20, 50, 4)
 x2 = rnorm(15, 54, 6)
 x3 = rnorm(15, 57, 7)
 x = c(x1, x2, x3)
 pv[i] = oneway.test(x~g)$p.val
 }
mean(pv <= 0.05)
[1] 0.90488             # aprx power
2*sd(pv <= 0.05)/sqrt(m)
[1] 0.001855511         # aprx 95% margin of sim error

The power of oneway.test at the 5% level of significance for this design is about $0.905 \pm 0.002.$
Notes: (1) I do not know of an exact formula for the power
of oneway.test, which has different denominator degrees
of freedom for each dataset, based on the observed variances of the various levels. See R documentation.
(2) A for-loop is not the most elegant way to program
the simulation in R, but it seems to be among the easiest for
beginners to understand.
Comment: The .90 power, given the not huge sample sizes suggests that one.way is a high powered test. That this is so is probably due to combination of 1. the broad alternative being any difference in means, and 2. your simulation using rnorm which of course satisfies the normality assumptions of one.way. Is this fair commentary on the .90 simulated power?
Comment: I chose sample sizes I thought would be just large enough to give good power in view of relatively small population SDs and differences among 3 level population means about $\sigma/2.$ (I've dealt with similar situations before.) // Almost all 'power and sample size' computations for ANOVAs assume normality. If populations are not normal, then maybe we should be doing simulation for power of nonparametric tests such as Kruskal-Wallis. // Your summary is not wrong. If it helps match your intuition with reality, then good. But don't be surprised if others prefer somewhat different summaries.
Comment: To clarify, I'm using ANOVA to compare results of gender (male, female, nonbinary) within my groups ie: expt group = 100, controls = 100. expt group So while my overall group numbers are equal, there is unequal number of male-female-nonbinary in my expt group for instance. And I'm trying to see if there are any gender differences in the results I'm getting from psych scales.


Can I plug both laptop and multi-fx to audio interface which is connected to a speaker?

Question: Looking to output my multi fx to my speaker but also at the same time output my laptop to the speaker. So setup is looking like:
Guitar -> Multi FX -> Focusrite Scarlett
Laptop -> Focusrite Scarlett
Focusrite Scarlet -> Speaker
Answer: I understand you want to connect the laptop using USB cable? It seems like this is exactly how it's supposed to be used, though you'd better check the user manual to make sure.
There is a potential of ground loop cause mains connections of the multi FX and the laptop, resulting in noise. If it happens, it can be solved or improved by connecting the multi FX to the XLR input and using ground lift, if available, or disconnecting the laptop from the power (though that might be quite inconvenient).
Comment: Hi thanks for the reply. I simply want to output my guitarfx and my laptop through the same speaker so I can play backing track at the same time for instance.
Comment: @elroikendo as mentioned in the answer, this is precisely what the interface is designed to to be used for. Plug the audio interface into your laptop via usb, chose it under sound devices (or similar, check the manual!) and verify the laptop plays back through your speakers. Then go ahead and plug the guitar fx into the front of the scareltt. Either get the guitar audio to the speakers by using the blend/mix knob on the front (direct) or route it via some audio software running on the computer (where you can further process/record etc).
Comment: Bless you good sir. Thanks for your kind answer, I am just worried that the thing may have weird latency cuz even abit of latency screws up electric guitar. Thanks!
Comment: @elroikendo no problem! It may have a bit of latency when first plugged in, but latency is something that can be set on any software DAW you may use (cubase, reaper etc). You increase or decrease latency (buffer) depending on your needs. For just playing along to a backing track from your computer, with your guitar going direct to the speakers it shouldn't be a problem you encounter. Your Scarlett should have a large knob labelled 'monitor', with that set all the way one way or the other it sends anything plugged into the front inputs directly to speakers with no latency to worry about.
Comment: @elroikendo Just try! You might encounter problems you didn't think of, but also realize that what you thought would be problems are not.
Answer: It sounds like you really want a mixer, but for mixing the backing track and the multi FX the Scarlett can do the job too. The setup is to direct the output of the laptop to the audio interface, plug the multi FX to Scarlett's input and turn on direct monitoring. No software on the laptop needed, no additional latency involved. The advice about ground loop applies.


dynamic path in form partial?

Question: How would I go about using a dynamic path in a form partial that can be set to different paths depending on which page I'm calling the form partial in?
for example, in my _form.html.erb file, at the bottom, I would like to be able to dynamically change the 'cancel' path depending on which page im calling it on:

    <%= form_for(@chef, :html => {class: "form-horizontal", role: "form" }) do |f| %>

        <%= f.label :chefname %>
        <%= f.text_field :chefname, class: "form-control",
                                placeholder: "Chef Name",
                                autofocus: true %>

        <%= f.label :email %>
        <%= f.email_field :email, class: "form-control",
                                 placeholder: "Email" %>

        <%= f.label :password %>
        <%= f.password_field :password, class: "form-control",
                                 placeholder: "Must be at least 5 characters" %>

        <%= f.label :password_confrimation, "Confirm Password" %>
        <%= f.password_field :password_confrimation, class: "form-control",
                                 placeholder: "Confirm Password" %>

        <%= f.submit "#{action} Account", class: "btn btn-primary" %>

    <% end %>

    <%= link_to "Cancel", cancel %>

    <% if logged_in? && (current_chef == @chef || current_chef.admin?) %>
      <%= link_to "Delete Account", chef_path(@chef), method: :delete,
                                     class: "btn btn-sm btn-outline-danger",
                                     data: { confirm: "Are you sure you want to delete this account and all corresponding recipes?" } %>
    <% end %>

Then in the new.html.erb where I'm calling it, I try to set 'cancel' to a path.
<%= render "form", action: "Create", cancel: root_path %>

What would be the proper way to do this? It seems to work in my browser, but then in my test I get undefined local variable or method 'cancel'.
ActionView::Template::Error: undefined local variable or method `cancel' for #<#<Class:0x00000001da1e38>:0x0000000322cf10>

Answer: You're very close. You just need to specify cancel as part of the locals to get it through to the partial:
<%= render "form", action: "Create", locals: { cancel: root_path } %>

dynamic path in form partial?


How to hook methods of MPIncomingPhoneCallController?

Question: I want to hook methods of class MPIncomingPhoneCallController in iOS 5 to do something when a call comes. I use
Class _$MPIncomingPhoneCallController = objc_getClass("MPIncomingPhoneCallController");

MSHookMessage(_$MPIncomingPhoneCallController,
              @selector(updateLCDWithName:label:breakPoint:),
             (IMP) &Hook_LCD,
             "pre_");

to hook updateLCDWithName:label:breakPoint:, but it failed.
How can I do this?
Comment: objc_getClass is used for instance methods. Sorry for the confusion, I don't know how I thought that you wanted to hook a class method. Anyhow, I'm assuming that you are trying to hook that one while your tweak is injected into SpringBoard. You have to know that this class is in a plugin for SpringBoard which is loaded quite late. So you can only hook it once that plugin has been loaded.
Comment: you don't hook Classes. You hook methods or functions. I suggest you google a bit and look for tutorials on how to use MobileSubstrate, but first learn more about the basics of programming.
PS: here you got to use objc_getMetaClass()
Comment: @YllierDev   Yes, you are right,I hook functions.But first I have to get the class.   objc_getMetaClass()  is used to hook class method while objc_getClass is used to hook othe methods.
Comment: @YllierDev  As it is loaded late so I get nil? [link](http://stackoverflow.com/a/8842239/965442)  Vertex mentioned iEnhancer there, I googled but find little info useful. Can you give me some guides?  Thanks.
Comment: I am sorry, but maybe nil is not the reason. I test others and they are also nil but methods are hooked. I will test more and sorry for this.
Comment: @Vertex,Loko  Can you give me some help on hooking methods of classes under SpringBoardPlugins ? Thanks
Comment: I don't know when SpringBoard is loading the plugins, you'll have to apply the hooks after the plugins have been loaded
Comment: If you're open to *other* ways to simply detect when an incoming call arrives, other than MS hooking, then [have a look at this related question and answer](http://stackoverflow.com/a/14765396/119114).
Answer: Class you are trying to hook is located in IncomingCall.serviceBundle which gets loaded in SpringBoard only when there is incoming call. To determine when it's actually loaded you need to hook SBPluginManager loadPluginBundle:. Wait until loaded bundle is com.apple.mobilephone.incomingcall. Only then you can hook what you want.


Why doesn't my class inheriting from array.array work?

Question: I want to inherit from the array.array class, and here's my code.
import array
a = array.array('d', [1.0, 2.0, 3.14])

import numpy as np

class diff_rle_array(array.array):
    def __init__(self, arr: array):
        self._internal = np.ediff1d(arr)

diff_rle_array(a)

But it gives an error
>>> diff_rle_array(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: array() argument 1 must be a unicode character, not array.array

But I have overridden the __init__ method. Is it because array.array is in the base library and hence special?
Comment: I thinks indeed it is library relying on some C code for efficiency, that's why adding attributes nilly-will does not always work
Comment: Obligatory note that subclassing builtins is generally not a great idea, as it leads to very brittle and confusing code. Consider composition over inheritance. The question you're asking is still perfectly valid as a theoretical quandary, mind, I'm just saying that if I saw this in production I'd balk at it.
Comment: Ian, `x = np.ediff1d(a)` works without issue
Comment: ```a.blabla = 3``` would not work for instance.
Comment: `array.array.__new__` may be doing some checking before `diff_rle_array.__init__` gets called; it's not clear what is actually raising the exception.
Comment: "I wanted to create an array that stores the data in efficient manner using diffs and run length encoding." - inheriting from `array.array` won't help you do that.
Comment: @chepner: It looks like `__new__` is the engine behind `array.array`, so it's not just doing the checking, it does all the work (both construction and initialization), leaving `__init__` unused. If you subclass it, you need to follow the same pattern, or at least overload `__new__` (because otherwise `__new__` will reject the wrong set of arguments).
Comment: I'm not sure what the error is but I don't think that your code will do what you want it to do. `np.ediff1d` takes an array e.g `x = np.array([1, 2, 4, 7, 0]) `. You could probably pass it an `array.array` but I don't really understand why you would (do explain if you have a good reason). See [np docs](https://numpy.org/doc/stable/reference/generated/numpy.ediff1d.html)
Comment: Even if this worked, it would be an utterly bizarre class to write. Why even inherit from `array.array`?
Comment: I wanted to create an array that stores the data in efficient manner using diffs and run length encoding. See Julia implementation https://discourse.julialang.org/t/is-there-a-readymade-array-type-that-stores-data-as-run-length-encoding-of-delta/63793/6
Answer: The storage of C-implemented builtins is not a named attribute, it's integrated into the methods and initializers of the type itself. _internal means nothing to array.array, it's just a random attribute you attached to it that is used by none of its methods. If you want to store the values where array.array stores them (so the methods use them implicitly), delegate up to the parent class. In this case, the real work in array.array is done in __new__ (the constructor), not __init__ (the initializer), which means you need to explicitly construct and return:
class diff_rle_array(array.array):
    __slots__ = ()  # Not necessary, but avoids creation of __dict__ for arbitrary attributes, saving memory
    def __new__(cls, arr: array):  # __new__ receives the class, not an instance
        return super().__new__(cls, 'd', np.ediff1d(arr))  # You must return the new instance created by delegating to parent,
                                                           # passing all the arguments it expects

Having done that, your expected results are produced:
>>> a = array.array('d', [1.0, 2.0, 3.14])
>>> diff_rle_array(a)
diff_rle_array('d', [1.0, 1.1400000000000001])

Answer: __new__ is called before __init__, with the same arguments.
diff_rle_array.__new__ is not defined, so array.array.__new__ gets used.
>>> diff_rle_array.__new__
<function array.__new__(*args, **kwargs)>

Now, since you have deviated from the parent class signature in the constructor (see Liskov substitution principle), the array.__new__ receives unexpected arguments - an array instance is sent in, in place of a typecode. That is what the error message means:
TypeError: array() argument 1 must be a unicode character, not array.array

It is not necessarily always wrong to violate LSP, but you would need to override __new__ as well.
Comment: To be clear, `array.array` doesn't have its own `__init__` naturally (it just inherits the no-op `__init__` from `object`). All the work of both construction and initialization is done in `__new__`. Probably best to override *only* `__new__`, rather than both `__new__` and `__init__`, both for efficiency and to keep from drifting too far from the superclass design.
Comment: The LSP isn't usually taken to apply to constructors, since the (immediate) client must know the type to construct (put differently, there is no externally visible object that might be substituted).  That's part of the reason they're not inherited (by default) in languages like C++ and Java.  There can of course be value in having the same signature to allow the classes to be treated interchangeably, but that doesn't seem to be the case here.


how to count the array values with key

Question: I have array like this i need to count by array values
Array ( [Cop] => Array ( [0] => Dozen [1] => Dozen [2] => Akls [3] => Akls ) [MSN] => Array ( [0] => Dozen ) [NeK] => Array ( [0] => Suhan [1] => Ebao ) [NetSE] => Array ( [0] => SuZhan [1] => Guhang ) )

For example
 Array ( [Cop] => Array ( [0] => Dozen [1] => Dozen [2] => Akls [3] => Akls ))

In the Cop key i have two different values for cop so i need cop should be 2
Cop - 2
MSn - 1
NeK - 2
NetSE - 2

I need the count like above how can i do this ?
Answer: Use array_unique() and then count.
count(array_unique($array['Cop']));// output 2

If you want to print for every key do following:
$array = array('Cop'=>array('Dozen','Dozen','Akls','Akls'), 'MSN'=> array('Dozen'), 'NeK'=> array('Suhan','Ebao'));
foreach($array as $key => &$value) {
    $value = count(array_unique($array[$key]));
}
print_r($array);

Output:
Cop = 2
MSN = 1
NeK = 2

Answer: Try simply using array_map,count,& array_unique like as
array_map(function($v) {
            return count(array_unique($v));
        }, $arr);

Comment: You cannot get a more elegant solution.
Comment: @Uchiha The alternatives? i guess the rest of the answers... but this is the most elegant one.
Answer: You should use array_count_values() for that, here's an example:
$data = array('cop' => array(0 => 'test', 1 => 'test', 2 => 'test2'));

foreach($data as $item){
    $result = array_count_values($item);
    print_r($result);
}

Outputs:
Array
(
    [test] => 2
    [test2] => 1
)

how to count the array values with key


Running games using functions

Question: My Code:
import threading
import time
import subprocess
Thread1 = threading.Thread(target=Run_exe)

def run_exe():
    subproccess.call("game.exe")

while True:
   time.sleep(3600)
   x = int(input(""))
   if x==1:
      Thread1.start()
   else:
      Thread1.join()

My objective is the following:

Run the game using the Run_exe function
Kill thread when I exit the game

I don't want to exit game from the game itself
the Python program should get an input to exit the games by killing the thread.
Comment: Do you have a question?
Comment: yes how run the game with python and exit it with python also without interfering with the games using functions and threads
Comment: Why are you using a thread?
Answer: Use subprocess.Popen constructor and save the pid:
process = subprocess.Popen("game.exe")
pid = process.pid

If you want to stop the process, call: (from this answer)
import os
import signal

os.kill(pid, signal.SIGTERM) #or signal.SIGKILL

Running games using functions


What is the best way to create Android library project and use it as a jar file in another project using Android Studio

Question: I have referred few of the link to know the procedure to create an Android library project, none of them have completely explained in detail. My intention is to create a Android library(ex mathsolve.jar ) project and distribute it as a .jar file so that others can use it in their android app.
Can any one please explain the below steps in detail
a) How to create a Android library project
b) How to export that Android library file as .jar file
c) Steps to integrate that .jar file to Another android app
d) And how to call a method of that .jar file from that android app
Any suggestion will help me a lot. Thanks in advance.
Comment: https://jitpack.io/docs/ANDROID/
Comment: "How to export that Android library file as .jar file" -- an Android library project creates an AAR, not a JAR. "Steps to integrate that .jar file to Another android app" -- publish the AAR to a Maven-style repository (e.g., a local repository on your development machine), then have the other app use `repositories {}` and `dependencies {}` to reference it.
Answer: Finally with the help of few post from statckoverflow and by doing trial and error method I am able to get the solution to my question. Here are steps
a) How to create a Android library project
step 01>  In Android Studio go to File -> New -> New Module
step 02>  Select Android Library and click on "Next" button

step 03> Choose minimum SDK supported and click on "Finish".

step 04> A new Module will be added and wait until the gradle sync. Now your library file is created
b) How to export that Android library file as .jar file
step 01> After completion of stage "a" you need to build the project once and you are done . The .aar file will be created in the path of your Android app -> Module Folder ->  build -> outputs -> aar -> module-release.aar
step 02> You just need to copy that module-release.aar and distribute it where ever you want.
c) Steps to integrate that .jar file to Another android app
step 01> Here the library type is in .aar format . The steps are same for both .jar file and .aar file. In Android Studio go to File -> New -> New Module
step 02> In that New Module window select "import  .JAR/.AAR Package" and press "Next" Button

step 03> A new file browser window will open . Here in "File name" section choose file browse and open your module-release.aar file and click on "Finish"
step 04> After successful build copy following compile statement into Your "App module gradle file"
dependencies {
  compile project(path: ':module-release')
}

step 05> Sync the gradle file.
step 06> If any, copy all permission given to your library file to your App Manifest.xml. Thats all you are done
d) And how to call a method of that .jar file from that android app
step 01> In your module you need to define a public method which can be accessible using class name . For example
public final class MyAPI {
    public static int SumOf(int a, int b){
           return a+b;
    }
}

step 02> And from your Host App you can call the SumOf method using
MyAPI.SumOf(2,4);


I want idea about delay function in JavaScript

Question: Sorry I want to ask about Javascript. I just started studying studying recently.
index.js
import FuncDelay from './FuctionDelay.js'
import Summ from './FuntionSumm.js'
Summ(4)
FuncDelay(1000,Summ(3))

FunctionSumm.js
export default function Summ(i){
    console.log(i+i)
}

FunctionDelay.js

I have problem in this file.js. This file about delay and callback function but function can't work after delay //cry

export default function asynchronousDelay(delay, callback) {
 setTimeout(function(){
  callback
 }, delay);
}

Thank You for Knowledge
Comment: callback would be a function ... you need to **call** the function ... e.g. `callback()` - instead, you are passing the result of calling `Summ(3)` as the callback argument
Comment: as jaromanda pointed out, you can call your function like this : FuncDelay(1000, function(){ Summ(3); }) wich will create a callback function fit your function in it.
Comment: i don't want to fix only Summ(3)... i want to know how i call function  because i try console.log(typeto callback) It show undefined .How callback get function @Neil
Comment: You dont have to fix your summ function. my explaination is too long, i'm gonna paste it in an answer ;)
Answer: As callback is (or must be) a function, you need to call it like this: callback(), you forgot the parenthesis.
First when you put a function with parenthesis as an argument to a big function, the argument function is executed before the big function.
FuncDelay(1000,Summ(3)) is transformed into FuncDelay(1000,undefined) before the functDelay is launched, beacause undefined is the return value of Summ. that explains why console.log(typeto callback) shows undefined.
You could get rid of the parenthesis so the argument will be the function and not the return of the function: FuncDelay(1000,Summ) but you obviously loose the argument 3 in it, so you need to create a function without any argument that holds your function with an argument. the quick notation is function(){Summ(3);}.
Comment: I got it. Thank you


Deriving the normal equations' coefficients

Question: Suppose we use the least squares criterion to fit a linear model for the following dataset: $(x_1,y_1),...,(x_m,y_m)\in R \times R$, by solving the following optimisation problem:
$$(a^*,b^*) = \text{argmin}_{a,b}\sum^m_{i=1}(y_i-ax_i+b)^2$$
Assume that the solution is unique. Now, my question is, would any of the following statements be true?
i) $\sum^m_{i=1}(y_i-a^*x_i+b^*)y_i = 0$
ii) $\sum^m_{i=1}(y_i-a^*x_i+b^*)x_i^2 = 0$
iii) $\sum^m_{i=1}(y_i-a^*x_i+b^*)x_i = 0$
iv) $\sum^m_{i=1}(y_i-a^*x_i+b^*)^2 = 0$
By my understanding, we have to take the derivative of the loss function wrt $a$ and $b$:
$$\frac{\partial }{\partial a}\sum_{i=1}^m(y_i-ax_i+b)^2 = 0 \\ \sum_{i=1}^m\frac{\partial }{\partial a}(y_i-ax_i+b)^2 = 0 \\ 2(y_i-ax_i+b)\frac{\partial }{\partial a}(y_i-ax_i+b) = 0 \\ 2(y_i-ax_i+b)(-x_i)=0 \\ -2(y_i-ax_i+b)x_i = 0 \\ (y_i-ax_i+b)x_i=0$$
So this means that statement (iii) should be true.
And for $b$:
$$\frac{\partial }{\partial b}\sum_{i=1}^m(y_i-ax_i+b)^2 = 0 \\ \frac{\partial }{\partial b}(y_i-ax_i+b)^2 = 2(y_i-a_i+b)\frac{\partial }{\partial b} (y-ax_i+b) = 0 \\ 2(y-ax_i+b)(+1) = 0 \\ (y-ax_i+b) = 0$$
So this means that every statement is true.
Surely my second deduction is incorrect? What am I doing wrong here?
Comment: Your calculations are incorrect.  Use the Chain Rule to find the derivatives.
Answer:
$$ (y-ax_i+b) = 0$$
So this means that every statement is true.
Surely my second deduction is incorrect? What am I doing wrong here?

You forgot a summation sign. It should be
$$\sum_{i=1}^m (y-ax_i+b) = 0$$
The same happend in your first deduction which should end with
$$\sum_{i=1}^m (y-ax_i+b) x_i= 0$$
and not $ (y-ax_i+b)x_i = 0$
Comment: silly me, I forgot about that. So just to confirm, only (iii) would be correct, right?
Comment: Yes only iii is right. Sidenote: you can also write the two equations in matrix form $$X^T(Y - X\beta) = 0$$ where $X$ is a matrix with one colum with $x_i$ and one column with $1$'s and $\beta$ is a column vector with $a$ and $b$ as elements. That matrix form can be rewritten as $$X^T Y-X^TX\beta = 0$$ or $$X^TX\beta = X^T Y$$ and finally the more well known $$\beta = (X^TX)^{-1}X^T Y$$


Como fazer com que dois arquivos html funcionem com o mesmo javascript

Question: Como faço para que eu clique em um botao em uma pagina html, e na outra pagina html apareça alguma coisa com um unico arquivo javascript?
exemplo abaixo:
HTML 1
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Teste</title>

    <link rel="stylesheet" href="style.css">

    <button onclick="adicionar()">Teste</button>

HTML 2
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Teste</title>

    <link rel="stylesheet" href="style.css">

JS
var ad = document.getElementById("teste")

function teste(){
    ad.innerHTML += "Teste"
}

function adicionar(){
    function teste()
}

nisso eu queria que, cada vez que eu clicasse no botao de uma pagina html, aparecesse "teste" na outra pagina html
Answer: Da maneira que explicou você explicou, eu vejo duas formas de fazer o que precisa. LocalStorage e WebSocket
Localstorage
function adicionar(){

  var element = document.getElementById('teste')

  if(typeof(element) != 'undefined' && element != null){
    ad.innerHTML += localStorage.getItem('texto');
  }else{
    localStorage.setItem('texto', 'texto que quero printar');
  }

}

Para usar o websocket vai precisar de uma bibliotecas de terceiros (subir um servidor de websocket).
Comment: vou entar aqui, vlw mano


libxgboost4j_gpu.so for x86 architecture inside h2o.jar for ppc64le

Question: I am trying out DAI 1.4.2 on ppc64le Redhat with V100 GPUs, but I find some weird error with dai-h2o daemon.
It seems like it cannot initialize its GPU backend, and I find libxgboost4j_gpu.so for x86 architecture (not ppc64le) inside h2o.jar.
Is this some kind of bug or doesn't this matter at all ?
<code>[root@localhost home]# systemctl status dai-h2o
● dai-h2o.service - Driverless AI (H2O Process)
   Loaded: loaded (/usr/lib/systemd/system/dai-h2o.service; enabled; vendor preset: disabled)
  Drop-In: /etc/systemd/system/dai-h2o.service.d
       └─Group.conf, User.conf
   Active: active (running) since Mon 2018-12-17 14:51:23 KST; 1s ago
 Main PID: 80685 (java)
    Tasks: 93
   Memory: 155.8M
   CGroup: /system.slice/dai-h2o.service
           └─80685
/opt/h2oai/dai/jre/bin/java -Xmx65536m -verbose:gc -XX:+PrintGCDetails -XX:+PrintGCTimeStamps -Ddai.tmp=./tmp -jar /opt/h2oai/dai/h...

Dec 17 14:51:24 localhost.localdomain dai-env.sh[80685]: ======================================================================
 Dec 17 14:51:25 localhost.localdomain dai-env.sh[80685]: Cannot load library from path lib/linux_64/libxgboost4j_gpu.so
Dec 17 14:51:25 localhost.localdomain dai-env.sh[80685]: Cannot load library from path lib/libxgboost4j_gpu.so
Dec 17 14:51:25 localhost.localdomain dai-env.sh[80685]: Failed to load library from both native path and jar!
Dec 17 14:51:25 localhost.localdomain dai-env.sh[80685]: Cannot load library from path lib/linux_64/libxgboost4j_omp.so
Dec 17 14:51:25 localhost.localdomain dai-env.sh[80685]: Cannot load library from path lib/libxgboost4j_omp.so
Dec 17 14:51:25 localhost.localdomain dai-env.sh[80685]: Failed to load library from both native path and jar!
Dec 17 14:51:25 localhost.localdomain dai-env.sh[80685]: Cannot load library from path lib/linux_64/libxgboost4j_minimal.so
Dec 17 14:51:25 localhost.localdomain dai-env.sh[80685]: Cannot load library from path lib/libxgboost4j_minimal.so
Dec 17 14:51:25 localhost.localdomain dai-env.sh[80685]: Failed to load library from both native path and jar!

[root@localhost home]# netstat -an | grep 12345

[root@localhost home]# ls -l
/opt/h2oai/dai/h2o.jar
-rw-r--r-- 1 root root 109623422 Dec  4 07:45 /opt/h2oai/dai/h2o.jar

[root@localhost home]# jar -xvf /opt/h2oai/dai/h2o.jar lib/linux_64/libxgboost4j_gpu.so
 inflated: lib/linux_64/libxgboost4j_gpu.so

[root@localhost home]# ls -l lib/linux_64/libxgboost4j_gpu.so
-rw-r--r-- 1 root root 34754400 Jul  8 12:56 lib/linux_64/libxgboost4j_gpu.so

[root@localhost home]# file lib/linux_64/libxgboost4j_gpu.so
lib/linux_64/libxgboost4j_gpu.so: ELF 64-bit LSB shared object, x86-64, version 1 (GNU/Linux), dynamically linked, BuildID[sha1]=c7c3682ccf33d3d0395772e924be1e416a60a2c4, not stripped
</code>
Answer: This does not matter at all.
The h2o.jar bundled with Driverless AI is not for GPU use at all.
All of the GPU use is from the Driverless AI python processes.


Stockcharts - Adding an offset to avoid drawing points at the edge

Question: Highcharts and stockcharts, they both provide the options to add some padding at the x axis in order to avoid drawing some values on the edge of the plot area (left or right).
According to the doc this is archived by employing the minPadding and maxPadding members of the xAxis property of the configuration object used for constructing the chart... but in practice this is not working for stockcharts. So i wonder how i can achieve this... i leave you with the examples...
var examples

Working example for highcharts
Not Working example for stockcharts

P.D: Using property min for setting the lowest x value also isn't working.
Answer: The maxPadding is applied when you not call the setExtremes() method. In the Highstock, we call the setExtremes to set the range on the navigator, as a result padding is ignored.
To achieve your goal, you can define the tickLength parameter and set x param per labels.
yAxis: {
  tickWidth: 1,
  tickLength: 50,
  labels:{
    x: 50
  }
},

Example:

http://jsfiddle.net/b6a42kz0/

OP Note: See the comments for updated answer.
Comment: Thanks @Sebastian, your workaround solves my problem!
Comment: Thanks Sebastian!! This helps a lot.. but i wonder how i can also achieve the same result for the points on the left edge of the x axis.
Comment: You can add extra yAxis and define offset etc. Example: http://jsfiddle.net/596mo1qc/ and http://jsfiddle.net/e1avsqoq/


Entity Framework Cascade Deleting, even though no CASCADE set up in database

Question: I have a foreign key relationship between two tables UserProducts and Users in my database, with UserProducts having a UserID referencing the UserID in the Users table.
ALTER TABLE [dbo].[UserProducts]  WITH CHECK ADD  CONSTRAINT [FK_UserProducts_Users] FOREIGN KEY ([UserID])
REFERENCES [dbo].[Users] ([UserID])
GO

ALTER TABLE [dbo].[UserProducts] CHECK CONSTRAINT [FK_UserProducts_Users]
GO

The UserID column in the UserProducts table is part of a composite primary key with another column ProductID. There are also two additional DateTime columns, so Entity Framework does not treat UserProducts as a link table.
There is NO cascade delete on that foreign key above, nor did I set up anything to handle OnDelete on the Entity Framework foreign key association. Yet, when I delete a User entity from code, Entity Framework is taking the liberty of deleting the UserProducts associated with it by UserID. It is also generating a lot of SQL to do it: there is a separate DELETE per related record in the UserProducts table.
The code to perform the entity deletion is as follows:
using (var context = new LicensingRegistrationContext(_csb))
{
    context.Database.Log = a => _logger.Trace(a);

    var dbUser = GetUserDbSetWithIncludes(context)
        .Where(a => a.UserID == user.Id).Single();

    context.DbUsers.Remove(dbUser);

    //TODO(MRL): Um...how are the dbUserProducts being removed???

    context.SaveChanges();
}

How is this happening? In EF 4 I am pretty sure EF never took this liberty of doing this: you HAD to load and then delete all related entities manually in code.
Thanks
Answer: Entity framework by default has a
OneToManyCascadeDelete

convention. Here is the link http://msdn.microsoft.com/en-us/library/system.data.entity.modelconfiguration.conventions.onetomanycascadedeleteconvention(v=vs.113).aspx
So entity framework cascade deletes the one to many relationship by default.
You can disable this by disabling the convention or explicitly disabled it for this relationship via the fluent API.
Comment: Bounty awarded as I didn't know about conventions, so despite not being the answer, this was still useful.
Answer: I found this on MSDN and I believe this is what is happening:

When a primary key of the principal entity is also part of the primary key of the dependent entity, the relationship is an identifying relationship. In an identifying relationship the dependent entity cannot exist without the principal entity. This constraint causes the following behaviors in an identifying relationship: Deleting the principal object also deletes the dependent object. This is the same behavior as specifying OnDelete Action="Cascade" in the model for the relationship. Removing the relationship deletes the dependent object. Calling the Remove method on the EntityCollection marks both the relationship and the dependent object for deletion.

This is what is happening in my model where the UserComponent table has a composite primary key: UserID, ComponentID and the UserID column is a foreign key to the UserID in the User table.


If $f$ is a polynomial, how does $f(\frac{d}{dt})$ act on $y$?

Question: If $f\left(\frac{d}{dt}\right)=a_n\frac{d^n}{dt^n}+\dots+a_1\frac{d}{dt}+a_0$, then whether
$$f\left(\frac{d}{dt}\right)(y)=a_n\frac{d^n}{dt^n}y+\dots+a_1\frac{d}{dt}y+a_0y$$
or
$$f\left(\frac{d}{dt}\right)(y)=a_n\frac{d^n}{dt^n}y+\dots+a_1\frac{d}{dt}y+a_0$$
I am confused.
Comment: Maybe it helps to see the types. If we denote the function space by $X$ (e.g. $C^\infty(\mathbb{R})$), then $f$ is of type $(X \to X) \to (X \to X)$. Given an input operator (e.g. $\frac{d}{dt}$), it outputs another (linear!) operator acting on the function space.
Answer: It is
$$
 f\left(\frac{d}{dt}\right)(y) = a_n \frac{d^n}{dt^n}y + \cdots + a_1 \frac{d}{dt}y + a_0 y.
$$
If this notation confuses you, it might help to write the operator as
$$
 a_n \frac{d^n}{dt^n} + \cdots + a_1 \frac{d}{dt} + a_0 I
$$
where $I$ is the identity operator.
Answer: The correct answer  is $$(\frac{d}{dt})(y)=a_n\frac{d^n}{dt^n}y+\dots+a_1\frac{d}{dt}y+a_0y$$
Otherwise you lose the linearity of your operator.
Answer: Writing $D_t$ for $\frac{d}{dt}$, we can see that $D_t$ is nothing more than an operator on functions (or variables, according to your choice of framework for real analysis). In general any operator $X$ can be iterated, and we write $X^n$ for the $n$-th iterate of $X$. $X^0$ is the $0$-th iterate of $X$, which is naturally the identity on the input domain of $X$.
Thus ${D_t}^0$ is the identity on (real) functions, and so ${D_t}^0(y) = y$ for any real function $y$.
As for polynomials applied to $D_t$... First define, for any real $c$ and operator $X$ on real functions and real function $v$, that $(c·X)(v) := c·X(v)$ where the latter is the scalar multiplication of $c$ with the function $X(v)$. Next define, for any operators $X,Y$ on real functions and real function $v$, that $(X+Y)(v) = X(v) + Y(v)$, where the latter is the pointwise sum of the real functions $X(v)$ and $Y(v)$. We can then verify that reals act via $·$ on operators on real functions, i.e. $(c+d)·X = c·X+d·X$ and $(cd)·X = c·(d·X)$ for any reals $c,d$ and operator $X$ on real functions.
Here are the identity chains in the verification:

$((c+d)·X)(y) = (c+d)·X(y) = c·X(y) + d·X(y) = (c·X)(y) + (d·X)(y)$.
$((cd)·X)(y) = (cd)·X(y) = c·(d·X(y)) = c·((d·X)(y)) = (c·(d·X))(y)$.

Without this reasoning, it is technically wrong to just claim willy nilly that one can apply a polynomial to $D_t$.
In general this shows that, given any set $S$ and a set $C$ that acts via $·$ on operators on $S$, it is meaningful to apply any polynomial over $C$ to any operator on $S$.
Comment: In case it is not clear, the "$a_0$" in the question must be interpreted to be "$a_0·id_{\mathbb{R}\to\mathbb{R}}$". Either you view it as a type coercion; since the other terms are operators this is the only sensible way to interpret it. Or you view it as an abuse of notation, and don't write it that way.


Solve matrix differential equation using a substitution

Question: I want to solve
$$t \frac{\mathrm{d} \mathbf{x}}{\mathrm{d} t}=\begin{pmatrix}
2 & 2\\
1 & 3
\end{pmatrix} \mathbf{x} ~~,~~\mathbf{x}(1)=\begin{pmatrix}
2\\
3
\end{pmatrix}$$
using the substitution $t=e^u$, $\mathbf{y}(u)=\mathbf{x}(e^u)$. I tried substituting
$$\frac{\mathrm{d} \mathbf{x}(e^{u(t)})}{\mathrm{d} t}=\frac{\mathrm{d} \mathbf{x}}{\mathrm{d} t}e^u \frac{\mathrm{d} u}{\mathrm{d} t}=\frac{\mathrm{d} \mathbf{x}}{\mathrm{d} t}e^u \frac{\mathrm{d}}{\mathrm{d} t}(\ln t)=\frac{1}{t}\frac{\mathrm{d} \mathbf{x}}{\mathrm{d} t}e^u$$
 and I fail to understand how does it help solving the problem. Any ideas?
Comment: Note that, for scalar $x$, you have $$
t\frac{{d\,x}}
{{d\,t}} = k\;x\quad  \Rightarrow \quad \frac{{d\,x}}
{x} = k\frac{{d\,t}}
{t}\quad  \Rightarrow \quad x = c\,t^{\,k}
$$
so your substitution is not right, because of the multiplying $t$, and you shall substitute with a combination of the above
Comment: @Moo - yes. Why?
Comment: @Moo - textbook on differential equations. It simply gives the initial value problem and asks to solve it using this substitution.
Answer: Here is how in works on the scalar equation:
Let $tx'=kx$ and let $t=e^u$.
Then
$$
x(t)=x(e^{u})=y(u)=y(\log t).
$$
Now
$$
\frac{dx}{dt}=\frac{dy}{dt}=\frac{dy}{du}\frac{du}{dt}=\frac{1}{t}y'.
$$
hence your equation becomes $y'=ky$, which is easy to solve. Do the same for your matrix notation.


Terminate watch command after run completes

Question: I'm using watch in a screenwindow to continually execute a PHP task which processes data every two seconds. Thus, I can logout of the server with it running and can check-in on it. I don't want to stop the task mid stream because it requires manual cleaning up if that happens, but I'd like to be able to reboot the server. Is there a way to stop watch between runs and be sure it hasn't started another copy of the task? Ie something like ctrl+c but that waits if the task is running in the background.
Alternatively, is there some other workflow that would accomplish this? I can't use a cron job since it needs to run every two seconds but never concurrently.
Also note, one run of the script takes between 10 seconds and 30 minutes depending on how big the data object is. (It processes one object per run.) This is why stopping watch between runs is very unlikely...
Answer: Just make a little bash script that loops as long as a file doesn't exist:
while [ ! -e /tmp/stoploop ]; do
    some_program
    sleep 2
done

Then touch /tmp/stoploop and it will stop looping.


Turn off web services in IIS 5 with ftp enabled

Question: I have enabled FTP using IIS in Windows 2000.  It is just for receiving files from an FTP server to a directory, and is working fine.
I'd like to disable the web component of IIS, but keep this ftp "client" interface working.  Currently, I've just changed settings to "choke" its capabilities, but is there a way to definitively turn HTTP services off?
Answer: To nuke it from orbit would be to stop the "World Wide Web Publishing Service" service and change the start up to Disabled.


Subgroups of $ \mathbb{Z}^n $

Question: I'm having a difficulty proving the following:
Let $ H \leq \mathbb{Z}^n $ be a subgroup. Prove that $ H \simeq \mathbb{Z}^k $, $ k \leq n $.
Moreover, prove that if
$ H = \{(c_1, \dots, c_n) \in \mathbb{Z}^n; a_1c_1 + \dots + a_1c_1 = 0 \} $,
where $ (a_1, \dots, a_n) \in \mathbb{Z}^n \setminus \{0\} $
then $ k=n-1 $
So what I've got, I can prove that every subgroup of $ \mathbb{Z^n} $ is finitely generated (and abelian, of course), therefore
$ H \simeq \mathbb{Z}_{q_1} \times \dots \times \mathbb{Z}_{q_r} \times \mathbb{Z}^k $ for some $ k \in \mathbb{N} $ and $ q_1, \dots, q_r $ - powers of primes. Maybe now I can say that no element of $ \mathbb{Z^n} $ except $ 0 $ is of finite order, but elements such at $ (1, 0, \dots, 0) $ are, which means that $ \mathbb{Z}_{q_i} \simeq \{0\} $. Knowing that $ k \leq n $ is rather obvious.
The other part is what gets me. I can see I'm gonna need using the first one, but I'm stuck there
Thanks in advance
Comment: You have written $a_1c_1+\cdots+a_1c_1=0$. Perhaps you can edit it, so it says what you meant to say. Anyway, all you need is $n-1$ independent generators, which you can get by letting all the coefficients except the 1st and the $j$th be zero, $j=2,\dots,n$.
Answer: Hint. There is an exact sequence $0 \to H \to \mathbb{Z}^n \to \mathbb{Z} \to 0$. In general, if $0 \to A \to B \to C \to 0$ is an exact sequence of abelian groups, then $\mathrm{rank}(B) = \mathrm{rank}(A) + \mathrm{rank}(C)$.
Comment: Well, so should it go this way:

Let $ \phi : H \rightarrow \mathbb{Z}^n; \phi(c_1, \dots, c_n) = (c_1, \dots, c_n) $ and $ \psi: \mathbb{Z}^n \rightarrow \mathbb{Z}; \psi(c_1, \dots, c_n) = c_1a_1 + \dots + c_1a_n $. Of course the image of $ \phi $ is the kernel of $ \psi $ and by the lemma you mentioned $ \mathrm{rank}(H) = n-1 $.

Could you please show me where to find a proof of this lemma?
Comment: Yes, but note that $\psi$ is not surjective, still the image is isomorphic to $\mathbb{Z}$ (why?). The Lemma is easy to prove when you know tensor products; in fact this reduces the statement to $\mathbb{Q}$-vector spaces, where it is well-known from linear algebra. Here you can also do the following: If $0\to\mathbb{Z}^r\to\mathbb{Z}^n\to\mathbb{Z}^m\to 0$ is exact, then it splits (why?), hence $\mathbb{Z}^n \cong\mathbb{Z}^{r+m}$. Now there are plenty of ways proving that this implies $n=r+m$, but since you have used the structure theorem for abelian groups, you probably already know this.
Comment: Yeah, of course. I'm not familiar with tensor products yet, but thank you. Of course every non-zero subgroup of $ \mathbb{Z} $ is isomorphic to $ \mathbb{Z} $. Thank you

Subgroups of $ \mathbb{Z}^n $


Not sure if my 10 threads are reading the same .txt files when they are started

Question: I have 10 threads that are started when my java class is started and they look into a directory and start looking for files . In one of my methods I change the .txt files extension to .working which indicates that a file is currently in process . When my java class is invoked or started I see sometimes only 5 files are being processed since their extension is .working . Kindly let me know how should I make sure that no 2 threads are calling the same .txt file !!
Comment: wouldn't starting 10 different threads for this purpose introduce race conditions?
Answer: The simplest approach is to read the list of files in one thread, then use a thread-safe producer/consumer queue (e.g. ArrayBlockingQueue) to publish these "files to process". The ten threads will then all take items off the same queue, which ensures that no item is processed twice.
Comment: Yes, that's just dandy.  My guess is that the OP has been reading that textbook that says 'To use threads in Java, you must create them with parameters, start them and wait for them to finish with join() to get results'.
Comment: This way, you won't have to go into renaming files either.
Answer: You are probably running into a race condition similar to the following pseudo code.  Multiple threads will make the exists test and then try the rename and process the same file.
File file = new File("file.txt");
File working = new File("file.working");
if (file.exists()) {
   // race condition may happen at this point
   file.renameTo(working);
   processWorking(working);
}

You should synchronize around the test and rename.  Something like:
private final Object lockObject = new Object();
...

boolean process = false;
// lock around the test and the rename
synchronized (lockObject) {
    if (file.exists()) {
       file.renameTo(working);
       process = true;
    }
}
// process the file outside of the lock
if (process) {
    processWorking(working);
}

Comment: Thanks for your code ! I tried using synchronized block before processing the .txt files but instead of having 10 .working files I was having only 1 .working while but with below code it worked the way I wanted .
Answer: You can use the following code in you thread program.
 try {
        // Get a file channel for the file
        File file = new File("filename");
        FileChannel channel = new RandomAccessFile(file, "rw").getChannel();

        // Use the file channel to create a lock on the file.
        // This method blocks until it can retrieve the lock.
        FileLock lock = channel.lock();

        // Try acquiring the lock without blocking. This method returns
        // null or throws an exception if the file is already locked.
        try {
            lock = channel.tryLock();
        } catch (OverlappingFileLockException e) {
            // File is already locked in this thread or virtual machine
        }

        // Release the lock
        lock.release();

        // Close the file
        channel.close();
    } catch (Exception e) {
    }

Comment: You really need give more information then this otherwise it seems you have just pasted some file locking code. How should the OP use this? Is it really necessary to first call `lock` and then immediately again `tryLock`?
Comment: That will lock the file and if another thread has already locked that file then it will not allow that thread to lock the file and it will throw and exception to the user that this file is already in use by another thread or process.
Comment: @MiserableVariable And by the way I have already use this mechanism in my program which is working perfectly.
Comment: Thanks Bhavik !! Your solution works perfectly with my scenario ! Thanks for the example !!


Losing data when pass from UIViewController to another class

Question: I do a simple test app. I pass an int value from UIViewController:
namespace Test
{
    public partial class TestViewController : UIViewController
    {
        Getter gt;
        public TestViewController (IntPtr handle) : base (handle)
        {
        }

        #region View lifecycle
        public override void ViewDidLoad ()
        {
            base.ViewDidLoad ();

            ClickBT.TouchUpInside += (object sender, EventArgs e) => {
                gt = new Getter(2);
            };

            // Perform any additional setup after loading the view, typically from a nib.
        }
}

to another class:
namespace Test
{
    public class Getter
    {

        public Getter (int x)
        {
            if (x != 0)
                Console.WriteLine ("Value isn't null: ", x);
            else
                Console.WriteLine ("Value is null: ", x);
        }
    }
}

When I click on the button, the result is always:
2015-01-12 09:02:31.063 Teste[5184:107203] Value isn't null:
2015-01-12 09:02:32.453 Teste[5184:107203] Value isn't null:
2015-01-12 09:02:32.630 Teste[5184:107203] Value isn't null:
But I don't have the value. Where should be the value, is blank.
I can't find it on internet...
Comment: You're not using the string formatting overload of Console.WriteLine correctly. Read up on string formatting in C#, it'll help you immensely.
Comment: No, I've tried it. The result is the same.
Comment: I've tried, right now, use the value on a label.
The label shows the value correctly. I think it's a log problem.
Comment: http://msdn.microsoft.com/en-us/library/586y06yf%28v=vs.110%29.aspx
Answer: The response in the console is correct, but in order to also display the number, you need to change your Console.WriteLine.
Your example
Console.WriteLine ("Value isn't null: ", x);

What it should be
Console.WriteLine ("Value isn't null: " + x.ToString());


What is the limit of the sequence: $n$-th root of the $n$-th Fibonacci number?

Question: My computer can not calculate numbers large enough for this.
If you take the $n$-th Fibonacci number $F_n$ and raise it to the $1/n$-th term, where does the sequence $F_n^{1/n}$ tend to?
Examples:

$13^{1/7}$
$21^{1/8}$
Comment: $\frac{\sqrt5+1}{2}$
Comment: There's a simple formula expressing the n-th fibonacci number as the sum of two numbers raised to the n-th power or similar. I'm sure you'll find details.The limit is then very easy.
Comment: Possible duplicate of [Is there a formula for fibonacci sequence?](http://math.stackexchange.com/questions/1654276/is-there-a-formula-for-fibonacci-sequence)
Comment: No not the same
Comment: It gives the answer because the larger root (golden ratio) dominates the growth of the Fibonacci sequence.
Answer: $F_n$ is the integer closest to $\frac{\varphi^n}{\sqrt5}$, where $\varphi=\frac{1}2\left(1+\sqrt5\right)$. Its $n$-th root is therefore approximately $\frac{\varphi}{5^{1/(2n)}}$, which approaches $\varphi$ as $n$ increases.
Answer: There are many ways to do this, but perhaps the easiest is a modified form of Binet's formula:
$$F_n=\left[\frac{\phi^n}{\sqrt{5}}\right],$$
where the brackets are the nearest integer function. You can squeeze the above between: $\frac{\phi^n}{\sqrt{5}}\pm 1$. Now confirm that:
$$(\frac{1}{\sqrt{5}}\phi^n+1)^{1/n}=\phi\exp\left(\frac{1}{n}\ln(\frac{1}{\sqrt{5}}+1/\phi^n)\right)\rightarrow \phi,$$
so by the squeeze theorem $F_n^{1/n}\rightarrow\phi$.
Answer:
THEOREM:-$F_n = \frac{a^n-b^n}{a-b}$ where $a$ and $b$ are the roots for the polynomial $x^2-x-1 $.

PROOF:-
Since $\frac{a^1-b^1}{a-b} = 1$ and $\frac{a^2-b^2}{a-b} = 1$, assume it work for $ F_n$ and $ F_{n+1 } $ then $a^{n+2}-a^{n+1}-a^n-b^{n+2}+b^{n+1}+ b^n =0  $ (why? factor $a^n $ and $b^n$ then notice it is the same polynomial as $x^2-x-1 $ ) which proves it work for $F_{n+2}$ by Induction ( rearrange the terms so ${a^{n+2}-b^{n+2}} ={a^n-b^n}+ {a^{n+1}-b^{n+1}}$ and divide both side by $ a-b  $) Therefore, by induction, the formula holds for all positive integers $n$.

Let $a>b$ $$ a\sqrt[n]{1-\left|\frac{b}{n} \right|^n}< \sqrt[n]{a^n - b^n }< a\sqrt[n]{1+\left|\frac{b}{n} \right|^n}$$
since $|a|> |b|$ then $\lim\limits_{n \to \infty}\left|\frac{b}{n} \right|^n =0$ then by squeeze theorem $\lim\limits_{n \to \infty}\sqrt[n]{a^n - b^n } =a$
$$\lim\limits_{n \to \infty}\frac{\sqrt[n]{a^n - b^n }}{\sqrt[n]{a-b}} =a$$


SQL query problem in 'login' script confusing situation

Question: I've got a problem with PHP, with WampServer. I'm doing such think first time of my life and I'm really confused, because every example I found is not working at all, or I'm getting no output. Could you please help?
enter code<?php
require_once "connect.php";

$connection = @new mysqli($host, $db_user, $db_password, $db_name);

//if($connection->connect_error)
//{
//  echo "Nie można połączyć się z bazą danych";
////} else
//{
    $mail = isset('$_POST[mail]');
    $haslo = isset('$_POST[haslo]');

    sql = "SELECT * FROM users WHERE mail='$mail' AND haslo='$haslo'";
    if ($result = @$connection->query($sql))
    {
        $user = $result->num_rows;
        if($user>0)
        {
            $row = $result->fetch_assoc();
            $user =  $row['mail'];

            header('Location:user.php');
            $result->close();
        } else {
            echo"Podałeś złe dane";
        }
    }
    $connection->close();
//  }
?>

Comment: isset checks if theres a value and then assign it to variable. $mail = $_POST['mail'] after checking isset
Comment: Please don't use `@` as a silencer in code.
Comment: `sql` should be `$sql` (missing $)
Comment: Also take a look at what `isset()` does/returns
Comment: Thank you @kerbholz appreciate you're help - sometimes this "$" is invisible xD
Comment: You need to use prepared statements.   `isset()` on those literal string values will return true or false.
Comment: You should create new connection.
https://www.c-sharpcorner.com/article/working-with-wampserver/
or use XAMP!
Answer: Welcome to SO.
Please find corrections below in the code:
<?php
require_once "connect.php";

$connection = @new mysqli($host, $db_user, $db_password, $db_name);

//if($connection->connect_error)
//{
//  echo "Nie można połączyć się z bazą danych";
////} else
//{
    $mail = isset($_POST['mail']) ? $_POST['mail'] : ''; // Added ternary operatr and properly placed single quotes.
    $haslo = isset($_POST['haslo']) ? $_POST['haslo'] : ''; // Same as above

    $sql = "SELECT * FROM users WHERE mail='$mail' AND haslo='$haslo'"; // Replaced sql by $sql as pointed out in comments.
    if ($result = $connection->query($sql)) // Removed @ (Error supressor, no need for it.)
    {
        $user = $result->num_rows;
        if($user>0)
        {
            $row = $result->fetch_assoc();
            $user =  $row['mail'];

            header('Location:user.php');
            $result->close();
        } else {
            echo"Podałeś złe dane";
        }
    }
    $connection->close();
//  }
?>

Comment: Prepared statements are a MUST.
Answer: there are some checks that need to update in such a way to get output values for manipulation
updated
<?php
require_once "connect.php";

$connection = @new mysqli($host, $db_user, $db_password, $db_name);

//if($connection->connect_error)
//{
//  echo "Nie można połączyć się z bazą danych";
////} else
//{
    $mail = isset($_POST['mail']) ? $_POST['mail'] : '';
    $haslo = isset($_POST['haslo']) ? $_POST['haslo'] : '';

    sql = "SELECT * FROM users WHERE mail='$mail' AND haslo='$haslo'";
    if ($result = @$connection->query($sql))
    {
        $user = $result->num_rows;
        if(isset($user) && $user > 0)
        {
            $row = $result->fetch_assoc();
            $user =  $row['mail'];

            header('Location:user.php');
            $result->close();
        } else {
            echo"Podałeś złe dane";
        }
    }
    $connection->close();
//  }
?>

Comment: Please do not encourage the use of the "stfu operator" (`@`). A proper solution will be implementing prepared statements with placeholders and bound variables.
Comment: yes but I only add correct things in existing code not delete anything. as i mentioned **updated** flag


Erro no "break" em códgo C++ impede a compilação

Question: Segue código:
#include <iostream>

using namespace std;

int main()
{
    float n1, n2;
    int s;
    float resul;
    cout << "Digite um número para começar" << endl;
    cin >> n1;

    cout << "Vc quer (1)somar (2)diminuir (3)mutiplicar (4)dividir" << endl;
    cin >> s;
    switch (s) {
    case 1:
        cout << "Com qual valor?" << endl;
        cin >> n2;
        resul = n1 + n2;
        break case 2 : cout << "Com qual valor?" << endl;
        cin >> n2;
        resul = n1 - n2;
        break case 3 : cout << "Com qual valor?" << endl;
        cin >> n2;
        resul = n1 * n2;
        break case 4 : cout << "Com qual valor?" << endl;
        cin >> n2;
        resul = n1 / n2;
        break default : cout << "Error 404" << endl;
    }

    cout << "O resultado é " << resul << endl;

    return 0;
}

Onde eu errei? É uma calculadora simples.
Comment: Qual é a duvida?
Comment: tava dando erro, mas eu descobri que era pq eu tinha esquecido de colocar o ; depois do Break hehe
Answer: Não sei já que não tem o que acontece de errado, mas pelo código há erros de digitação, falta o ; após cada break.
Organizando o código um pouco melhor ficaria assim:
#include <iostream>
using namespace std;

int main() {
    float n1, n2, resultado;
    int s;
    cout << "Digite um número para começar";
    cin >> n1;
    cout << endl << "Vc quer (1)somar (2)diminuir (3)mutiplicar (4)dividir";
    cin >> s;
    cout << endl << "Com qual valor?";
    cin >> n2;
    switch(s) {
    case 1:
        resultado = n1 + n2;
        break;
    case 2:
        resultado = n1 - n2;
        break;
    case 3:
        resultado = n1 * n2;
        break;
    case 4:
        resultado = n1 / n2;
        break;
    default:
        cout << endl << "Error 404";
        return 0;
    }
    cout << endl << "O resultado é " << resultado << endl;
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Comment: kkk Isso msm, sou muito esquecido.Vlw^^
Answer: Apenas coloque um ; após o break.
Comment: na frente ou depois?
Comment: o que sua resposta acrescenta no que já foi dito na outra resposta?


Why doesn't IndexOf work with StringCompare?

Question: I get this error
    string v = "aeiou";
    foreach(int i in lokacija.Naziv) {
      if(v.indexOf(lokacija.Naziv[i], StringComparison.CurrentCultureIgnoreCase) = -1)
        s+=lokacija.Naziv[i];
    }

The error says "cannot convert from System.StringComparison to int". But I know there is an overload of the method indexOf(string) which accepts arguments of the type StringComparison. So how can I resolve this?
Comment: I'd guess that `lokacija.Naziv[i]` likely provides a `Char`. [`.IndexOf()`](https://msdn.microsoft.com/en-us/library/system.string.indexof.aspx) only accepts `StringComparison`s when the 1st argument is a `String`.
Comment: what version of .net?
Comment: @JonathanLonowski it depends of the .NET Framework used. There **is** such a function in .NET Core 3.1: https://learn.microsoft.com/en-us/dotnet/api/system.string.indexof?view=netcore-3.1#System_String_IndexOf_System_Char_System_StringComparison_
Comment: @djomles, did you have the chance to try what I suggested?
Answer: First of all, you should be using == for comparison.
Second, all IndexOf overloads whose first parameter is a char, their second parameter is an int. That's why you get that error. In order to use the overload that receives a StringComparison, make that first parameter a string, like this:
if (v.indexOf(lokacija.Naziv[i].ToString(), StringComparison.CurrentCultureIgnoreCase) == -1)

BTW, are you trying to remove vowels from a string? I recommend you try this.
Comment: not quite true your second point. In .NET Core we have the overload `char, StringComparision` https://learn.microsoft.com/en-us/dotnet/api/system.string.indexof?view=netcore-3.1#System_String_IndexOf_System_Char_System_StringComparison_
Comment: Well, .NET Core Initial release: June 27, 2016, my bad for not knowing the future.
Answer: you loop seems strange... did you mean this?
foreach(string ssub in lokacija.Naziv) {
  if(v.indexOf(ssub, StringComparison.CurrentCultureIgnoreCase) = -1)
    s+=ssub;

Answer: @Johnathan-Lonowski hit the nail on the head- you are getting this version of String.IndexOf, not this one, because you are looking for a character in a string, not an occurrence of one string in another.
Comment: there **is** a function with `(char, ComparisonType)`, in .NET Core


Where do chi squared p-value lookup tables come from?

Question: I'm doing a lot of labs in science and my teacher always wants us to find the chi-squared values of our data and find the probability of that occurring from a lookup table. Where do these probabilities come from in the lookup table? Is there a function or functions that output these numbers?
Comment: the lookup tables your teacher mentions are the distribution tables. For example, you can get your p value for z score from normal distribution table while chi squared  p-values would come from corresponding chi squared distribution. There are lots of online websites that replaced the traditional tables. for example see [here](https://stattrek.com/online-calculator/chi-square.aspx)
Answer: A little about statistics and statistical tests.
When you use the data to compute these chi-square values, we idealize whatever you compute as coming from a probability distribution. The distribution is called the chi-square distribution.
The chi-square distribution depends on a parameter called "the degrees of freedom". Since probability distributions are just functions (you know about functions), I can plot them.  I've plotted the chi-square under a couple of degrees of freedom below.
[
Now, onto p-values.  Let's say you conduct your experiment and get a chi-square value.  You go to your table and find the corresponding p-value.  Those p-values in those tables are what we call "tail probabilities".  So for example, let's say your experiment has 2 degrees of freedom (corresponding to the top left picture).  You get a chi-square value of 2.  Then, your p-value is the area under the curve to the right of 2 (the shaded region).
What those tables do is tell you the area under the curve for a variety of chi-square values.  We obtain the values in the table by computing the area under the curve.  It is easier to compute the areas under the curves once and put them in a table rather than have you compute the areas yourself, hence why you look up values in tables.
Math, if you are interested...
The function for the chi-square distribution is
$$f(x) = \begin{cases} \dfrac{x^{k/2 - 1}e^{-x/2}}{2^{k/2} \Gamma(k/2)} \quad x>0 \\
0 \qquad\qquad  \text{else}  \end{cases}$$
Here, $k$ is the degrees of freedom.  Suppose you get a chi-square value of $\chi$.  Then the p-value is
$$ \lim_{s\rightarrow \infty} \int_{\chi}^s f(x) \, dx$$
We know this integral converges, and that it is less than 1 unless $\chi=0$.  The table is created by computing this integral for various $k$ and $\chi$.


Regular expression to delete lines

Question: I'm working with some fonts and quite often I need to remove some stuff but doing by hand, oops, meaning doing manually, takes an eternity :(
The code looks like this
SplineSet
81 830 m 2xd4
664 830 l 2
725 830 742 813 742 766 c 2
...more numbers
Named: "BOX"

It should look like this:
SplineSet

So simply I need to remove a line name "BOX" from glyphs and all numbers and lines associated to this "BOX".
So how can I remove those nasty lines with a regular expression?
Answer: You can use this:
Find what: ^(\d.*\R)+Named: "BOX"\s*
Replace with: (empty)
◉  Regular expression
☐  . matches newline
It will find those lines preceding the Named: "BOX" line that start with a digit. That group of lines is removed.

Regular expression to delete lines


Is there a PEP for Python's EGG format?

Question: Since there is a PEP for the Python Wheel format (actually two: here and here), I am wondering if there is a specification, similar to that of the wheel format, for Python's EGG format.
Answer: I don't think there's a PEP for it, but there is this from the setuptools documentation.

Is there a PEP for Python's EGG format?


Is there a specific name for this formula?

Question: I was wondering if there was a specific name for this formula and if it is involved in an established statistical process (like how chi-squared tests are for comparing observation classes or t tests are for distributions without a known population stddev), or if this is an original development from the referenced article author. I wish to understand its usage a bit more is why.
How it is referenced in the article:

A further test, based on the work of Ellegard and Thomson, was
  devised to determine "Distinctive Numbers" ... The "distinctive numbers" which result
  are therefore given the symbol D. This test is in fact finding where x-epsilon is the expected occurrence, x-0 the observed occurrence and x the average occurrence in the grand total. The effect of this is to increase the denominator when the Stowe manuscript uses a word either more often or less often than the average, giving a lower D value and weighting the result so that increased notice is taken of occurrences when abnormalities in the texts coincide.

The formula in question:
$$
D=\sum\frac{[(x_\epsilon-\bar{x}) - (x_0-\bar{x})]^2}{|x_\epsilon-\bar{x}|}
$$
The article where I found it: Harvey, P. (1970). Stylistic Analysis
Answer: It looks something like a $\chi^2$ test, though the denominator is slightly different.
If you run through the (trivial) algebra, the numerator reduces to ($x_\epsilon - x_o)^2$, which is just like the $\chi^2$ test's numerator of $(N_{\textrm{expected}} - N_{\textrm{observed}})^2$. The denominator for a $\chi^2$ test is normally just the expected value ($x_\epsilon$ in your notation). Here, they appear to be adjusting the expected value for each candidate according to its prevalence in their entire corpus. I can see why you'd want to do this pragmatically, but it does mean that you can no longer treat the result as an actual $\chi^2$ value (e.g., for looking it up on a table).
If you didn't want to call it a "distictive number", I suspect you might get away with calling it a "modified $\chi^2$ value" or something like that--I'm not sure it has another name.


Evaluating the long-run component of time-series

Question: Consider the following time-series process
$$y_{t+1}=y_{t}-x_t+\epsilon_{t+1},$$
where $\epsilon_{t+1}\sim N(0,\sigma^2)$ (and i.i.d. over time) and $x_t$ is a stationary process. I am interested in forward solutions of $y_t$. Specifically, we can iterate this forward to obtain
$$y_t=\mathbb{E}_t\sum_{j=0}^{\infty}x_{t+s}+\lim_{s\rightarrow\infty}\mathbb{E}_ty_{t+s},$$
assuming $\mathbb{E}_ty_{t+s}$ is well-defined. How is the term $\lim_{s\rightarrow\infty}\mathbb{E}_ty_{t+s}$ typically evaluated? Also any references to related material are welcome.
Comment: This is a random walk with a deterministic drift, a very well known process. Lookup in interweb. You can re-write it as $\Delta y_t=-x_{t-1}+\varepsilon_t$.
Comment: @Aksakal, if $x_t$ is a stationary process, then generally the drift is stochastic, not deterministic, which might make it harder to find.
Comment: @Aksakal, check out the second paragraph, there it says $x_t$ is a stationary process. I did not mean estimation, I meant finding the related literature (poor formulation on my side).
Comment: @RichardHardy, he didn't say what is the process for $x_t$. also OP doesn't seem to be interested in estimation
Comment: @RichardHardy, right, but what is that process? If it's AR, then the whole thing can look like Kalman filter.
Comment: The explicitly stated question doesn't look useful, because the stationarity of $(x_t)$ implies all $x_t$ have a common expectation $\mu$ and the relation $$E[y_{t+1}]=E[y_t] - E[x_t] + E[\epsilon_{t+1}] = E[y_t]-\mu$$ inductively implies $E[y_{t+s}]=E[y_t]-s\mu$ for all $s.$ This is a standard arithmetic progression with constant difference $\mu.$ Either $\mu=0,$ in which case the limit obviously is $E[y_t],$ or else the sequence diverges.
Answer: As pointed out in the comments (hat tip to Aksakal and Richard Hardy), if you condition on the sequence $\mathbf{x} \equiv \{ x_t | t \in \mathbb{Z} \}$ then the sequence of interest is a random walk with with this conditioning sequence giving drift terms.  You can write your model in the form of an adjusted random walk as:
$$\Delta y_t = -x_{t-1} + \epsilon_t
\quad \quad \quad \quad \quad
\epsilon_t \sim \text{IID N}(0, \sigma^2).$$
Now, if $\mathbf{x}$ is even weakly stationary (you stipulate in your question that it is stationary) then you must have a common mean $\mathbb{E}(x_t) = \mu$ so you get $\mathbb{E}(\Delta y_t) = -\mu$, which then gives $\mathbb{E}(y_{s+t}) = \mathbb{E}(y_s) - t \mu$.  The limiting term of interest to you is zero if $\mu=0$ and it diverges if $\mu \neq 0$.

Typically, we would not try to write a random walk in the form you are using, since the limit you are trying to use as a reference point usually diverges.  Instead we would write the value of the time-series relative to a reference point at an arbitrary "starting time".  Using the starting point at time $s$ we get the equation:
$$y_{s+t}
= y_s + \sum_{i=1}^t \Delta y_{s+i}
= y_s - \sum_{i=0}^{t-1} x_{s+i} + \sum_{i=1}^t \epsilon_{s+i},$$
which gives the conditional distribution:
$$y_{s+t} | y_s, \mathbf{x}
\sim \text{N} \bigg( y_s - \sum_{i=0}^{t-1} x_{s+i}, \ t \sigma^2 \bigg).$$
If you are willing to stipulate a joint distribution for the values in the sequence $\mathbf{x}$ you can then use the law of total probability to find the conditional distribution of $y_{s+t} | y_s$.


How to get data in between time intervals

Question: Here is my table
T_idx          T_Tag         T_Date
1              x             2014-03-15 23:58:00.000
2              y             2014-03-15 23:57:00.000
.               .                  .
.
.               .                  .
.
555            xy            2014-03-15 5:10:00.000

From the above table,  I want to see the data in between 5:30 AM to 6:30 AM every day
Could you please any one suggest me the query to get the data.
Answer: You can do it this way in SQL Server 2005:
select * from mytable
where convert(datetime, convert(char(5), T_Date, 108)) >= '5:30'
and convert(datetime, convert(char(5), T_Date, 108)) <= '6:30'

In SQL Server 2008 and above, you can simply cast it to time data type:
select * from mytable
where convert(time, T_Date) >= '5:30'
and convert(time, T_Date) <= '6:30'

Comment: yes it did it correctly !!!! thank you very much !!! i will create a new question for .BAT file problem.
Comment: created '.Bat' by using above code and running schedule task (Control panel) everyday but the file running continuously even after execution of result. Please find the below code in the bat file                                              sqlcmd -q "Select top 1000 from my table where convert(datetime, convert(char(5), T_Date, 108)) >= '5:30'
and convert(datetime, convert(char(5), T_Date, 108)) <= '6:30' order by T_Date DESC" -oF:\export\export.txt -h-1-s";" exit                                   i need to stop ".BAT" file execution after completion of above task, help me to stop in auto
Comment: @venkat Did it select the records correctly? On Stack Overflow, you should ask one problem in one question. You will be better off to create a new question for your .bat file problem.
Answer: Try this
SET @start_date = DATEADD(minutes,30,DATEADD(hour, 5, DATEDIFF(DAY, 2, GETDATE())))
SET @end_date = DATEADD(hour, -1, @start_date)

SELECT
    T_idx, T_Tag
FROM
    YourTable
WHERE
    T_Date BETWEEN @start_date AND @end_date


Oracle SQL Data between two Dates

Question: I'm looking at some SQL and trying to understand what it's trying to do. I was told it returns data between yesterday at midnight and today. Can someone translate the follow excerpt into plain English for me?
SELECT ...
FROM ...
WHERE CREATEDATE >=TO_DATE(TRUNC(SYSDATE-1) || ' 00:00:00', 'DD-MON-YY HH24:MI:SS')
AND CREATEDATE <=TO_DATE(TRUNC(SYSDATE-1) || ' 23:59:59', 'DD-MON-YY HH24:MI:SS')

This doesn't seem to work unless I change the bottom line to:
AND CREATEDATE <=TO_DATE(TRUNC(SYSDATE) || ' 23:59:59', 'DD-MON-YY HH24:MI:SS')

Any help with understanding this code will be appreciated.
Comment: The oracle documentation will tell you what each function does.
Comment: And if CREATEDATE is declared as VARCHAR and not DATE, Sister Mary Stigmata should strike their head with the ruler too.
Comment: I lol'd. Luckily for the author of this piece of SQL, CREATEDATE is indeed of type DATE.
Comment: Apparently, someone deleted my first comment. I suspect it must have been  someone who doesn't appreciate a reference to a scene in a 1980 film where the characters played by John Belushi and Dan Akroyd visit "the penguin" at the orphanage.
Answer: The predicates look way more complicated than they need to be.
Why wouldn't this return the result you are looking to return?
   WHERE CREATEDATE >= TRUNC(SYSDATE-1)
     AND CREATEDATE <  TRUNC(SYSDATE)

To explain that in "plain english", all three of the expressions returned by this SELECT statement:
 SELECT SYSDATE
      , TRUNC(SYSDATE)
      , TRUNC(SYSDATE-1)
   FROM DUAL

return DATE values (values that are of Oracle datatype DATE).
  -------------------  -------------------  -------------------
  2016-04-16 13:59:26  2016-04-16 00:00:00  2016-04-15 00:00:00

What we're not seeing is the datatype of CREATEDATE. Obviously, we expect it to be defined as DATE.  But if you've declared it as VARCHAR and are storing strings in format like  '16-APR-2016 13:59:26' then "doesn't seem to work unless" issue you are observing is just the tip of an iceberg.
(The behavior you are observing can easily be explained if CREATEDATE is declared as VARCHAR rather than DATE.)

If your SQL is working as it is written, it's dependent on the current setting of NLS_DATE_FORMAT.  That is, your SQL could be easily broken with a relataively innocuous statement, such as:
 ALTER SESSION SET NLS_DATE_FORMAT='YYYY-MM-DD' ;

A rundown of some of the components of the expressions in your current query...

SYSDATE returns the current date and time as a DATE
SYSDATE-1  subtracts 1 day from the current date and time and returns a DATE
TRUNC(<dateexpr>) "lops off" the time component from a DATE value, returning just the date portion with time set to midnight
||  is the string concatenation operator

(NOTE: performing string concatenation with a DATE expression requires Oracle to perform an implicit TO_CHAR conversion. Oracle use NLS_DATE_FORMAT as the default format model.)

' single quotes enclose string literals

The second argument of the TO_DATE function is a format model.

DD is two digit day  (e.g. 07 or 16)
MON is three letter abbreviation for the month
YY  is two character representation of the year, with implied century  (
HH24 is two digit hour (24 hour clock),  00 thru 23
MI is two digit minutes,  00 thru 59
SS is two digit seconds,  00 thru 59

(NOTE: Didn't we already fix the Y2K problem? Why are we re-creating it?)

I think the most important things to understand about the current SQL: It's using expressions that are more convoluted than is required.  And I see the expressions as being broken in three ways:

dependent on NLS_DATE_FORMAT for the implicit TO_CHAR function to appropriately match the explicit format model in the the TO_DATE function
no excuse for using a two character year where we could easily use four digit year. Especially when there's no need to convert DATE values to strings in the first place.
using a <= comparison rather than a < comparison, depending on the maximum precision of a datetime type to be one second, when we can just as easily specify "less than" midnight of the following day, with a pattern that handles fractional seconds.

If CREATEDATE is declared as VARCHAR, it's broken in another way... the comparisons are being performed as string comparisons. There's an implicit TO_CHAR conversion for the expressions on the right side of the comparisons. And those conversions are (again) dependent on NLS_DATE_FORMAT setting. With the age-old Oracle default setting of DD-MON-YY, the string comparisons will work in a sense that it's not invalid syntax, but in terms of returning date values that are between two other date values, those comparisons are broken.
Comment: Thanks for your thorough answer. This helped quite a bit.
Answer: So what's going on is kind of weird.
The conversions here are a bit confusing, but let's dig into it.
TRUNC(SYSDATE-1) is translated to a VARCHAR2 in this case, and based on the default NLS parameters, is translated to the date of yesterday.
Today it's 4/18/2016, so it would just return the string '17-APR-16' (based on the default NLS format).
Next, you concatenate to this string, the "time" string - 00:00:00.
this builds the string '17-APR-16 00:00:00' - midnight of yesterday.
This is wrapped up in "To_date" with a format of 'DD-MON-YY HH24:MI:SS' which makes it an actual date (the dataDATE).
The second date which is constructed is Yesterday's last minute - '17-APR-16 23:59:59' ...
So you are looking for all the records which were created yesterday in this query.
It's a bit confusing since the "TRUNC" of a date returns a date, but the concatenation to a string forces an implicit conversion.
Let me know if you have more questions about what's going in there.
P.S. I would recommend to rewrite the query with only dates, since the query will fail with different NLS settings...
Comment: Thank you. I wish I could select two correct answers, as this was very helpful as well.

Oracle SQL Data between two Dates


Nested Chaning promise response getting undefined in Controller by using UI Route resolve

Question: for past 3 days , i have struggling in getting a value from nested service through controller,
I have a service 1 call and pass the service 1 call to service 2 and getting a response and pass to controller,In controller , i am getting undefined.
So when i pass a single response call , that means service1 call , getting a value in controller by using Ui route resolve.
What wrong here ?
This is my factory call.
app.factory('LogHomService', function (Service1, Service2)
{
    var MyService = function (data)
    {

   Service1.log("user", encodeURIComponent("ad"))
        .then(function(response) {
          var FullUrl = response.strURL;
          var objs = response.products; // getting the response here

         Service2.pageLoad(objs)
            .then(function(response) {
               var homeScreen = response; // getting the response here
               return homeScreen;

                        });
                     });

        };

    return {

            MyService:  MyService
        }
});

Route call:
.state('home.prod', {
  url: '/product',
  views: {
    '@': {
      templateUrl: baseUrl + 'home/product',
      controller: 'productController'
    }
  },
  resolve: {
    param2: function(LogHomService) {
      return LogHomService.MyService();
    }
  }
})

Controller:
var productController = function ($scope, $rootScope, $state, $stateParams,param2)
{
       console.log(param2); // getting undefined
}
productController.$inject = ['$scope', '$rootScope', '$state','$stateParams','param2');

Note:
When I return a single response getting a value in controller which means return a service 1 call getting response.
When i tried to return a service2 call getting undefined.
This is my factory call.
app.factory('LogHomService', function (Service1, Service2)
{
    var MyService = function (data)
    {

   Service1.log("user", encodeURIComponent("ad"))
        .then(function(response) {
          var FullUrl = response.strURL;
          var objs = response.products; // getting the response here

        return objs;
            });
        };

    return {

            MyService:  MyService
        }
});

Comment: I don't think you should directly call the service in the resolve, you have: `return LogHomService.MyService()`, try `return LogHomService.MyService`
Comment: thanks,Now in params getting  function call MyService there, how can i get the second service response data? in param2 in controller?
Comment: Store the data that gets loaded in the request in the factory itself so that it will be there when it gets resolved.
Answer: In response to your question in the comments, in order to access the data in the service in your controller, you could do something like this:
app.factory('LogHomService', function (Service1, Service2) {
   var service = {}
   service.myMethod = function (data) {
     Service1.log("user", encodeURIComponent("ad"))
        .then(function(response) {
          var FullUrl = response.strURL;
          //at this point, you will have access to LogHomService.objs
          service.objs = response.products;
          return service.objs;
         });
      };

    return service
});

Comment: I have tried your solution, In controller console.log(param2) when debugging its showing function LogHomeService.myMethod(data) in the data showing this code factory code not return a response value. something went wrong why its showing script instead of response in controller  param2
Comment: So i tried simple return string  in factory , gets in controller `app.factory('LogHome', function (Service1, Service2) {
    var service = {};
    service.MyService = function (response) {

    return "HelloWorld"

    };
    return service;
});` its working when i use the function call in resove
`resolve: {
    param2: function(LogHomService) {
      return LogHomService.MyService();
    }` when i tried to give this return LogHomService.MyService return function.
Comment: So what data are you trying to get into the controller via the resolve?
Comment: Thanks man for your replies at last this code is working with your latest factory code
resolve: {
    param2: function(LogHomService) {
      return LogHomService.MyService();
    }
Comment: @reptilicius if you know pls help me to this issue http://stackoverflow.com/questions/37994004/how-to-form-the-query-string-in-web-address-url-in-angular-state-router-by-using
Answer: This line:
return LogHomService.MyService();

will always return null because MyService function returns nothing.
Here is a purposed fix:
var MyService = function (){
 return Service1.log("user", encodeURIComponent("ad"))
    .then(function(response) {
      var FullUrl = response.strURL;
      var objs = response.products;
      return Service2.pageLoad(objs);
    };
}

I've also cleared some unnecessary stuff.
Answer: Service2 object response from the controller,In controller getting Function call when i use return LogHomService.MyService; if i use return LogHomService.MyService(); shows undefined. i will attached the screenshot below.
But in Service response have values , Don't know why.
When I click the data , its shows factory code.


Delete Cascade with Script

Question: I have 3 tables,which are not created with the ON DELETE CASCADE option, nor is it an option to create them as such.
I may need to delete from all three tables in succession.  Is there a way to do this using only the promotion_id as a key?  Because I need to delete in reverse order, the promotion_id is gone by the time I get to the dependent tables.
I am thinking that the only way to do this is to SELECT the keys of the 3 tables using a JOIN, and then use them individually.  But it would be nice if there was a pure SQL solution to it.
I am using JDBC, Spring, and Oracle.  Thanks.
create table test_rates (
      rate_id varchar2(10) primary key,
      rate number
    );
create table test_offers (
  offer_id varchar2(10) primary key ,
  rate_id varchar2(10),
  foreign key (rate_id) references test_rates (rate_id)
);

create table test_promotions (
  promotion_id varchar2(10) primary key ,
  offer_id varchar2(10),
  foreign key (offer_id) references test_offers (offer_id)
);

insert into test_rates (rate_id,rate) values (1,199);
insert into test_offers (offer_id,rate_id) values (11,1);
insert into test_promotions (promotion_id,offer_id) values (21,11);

commit;

delete from test_promotions where promotion_id = 21;

delete from test_offers where offer_id in (select offer_id from test_promotions where promotion_id = 1);  -- key is gone by now

Answer: In the common case, when there are N promotions (N>1) for a single offer, it wouldn't make sense to delete the offer if one promotion only is deleted. You would end up with orphaned promotions.
If you want to delete a rate, it would make sense to start with deleting all children promotions then all children offers then delete the rate. In that case though, the rate_id could be used along the way.
If you delete a child record, there's no need to delete the parent record unless of course this is a requirement, in which case start with looking for the parent id and see above.

Delete Cascade with Script