Bounded differentiation operator

Question: Is there an example of a normed space $X$, $\dim X=\infty$ such that the differentiation operator $T=\frac{d}{dx}$ is bounded, meaning that $T \in B(X)$ ?
Comment: $X=\{0\}$ comes to mind.
Comment: Slightly less trivial: any finite dimensional space of differentiable functions as the space of all polynomials of degree $\leq n$ for some $n\in\mathbb{N}$.
Comment: Oh, of course, if $\dim X < \infty$, then every operator is bounded. But I was looking for an example in the infinite dimensional case. (So, I have now added the dimension $=\infty$ condition in the question.)
Answer: Let $X$ be the set of all functions of the form
$$
     \frac{1}{\sqrt{2\pi}}\int_{-R}^{R}f(s)e^{-isx}ds, \;\; f \in L^2[-R,R].
$$
This is a linear space over $\mathbb{C}$. You can use the $L^2(\mathbb{R})$ norm on $X$. By the Plancherel Theorem,
$$
          \left\|\frac{1}{\sqrt{2\pi}}\int_{-R}^{R}f(s)e^{-isx}ds\right\|=\|f\|_{L^2[-R,R]}.
$$
This space $X$ is an infinite-dimensional Hilbert space because it is unitarily equivalent to $L^2[-R,R]$.
The functions in $X$ are infinitely differentiable, with
\begin{align}
       \left\|\frac{d}{dx}\frac{1}{\sqrt{2\pi}}\int_{-R}^{R}f(s)e^{-isx}ds\right\|
      & = \left\|\frac{1}{\sqrt{2\pi}}\int_{-R}^{R}(-is)f(s)e^{-isx}ds\right\| \\
      & = \left(\int_{-R}^{R}s^2|f(s)|^2ds\right)^{1/2}\\
      & \le R\left(\int_{-R}^{R}|f(s)|^2ds\right)^{1/2}\\
   & =R\left\|\frac{1}{\sqrt{2\pi}}\int_{-R}^{R}f(s)e^{-isx}ds\right\|
\end{align}
So the differentiation operator is bounded on $X$ with a bound of $R$.
Comment: $X$ is complete, right?
Comment: @CameronWilliams : Yes, it is unitarily equivalent to $L^2[-R,R]$ by Plancherel's Theorem. This is a spectral projection onto a bounded part of the spectrum of the differentiation operator. :)
Comment: I somehow had completely missed that remark in your post. My bad!
Comment: @TrialAndError: Thanks! Indeed, the Fourier transform changes the roles of the differentiation and multiplication operators.
Comment: @Eeyore : If you like the answer, you can select the checkmark and/or accept it has an answer. By the way, this type of technique works or every unbounded selfadjoint operator. The idea comes from the Spectral Theorem.
Answer: Another example: Let $I\subset\mathbb{R}$ be an interval and $X=\{f\in C^\infty(I)\mid \sup_{n\geq 0}\|f^{(n)}\|_\infty<\infty\}$ endowed with the norm $\|f\|_X=\sup_{n\geq 0}\|f^{(n)}\|_\infty$. Then $\|f'\|_X=\sup_{n\geq 1}\|f^{(n)}\|_\infty\leq \|f\|_X$. If $I$ is bounded, then $X$ contains all polynomials, so it's certainly infinite-dimensional.
Of course, this can be done more generally: Let $Y$ be a normed space and $T\colon D(T)\to Y$ a linear operator defined on a subspace $D(T)\subset Y$. Let $X=\{u\in\bigcap_{n\geq 0} D(T^n)\mid \sup_{n\geq 0}\|T^n u\|_Y<\infty\}$ with norm $\|u\|_X=\sup_{n\geq 0}\|T^n u\|_Y$. Then $T\colon X\to X$ is bounded. If $X$ is infinite-dimensional depends on the operator $T$.
Remark: As usual, $D(T^n)$ is defined recursively by $D(T^{n+1})=\{u\in D(T)\mid Tu\in D(T^n)\}$.
Comment: If $f\in\mathcal{D}(\mathbb{R})$, then every derivative of $f$ is bounded, but they are not necessarily uniformly bounded. So $\mathcal{D}(\mathbb{R})$ is not contained in $X$.
Comment: Thanks! But did you mean that $f \in C^\infty(I)$  ?
Comment: @Eeyore: You're right. I corrected it.
Comment: But can we take $X$ as the set of smooth functions on $R$ rather than on an interval?
Comment: Yes. In this case, all functions of the form $\sin(\alpha\,\cdot)$ with $|\alpha|\leq 1$ are contained in $X$, and they form an infinite-dimensional vector space.
Comment: I don't understand something here. Isn't the space of test functions ${\mathcal D}({\mathbb R})$ a subspace of $C^\infty({\mathbb R})$?  Then does it mean that $||f||_X$ makes ${\mathcal D}({\mathbb R})$ a normed space?
Comment: @MaoWao In what reference could I find that space with said norm?
Comment: @eraldcoil I don't know.

Bounded differentiation operator


AngularJS - access "element" inside scope.$watch callback function

Question: For the following fiddle https://jsfiddle.net/qcuennL5/, I want to access "element" inside scope.$watch('$select.isOpened', ...). How can I do it?
scope.$watch('$select.isOpened', function(isOpened) {

if(isOpened) {
    //Don't have access to 'element'. Hacked with $('...')
        $('div.dropdown').show();
    } else {
        $('div.dropdown').hide();
}

Comment: You have it there as `element` parameter. Just use it.
Answer: You have the access to element parameter.
From the chrome debugger, we won't be able to check the closure properties if the property being checked is not used inside the function being executed.
Console statements will print the value properly.
Not sure if this is a chrome bug.
Comment: Vinay K, you don't have access to element inside scope.$watch('$select.isOpened', ...). Just put a breakpoint inside to see.
Comment: with debugger it may not show, try console.log(element)
Comment: @cosmi.nu, please check the console logs in this fiddle : https://jsfiddle.net/qcuennL5/1/
Comment: Vinay K, this is correct. When I use console.log(element), I have access to it. Why is this happening? Also please modify your original answer, so that I can vote your answer as useful. Thanks!
Answer: You don't need to use jQuery or watch any objects on the scope.
Just use the ng-show directive like this ...
ng-show="$select.isOpened"

JS/TEMPLATE
template: '
' +
                '
{{title}}
' +
                '

' +
                '
This is a dropdown!
' +
          '
'

Also remove the display property from div.dropdownin your CSS
JSFIDDLE
Using $watch
scope.$watch('$select.isOpened', function (isOpened) {
    scope.isOpened =   isOpened;  // assign isOpened to new variable on the scope.

    // Stick the rest of your logic here
});

HTML
'
This is a dropdown!
'

Comment: Using `ng-show` is the "angular way" but if you don't mind including jQuery then that's ok. You can still have the `$watch` logic in there and also use the `ng-show` directive.
Comment: dcodesmith, using `ng-show` or not using it is not the real problem inside the code. The real problem is that if you debug my original fiddle and put a breakpoint inside `scope.$watch(...)`, you'll see that `element` is undefined. Also, as Vinay K suggested, if you simply use it (`console.log(element)`) and not trying to evaluate it in the console, you'll have access to `element`. Hope that now you understand what was the real problem in the code.


Weak lower semicontinuity property of a bounded, coercive and linear operator

Question: Let $A\colon V \to V^*$ be a bounded linear coercive operator on a Hilbert space $V$.
Does it follow that for if $u_n \rightharpoonup u$ in $V$ (weak convergence) then
$$\langle Au, u \rangle \leq \liminf \langle Au_n, u_n \rangle?$$
This is somehow related to weak lower semicontinuity of norms..?
Answer: By coercivity:
$$0\le\langle A(u_n-u),u_n-u\rangle = \langle A(u_n),u_n\rangle-\langle A(u_n),u\rangle-\langle A(u),u_n\rangle+\langle A(u),u\rangle$$
So:
$$\langle A(u_n),u\rangle+\langle A(u),u_n\rangle-\langle A(u),u\rangle\le\langle A(u_n),u_n\rangle.$$
Now, $A$ is continuous, so by $u_n\rightharpoonup u $ it follows that $\langle A(u_n),u \rangle  \rightarrow \langle A(u),u\rangle$ and $\langle A(u),u_n\rangle\rightarrow \langle A(u),u\rangle$. Then:
$$\langle A(u_n),u\rangle+\langle A(u),u_n\rangle-\langle A(u),u\rangle\rightarrow \langle A(u),u\rangle, n\rightarrow\infty.$$
Then:
$$\langle A(u),u\rangle=\liminf_{n\rightarrow\infty}\left(\langle A(u_n),u\rangle+\langle A(u),u_n\rangle-\langle A(u),u\rangle\right) \le \liminf_{n\rightarrow\infty}\langle A(u_n),u_n\rangle$$


Inter-arrival times of Weibull distribution

Question: How can I generate inter-arrival times from a Weibull distribution, p.d.f. $f(t)=\frac{\beta}{\alpha}\big(\frac{t}{\alpha}\big)^{\beta-1}\exp\big(-\frac{t}{\alpha}\big)^\beta$, where $\beta$ is the shape parameter and $\alpha$ is the scale parameter?
Answer: The Weibull is a powered exponential distribution.  Its survival function
$$q = 1 - F(x) = e^{(-x/\alpha)^\beta}$$
therefore has a particularly tractable form: it is readily inverted to give
$$x = \alpha(-\log(q))^{1/\beta}.$$
You therefore need only generate $q$ uniformly in the interval $(0,1)$ and compute $x$.  Here's an R example:
alpha <- 2
beta <- 3
n <- 1e5                                 # Sample size
x <- alpha * (-log(runif(n))) ^ (1/beta) # Sample
hist(x, freq=FALSE, breaks=50)
curve(dweibull(x, beta, alpha), add=TRUE, col="Red", lwd=2)

The work is all done on a single line labeled "Sample".  The output is a histogram on which the Weibull density function is plotted.  The agreement in this simulation is excellent.

(R of course offers a built-in generator rweibull.  The point of this answer is to show how it might work and to provide enough details to enable a generator to be implemented in any language.)


TypeError: SparseArray does not support item assignment via setitem

Question: Given:
import pandas as pd
print(pd.__version__) # '2.1.0'
df=pd.DataFrame([[1., 0., 1.5], [0., 2., 0.]], dtype=pd.SparseDtype("float32"))

I'd like to assign custom values in my sliced pandas sparse dataframe, so I do the following:
df_sliced=df.iloc[0].copy() # OK
df_sliced.iloc[:]=0 # ERROR

I get the following error:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/CSC_CONTAINER/miniconda/envs/env1/lib/python3.9/site-packages/pandas/core/indexing.py", line 885, in __setitem__
    iloc._setitem_with_indexer(indexer, value, self.name)
  File "/CSC_CONTAINER/miniconda/envs/env1/lib/python3.9/site-packages/pandas/core/indexing.py", line 1895, in _setitem_with_indexer
    self._setitem_single_block(indexer, value, name)
  File "/CSC_CONTAINER/miniconda/envs/env1/lib/python3.9/site-packages/pandas/core/indexing.py", line 2138, in _setitem_single_block
    self.obj._mgr = self.obj._mgr.setitem(indexer=indexer, value=value)
  File "/CSC_CONTAINER/miniconda/envs/env1/lib/python3.9/site-packages/pandas/core/internals/managers.py", line 399, in setitem
    return self.apply("setitem", indexer=indexer, value=value)
  File "/CSC_CONTAINER/miniconda/envs/env1/lib/python3.9/site-packages/pandas/core/internals/managers.py", line 354, in apply
    applied = getattr(b, f)(**kwargs)
  File "/CSC_CONTAINER/miniconda/envs/env1/lib/python3.9/site-packages/pandas/core/internals/blocks.py", line 1758, in setitem
    values[indexer] = value
  File "/CSC_CONTAINER/miniconda/envs/env1/lib/python3.9/site-packages/pandas/core/arrays/sparse/array.py", line 583, in __setitem__
    raise TypeError(msg)
TypeError: SparseArray does not support item assignment via setitem

What's an efficient way (workaround) to assign values in SparseDtype in Pandas?
Comment: @Corralien, your link is about `scipy.sparse`.  Here it's the (cutrrent) pandas version of SparseArray.  Still I'm not surprised that there indexing limitations in the pandas version.
Comment: It's not possible: [Assign a the value of a sparse matrix to numpy array](https://stackoverflow.com/q/48146072/15239951)
Answer: The error traceback with more context is:
SparseArray.__setitem__(self, key, value)
    581 def __setitem__(self, key, value):
    582     # I suppose we could allow setting of non-fill_value elements.
    583     # TODO(SparseArray.__setitem__): remove special cases in
    584     # ExtensionBlock.where
    585     msg = "SparseArray does not support item assignment via setitem"
--> 586     raise TypeError(msg)

This tells me that SparseArray is still under development, and that, for now, setting values, is not working.  I know, from working with scipy.sparse, that setting sparse values takes more work, especially if fill values might be changed to non-fill.
scipy.sparse.coo_matrix format doesn't implement indexing at all - get or set.  csr_matrix, which is used for most calculations, does implement indexing, but gives an efficiency warning with the set.  Potentially set can change the 'sparsity', the mix of zero ('fill') and non-zero values, and hence the underlying indexing.


How to view the city/state/country in google analytice ecommerce tracking?

Question: I want to use google analytice ecommerce for some requirements.
So, I used the following code snippet from google.
<code>_gaq.push(['_setAccount', 'UA-XXXXX-X']);
_gaq.push(['_trackPageview']);
_gaq.push(['_addTrans',
   '1234',           // order ID - required
   'Womens Apparel', // affiliation or store name
   '28.28',          // total - required
   '1.29',           // tax
   '15.00',          // shipping
   'San Jose',       // city
   'California',     // state or province
   'USA'             // country
]);
_gaq.push(['_addItem',
   '1234',           // order ID - necessary to associate item with transaction
   'DD44',           // SKU/code - required
   'T-Shirt',        // product name
   'Olive Medium',   // category or variation
   '11.99',          // unit price - required
   '1'               // quantity - required
]);
_gaq.push(['_trackTrans']);
</code>
So with this code sample my transactions are getting tracked.
But in my google analytics profile, I'm not seeing the city, state, country. Though other details like order_id, shipping, etc SKU are getting tracked.
Please let me know if you have any idea on this.
Thanks,
Uttam
Answer:
All other variables within the addTrans method are optional.

The affiliate field is not required, and was removed from the Google
  Analytics Ecommerce reports. You can still use the affiliate field for
  custom reports and filtering.
Tax and shipping appear in the transactions report if you have access
  to those variables.
The city, state, and country are currently not being used by Google
  Analytics, but the information is still being collected. You can
  however use these fields within the profile filters if you have a use
  for them.

Source: http://www.roirevolution.com/blog/2009/05/stressing_about_your_ga_ecommerce.php


Weblogic 126.96.36.199 from Moxy to Jackson

Question: I would like to change the JSON parser from Moxy to Jackson, and I have followed the shared library approach, but without any result, Moxy is still used.
Note: the shared library is not necessary!!!
The shared library
I have created a maven project with the following dependencies and descriptors.
pom.xml
 <properties>
    <jackson.annotations.release>2.8.6</jackson.annotations.release>
    <jersey.version>2.22.4</jersey.version>
 </properties>

 <dependencies>
    <dependency>
        <groupId>com.fasterxml.jackson.module</groupId>
        <artifactId>jackson-module-jaxb-annotations</artifactId>
        <version>${jackson.annotations.release}</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.jaxrs</groupId>
        <artifactId>jackson-jaxrs-json-provider</artifactId>
        <version>${jackson.annotations.release}</version>
    </dependency>

    <dependency>
        <groupId>org.glassfish.jersey.containers</groupId>
        <artifactId>jersey-container-servlet</artifactId>
        <version>${jersey.version}</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.core</groupId>
        <artifactId>jersey-client</artifactId>
        <version>${jersey.version}</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-multipart</artifactId>
        <version>${jersey.version}</version>
        <type>jar</type>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-json-jackson</artifactId>
        <version>${jersey.version}</version>
    </dependency>
</dependency>

weblogic.xml
 <container-descriptor>
    <prefer-application-packages>

        <package-name>javax.ws.rs.*</package-name>

        <package-name>com.google.common.*</package-name>

        <package-name>org.glassfish.jersey.*</package-name>
        <package-name>jersey.repackaged.*</package-name>

        <package-name>org.jvnet.hk2.*</package-name>
        <package-name>org.jvnet.hk2.tiger_types.*</package-name>
        <package-name>org.glassfish.hk2.*</package-name>
        <package-name>javassist.*</package-name>

        <package-name>com.fasterxml.jackson.*</package-name>

        <package-name>weblogic.jaxrs.api.client.*</package-name>
        <package-name>weblogic.jaxrs.internal.api.client.*</package-name>
        <package-name>weblogic.jaxrs.dispatch.*</package-name>
        <package-name>weblogic.jaxrs.monitoring.util.*</package-name>
    </prefer-application-packages>
</container-descriptor>

MANIFEST.MF
Manifest-Version: 1.0
Implementation-Title: Jackson Weblogic
Implementation-Version: 1.0
Specification-Title: Jackson Weblogic
Extension-Name: jackson-weblogic
Specification-Version: 1.0

Web Application
I add the web.xml and the weblogic.xml.
web.xml
<servlet>
    <servlet-name>com.dummy.MyApplication</servlet-name>
        <init-param>
            <param-name>jersey.config.server.provider.classnames</param-name>
            <param-value>com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider</param-value>
        </init-param>
</servlet>

<servlet-mapping>
    <servlet-name>com.dummy.MyApplication</servlet-name>
    <url-pattern>/api/*</url-pattern>
</servlet-mapping>

weblogic.xml
<?xml version="1.0" encoding="UTF-8"?>
<weblogic-web-app xmlns="http://xmlns.oracle.com/weblogic/weblogic-web-app">
    <library-ref>
        <library-name>jstl</library-name>
        <specification-version>1.2</specification-version>
        <implementation-version>1.2</implementation-version>
        <exact-match>false</exact-match>
    </library-ref>
    <library-ref>
        <library-name>jackson-weblogic</library-name>
        <specification-version>1.0</specification-version>
        <exact-match>false</exact-match>
    </library-ref>
</weblogic-web-app>

Then I reference in the weblogic.xml the shared library, but Moxy is still used. Have I done something wrong?
Update: I have added the web.xml and the weblogic.xml of the web application.
Solution
I have checked the folder oracle_common\modules and I have found all the Jackson dependencies needed. So I have preferred to configure Jersey to disable the use of MOXy as follows:
import javax.ws.rs.core.Application;
public class MyApplication extends Application
{
    @Override
    public Map<String, Object> getProperties()
    {
        Map<String, Object> proprties = new HashMap<>();
        proprties.put("jersey.config.server.disableMoxyJson", true);

        return proprties;
    }
}

Pay attention:

that the method getProperties() comes with javax.ws.rs 2.0;
no specific shared library is necessary for Jackson, but just for jstl and jax-rs 2.0;
no info inside web.xml is required;
as reported by @abbas JAX-RS 2.0 comes by default with Weblogic 220.127.116.11.0 in my case I has a transitive dependency on javax.ws.rs:jsr311-api so the method getProperties() was not invoked.

Final weblogic.xml
<?xml version="1.0" encoding="UTF-8"?>
<weblogic-web-app xmlns="http://xmlns.oracle.com/weblogic/weblogic-web-app">

    <context-root>/web-app</context-root>
    <container-descriptor>
        <prefer-application-packages>
            <package-name>org.apache.commons.net.*</package-name>
        </prefer-application-packages>
    </container-descriptor>

    <library-ref>
        <library-name>jstl</library-name>
        <specification-version>1.2</specification-version>
        <implementation-version>1.2</implementation-version>
        <exact-match>false</exact-match>
    </library-ref>
</weblogic-web-app>

Comment: If both are on the classpath, MOXy will always win out, unless you explicitly register the `JacksonFeature`.
Comment: @peeskillet do you mean what I have added in the `web.xml`? or is it better to register the feature in a different way? Jax-rs 2.x uses SPI-based auto-registration so I have though it was not necessary the `web.xml` but even with it `weblogic` still uses `moxy`. Thanks for your time ;-)
Comment: @peeskillet thanks again, I think I have found another solution, I have tested in WildFly as well and it seems there are no drawbacks so far.
Comment: at least you do not need to library-ref for JAX-RS 2.0 because it is now part of Weblogic 12.2.1
Comment: @abbas the lib JAX-RS 2.0 is under the folder `wlserver\common\deployable-libraries` and as far as I have understood it has to be deployed otherwise the method `getProperties()`, part of specification 2.0, is not called. I suspect that Weblogic by default uses the old library.
Comment: Check this sample project which I created last night

https://github.com/esafzay/jax-rs-2-java-ee-6-weblogic-12.2.1
Comment: @abbas thanks a lot, you are right, it is not necessary to deploy the shared library JAX-RS 2.0, the issue on my side was to due to `swagger` having a dependency on `jsr311` and so loading wrong version, once I removed it everything was fine.
Answer: Mention JAX-RS 2.0 as a dependency in your pom.xml
<dependency>
    <groupId>javax.ws.rs</groupId>
    <artifactId>javax.ws.rs-api</artifactId>
    <version>2.0.1</version>
    <scope>provided</scope>
</dependency>

In WebLogic 12.2.1 you do not need to deploy it as a shared library.

Weblogic 12.2.1.3 from Moxy to Jackson


How to find the effective bandwidth correctly using statistics?

Question: I have done an experiment to find the effective n/w bandwidth.
The data I got in kbps is
223, 221, 510, 220, 471, 229, 222, 221, 220, 221
How can I find the effective bandwidth? Averaging gives 275.8. But if I have done only first 4 rounds then the average is 293.5. How can I find out a more reasonable value as the effective bandwidth. Or is averaging the correct way of doing this?
Comment: n/w = network? Isn't packet-transmission data usually long-tailed?
Comment: n/w = Network. Sorry for using the abbreviation. I have transmitted 1MB of data to the peer system. like that I computed the bandwidth
Answer: From what I can understand, I think you have the following options:

Sample more! n = 10 is hardly enough for drawing conclusions
If you don't/can't do "enough" sampling, you can always try to do some Monte Carlo type study with bootstrapping
Comment: So averaging is the most recommended way? Can I conclude like that?
Comment: I am not sure what you want to do would be an accurate measure of the bandwidth. The bandwidth represents how much COULD be transmitted down the connection and not how much actually gets transmitted. If you want to get a measure of average tranfer speed then yes, averaging would be the way to go. Regardless, I would prefer to supply mean, median and a std deviation together, then you summarize your data better


How to find the image cache url for images

Question: I want to get the url to a specific image from image cache. I have the image file name (my_image.jpg), file path (site/default/files/my_image.jpg). From this value I want to get the url to a certain image cache folder (sites/default/files/imagecache/240x135/my_image.jpg). I cannot use any drupal methods/modules to get this because I am using external scripts to directly access the back-end database, from where I can get the image name, actual image path, but couldn't find the table where the url to image cache is stored.
How can I do this?
Answer: You can use the imagecache_create_url() function:
$path = imagecache_create_url($presetname, $filepath);

$presetname: String specifying an ImageCache preset name.
$filepath: String specifying the path to the image file.
Comment: It allows other modules to alter the URL before it's finalised. Whether or not you need to re-implement that depends on what you've got installed really
Comment: @SayemAhmed No worries, the idea is you tick the answer that helped you the most. If there are other answers that also helped you can upvote them, or not, totally up to you :)
Comment: +1, yeah, it will work no doubt. The problem is, I want to get the url in a stand-alone php script. It has no connection whatsoever with the drupal modules. It's accessing the back-end database directly.
Comment: From the documentation that you've sent me, I see that they basically append the preset name with the filename. If this is the case, then probably I can build it myself. But I don't know what to do if the image is not in image cache.
Comment: Yes it should be pretty easy to reproduce that function outside of Drupal it's not particularly complicated
Comment: I can understand almost all parts of the function implementation, except the `drupal_alter('file_url', $altered_path)` bit. What does this do? How can I replace this in my script?
Comment: Your answer is really great! Only if I could accept more than one answer.......
Answer: You can always load Drupal API in your custom php
All you have to do is copy the code from your index.php to your custom one or write
/** bootstrap drupal **/
chdir("/path/to/drupal/site/htdocs");
require_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

Comment: That's missing at least one line...
Comment: @Clive What do you mean ? all we need is the first two lines of this file
[http://api.drupal.org/api/drupal/index.php/6]
Comment: That link is a 404...you're missing `define('DRUPAL_ROOT', getcwd());`, in my experience that's required
Comment: Only just noticed the '6' tag, maybe you don't need that line for D6. Definitely do for D7 though :)
Comment: Thank you very much, it's really helpful. I am accepting this one as accepted as this inclusion of drupal will allow me to do further manipulation in my scripts!
Answer: The way imagecache and drupal work is based upon the behavior that drupal is called into play only when a file is requested that doesn't actually exist.  For example, if a user requests
/sites/default/files/imagecache/WIDTHxHEIGHT/foo.jpg

and it doesn't exist, drupal is booted up and a menu handler is called within imagecache which grabs the original foo.jpg and applies the WIDTHxHEIGHT preset and then stores the file back in place.  Then the next time someone requests it, it does exist and the webserver happily sends it to the requesting user without getting drupal involved.
So... to your question, if you are using public files, eg:
/sites/default/files/foo.jpg

and have an imagecache preset of WIDTHxHEIGHT, the url of the file will be:
/sites/default/files/imagecache/WIDTHxHEIGHT/foo.jpg

eg, it is stuffing imagecache/PRESET_NAME after the basepath of your public file directory and before the file in question.  If you had an original file:
/sites/default/files/avatars/USERNAME/bar.jpg

it would turn into
/sites/default/files/imagecache/WIDTHxHEIGHT/avatars/USERNAME/bar.jpg

Hopefully you see the pattern emerging.  And thus nothing is needed to be kept in the database to do all of this.
Imagecache DOES however use permissions to allow/disallow users to use each specific preset, so, you can use them to stop users from requesting files that will never be used on your site by them manually surfing around to presets.
Hope this sheds some light on it all.
Comment: +1, thank you very much for your answer, it's really helpful! Only if I could accept more than one answer........


Fourier transform of $f(x) = [-i(x+i\epsilon)]^{-\alpha}$ for $\alpha>0$

Question: Let $\epsilon>0$ be a positive infinitesimal constant. What is the Fourier transform of $f(x) = [-i(x+i\epsilon)]^{-\alpha}$ for $\alpha>0$ (we always consider the principal branch); in other words, what is
$$\lim_{\epsilon\to 0^+} \int_{-\infty}^\infty f(x) e^{-ikx} dx?$$
The integral is understood as the improper Riemann integral. Mathematica says that the answer is
$$\frac{2\pi}{\Gamma(\alpha)} k^{\alpha-1} \theta(k),$$
where $\Gamma$ is the Gamma function and $\theta$ is the Heaviside function. How can I obtain this analytically?
Note: (1) The integral is easily seen to be zero for $k<0$, by using the residue theorem; closing the contour on the upper half plane, the function $f$ does not have any poles or branch cuts.
(2) If $\alpha$ is an integer, then the result for $k>0$ is again obtained from the residue theorem. For fractional $\alpha$, due to the branch cut of $f$ on the lower half plane, the residue theorem is not straightforward.
Comment: There is a branch point at $-i\varepsilon$.  How are you defining $f$?
Comment: Mathematica tells me the Fourier transform $\mathcal{F}_x\left[(-i x)^{-\alpha }\right](k)=\int\limits_{-\infty }^{\infty } (-i x)^{-\alpha}\, e^{-i k x} \, dx=\frac{2 \pi k^{\alpha-1}}{\Gamma (\alpha )}$ (assuming $k>0$) is only valid for $0<\Re(\alpha)<1$.
Comment: A very similar integral is in here somewhere: https://open.library.ubc.ca/soa/cIRcle/collections/ubctheses/24/items/1.0402359

Basically you use a square contour and you can determine it's either zero or an exponential depending on the sign. There's a math stack exchange question about this integral somewhere too.
Comment: @StevenClark The Fourier Transform exists as a distribution for all $\alpha \in \mathbb{C}$.
Answer: The function $f(z)=\frac1{(-i(z+i\varepsilon))^\alpha}$, with $\alpha>0$ and $\varepsilon>0$, is multivalued with a branch point at $z=-i\alpha$.
We choose to cut the plane from $z=-i\alpha$ along a ray on the imaginary axis.  Then, for $k>0$, we close the contour in the upper-half plane and find that
$$\int_{-\infty}^\infty \frac{e^{-ikx}}{(-i(x+i\varepsilon))^\alpha}\,dx=0\tag1$$
For $k<0$, we close the contour in the lower-half plane, deforming around the branch cut and find that for $\nu>0$
$$\int_{-\infty}^\infty \frac{e^{-ikx}}{(-i(x+i\varepsilon))^\alpha}\,dx=2\sin(\alpha \pi)e^{-ik\varepsilon}\int_{\nu}^\infty \frac{e^{-kt}}{t^\alpha}\,dy-e^{-k\varepsilon}\nu^{1-\alpha}\int_{-\pi}^\pi e^{\nu ke^{i\phi}}e^{i(1-\alpha)\phi}\,d\phi\tag2$$
Next, we let $\nu\to 0$.  To do this, we repeatedly integrate by parts ($\lfloor \alpha \rfloor$ times) the first integral on the right-hand side of $(2)$.  This is left as an exercise for the reader.
Comment: Sorry for a delayed response. I have a question on Eq. (2).

First, why one introduces $\nu>0$? What is the meaning of this parameter?
Second, I think the first term in the RHS of (2) is $2\sin(\alpha \pi) e^{-ik\epsilon} \int_\nu^\infty \frac{e^{-kt}}{t^\alpha} dt $. I think the substitution $ix=t$ is made.
Third, I cannot see how the last term in the RHS of (2) arises, and what $\phi$ means.
Comment: Good questions.  There is a branch point at $z=-i\varepsilon$.  We need to deform the contour around the branch point.  We do so with a circular contour of radius $\nu<\varepsilon$.   So the deformed contour is comprised of rays from $(1)$ $-i(\nu+\varepsilon)$ to $-i\infty$ to the right of the branch cut, $(2)$ $-i\infty$ to $-i(\nu+\varepsilon)$ to the left of the branch cut, and $(3)$ a circular contour with center at $-i\varepsilon$ and radius $\nu$ around the branch point.


How to read hrm polar files into R

Question: Is there any way to read a hrm file (hrm file) into R without ending in a super messy dataframe?
Answer: I finally have found the answer in the description of the RHRV package:
<code>library(RHRV) # loading RHRV package

hr.data <- CreateHRVData()
hr.data <- SetVerbose(hr.data, TRUE)
hr.data <- LoadBeatPolar(hr.data, "filepath/filename.hrm")
</code>

How to read hrm polar files into R


ERRO no INSTER MYSQL PHP PDO

Question: Estou tentando fazer um insert utilizando o PHP PDO, mas ele sempre está retornando um erro, que não estou sabendo resolver
<code>$insert = "INSERT INTO usuarios ('usuario', 'senha', 'telefone', 'email', 'tipo', 'status', 'nivel', 'hash') VALUES (:usuario, :senha, :telefone, :email, :tipo, :status, :nivel, :hash)";

    try{
        $result = $conexao->prepare($insert);
        $result->bindParam(':usuario', $usuario, PDO::PARAM_STR);
        $result->bindParam(':senha', $senha, PDO::PARAM_STR);
        $result->bindParam(':telefone', $telefone, PDO::PARAM_STR);
        $result->bindParam(':email', $email, PDO::PARAM_STR);
        $result->bindParam(':tipo', $tipo, PDO::PARAM_STR);
        $result->bindParam(':status', $status, PDO::PARAM_STR);
        $result->bindParam(':nivel', $nivel, PDO::PARAM_STR);
        $result->bindParam(':hash', $hash, PDO::PARAM_STR);
        $result->execute();
        $contar = $result->rowCount();
        if($contar>0){
            $ret['status'] = "OK";
        }else{
            $ret['status'] = "ERRO";
        }
    }catch(PDOException $e){
        echo $e;
    }
</code>
e está retornando o seguinte errro:
PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''usuario', 'senha', 'telefone', 'email', 'tipo', 'status', 'nivel', 'hash') VALU' at line 1 in /var/www/html/trocadex/src/php/cadastro.php:32 Stack trace: #0 /var/www/html/trocadex/src/php/cadastro.php(32): PDOStatement->execute() #1 {main}null
Answer: não precisa de aspas nas colunas "INSERT INTO usuarios (usuario, senha, telefone, email, tipo, status, nivel, hash) VALUES (:usuario, :senha, :telefone, :email, :tipo, :status, :nivel, :hash)"

ERRO no INSTER MYSQL PHP PDO


Real positive index Sobolev spaces are Hilbert spaces

Question: I'm trying to prove that, for $k\geq 0$, Sobolev spaces defined in this way:
$H^k(\mathbb{T})=\{f\in L^2(\mathbb{T}): \sum_{n=-\infty}^{+\infty}(1+n^2)^k|\hat{f}(n)|^2 < +\infty\}$
are Hilbert spaces over $\mathbb{C}$ with respect to the inner product:
$(f,g)=\sum_{n=-\infty}^{+\infty}(1+n^2)^k\hat{f}(n)\overline{\hat{g}(n)}$,
where $\hat{f}$ is the Fourier transform of $f$ in $\mathbb{T}=[-\pi, \pi)$.
I proved that $H^k(\mathbb{T})$ is a vector space over $\mathbb{C}$ $\forall k\geq 0$ and that is an inner product space. Now I need to prove that $H^k(\mathbb{T})$ is complete with respect to the distance induced by the norm $||\cdot||=(\cdot,\cdot)^{1/2}$.
So I considered a Cauchy sequence $\{f_m\}_{m\in\mathbb{N}}\subseteq H^k(\mathbb{T})$. This means in particular that, $\forall n\in\mathbb{Z}$, the sequence $\{\hat{f_m}(n)\}_{m\in\mathbb{N}}$ is a Cauchy sequence in $\mathbb{C}$, therefore it converges to some $g(n)\in\mathbb{C}$, because $\mathbb{C}$ is complete. So I defined
$f(x):=\sum_{n=-\infty}^{+\infty} g(n)e^{inx}$, $\forall x\in\mathbb{T}$.
I managed to prove that $\hat{f}(n)=g(n)$, $\forall n\in\mathbb{Z}$, but now I'm finding troubles in showing that $f\in H^k(\mathbb{T})$ and that $f_m\rightarrow f$ with respect to the norm in $H^k(\mathbb{T})$.
Is my idea correct? How could I proceed?
Comment: how do you know the definition of $f$ is valid? That is, how do you know the infinite sum converges? Moreover, how did you show that $\hat{f}(n) = g(n)$ for all $n \in \mathbb{Z}$?
Answer: I would personally take the $L^2$ route, to avoid issues I brought up in my above comment. Note that $(f_m)_m$ is Cauchy in $L^2$: for any $\epsilon > 0$ and for $m,l$ large enough, we have $$||f_m-f_l||_2^2 = \sum_{n=-\infty}^\infty |\widehat{f_m}-\widehat{f_l}|^2 \le \sum_{n=-\infty}^\infty (1+n^2)^k |\widehat{f_m}-\widehat{f_l}|^2 \le \epsilon.$$ Since we know $L^2$ is complete, let $f$ be the $L^2$ limit of the $f_m$'s. It remains to show $f \in H^k(\mathbb{T})$ and $f_m \to f$ in $H^k$. But these should just be some easy triangle inequality or Cauchy-Schwarz arguments.
Comment: You're right, I did a huge mistake in one inequality. Still I cannot show the rest... how can I be sure that the Fourier coefficients of $f$ decrease sufficiently fast in order to have $||f||$ finite?


Nuget Custom package Restore from URI on Build Server

Question: Could anyone suggest me the best way to restore custom Nuget packages on a build server after a TFS build definition is triggered.
Whether to pass the packagesource URI through nuget.config, or restore it using powershell
Answer: You could install your custom Nuget packages by right clicking the project in VS -- select Manage NuGet Packages, and check in the packages.config file.
Then, in your TFS build definition, add a NuGet Installar task before VS Build task to restore the packages.
Comment: I have added custom packages as package source in nuget.config file and also added the source in the nuget installer task in build definition. This worked as expected.


C# ListObject iterate through table besides for last row

Question: I have this current function that clears a row where column 2 value equals -1 while iterating through the table. The issue that I am having is that I don't want to check the last row in the table. How can I go about of doing this?
foreach (Excel.ListRow lr in xlWorkBook.Worksheets["Sheet1"].ListObjects["table1"].ListRows)
{
    CurrentRow = CurrentRow + 1;
    if (xlWorkBook.Worksheets["Sheet1"].ListObjects["table1"].Range[CurrentRow, 2].value == -1)
    {
        lr.Range.Clear();
        //CALL MoveEmUP
        //ListRow = ListRow - 1? I'd like to possibly do something like this.
    }

OLD VBA Code I'm trying to convert into C#
For CurrentRow = 1 To Tablesize
    If Lo.ListColumns("Column2").DataBodyRange(CurrentRow) = -1 Then
        Ros(CurrentRow).Range.Clear
        MoveEmUpOne Lo, CurrentRow, Tablesize
        Tablesize = Tablesize - 1 'table didn't really get smaller, but number of "real"rows decreased by 1
        CurrentRow = CurrentRow - 1 ' check this row again -- stuff from below might need cleard
    End If

So, I am trying to have it defined afterword "MoveEmUp"
 gets called.
Answer: Use for loop. Count property will return number of rows in your collection, you specified count-2 to have it from 0 to lastOne-1.
var listRowsValue = WorkBook.Worksheets["Sheet1"].ListObjects["table1"].ListRows;

for(int i=0; i < listRowsValue.Count - 2; i++)
{
    //do your stuff;

    var lr = listRowsValue[i];
}

Comment: is there way a way to define the subtraction from total table count below? I'll re-define my question so it makes more sense what I'm trying to achieve.
Comment: @Brandon you can do everything like in your foreach. The lr is the same li in foreach. So if you have a concept what to do in the foreach you can do it in the for lopp too.
Comment: Also stick with one question per post. If this is clear create new one with your another question.
Comment: Sorry that I described my question indirectly.


can music theory sabotage creativity

Question: when I started composing I didn't have any music theory background as I began learning I saw that I used intuitively many aspects of the way to compose like modulation etc...
but now as my studying is getting deeper I fear that when I will compose I will be influenced by the theory, no more able to play like a child daring and inventing compositions that sound nice. even now when I play an old song of mine and I see all of a sudden the scale I used I get sad knowing what it is and then I force my brain to forget it. don't want to lose this innocence of not knowing.
can some one understand me, can some one ease my fears, is there a way to get deeper without losing this innocence, is there a way that knowing music theory will even increase creativity ?
Comment: Unfortunately, I think this is either opinion based or too broad. Anything can potentially sabotage or inspire creativity, depending on the artist, situation, culture, genre, etc.
Comment: Knowledge of theory did not seem to stifle the creativity of Bach, Beethoven or Brahms, for starters - or Duke Ellington, Charles Mingus,  Thelonious Monk or Frank Zappa either, for that matter.
Comment: @Stinkfoot - Leo Fender was a radio repairer, who knew little about music. Although I guess he relied on his guitar playing mates for advice - he was not a player, apparently. But point taken.
Comment: @ToddWilcox - although, he's asking for our experiences on this issue, which, true, may be subjective, but could produce insight into the 'problem'.
Comment: Related: https://music.stackexchange.com/q/4899/28
Comment: @Stinkfoot - we'll never know. They might have been even greater without ! I'm certain the list could be matched from the other side, too.
Comment: @Tim - you cannot build a Strat, or a Steinway without advanced technology - nor can you write Art of the Fugue or Beethoven's 9th without knowledge of theory. Take it to the next step: We don't find anybody who's made anything _comparable_ to a Strat, or a Steinway without technology. Where is your comparable music without theory? It's not there. Fictional _alternative history_ is meaningless.
Comment: @Tim - I used the Strat and the Steinway only because they are musical examples. I could just as well have used the smartphone or the Hubble Telescope.
Answer: Several excellent answers have been posted about the general relationship of theory to creativity.
As to your situation in particular, it's entirely natural for you to feel the way you do because you are still at the beginning of your studies. You are dealing with a learning curve, which makes you feel constrained and encumbered.
That's only because it's still new material: Our brains have certain limitations regarding how much they can absorb and deal with at one time. If your mental resources are devoted to thinking about theory, naturally your creative energy will be diminished.
Once you get over the initial learning curve and become familiar and fluent with the fundamentals of theory, that will change. The theory will become instinctive - a natural part of your creative vocabulary. Then theory will become a tool to serve you, instead of an obstacle.
The stipulation is that you follow the advice given in some of the other answers, which perhaps could be distilled this way:
For musicians and composers (to exclude pedagogues and scholars) theory is a tool that helps you create music, not a goal unto itself - a "means", not an "end".

Bottom Line:

can some one understand me, can some one ease my fears, is there a way
  to get deeper without losing this innocence, is there a way that
  knowing music theory will even increase creativity ?

Not to worry: With the possible exception of a few very rare geniuses, everyone has to learn. Beethoven studied hard with several teachers when he was a teenager and young man, precisely because he was very aware of his boundless innate talent for composition, and knew he needed to learn the tools necessary to unlock it. He was never afraid of 'losing his innocence' - just the opposite.
Paul McCartney was musically illiterate in the traditional sense during the early Beatle years. But as he progressed, became rich and famous and had a chance to reflect on his unlocked potential and how much he didn't know, he learned how to read and write music and deal with theory. He even wrote some classical stuff. Many others have followed similar routes.
If you have talent, learning (with the correct approach - a different subject entirely) will not destroy your talent, although the learning process may sometimes mask it and seem to hold you back. "Innocence" is not the same as talent - that point might be confusing you, and it's you talent that's important, not your "innocence".
Once you have learned your lessons well, you will be able to leverage your talent to a far greater extent - writing music is not just an art, but also a craft - a skill. To get good at it requires study, training and practice.
Comment: +1 for the mention of theory becoming instinctive. Using theory or instructions can seem awkward when learning a creative task that is supposed to be authentic. With time and practice, I think this feeling usually disappears as one's talents grow.
Comment: @jdjazz - I noticed this sort of question  is always asked (not here, but in general) by those just getting started with theory, or those who really know nothing about it all, and are too afraid (lazy?) to learn. The reason is because of the initial learning curve. There are a number of good answers here, from people who know their theory quite well: They have gotten over the learning curve and now understand theory's proper place. (BTW-u asked for info about the evolution of the leading tone in the melodic minor (?) - I learned about that and I keep forgetting to check my notes and post it.)
Answer: Music theory gives you more tools for composition. In effect, music theory does not tell you what's good or correct, it tells you what people have chosen to do in the past and what effects they achieved. You get more choices. If you were into some DIY project, having an extra hammer or drill never hurts even though you may choose not to use either.
Personally, I find theory most useful when I get stuck or when what I wrote isn't what I think I heard mentally. When things sound right, theory is not so necessary; when things don't sound right, theory gives me different options.
Answer: Can grammar sabotage speaking?  Can road maps sabotage exploration?  Well, is exploration actually a goal in itself if you are not actually getting anywhere?
Music theory helps you actually channel your creativity in ways leading somewhere interesting.  It helps you not to waste it on matter that is already charted and well-understood.
Comment: Except my dictionary states that 'an explorer is a traveller into undiscovered territory'. If a map of it exists, it's not undiscovered. And, an awful lot of people seem to manage to talk a lot with little or no grammatical knowledge. However, it's not a bad analogy.
Comment: @Tim - The map tells you how to get from point A to point B. It doesn't tell you what's in between point A and point B. That remains undiscovered territory until you explore it. If you have a map that tells you how to cross the Alantic and on the way over you bump into an island where no-one has ever been, you can explore it.  But if you don't have a map to get you to the other side, you will be f---kd. **Very crude example:** Theory would tell you how to get from the root to the 5th using 7 notes, but the order and accents of those notes - and which ones you chose to use -  that's up to you.
Comment: @Stinkfoot - a map telling you how to cross the Atlantic. An interesting concept. 'Leave Canary Is., travel West, keep going till you hit land..., you'll have sea around you for some time... Keep following the line on the map...!'  It made me smile, so thanks for that.
Comment: @Tim - OK well  - on this side of the pond, "explorer" generally brings to mind Columbus. He had maps - they just just didn't tell him that on the way to India, he'd bump into a very large island after 'having sea around him for some time'. BTW, I'm not sure your dictionary is completely accurate: I'd replace "undiscovered" (a very sketchy, subjective term) with "uncharted" : Unmapped - all the water, and whatever else might be there, between A and B.
Answer: I can sympathise with that. A significant number of my students have said similar - 'I can't hear songs like I used to any more, now I'm analysing what's happening, and grinning 'cos I know exactly what that guitarist is doing at that point,' etc.
It's a mixed blessing. A double edged sword. Sometimes it's reassuring to actually know what's going on, others, it would be good just to relax and enjoy the ride.
It's true that a lot of music has been produced 'in ignorance', and nothing has got in the way of the creative process, but sometimes, the theory can come to the rescue at sticky moments. Knowing what chords work with each other, what 5/4 time really is, what triplets are, can help dig yourself out of the mire.
It's the same with some of the guys I have played with. I've held back from trying to explain why such and such works, as I'm aware that once they get bogged down, for want of a better term for them, with theory, the creative juices may not flow so freely.
Comment: One of the tricks is learning how / when to turn the "analyzing" ears off and to just enjoy the music for its own sake.
Comment: @Stinkfoot - I answered partly from the standpoint of so many questions posed here - 'the theory says I can't do this...' etc.
Comment: @Stinkfoot - go for it: we need many different points of view about this topic. It seems to have opened at least a little can of worms.
Comment: _as I'm aware that once they get bogged down... may not flow so freely_ - for the time being, because it's new. If they took the time to study and absorb, that would no longer be the case. Note that OP's question is often asked by those just beginning to plumb the depths of theory-there is a learning curve that slows you down, initially - _A significant number of my **students** .. similar_ : but **you** aren't saying it. When you absorb things and they become automatic, it's different. The vast majority of theory-knowledgeable are not troubled by the question, as shown by other answers here.
Comment: @Tim - OK understood. I'm see that I'm actually giving the OP an answer to their question as much as a comment on your answer .
Comment: Sometimes we need to realise that even if we can see where 'theory' is taking a song, there's no need to do something different just for the sake of novelty!
Answer: I'll answer the two questions separately:

is there a way that knowing music theory will even increase creativity ?

Yes: at least for me, learning Royal Conservatory of Music Grade 5 Harmony, History, and Analysis (probably called Advanced Harmony/History/Analysis nowadays) increased my creativity by exposing me to new chords and newly acceptable chord progressions. For example, I've noticed that I've never used Neapolitan chords or French Augmented 6ths in my compositions until I learned, in my Grade 5 Harmony classes, that they exist.
I'm also of the type where I need to know the structure of my piece or I won't be able to get that piece into a publishable state, so learning more musical forms in my music theory classes helped my publishable creativity in that way.
(Admittedly, I'm learning heavy metal music theory almost solely by listening to heavy metal. I've developing different sub-sections for power metal, neoclassical metal, and death metal, for example. One feature of power metal music theory that I've found out by myself is that it tends to be more consonant than other sub-genres of heavy metal.)
As for this question:

is there a way to get deeper without losing this innocence

Unfortunately, I suspect not. You may (eventually) be able to turn off your theory section of your brain while improvising/composing/analyzing others' works, but I haven't, so don't count on being able to.
One way I've lost that innocence is that I analyze the higher-level chord progressions of my compositions, so I'm currently taking a break from composing ragtime after finding out that the C and D sections of one of my most recent rags share their entire chord progression with the C and D sections of my very first rag. This implies that I'm less creative at improvising rags than I would like.
But the most important thing about that loss of innocence is this, IMO: Don't worry about losing that innocence. Don't worry that you'll lose your creativity because of it. And don't stop all your composing because you know the theory behind it.
Answer: Only if you make the mistake of treating theory as a set of permissions rather than a set of descriptions.  Always remenber, when something that sounds good doesn't 'fit the theory',  it's the theory that's lacking something, not the music.  Or you haven't yet learned the bit of theory which describes that particular thing.
'Theory describes.  It does not command'.
Answer: Great question. Ultimate creativity would be the ability to do something never done before even if it is using well known things in a different way. Music Theory, although it adds a caveat that anything is allowed or possible, mostly focuses on things that have been done before that had good results using a mixture of science, psychoacoustics, and culture. If you were a master of Music Theory, you could rule out everything that has been done before in order to find what is unique. Or you could use your vast knowledge of all existing ideas and use those ideas in a way that would be completely unique.
Comment: Thank you Mr. Stinkfoot. I can agree with the comment that "Not all great composer were great because they did something new." But the question is not about aesthetics, greatness, or being an extraordinary composer. It is about his concern with the effects that Music Theory may have on his creativity. Creativity is about originality and imagination. Aesthetics and greatness is completely subjective even if it is widely recognized. What I actually proposed was two ideas of how his creativity may be effected by Music Theory. I also agree that it would work for puzzles and lotteries.
Comment: _Ultimate creativity would be the ability to do something ... if it is using well known things in a different way_  - Not enough for music. What you've proposed might be good for making jig-saw puzzles or making a new kind of lottery. But great creativity in music means composing something with aesthetic value -born of inspiration and implemented by creating something **expressive**, not just different. Not all great composer were great because they did something **new**, but because they did something extraordinarily expressive with old forms and genres. "newness" is not the yardstick.
Comment: Creativity in music means **musical** creativity - not simply "originality and imagination" - one can compose really cruddy music that might be "original and imaginative". Musical talent is not the same talent that's needed for inventing a new sort of lottery. Greatness is not relevant, but aesthetics is - we're talking about an art form. [ Thank you for addressing me using the appropriate title - I appreciate the respect. Life can be hard carrying a name like Stinkfoot.... ] –
Comment: You're welcome Mr. Stinkfoot and I'm glad you took the time to reply. Once again, I agree with most of your comment. I have no idea what LoveIsHere considers to "sound nice." Could he be working to compose something that appeals to the majority? Philip Glass was physically attacked by people that claimed that he was writing cruddy music but he continued because he valued his new ideas that were not valued by others. This was a composer that had vast knowledge of Music Theory and intentionally tried things to simply be original. And the outcome swayed what people believed to be aesthetic.
Comment: I am familiar with Glass and his ideas. (He was not the first to take that route) I never physically attacked him, but he did not succeed with me. I tend to doubt he **truly** succeeded with anyone. People like to talk themselves into thinking something that's cruddy is actually good, if it's cool and trendy to do so. There was a question up here a while back about that subject - 'can people really like cruddy music' (to paraphrase...)  but for some reason it was deleted. I think I still have my answer (accepted at the time). Interesting topic. If you'd like, we can chat about that.
Comment: I opened a chat room - jump in if you care to - I'll check in later. It is a fertile subject: https://chat.stackexchange.com/rooms/64972/relative-musical-aethetics
Answer: Music theory won't sabotage creativity, so long as you abide by a particular conception of what "theory" actually is. Note that this particular conception (which I ascribe to) differs from what some accept to be good theory.
There are certain aspects of accepted music theory which I think stifle both thought and creativity.
To eschew theory requires musical talent.
Comment: Theory _does not_  "stifle both thought and creativity". Theory just gives you the ability to talk about, understand, and pick apart what you play and hear.
Comment: Please enlighten us... what *is* theory? Isn't this a relevant part of your answer?
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](http://chat.stackexchange.com/rooms/64968/discussion-on-answer-by-alephzero-can-music-theory-sabotage-creativity).
Answer: I have struggled with the same concern, and have concluded that although it is unfortunate it is unavoidable that you must learn theory to progress.
First, I must explain why it is unfortunate. There are many stable states for harmony, many more in fact than are considered stable by the theory. The limitations of our 12-tone system and the dominating force of the standard triad based forms of analysis tend to make it difficult to hear other equally valid ways of interpreting the music. I say that there are many stable states because mathematically there "should be" more stable states. People hear them all the time and then fit them into theory in increasing obscure ways, like a tone row, when there "should be" a more concise way of explaining why the composition sounds good. I have quoted "should be" because I can't really do justice to by I think this is the case, and that means this proposition is almost a statement of faith for me. Read about just intonation to get a feel for what I mean. All this goes to say that there are patterns and relationships that you may be hearing that do not fit easily into music theory, especially basic music theory, and as you study music theory there will be a strong tendency to loose those intuitions as you adopt a more standard understanding and train your ear to hear in the same way as everybody else.
However, it is unavoidable because so much of what you hear intuitively has been explored by others before you and reproducing what you are hearing can be very difficult without learning enough theory to be able to understand what you are hearing. There will be a mix of already well-explored ideas, erroneous ideas and subtly new ideas in what you hear intuitively as good. Teasing apart what is good and what is new from what is bad and what is well known requires developing a language that allows you to communicate with others, and that language is music theory.
Answer: If you are relying solely on "Music Theory" to create music, then it can hinder the creative aspect.  Creating means doing.  Thinking about doing is just thinking.  And Theory is thinking.
Comment: _And Theory is thinking_ Playing or composing music is also "thinking" - but you don't notice it because you've practiced so that it becomes reflex. If you start **thinking** a lot about your technique -
 nothing to do with theory - you'll also get screwed up - it's a distraction. You think about that at practice time, not when you're playing. It's the same with theory. Absorb it until it becomes reflexive - then it becomes an integral part of your music - not "thinking" per se.

can music theory sabotage creativity


calculation of conditional statement within pandas

Question: In the past I used to make calculation of conditional statements through pandas dataframe which returns Y/N to 1/0 and then calculate and get score. However I want to learn advanced method to implement calculation with larger dataset within a list.
Here is my code :
a=[234,45,57]
b=[26,51,59]
c=[87,23,56]

avrg_score = [['A',a[0]>0],
               ['B',b[0]>0],
               ['C',b[0]>0],
              ['C',a[0]*b[0]>c[0]],]

avrg_score = pd.DataFrame(avrg_score, columns=['Figure','Pass'],dtype=float).round(3)
x=avrg_score.Figure.count()
y=avrg_score.Pass.sum()
avrg_score_result=(x/y)*100

output:
100

But this is for index [0] for 3 lists (a,b,c) , however I need manually do for the rest of the indexes of the lists.
How can I do automatically for all indexes for the given lists?
when I put such format for the full list:
avrg_score = [['A',a>0],
               ['B',b>0],
               ['C',b>0],
              ['C',a*b>c]]

I get such error:
'>' not supported between instances of 'list' and 'int'

Would appreciate any help.
Comment: what will be columns in your DataFrame for all indices? I am assuming the list ids A, B, C are going to be the DataFrame index
Comment: I believe that the marked question covers the principles you're trying to implement.
This is included in many PANDAS tutorials, but this one is farther down the sequence than you might want to go at the moment.
Answer: Is this what you are expecting? I am assuming the list ids A, B, C are going to be the DataFrame index and columns for each of the 3 list items as 'Pass_1', 'Pass_2' and 'Pass_3'
import pandas as pd
import inspect

a=[234,45,57]
b=[26,51,59]
c=[87,23,56]

def getname(var):
    callers_local_vars = inspect.currentframe().f_back.f_locals.items()
    return (str([k for k, v in callers_local_vars if v is var][0]))

lists = [a, b, c]
fig_list = ['A', 'B', 'C']
cols = ['Pass_1','Pass_2','Pass_3']
df_result = pd.DataFrame(columns=cols, dtype=float)
for item in lists:
    df_result.loc[getname(item)] = [i>0 for i in item]
print(df_result)

Output:
   Pass_1  Pass_2  Pass_3
a     1.0     1.0     1.0
b     1.0     1.0     1.0
c     1.0     1.0     1.0

But remember, the print_this function getname() inspects the locals and it could be costly when doing to large lists. Instead I would have the list names/dataframe index names as list of strings and use it in the loop.
Comment: your code works with i>0, but I cannot  give lists different condition such as all indexes in list a more than 20, in b more than 30 , a>b for all indexes both in a and c. How to do that?
Comment: @Nina I am not sure if I understood what you are asking. Based in the original question, I assumed that for the list a with 3 elements, you want to find out each element is greater than 0 and store it in a df column. So, if your list has 3 elements you have 3 columns (one for each element) in your data frame. Now how do you want to store the result for 3 elements consolidated in one column? Do you want to check if each element in the list is greater than 0 and store the result in one column or count all the elements in the list that are greater than 0 and store the sum in the result df column?


X Approaches Infinity! What does that Mean ? lim t → ∞ [(t^1/2) + t2] / 4t − t2 What should be my Strategy at Solving these types of problems.

Question: I have had a tutor. He cannot convince me how one should solve limit approaching infinity problems. What is the strategy? Do you follow the limit laws if "the number x is approaching" is not in the domain? Since the number is infinity, what does that mean? I need clarity. In the below equation I am lost after step 2? Where did they get (4) / (t-1) shouldn't it be (4-1) / (t) if we are dividing by t^2?
Comment: The first term of the nominator and that of the denominator go to zero if t goes to the infinity. This is because the exponents are greater then one.
Answer: We know that the $$\lim_{t\to\infty}\frac{1}{t}=0$$So the idea is to get terms in this form.
The expression you are given is:$$\lim_{t\to\infty}\frac{\sqrt{t}+t^2}{4t-t^2}\tag{1}$$What we do here is divide the numerator and the denominator of this expression by $t^2$. If you look at just the numerator and divide it by $t^2$ you get:$$\frac{\sqrt{t}+t^2}{t^2}=\frac{\sqrt{t}}{t^2}+\frac{t^2}{t^2}=\frac{1}{t^{3/2}}+1\tag{2}$$Similarly, if you look at just the denominator and divide it by $t^2$ you get:$$\frac{4t-t^2}{t^2}=\frac{4t}{t^2}-\frac{t^2}{t^2}=\frac{4}{t}-1\tag{3}$$If we now substitute (2) and (3) into (1) we get:$$\lim_{t\to\infty}\frac{\sqrt{t}+t^2}{4t-t^2}=\lim_{t\to\infty}\frac{\frac{\sqrt{t}+t^2}{t^2}}{\frac{4t-t^2}{t^2}}=\lim_{t\to\infty}\frac{\frac{1}{t^{3/2}}+1}{\frac{4}{t}-1}$$Hopefully you understand the rest of the steps.
Comment: Excellent presentation. You have taught someone today.
Comment: Thank you for your kind comments :)


Where are Windows Event Forwarding (WEF) subscriptions filters applied?

Question: I configured Windows Event Forwarding (WEF) in my LAB domain and I'm setting up subscriptions. My subscription is configured on my DC and is source-initiated, the collector is DC01.acme.com and sources are WIN7.acme.com and WIN10.acme.com. Suppose I have the following query filter configured for my subscription:

This means that I only want Security event logs with ID 4776 forwarded to DC01.acme.com, this works like a charm, no issues here. My only question is: where is the filter really applied, in the DC (collector) or in the workstations (sources)? In my mind there are two possible scenarios:

Source forwards all event logs, those logs arrive at the collector
and then the collector applies the filter
Source applies the filter locally and only forward the intended event logs to the collector
Answer: To answer your question, the filtering is applied on the source (like servers, workstations, ...) and not on the collector. This means that if you specify a single event ID, your collector server will just collect the specified event ID (option 2 based on your question).
Comment: The source knows which events ID to send based on the query filter  you have defined inside the subscription (as in your picture). Indeed, each subscription has its own query filter which is applied to a specific group of hosts in order to send only the requested event ID.
This information is provided by Microsoft in their very good documentation : https://docs.microsoft.com/en-us/windows/security/threat-protection/use-windows-event-forwarding-to-assist-in-intrusion-detection
Comment: Thank you so much for the answer. Is there a Microsoft source for that or did you find it out by experience and/or trial and error? For example, how can the source knows that it only needs to forward security events ID XYZ? Does it get this information from the subscription manager URL GPO (Server=hxxp://dc01.acme.com:5985/wsman/SubscriptionManager/WEC,Refresh=60)?


Erro: Notice: Undefined index: d1

Question: Estou a criar um filtro para uma loja online, que terá estes campos:

E ate agora o select * estava a funcionar, mas quando eu comecei a implantar o filtro deixou de funcionar.
Aqui está o código do formulário e a ordem para imprimir:

Molas de compressão Pesquisa

      <form action="action.php" method="POST">
        Referencia:
        <input type="text" placeholder=" Search" name="referencia"style="font-family:Arial, FontAwesome">

          Diametro do Aço (d):

            <input type="text" name="d1" size="6" placeholder="min">
            <input type="text" name="d2"  size="6" placeholder="max">

          Comprimento total (L0):

            <input type="text" name="comp1"  size="6" placeholder="min">
            <input type="text" name="comp2"  size="6" placeholder="max">

          Diametro Exterior (DE):

            <input type="text" size="6" name="de1" placeholder="min">
            <input type="text" name="de2" size="6" placeholder="max">

          Passo (P):

            <input type="text" name="passo1" size="6" placeholder="min">
            <input type="text" name="passo2" size="6" placeholder="max">

            Ordenar por:
            <select class="form-control" name="ordenar">
              <option>Referencia</option>
              <option>Diametro do Aço (d)</option>
              <option>Comprimento total (L0)</option>
              <option>Diametro Exterior (DE)</option>
              <option>Passo (P)</option>
            </select>

          <button type="reset" align="right" class="btn btn-primary">Reset</button>
          <button type="submit" align="right" class="btn btn-primary">Continuar</button>

      </form>

Referência

Diametro do Aço (DE)

Comprimento Total (L0)

Diametro Exterior

Passo

Preço

Aqui está o outro ficheiro que deveria fazer o select e depois imprimir na outra pagina:

<?php

$d1=$_POST["d1"];
$d2=$_POST["d2"];
$comp1=$_POST["comp1"];
$comp2=$_POST["comp2"];
$de1=$_POST["de1"];
$de2=$_POST["de2"];
$passo1=$_POST["passo1"];
$passo2=$_POST["passo2"];
$ordenar=$_POST["ordenar"];

include ("db.php");

if(isset($_POST["getproduct"])){
    $ordenar="nome";
}
else{
$ordenar=$_GET["ordenar"];
}
switch($ordenar){
case "referencia":
 $ordenar_por="order by referencia";
case "diametroaco":
 $ordenar_por="order by diametroaco";
case "comprimentototal":
 $ordenar_por="order by comprimentototal";
case "diametroexterior":
 $ordenar_por="order by diametroexterior";
case "passo":
 $ordenar_por="order by passo";
}

    // $molcomp_query="SELECT * FROM stock_comp";
    $molcomp_query="select * from stock_comp where diametroaco BETWEEN '".$d1."' and '".$d2."' $ordenar_por";
   $run_query = mysqli_query($con,$molcomp_query);
    if (mysqli_num_rows($run_query) > 0){
        while($row = mysqli_fetch_array($run_query)){
        $id_mol_comp=$row['id_mol_comp'];
        $referencia=$row['referencia'];
        $diametroaco=$row['diametroaco'];
        $comprimentototal=$row['comprimentototal'];
        $diametroexterior=$row['diametroexterior'];
        $passo=$row['passo'];
        $preco=$row['preco'];

           echo"

$referencia

$diametroaco

$comprimentototal

$diametroexterior

$passo

$preco

  

";
        }
    }

?>

E agora quando eu clico no botão "continuar" do formulário, o site troca de pagina, para http://localhost/fanamol/action.php devido a <form action="action.php" method="POST">. Como eu posso clicar no botão continuar, e a ação ser executada no ficheiro action.php e devolver a informação para o ficheiro principal, sem que o ficheiro principal saia do ecrã?
Comment: Para fazer o que deseja, pesquise por Ajax
Comment: Eu sei o que é ajax, mas nao posso simplesmente fazer um select com condições e imprimir na mesma pagina onde já imprimia o select * antes?
Comment: Pode, com Ajax. Senão necessariamente você terá que sair da página.
Comment: Exatamente como o @AndersonCarlosWoss disse.
Answer: O <select> estava com os <option> sem value, use:
<select class="form-control" name="ordenar">
    <option value="referencia">Referencia</option>
    <option value="diametroaco">Diametro do Aço (d)</option>
    <option value="comprimentototal">Comprimento total (L0)</option>
    <option value="diametroexterior">Diametro Exterior (DE)</option>
    <option value="passo">Passo (P)</option>
</select>

Usando o <form method="POST"> todos os parametros passados para o arquivo PHP da action="action.php" deveriam estar como $_POST, por exemplo, aqui está correto:
$d1=$_POST["d1"];
$d2=$_POST["d2"];
$comp1=$_POST["comp1"];
$comp2=$_POST["comp2"];
$de1=$_POST["de1"];
$de2=$_POST["de2"];
$passo1=$_POST["passo1"];
$passo2=$_POST["passo2"];
$ordenar=$_POST["ordenar"];

Porém aqui, esta com $_GET:
if(isset($_POST["getproduct"])){
    $ordenar="nome";
}else{
    **$ordenar=$_GET["ordenar"];**
}

Mas como a variável $ordenar já foi definida anteriormente, basta apenas fazer o if():
if(isset($_POST["getproduct"])){
    $ordenar="nome";
}

Se for por $.ajax():

$('#send').click(function(){
    var arr = [];
    $.each($('input[type="text"]'),function(){
        var key = $(this).attr('name');
        arr[key] = $(this).val();
    });
    arr['ordenar']=$('#ordenar option:selected').val();
    $.ajax({
        type:"POST",
        url:"action.php",
        data:arr,
        success:function(callback){
            $('#get_product').html(callback);
        }
    });
});

Molas de compressão Pesquisa

                Referencia:
                <input type="text" placeholder=" Search" name="referencia"style="font-family:Arial, FontAwesome">

                    Diametro do Aço (d):

                        <input type="text" name="d1" size="6" placeholder="min">
                        <input type="text" name="d2"  size="6" placeholder="max">

                    Comprimento total (L0):

                        <input type="text" name="comp1"  size="6" placeholder="min">
                        <input type="text" name="comp2"  size="6" placeholder="max">

                    Diametro Exterior (DE):

                        <input type="text" size="6" name="de1" placeholder="min">
                        <input type="text" name="de2" size="6" placeholder="max">

                    Passo (P):

                        <input type="text" name="passo1" size="6" placeholder="min">
                        <input type="text" name="passo2" size="6" placeholder="max">

                        Ordenar por:
                        <select class="form-control" name="ordenar" id="ordenar">
                            <option value="referencia">Referencia</option>
                            <option value="diametroaco">Diametro do Aço (d)</option>
                            <option value="comprimentototal">Comprimento total (L0)</option>
                            <option value="diametroexterior">Diametro Exterior (DE)</option>
                            <option value="passo">Passo (P)</option>
                        </select>

                    <button type="reset" align="right" class="btn btn-primary">Reset</button>
                    <button align="right" class="btn btn-primary" id="send">Continuar</button>

Referência

Diametro do Aço (DE)

Comprimento Total (L0)

Diametro Exterior

Passo

Preço

Comment: esta parte está a dar um erro: Undefined index: d1
que corresponde a esta parte :$d1=$_POST["d1"];
$d2=$_POST["d2"];
$comp1=$_POST["comp1"];
$comp2=$_POST["comp2"];
$de1=$_POST["de1"];
$de2=$_POST["de2"];
$passo1=$_POST["passo1"];
$passo2=$_POST["passo2"];
$ordenar=$_POST["ordenar"];
Comment: faz um verificador de post
Comment: if(isset($_POST)&&!empty($_POST)){
//código
}
Comment: opah peço desculpa pelo incomodo, mas nao funcionou ainda, continua com o mesmo erro, mesmo depois de ter posto if(isset($_POST)&&!empty($_POST)){ //código }

ficou assim:

if(isset($_POST)&&!empty($_POST)){

$d1=$_POST["d1"];

$d2=$_POST["d2"];
$comp1=$_POST["comp1"];
$comp2=$_POST["comp2"];
$de1=$_POST["de1"];
$de2=$_POST["de2"];
$passo1=$_POST["passo1"];
$passo2=$_POST["passo2"];
$ordenar=$_POST["ordenar"];
}
Comment: vc ta usando form ou ajax?
Comment: Vamos [continuar esta discussão no chat](https://chat.stackexchange.com/rooms/77245/discussion-between-wees-smith-and-edshewa).
Comment: estou usando form

Erro: Notice: Undefined index: d1


how to assign the javascript variable value to textbox - in PHP

Question: I am trying to display some javascript variable on my html page.
var resultDis = 10;
document.getElementById("totalAmount").value= resultDis;

using
<input type="number" id="totalAmount" name="totalAmount"
class="form-control" ng-model="form.totalAmount"
placeholder="Total Amount" value="">

Here
totalAmount : id of text those i want assign the value
But on the form submission, null value goes of that textbox.
Comment: Welcome to SO. Please visit the [help] to see how and what to ask. HINT: Post a [mcve] so we can see your HTML. For example use the `<>` button in the editor. We cannot see if your inpute field has a name
Comment: When are you assigning var resultDis = 10; ? Some event? Is it possible you have not assigned the value before form submission? Or maybe the problem is in the php code? Because what you posted in your question is working.
Answer: add id="totalAmount" to your text box.
<input id="totalAmount" ...>

Answer: As you have in your input ng-model="form.totalAmount" you can update the value with AngularJS:

angular
  .module('MyApp', [])
  .controller('MyController', function($scope) {
    var resultDis = 10;

    $scope.form = {};

    // value assignment to form.totalAmount model
    $scope.form.totalAmount = resultDis;
});

  <input
         type="number"
         id="totalAmount"
         name="totalAmount"
         class="form-control"
         ng-model="form.totalAmount"
         placeholder="Total Amount"
         value="">

Note that now the input will show the variable resultDis value on the view.. But, how are you handling the form submit? Can you update your question with more code?
Comment: I updated your question. Please do that yourself from now on. How are you submitting? Ajax or normal form submit? Please update your question with your form and the form handling on the server
Comment: thanks sir,its work but when i submit the form then these textbox value goes to null
Comment: See and answer my comment on your question @PrashantKumbhar - for example you may need a `name="totalAmount"`
Comment: Than it should be something else in your code.. You have to make a deep review and show us more code in order to help you..
Comment:
Comment: sounds good javascript value variable shows in the text box like you but actually now  submit in the database
Answer: if you work in Visual Studio, you have to use ClientID:
var resultDis = 10; document.getElementById("<%=totalAmount.ClientID%>").value= resultDis;

Comment: not on Visual Studio works with PHP framework LARAVEL
Comment: please check document.getElementById("totalAmount").value in your browser console, after assigning resultDis value. if result is same as resultDis value, This will mean that maybe your javascript code has not any problem and your question is related to PHP.
Comment: it could be sir but when i enter the value manually other wise edit the value those are display from the javascript then it will works 100% perfect but not works without edit value
Comment: where is placed your javascript code. you have to place it on document ready($.ready(function(){ })) or event.


Jasmine mocking a external API function with a callback argument

Question: I'm calling a external API method for a post method, but I'm not able to get it cover using jasmine.
I have already mocked the external API function using window object and created a function to mock the callback by returning some object. But nothing helps.
Javascript
function loadApi() {
  extAPI.load({
    email: 'testEmail.test.com'
  }, function(resultObject) {
     if(resultObject.approved) {
       // callback with result object - not able to cover this
     }
  });
}

Spec.js & Mock-ups
beforeEach(function() {
  function mockLoadCallback() {
            var object = {
              approved: false
            };

            return object;
        }
  widnow.extAPI = {
       load: function(object, Function) {
                    var deferred = $.Deferred();

                    deferred.resolve(mockLoadCallback);

                    return deferred.promise();
        }
  }

});

it('load the external API response', function() {
  var loadSpy = spyOn(extAPI, 'load');
  loadApi();
  expect(loadSpy).toHaveBeenCalled();
});

statements and logic in the load call back should be covered but not even calling after the spy. what I'm doing wrong here.
Answer: You are missing .and.callThrough() after the call to spyOn`. Your test should look like this:
it('load the external API response', function() {
  var loadSpy = spyOn(extAPI, 'load').and.callThrough();
  loadApi();
  expect(loadSpy).toHaveBeenCalled();
});

The callThrough method ensures that after the spy is invoked, the spy delegates to the original behavior.


MSSQLSvc Service Principal Names, Kerberos, and NTLM

Question: Was recently helping a DBA with an issue that appeared to be related to an invalid SPN.  Discovered that a good number of SQL service accounts simply don't have an SPN set, resulting in NTLM authentication.
I've added SPN configuration to our build process, but am unsure whether going back to existing systems using NTLM and configuring an SPN to allow Kerberos authentication will break anything.
Are there any common scenarios where configuring MSSQLSvc SPNs to allow Kerberos authentication will break existing systems that are functioning without issue over NTLM?
Here's the code I'm using:
<code>#Query to identify authentication type for various connections on a SQL server
    $query = "SELECT
        s.session_id,
        c.connect_time,
        s.login_time,
        s.login_name,
        c.protocol_type,
        c.auth_scheme,
        s.HOST_NAME,
        s.program_name
    FROM sys.dm_exec_sessions s
    JOIN sys.dm_exec_connections c
    ON s.session_id = c.session_id"

#Everything comes back NTLM
#Source: https://raw.githubusercontent.com/RamblingCookieMonster/PowerShell/master/Invoke-Sqlcmd2.ps1
    Invoke-Sqlcmd2 -ServerInstance ServerInQuestion -query $query

#Get a list of SPNs associated with ServerInQuestion
#Results indicate no SPNs exist
#Source: http://gallery.technet.microsoft.com/scriptcenter/Get-SPN-Get-Service-3bd5524a
    Get-SPN -ServiceType MSSQLSvc -ComputerName ServerInQuestion

#Configuring SPNs for test systems results in Kerberos working without issue
    setspn -A "MSSQLSvc/ServerInQuestion.DOMAIN.XXX:1433" DOMAIN\SVCACCOUNT
    setspn -A "MSSQLSvc/ServerInQuestion.DOMAIN.XXX" DOMAIN\SVCACCOUNT
</code>
My concern is that if I go back to existing systems and configure SPNs, I might break existing applications or processes that work with NTLM but not Kerberos.  I assume they would fail back to NTLM if needed, but this isn't my area of expertise and I'm uncomfortable making that assumption.
Thanks!
Answer: You're probably right to be at least a little concerned. Unfortunately, whether a specific application will break or not all depends on the application. But in general, it is not likely that anything will break as long as you set the SPNs properly.
My main piece of advice would be:  An incorrect SPN is worse than no SPN at all.
The only thing I see being a potential problem for you is if the SPNs are set, but set incorrectly.
Take this example:

If a remote client attempts to authenticate to SQL and finds a valid SPN, it will use Kerberos.
If the remote client attempts to connect and finds no SPN, it will use NTLM.
If the remote client attempts to connect and finds an SPN, and then tries to use that SPN to authenticate via Kerberos but fails because the SPN was invalid... will it still fail back to NTLM or not?

That last question is very specific behavior that varies by application and Windows version.
This is a good follow-up article, even though it's old, it's still mostly relevant:
http://blogs.msdn.com/b/sql_protocols/archive/2006/12/02/understanding-kerberos-and-ntlm-authentication-in-sql-server-connections.aspx

Update:
If it's any consolation, I just ran a test using SQL Server 2012, and a remote client running Server 2012 R2 and SQL Management Studio. When the SPN was registered properly, Kerberos was used. When the SPN was absent, the SQL Management Studio failed over to NTLM.  When I purposely introduced a typo into the SPN on the service account, the connection was still established, and failed over to NTLM. So that's good news, but the fact remains that other unspecified applications might not implement Windows authentication correctly to take advantage of that negotiate protocol... so if you have odd applications, you'll still want to test them.  And in your testing, don't forget that NTLM will always be used for local connections, regardless of SPNs... depending on OS version. :D
Comment: We decided against retrofitting this, too many one-off applications from vendors or individuals I don't trust : )  Our updated server deployment system adds SPNs to the SQL service accounts it creates, so we're good going forward.  Thanks for the link, that was definitely one of the more helpful articles, despite the date.
Comment: That's fair. I've personally experienced applications that will make a SQL connection when no SPN exists, and also when the SPN exists, but they will fail when the SPN exists but is invalid. Essentially, the application doesn't properly implement the negotiation protocol.


How do I solve this PDE?

Question: How do I solve the partial differential equaiton
$u_{t} = (u_{x})^{-1}$
subject to the conditions $u(t,x) \geq 0$ and $u(0,0) = $0. Use the separation Ansatz $u(t,x) = f(t)g(x)$.
The inverse in confusing me
Answer: You have $u_tu_x=1$ and $u=fg$
$u_t=f'g$ and $u_x=fg'$
$u_tu_x=1\implies ff'gg'=1\implies ff'=K=1/(gg')$
$f=\sqrt{2Kt}$ and $g=\sqrt{2x/K}$
$u=2\sqrt{tx}+C$ Not the general solution, but the overall requirement of $u\leq0$ makes it valid and it can fulfill the initial condition of $u(0,0)=0$. So,
$u=2\sqrt{xt}$
Comment: I don't want to be rude, only I can be mistaken, but why don't you close as answered questions that for all respects seem answered? It affects the way the search utility gives results.
Comment: Would you mind explaining how you went from the third to the fourth line?
Comment: Yes, sorry: $(1/2)(f^2)'=(1/2)(f'f+ff')=ff'=K$ And after integrating: $f^2= 2Kt$
Comment: Ah that makes sense, thank you

How do I solve this PDE?


category url without https redirect to homepage in magento

Question: we have enabled https in our website and enabled 301 in admin section.
But the issue is with the category urls. Suppose if we select http:// www.testsite.com/ category.html, it will redirect to homepage. So after some searching i found a solution, which told me to add
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https:// %{HTTP_HOST}%{REQUEST_URI} [L,R=301]

after
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
in .htaccess
Now this url http:// www.testsite.com/ category.html redirects to https:// www.testsite.com/ category.html.
But for this url http:// testsite.com/ category.html, it redirects to homepage. I think some tweak on the above code is required. Could anybody help me in this please.
Answer: Looks like you're simply trying to force the WWW and force the HTTPS. While this should typically be done inside of a virtualhost configuration, I can understand if that's not an option.
The solution is simple, and is as follows:
# Start the Rewrite Engine
RewriteEngine On

#Set the base url to / unless you're in a subdirectory, so not modify this.
RewriteBase /

#Redirect all requests to WWW.
RewriteCond %{HTTP_HOST} ^testsite\.com
RewriteRule (.*) http://www.testsite.com/$1 [R=301,L]

# If requests are made on port 80, rewrite to HTTPS which will server over port 443.
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://testsite.com/$1 [R,L]

If you're looking to only redirect specific subdirectories, or pages, simply append the path to the condition and rules above.


Holder continuous but not Lipschitz

Question: Is there a function that is Holder continuous but not Lipschitz continuous?
Answer: From wiki,
The function $f(x) = x^\beta$ (with $\beta \le 1$) defined on $[0, 1]$ serves as a prototypical example of a function that is $C^{0,\alpha}$ Hölder continuous for $0 < \alpha \le \beta$, but not for $\alpha>\beta$. In particular, if we choose $\beta<1$, it's not Lipschitz.
Do you know how to check this statement?
Comment: I know how to check the Hölder continuity where it is Hölder, but I don't know how to show it's not Lipschitz.

Holder continuous but not Lipschitz


SQL Server switch data to display something else

Question: I am trying to figure out I can change the data on the fly.
This is my current query:
SELECT [EmployeeTC_No] AS "Employee TC#"
      ,[pye_nlast] AS "Name Last"
      ,[pye_nfirst] AS "Name First"
      ,[Dept] AS "Department"
      ,[pye_status] AS "Active"
      ,[HireDate] AS "Hire Date"
      ,[SeparationDate] AS "Separation Date"
  FROM [testing].[dbo].[testing]

In the column of pye_status the data comes in as "A" or "T" and I want it to be "1" or "0".
I have tried to add a case statement trying to do some kind of switch but nothing appears to even get me close.
Comment: A simple case statement should work, what did your case statement look like?
Answer: CASE/WHEN should do the trick:
,CASE WHEN [pye_status] = 'A' THEN 1
WHEN [pye_status] = 'T' THEN 0
ELSE NULL END AS "Active"

Or a simple case/when will work too:
, CASE [pye_status]
WHEN 'A' THEN 1
WHEN 'T' THEN 0
ELSE NULL END AS "Active"

Answer: Use CASE expression or IIF() function as
CASE WHEN [pye_status] = 'A' THEN 1 ELSE 0 END AS [Active]

OR
IIF([pye_status] = 'A', 1, 0) AS [Active]


Multi-site just separated content

Question: There is a lot of blog posts and tutorial about multi-site with content sharing.
But what about inverse of it? Multi-site with separated contents?
Exactly which tables should be shared?
here is my settings.php for sub-site:
$databases = array(
    'default' =>
    array(
        'default' =>
        array(
            'database' => 'xxx',
            'username' => 'xxx',
            'password' => 'xxx',
            'host' => 'localhost',
            'port' => '',
            'driver' => 'mysql',
            'prefix' => 'default_portal_',
            'prefix' => array(
                'default' => 'default_portal_',
                // Users
                'users' => '',
                'sessions' => '',
                'role' => '',
                'role_permission' => '',
                'authmap' => '',
                'blocked_ips' => '',

                // Blocks
                'block' => '',
                'block_custom' => '',
                'block_node_type' => '',
                'block_role' => '',

                // CKEditor
                'ckeditor_input_format' => '',
                'ckeditor_settings' => '',

                'comment_notify_user_settings' => '',

                // Configuration
                'date_formats' => '',
                'date_format_locale' => '',
                'date_format_type' => '',
                'field_config' => '',
                'field_config_instance' => '',
                'filter' => '',
                'filter_format' => '',
                'i18n_block_language' => '',
                'i18n_string' => '',
                'i18n_translation_set' => '',
                'image_effects' => '',
                'image_styles' => '',
                'languages' => '',
                'locales_source' => '',
                'locales_target' => '',
                'node_type' => '',
                'quicktabs' => '',
                'rdf_mapping' => '',

                // Support
                'support_assigned' => '',
                'support_client' => '',
                'support_priority' => '',
                'support_reference' => '',
                'support_states' => '',
                'support_ticket' => '',
                'support_ticket_comment' => '',

                // System
                'system' => '',
                'taxonomy_term_data' => '',
                'taxonomy_term_hierarchy' => '',
                'taxonomy_vocabulary' => '',
                'variable' => '',
                'variable_store' => '',

                // Views
                'views_display' => '',
                'views_view' => '',

                // WYSIWYG
                'wysiwyg' => '',
                'wysiwyg_user' => '',
            ),
        ),
    ),
);

EDIT
Above configuration works after cache clearing, but some tables should not shared: variable and variable_store because of site_title and site_slogan ...
EDIT
If I share block table, I should enable all themes in main site.
yet I have question to ensure which tables should share?
Comment: I need just one expert guy approves my `settings.php`
Answer: Yes , this is good idea, in one of my past work we do something like this, dedicated  drupal core but with separate content .

Multi-site just separated content


How to extract values from a complex list

Question: In Python3
If I have some complex lists such like:
<code>[1, [2, 3], [4, 5, 6]]
</code>
or maybe looks like:
<code>[1, [2, [3]], 4, [5, 6]]
</code>
I'm sure there is no repeat value in this list, but I don't know what the list's exactly  structure is.
how can I extract the values (recursive) from this complex uncertain list?
I want to get a plain list consist of these values:
<code>[1, 2, 3, 4, 5, 6]
</code>
Is there any elegant way to solve this issue?
Answer: Example:
<code>>>> from compiler.ast import flatten
>>> flatten([0, [1, 2], [3, 4, [5, 6]], 7])
[0, 1, 2, 3, 4, 5, 6, 7]
</code>
Try this:
<code>import re

def Flatten(TheList):
    a = str(TheList)
    b,crap = re.subn(r'[\[,\]]', ' ', a)
    c = b.split()
    d = [int(x) for x in c]

    return(d)
</code>
Comment: Input: [1, 2, [3]]    Raise: TypeError: 'int' object is not iterable
Comment: and also doesn't work to [["a", "b", ["d"]], ["c"]]
Comment: changed the solution sorry..
Comment: em, the module compiler has been removed in python3, I have seen [Flatten (an irregular) list of lists in Python](http://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists-in-python). it seems like there isn't any elegant(simply) solution


crossfilter2 dimension filter not working as expected

Question: <code>const crossfilter = require( 'crossfilter2');
const _ = require('lodash')
function randomGaussian() {
  return (
    Math.sqrt(-2 * Math.log(Math.random())) *
    Math.cos(2 * Math.PI * Math.random())
  );
}

const data = _.range(256).map(i => {
    // console.log(i, " -- ", randomGaussian() + 8);
    return [i, randomGaussian() + 8];
  });
    const filter = crossfilter(data);
    const value1 = filter.dimension(d => d[1]);
  const valueGroup = value1.group().reduceSum(d => d[1]);

value1.filter([7.2,8.1])
console.log(value1.top(Infinity).length)
console.log(valueGroup.all().filter(d => d.value ).length)
</code>
I expect the group length to be same as the dimension length...
Any idea what I am doing wrong?
Answer: Figured out that the dimension filter will not apply to the group as per the documentation.
"
Note: a grouping intersects the crossfilter's current filters, except for the associated dimension's filter. Thus, group methods consider only records that satisfy every filter except this dimension's filter. So, if the crossfilter of payments is filtered by type and total, then groupAll by total only observes the filter by type."
Comment: Yes. Weirdly, `dimension.top()` observes all filters, but `group.all()` and `group.top()` only observe filters on other dimensions. It's not true in general that `dimension.top()` and `group.all()` will have the same length, but it is unlikely that two items will fall in the same bin if the keys are random doubles.


What do we call the construction of a one object $n+1$-category (etc.) from multiobject $n$-category (etc.)?

Question: In general, when we have an $n$-something ($n$-category, etc.) and we decide to push everything up a notch, so $n$-cells become $n+1$-cells, and we end up with a $1$-object $n+1$-something, what do we call this?
Answer: You need more structure to do this, namely a monoidal structure. E.g. to push a set up to a one-object category that set needs to be a monoid. Then this procedure is called delooping.


Custom Webform handler not working on Wizard Webform

Question: I am attempting to write a simple webform handler to add to the end of a multi-step webform, ultimately to generate a barcode with the submitted data. I've had success with other handlers on single step forms but it looks like the handler causes the wizard form to freeze and not progress to the next step.
My suspicion is that I'm missing something in my plugin code but I can't seem to find an answer to the problem in similar issues.
So far there's no functionality attempted in the handler because the form freezes on the first step.
Ultimately I only need this handler to fire upon final submission of my form.
I'm trying to test for the forms state with $webform_submission->getState() but I can't seem to get it right
<code>  public function postSave(WebformSubmissionInterface $webform_submission, $update = TRUE) {

   $state = $webform_submission->getWebform()->getSetting('results_disabled') ? WebformSubmissionInterface::STATE_COMPLETED : $webform_submission->getState();
    if ($this->configuration['states'] && in_array($state, $this->configuration['states'])) {
       //do something

    }
  }
</code>
Comment: Any errors in `/admin/reports/dblog` ?
Comment: HI.  No Errors showing.  I've tried both with and without ajax and either way the form just won't progress when I hit the next button.  Doesn't trigger any activity from the handler either.
Comment: Turns out I couldn't use var_dump() to debug.  I needed to find the serial of the submitted webform and var_dump was causing the form to crash ... I used drupal_set_message() to dump variables instead and the handler seems to work fine.
Answer: Hopefully this will help someone out there but this is the code I finally got working.  It takes the serial value from a webform submission and writes a Png barcode for use in emails.  I'm using the Barcodes Module for Drupal 8.
<code>use Com\Tecnick\Barcode\Barcode as BarcodeGenerator;

class BarcodeHandler extends WebformHandlerBase {
  /**
   * {@inheritdoc}
   * Write PNG barcode for registration emails
   */
 public function postSave(WebformSubmissionInterface $webform_submission, $update = TRUE) {
   $regId = $webform_submission->serial();
   $type = 'C39';
   $barcode_file = 'registration/barcodes/' . $regId . '.png';
   $barcode = new BarcodeGenerator();
   $barcode_obj = $barcode->getBarcodeObj($type, $regId, 250, 50, 'black');

   file_put_contents($barcode_file, $barcode_obj->getPngData());

  }
}
</code>


view handler date not working

Question: I am creating views handler for date in hook_views_data. All other fields working fine but date. I am assigning views_handler_field_date and views_handler_filter_date in fields and filter respectively.
The problem is that when I select date field in views I get empty response as well as got bunch of errors.
Comment: edit with your code please
Answer: I am not sure what your code looks like, but my suggestion is to use custom handler if  the core is not working. I used custom handler in almost all my projects if I get any issue in core handler. Example is:
/**
 * A handler to display dates as just the time if today, otherwise as time and date.
 *
 * @ingroup views_field_handlers
 */
class views_handler_cusom_field_date extends views_handler_field_date {

  function options_form(&$form, &$form_state) {
    parent::options_form($form, $form_state);
    $form['date_format']['#options']['example_custom'] = t('My custom format');
  }

  function render($values) {
    $format = $this->options['date_format'];
    $value = $values->{$this->field_alias};
    // check for our custom format
    if ($format == 'example_custom') {
      // check to see whether value is whithin today range
      $timezone = new DateTimeZone("Australia/Melbourne");
      $date = new DateTime();
      $date->setTimezone($timezone);
      $today = strtotime($date->format('Y-m-d 00:00:00'));
      if ($value >= $today) {
        // this value is still within today
        return format_date($value, 'custom', 'g:i A');
      }
      else {
        // this value is older than today
        return format_date($value, 'custom', 'j M Y g:i A');
      }
    }
    // otherwise render the date using the normal date handler
    else {
      return parent::render($values);
    }
  }

}

And then call this custom handler in your date field
'date' => array(
           'title' => t('Date'),

           'field' => array(
              'handler'=> 'views_handler_cusom_field_date'
              'click sortable' => TRUE,
           ),

Comment: thank you for the answer. I researched on the forum and created a custom handler and bypassed all other logic just rendered the date in my format and it solved the problem

view handler date not working