text:
Q: What is the mathematical name for Haskell's Alternative Functor Haskell's Applicative Functor is called Lax Monoidal Functor in mathematics.
What is Haskell's Alternative Functor called in mathematics?
Recall that Haskell's Alternative Functor is defined as follows:
class Applicative f => Alternative f where
    -- | The identity of '<|>'
    empty :: f a
    -- | An associative binary operation
    (<|>) :: f a -> f a -> f a

Edit: In other words, an Alternative Functor f is an Applicative Functor such that for every type a, f a is a monoid, where <|> is the binary operation of type f a -> f a -> f a and empty is the identity of type f a. Uncurrying the type of <|>, we get
$$f\ a \times f\ a \rightarrow f\ a$$
and empty can be equivalently defined to have type
$$1 \rightarrow f\ a$$
In the Haskell definition, the type variable a is universally quantified. As far as I know, this translates to the requirement that they are natural in a.

A: This is not a complete answer, just a translation of Haskell to math so that the resident category theorists can tell what the question is.
As is usual in such cases, the terminology and the concepts in Haskell are slightly modified concepts from mathematics. It is best in the first iteration to look just at the broad similarities and not worry so much about the details.
Recall from Section 7 of the paper by Connor McBride and Ross Paterson that Haskell's Applicative is a lax monoidal functor (kind of as the Haskell definition uses internal Hom-sets where one would expect the external ones).
The definition of Alternative translates into: a functor $F : \mathcal{C} \to \mathcal{C}$, where $C$ is at least cartesian, together with natural transformations $e : 1 \to F$ and $m : F({-}) \times F({-}) \to F$, or concretely, for every object $A \in \mathcal{C}$ we have arrows
$$e_A : 1 \to F(A)$$
and
$$m_A : F(A) \times F(A) \to F(A)$$
such that $(F(A), e_A, m_A)$ is a monoid for all $A$, naturally in $A$. What would you call such a thing?
The next question to ask is whether there is anything extra about having a lax monoidal functor which also has the above structure of monoids? I don't know off the top of my head. If there is another view of the same situation, it will surely be useful for various Haskell hacking tricks. Haskell people are very good at using category-theoretic algebra for all sorts of cool purposes.
Let me also explain on the difference between parametricity and naturality. When we define a "functor" $F$ in Haskell, that is not really a functor. It is acertain mapping from types to types which acts on internal hom-sets as a functor would. In addition, this mapping has a strong property known as parametricity which says that $F$ behaves "in the same way" on all types. Parametricity is quite similar to naturality, and there is a way to view it semantically as such, but it is not precisely naturality. This is not a detail into which we should worry about here, though.

A: A slightly different set of primitive operations that we can look at is the following:
class Functor f => Alternative' f
  where
  unit :: () -> f Void
  zip :: (f a, f b) -> f (Either a b)

This represents a lax monoidal functor from the monoidal category of -> under the tensor Either to the monoidal category of -> under the tensor (,). The laws are the usual laws for the coherence maps of lax monoidal functors, including those that demand conformance with the functor (i.e. you can crib them with minor adjustments from the Applicative typeclass).
By contrast, the operations and laws of the Alternative typeclass of today seem to amount to type Alternative f = Monoid (forall a. f a). We can witness a pair of maps that convert between the primitive operations of Alternative' and Alternative:
instance Alternative f => Alternative' f
  where
  unit _ = empty
  zip (fa, fb) = (Left <$> fa) <|> (Right <$> fb)

instance Alternative' f => Alternative f
  where
  empty = absurd <$> unit ()
  fa1 <|> fa2 = either id id <$> zip (fa1, fa2)

However, it seems likely that this is not truly an isomorphism, due to the difference in constraints and laws between the two typeclasses.
On one hand, Alternative is more permissive than Alternative', since it does not demand any form of compatibility between the monoid and the functor, whereas the commutative diagrams of a lax monoidal functor do.
On, the other hand, Alternative demands Applicative, a constraint that Alternative' does not demand. When viewed through the lens of lax monoidal functors, Applicative f simply means that f coheres the (,) monoidal structure to (,), and Alternative f means that it coheres the Either monoidal structure to (,). These are orthogonal claims, so there is no need for Alternative' f to demand a Applicative f constraint.
That said, I conjecture that most types that support Alternative instances also support a lawful instance of Alternative', and so you can imagine them to be "applicatives for different tensor".

A: This might not be the right approach, but here's my take on the question:
If $(\mathcal{C}, \otimes, I, \dots)$ is a (strict, for the sake of readability) monoidal category, we can endow $[\mathcal{C}, \mathcal{C}]$ with two different monoidal structures:

*

*The "usual" monoidal structure, where $\circ$ is the product and $\mathbf{1}_\mathcal{C}$ is the unit. This is the monoidal category whose monoids are called monads. Notice how this doesn't actually use the fact that $\mathcal{C}$ is endowed with a monoidal structure.

*The "other" (I sometimes refer to it as "pointwise") monoidal structure has "pointwise $\otimes$" (let's call it $\boxtimes$) as product, and $\Delta_I$ (the constant functor on the unit object of $\mathcal{C}$) as monoidal units. In this category, monoids are related to what Haskell programmers call "alternative" functors, but without the part about being "applicative" and with one additional property. This can be further generalized to the case of functors $\mathcal{B} \to \mathcal{C}$ where $\mathcal{B}$ is not required to be monoidal, and everything that follows should work just fine (but I won't venture there).
Let me elaborate on the latter, since the former is (probably) already well-known to most haskell programmers here (other than being significantly less relevant):
First we'll need to properly define $\boxtimes$: if we fix functors $\mathcal{F}, \mathcal{G} : \mathcal{C} \to \mathcal{C}$ we can define $(\mathcal{F} \boxtimes \mathcal{G}) (a) := \mathcal{F}(a) \otimes \mathcal{G}(a)$ (the definition for morphisms is analogous). This, together with $\Delta_I$ as a unit, defines a monoidal category: all axioms (and further properties, such as symmetry and strictness) follow trivially from the monoidal structure on $\mathcal{C}$.
Now, monoids in this monoidal category are what haskell programmers call "alternative" functors, but that's not all: they are so in a functorial way, meaning that if $f : a \to b : \mathcal{C}$ and $\mathcal{M}$ is a monoid in $([\mathcal{C}, \mathcal{C}], \boxtimes, \Delta_I)$ then $\mathcal{M}(f)$ is a morphism of monoids.  To see this, note how this diagram needs to commute in a pointwise fashion, and the same applies to this other diagram too. We're in the strict case, but nothing significant changes in the general one (except that you need to keep track of the coherence laws).
A more abstract (but equivalent) formulation is that each object $\mathcal{M} : \mathbf{Mon}([\mathcal{C}, \mathcal{C}])$ naturally defines a functor $\hat{\mathcal{M}} : \mathcal{C} \to \mathbf{Mon}(\mathcal{C})$, and this point of view leads to the observation that this actually defines a functor $(\hat{-}) : \mathbf{Mon}([\mathcal{C}, \mathcal{C}]) \to [\mathcal{C}, \mathbf{Mon}(\mathcal{C})]$.
What this amounts to is just that a "monoidal" natural transformation $\nu : \mathcal{M} \to \mathcal{N} : \mathbf{Mon}([\mathcal{C}, \mathcal{C}])$ between monoid object in this "pointwise" monoidal category of (endo)functors also defines a natural transformation $\hat{\nu} : \hat{\mathcal{M}} \to \hat{\mathcal{N}} : [\mathcal{C}, \mathbf{Mon}(\mathcal{C})]$: the argument is similar but you need to look at the diagrams for morphisms of monoids.
Things are not over yet: it seems that $(\hat{-})$ is actually an equivalence of categories! You can convince yourself of this if you squint hard enough, and the argument is roughly "brute force":
Let's construct a strict inverse to $(\hat{-})$, call it $(\tilde{-})$: take $\mathcal{F} : \mathcal{C} \to \mathbf{Mon}(\mathcal{C})$, compose it with the forgetful functor $\mathbf{U} : \mathbf{Mon}(\mathcal{C}) \to \mathcal{C}$. We'll now use the "forgotten structure" on $\mathcal{F}$ to endow $\mathbf{U} \circ \mathcal{F}$ with the structure of a monoid in $[\mathcal{C}, \mathcal{C}]$: to do this, notice how the monoid structure on $\mathcal{F}(a)$ (for $a : \mathcal{C}$) needs to be such that each morphism $\mathcal{F}(f) : \mathcal{F}(a) \to \mathcal{F}(b)$ is a morphism of monoids: this amounts to saying that the correspondences $a \mapsto \mathbf{m}^{\mathcal{F}(a)}$ and $a \mapsto \mathbf{e}^{\mathcal{F}(a)}$ are natural in $a$ and hence natural transformations (its now trivial to check that these endow $\mathbf{U} \circ \mathcal{F}$ with the structure of a monoid in $[\mathcal{C}, \mathcal{C}]$).
We now need to check that $(\hat{-}) \circ (\tilde{-}) = \mathbf{1}_{[\mathcal{C}, \mathbf{Mon}(\mathcal{C})]}$ and $(\tilde{-} \circ \hat{-}) = \mathbf{1}_{\mathbf{Mon}([\mathcal{C}, \mathcal{C}])}$: they should both be long and trivial computations, and I'll (boldly) omit them.
Edit: this can probably be "merged" to the other answer by Andrej Bauer to give a more complete answer


text:
Q: ObjC2J not working I am trying to use this tool, ObjC2J, but it keeps asking for me to put the "converter.properties" file in the MacOSX.sdk file. I am copying the converter.properties file from the file that consists of the tool to
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.8.sdk/System/Library/Frameworks
This was the only appropriate place I saw for this file as this is where the sdk resides and the path of the txt file is similar to my path yet i still get the "You should create 'converter.properties' file and place there path to MacOSX.sdk" error. What am I doing wrong?

redpajama_set_name: RedPajamaStackExchange


text:
Q: What happens if the private IP range of a VPC falls outside the IANA defined ones? The VPC documentation says:

When you create a VPC, we recommend that you specify a CIDR block (of /16 or smaller) from the private IPv4 address ranges as specified in RFC 1918:

*

*10.0.0.0 - 10.255.255.255 (10/8 prefix)

*172.16.0.0 - 172.31.255.255 (172.16/12 prefix)

*192.168.0.0 - 192.168.255.255 (192.168/16 prefix)

You can create a VPC with a publicly routable CIDR block that falls outside of the private IPv4 address ranges specified in RFC 1918; however, for the purposes of this documentation, we refer to private IP addresses as the IPv4 addresses that are within the CIDR range of your VPC.

What happens if a VPC is created with a range outside of those ranges, for example, 172.40.0.0/16? Probably nothing immediately, but what would I need to watch out for if I did that?

A: With a typical configuration for your router, this would mean that all packets destined for a "real" internet IP address like 172.40.1.2 (say) would not be reachable from your network since your router would try to find the relevant Internet device within your network.

A: Let us assume you have assigned an IP address to a host eg:172.40.0.1
It is a public IP address which means someone already bought this IP.
Let us see the whois data.
IP address: 172.40.0.1
hostname:   172.40.0.1
ISP:    T-Mobile USA
Country:    United States (US) flag
latitude:   37.751
longitude:  -97.822

Now if you are using custom DNS server for VPC then you can make use of it inside VPC locally. Although we may configure it locally, networks still create conflicts because we don't have control on few of the system discovery methods.

A: Your networking will be just broken, I mean your container will be not acessible from outside (internet) nor your PVC could send anything to outside to the world. Amazon had preconfigured their listed private networks to be only accepted as a source and destination address pools for PVC.
Having two own PVC on same real hardware node it is possible they could communicate just to each other, having both addresses assigned from unauthorized by amazon pool 172.40.1.2 and, say, 172.40.1.1, but I'm not sure, it depends on networking setup amazon have there.


text:
Q: Implementing Swagger in a Java Spring project I want to add Swagger to my Spring application. But I can't figure out why it's not working. I found so many solutions for that but for now nothing worked for me.
@EnableSwagger2
@Configuration
public class SpringFoxConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();
    }
}

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.0.0</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.portfolio-generator</groupId>
    <artifactId>backend</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>backend</name>
    <description>portfolio generator</description>
    <properties>
        <java.version>19</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
            <version>3.0.0</version>
        </dependency>
        <dependency>
            <groupId>commons-validator</groupId>
            <artifactId>commons-validator</artifactId>
            <version>1.4.1</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

current error:

java.lang.TypeNotPresentException: Type javax.servlet.http.HttpServletRequest not present
at java.base/sun.reflect.generics.factory.CoreReflectionFactory.makeNamedType(CoreReflectionFactory.java:117) ~[na:na]
at java.base/sun.reflect.generics.visitor.Reifier.visitClassTypeSignature(Reifier.java:125) ~[na:na]
at java.base/sun.reflect.generics.tree.ClassTypeSignature.accept(ClassTypeSignature.java:49) ~[na:na]
at java.base/sun.reflect.generics.visitor.Reifier.reifyTypeArguments(Reifier.java:68) ~[na:na]
at java.base/sun.reflect.generics.visitor.Reifier.visitClassTypeSignature(Reifier.java:138) ~[na:na]
at java.base/sun.reflect.generics.tree.ClassTypeSignature.accept(ClassTypeSignature.java:49) ~[na:na]
at java.base/sun.reflect.generics.repository.ClassRepository.computeSuperInterfaces(ClassRepository.java:117) ~[na:na]
at java.base/sun.reflect.generics.repository.ClassRepository.getSuperInterfaces(ClassRepository.java:95) ~[na:na]
at java.base/java.lang.Class.getGenericInterfaces(Class.java:1250) ~[na:na]
at org.springframework.core.ResolvableType.getInterfaces(ResolvableType.java:500) ~[spring-core-6.0.2.jar:6.0.2]
at org.springframework.core.ResolvableType.as(ResolvableType.java:448) ~[spring-core-6.0.2.jar:6.0.2]
at org.springframework.core.ResolvableType.forClass(ResolvableType.java:1048) ~[spring-core-6.0.2.jar:6.0.2]
at org.springframework.plugin.core.config.PluginRegistriesBeanDefinitionRegistrar.getTargetType(PluginRegistriesBeanDefinitionRegistrar.java:101) ~[spring-plugin-core-2.0.0.RELEASE.jar:2.0.0.RELEASE]
at org.springframework.plugin.core.config.PluginRegistriesBeanDefinitionRegistrar.registerBeanDefinitions(PluginRegistriesBeanDefinitionRegistrar.java:71) ~[spring-plugin-core-2.0.0.RELEASE.jar:2.0.0.RELEASE]
at org.springframework.context.annotation.ImportBeanDefinitionRegistrar.registerBeanDefinitions(ImportBeanDefinitionRegistrar.java:86) ~[spring-context-6.0.2.jar:6.0.2]
at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.lambda$loadBeanDefinitionsFromRegistrars$1(ConfigurationClassBeanDefinitionReader.java:373) ~[spring-context-6.0.2.jar:6.0.2]
at java.base/java.util.LinkedHashMap.forEach(LinkedHashMap.java:729) ~[na:na]
at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsFromRegistrars(ConfigurationClassBeanDefinitionReader.java:372) ~[spring-context-6.0.2.jar:6.0.2]
at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsForConfigurationClass(ConfigurationClassBeanDefinitionReader.java:148) ~[spring-context-6.0.2.jar:6.0.2]
at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitions(ConfigurationClassBeanDefinitionReader.java:120) ~[spring-context-6.0.2.jar:6.0.2]
at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:409) ~[spring-context-6.0.2.jar:6.0.2]
at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:283) ~[spring-context-6.0.2.jar:6.0.2]
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:344) ~[spring-context-6.0.2.jar:6.0.2]
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:115) ~[spring-context-6.0.2.jar:6.0.2]
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:745) ~[spring-context-6.0.2.jar:6.0.2]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:565) ~[spring-context-6.0.2.jar:6.0.2]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:146) ~[spring-boot-3.0.0.jar:3.0.0]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:730) ~[spring-boot-3.0.0.jar:3.0.0]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:432) ~[spring-boot-3.0.0.jar:3.0.0]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:308) ~[spring-boot-3.0.0.jar:3.0.0]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1302) ~[spring-boot-3.0.0.jar:3.0.0]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1291) ~[spring-boot-3.0.0.jar:3.0.0]
at com.portfoliogenerator.backend.BackendApplication.main(BackendApplication.java:11) ~[classes/:na]
Caused by: java.lang.ClassNotFoundException: javax.servlet.http.HttpServletRequest
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641) ~[na:na]
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188) ~[na:na]
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521) ~[na:na]
at java.base/java.lang.Class.forName0(Native Method) ~[na:na]
at java.base/java.lang.Class.forName(Class.java:495) ~[na:na]
at java.base/java.lang.Class.forName(Class.java:474) ~[na:na]
at java.base/sun.reflect.generics.factory.CoreReflectionFactory.makeNamedType(CoreReflectionFactory.java:114) ~[na:na]
... 32 common frames omitted

A: Spring Boot 3 does not support javax packages. You should replace them with jakarta packages.
You can read about version 3 updates here.
The swagger dependency in your pom requires classes from javax package, that`s why it is failing.
You can try with Swagger 3:
<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-ui</artifactId>
    <version>1.2.32</version>
</dependency>

https://www.baeldung.com/spring-rest-openapi-documentation
https://www.javainuse.com/spring/boot_swagger3


text: Q: Why is the azimuthal current density $j_\phi = \frac{Q}{T}$? I am looking at the solution for one of the problems I had for homework. I have an infinite cable of linear charge density $-\lambda$ and an insulating concentric cylindrical shell around the cable. The cylinder starts rotating and, at the end, there is a magnetic field because of the rotating shell moving the charges in the insulator (This is my guess). To calculate this magnetic field, I am supposed to use Ampere's Law $\oint \mathbf{B}\cdot \mathrm{d} \mathbf{l} = \mu_0 I_{enc}$. So I need to calculate these current enclosed. The solution says that I have to use the azimuthal current density formula $j_\phi = Q/T$. Where does this formula come from?


text:
Q: Convert pandas.TimeSeries to R.ts I have some pandas TimeSeries with date index:
import pandas as pd
import numpy as np
pandas_ts = pd.TimeSeries(np.random.randn(100),pd.date_range(start='2000-01-01', periods=100))

I need convert it to R TS (like sunspots dataset) to call some R function (slt) with my TS, which works only with timeseries. But i found that in pandas.rpy and rpy2 API's there is only DataFrame support. Is there another way to do this?
If there is no such I can convert TS to DataFrame in python, then convert it to R DF and convert it to TS in R but I have some troubles at last step because i'm new in R.
Any ideas or help in converting in R? =)

A: I am not a pandas proficient , But you can save you pandas time series to csv file and read it from R.
Python:
## write data
with open(PATH_CSV_FILE,"w") as file:
   pandas_ts.to_csv(file)
## read data
with open(PATH_CSV_FILE,"r") as file:
   pandas_ts.from_csv(file)

R:
library(xts)
## to read data
ts.xts <- read.zoo(PATH_CSV_FILE,index=0)
## to save data
write.zoo(ts.xts,PATH_CSV_FILE)

A: The easiest might just be to use the R function ts() in a call corresponding to your pandas.date_range() call.
from rpy2.robjects.packages import importr
stats = importr('stats')
from rpy2.robjects.vectors import IntVector
# The time series created in the question is:
# pd.date_range(start='2000-01-01', periods=100)
stats.ts(IntVector(range(100)), start=IntVector((2000, 1, 1)))

A: Inspired by the answers given here already, I created a small function for conversion of an existing Pandas time series towards an R time series. It might be usefull to more of you. Feel free to further improve and edit my contribution.
def pd_ts2r_ts(pd_ts):
    '''Pandas timeseries (pd_ts) to R timeseries (r_ts) conversion
    '''
    from rpy2.robjects.vectors import IntVector,FloatVector
    rstats = rpackages.importr('stats')
    r_start = IntVector((pd_ts.index[0].year,pd_ts.index[0].month,pd_ts.index[0].day))
    r_end = IntVector((pd_ts.index[-1].year,pd_ts.index[-1].month,pd_ts.index[-1].day))
    freq_pandas2r_ts = {
        # A dictionary for converting pandas.Series frequencies into R ts frequencies
        'D' : 365, # is this correct, how about leap-years?
        'M' : 12,
        'Y' : 1,
    }
    r_freq = freq_pandas2r_ts[pd_ts.index.freqstr]
    result = rstats.ts(FloatVector(pd_ts.values),start=r_start,end=r_end,frequency=r_freq)
    return result


text:
Q: Views versus a function for getting the top records of a table? I'm talking with a coworker about a way to approach a problem.
We have a table that keeps track of a filling process, that has unique index columns (or should at least) on columns Lot and TestGrade.
Recently, we added logic so that when a TestGrade of anything higher than 1 is created, all the lower levels.  Some logic is done so the lower level rows are not necessarily identical to the top level.
For example, I INSERT something with Lot='ABCD' and TestGrade=5 then in my Fills table I see
id    Lot    TestGrade   OtherColumns
======================================
10    'ABCD'     1          blah3
9     'ABCD'     2          bar
8     'ABCD'     3          foo
7     'ABCD'     4          blah1
6     'ABCD'     5          blah

Now the issue is in many instances, I only want the top level records of of the Fills table, so in the example, I would only want the record with id=6.
We have two ideas on how to do this.  I want to make a view that looks like
CREATE VIEW [dbo].[vwFills]
AS
SELECT t.* FROM [dbo].[Fills] t
JOIN (SELECT [Lot], MAX(TestGrade) as TestGrade FROM dbo.Fills GROUP BY [Lot]) t2 ON t.[Lot] = t2.[Lot] AND t.[TestGrade] = t2.[TestGrade]

My coworker wants to do something similar but inside a function that will look like this
ALTER FUNCTION [dbo].[fnFills] (
 @Fills tyFills READONLY
 )
RETURNS @returnTable TABLE(
//Copy of the table definition of Fills, without
    id INT NOT NULL,
    Lot VARCHAR(10) NOT NULL,
    TestGrade INT NOT NULL,
    //rest of the columns..
    )
AS

Begin

insert into @returnTable
    select t2.* from (
        select [Lot], max([TestGrade]) as TestGrade from @Fills) t1
            left join Fills t2
            on t1.[Lot] = t2.[Lot] and t1.[TestGrade] = t2.[TestGrade]

Return

End

Then to call this function, it would look like
DECALARE @FillRecords tyFills;
INSERT INTO @FillRecords SELECT * FROM db.Fills;
SELECT * FROM dbo.fnFills(@FillRecords);

Our dbo.Fills does have indexes on Lot and TestGrade.  However, it's my intuition that with the function approach where we insert into a variable and then feed it to a function, we lose these indexes and so with this join we're looking at O(n^2) performance.  Is that a fair assessment?  I'm concerned about performance as the the server is not robust hardware wise, and so anything to help with query execution is preferred.
Generally speaking, in this sort of scenario, is there a best practice method - is a view or a function the "obvious" or better choice?

A: functions in sql server are usually bad ideas
Functions in SQL Server, specifically scalar, and multi-statement table valued functions, have a lot of issues. I'm going to skip over scalar UDFs, since that's not what your question is about.
For the type of function your co-worker suggested, a multi-statement table valued function, the issue is mostly around the @table variable that backs it up. The problems you'll have here are:

*

*Insert query will be forced to run single-threaded

*Lousy row estimates when @table variable is queried

*No column-level statistics about the @table variable contents

Even indexing the @table variable wouldn't be terribly useful for you here.
You could avoid most of the issues by using an inline table-valued function. Their performance is only as bad as the query you put in them, and the supporting indexes available.
CREATE OR ALTER FUNCTION
    dbo.fnFills_Inline
(
    @Fills tyFills READONLY
)
RETURNS table
AS
RETURN

    SELECT
        t2.*
    FROM
    (
        SELECT
            [Lot],
            MAX([TestGrade]) AS TestGrade
        FROM @Fills
     ) t1
     LEFT JOIN Fills t2
         ON  t1.[Lot] = t2.[Lot]
         AND t1.TestGrade = t2.[TestGrade];

There should be no material difference between the view and function in this case, but in views where window functions are involved, an inline table-valued function may be necessary to push a predicate past the sequence project operator.

A: While I agree with the other answers that generally a View will have less potential to run into performance issues than a Function, it also depends specifically on the query one writes too. I mention this because option C is to use a View that leverages the ROW_NUMBER() window function to efficiently get the top record of each Lot like so:
WITH LotGradesSorted AS
(
    SELECT id, Lot, TestGrade, OtherColumns,
        ROW_NUMBER() OVER (PARTITION BY Lot ORDER BY TestGrade DESC) AS GroupSortId
    FROM dbo.Fills
)

SELECT id, Lot, TestGrade, OtherColumns
FROM LotGradesSorted
WHERE GroupSortId = 1

This generates a unique ID for each row within the grouping (PARTITION) on the Lot field ordered by the TestGrade field descending, such that the row with the largest TestGrade within each group of Lots is always the first row. The final SELECT query only returns those rows (with the WHERE GroupSortId = 1 filter).
Note that this only works when the field(s) in the ORDER BY clause of the window function are unique within the grouping on the field in the PARTITION clause (i.e. if you never have the same TestGrade duplicated within the same Lot). Otherwise, if the fields being ordered on are not unique, then the ordering is nondeterministic (because two rows will have the same exact values to order by so there's no consistent way to choose in a tie) which can result in semi-random results. But as long as your TestGrade field is unique within each grouping of Lots then you'll never have this issue.
The reason this query inside of your View can before more efficient than your proposed query is because it should result in less passes over your table, and Microsoft has designed window functions to be performant tools when used under the correct circumstances.

A: Your intuition is right. The view is the way to go.  The function doesn't do anything else than a simple SELECT statement, no procedural logic involved at all.
A function can be used too, but it would be much better to define it as an inline table-valued function:
CREATE FUNCTION dbo.fnFills()
RETURNS TABLE
RETURN(
SELECT t.*
FROM [dbo].[Fills] t
JOIN (SELECT [Lot], MAX(TestGrade) as TestGrade FROM dbo.Fills GROUP BY [Lot]) t2 ON t.[Lot] = t2.[Lot] AND t.[TestGrade] = t2.[TestGrade]
);

Here is a good explanation of difference between table value function and inline table value functions.
But the function doesn't give any advantage over the view in this situation, so I would just stick with a good old view.
Note: I took your query as is, but it's considered best practice to avoid "SELECT *" statements.


text:
Q: automorphism groups now I'm searching for general results to computations to automorphism groups.
Let G be a group. Is there any nice way of computing $\operatorname{Aut}(G)$ without using $\operatorname{Aut}(G)\cong \operatorname{Inn}(G)\rtimes \operatorname{Out}(G)$? I think: no!
Does $\operatorname{Aut}(\cdot)$ behave nicely in the sense, that it commutes with (semi)direct products?

A: $\text{Aut}(\cdot)$ doesn't commute with direct products.  For example, if $G$ is any nontrivial group, then $\text{Aut}(G\times G)$ includes not only automorphisms of the form $(x,y)\mapsto(\alpha(x),\beta(y))$ with $\alpha,\beta\in\text{Aut}(G)$ (which form a copy of $\text{Aut}(G)\times\text{Aut}(G)$), but also $(x,y)\mapsto(y,x)$.


text:
Q: Analogue operation to $\frac{d x^n}{d x}=nx^{n-1}$ but ending with $nx^{n-i}$ instead ($i$ is complex ) EDIT : $i$ is a complex value, not just another real value.
Looking for an analogue operation to $\frac{d x^n}{d x}=nx^{n-1}$ but ending with  $nx^{n-i}$ instead ( Where $i$ is the complex value, instead of the $1$ in the $\frac{d x^n}{d x}=nx^{n-1}=nx^{n-(1+0i)}$
More generally if it was possible to express $\frac{d x^n}{d x}=nx^{n-(\alpha+\beta i)}$ where in case of normal differentiation $\alpha=1$ and $\beta = 0$ reducing to $nx^{n-1}$.
I have no reason or application for this just wondered what is specific to differentiation that causes shifting by real magnitudes only, I am assuming that there is a more general operation where the normal differentiation is special case when a specific value is used then it sets $\alpha=1$ and $\beta=0$ , maybe for other values $\alpha \neq1$ and $\beta \neq 0$.

A: You seem to be asking multiple different questions here, and I'll do what I can to separate them.

*

*"what is specific to differentiation that causes shifting by real magnitudes only"

*"I am assuming that there is a more general operation where the normal differentiation is special case when a specific value is used."

*"Looking for an analogue operation to $\frac{d x^n}{d x}=nx^{n-1}$ but ending with $nx^{n-i}$ instead."

1. Why real shift in differentiation?
Traditionally, we only differentiate a nonnegative integer number of times, and differentiating $k$ times is just differentiating once again and again, so this question seems to reduce down to "Why do we get an $n-1$ in the exponent when evaluating $\dfrac{\mathrm dx^n}{\mathrm dx}$?"
The way I like thinking about this is geometrically. If $n$ is a positive integer, then something that grows like $x^n$ (e.g. the volume of tetrahedron of side length $x$ for $n=3$) changes based on a surface which necessarily has dimension one lower, and so which grows like $x^{n-1}$. This is explored in 3Blue1Brown's Derivative Formulas Through Geometry chapter of his calculus series.
Even if $n$ is not a positive integer, you can still think in terms of physical units: If $\mathrm dx$ has the same units as $x$, then $\dfrac{\mathrm dx^n}{\mathrm dx}$ should have the same units as $x^{n-1}$, by division in the difference quotient.

2. More general operation?
We can look for more natural generalizations that yield different powers of $x$. For example, for a positive integer $k$, we have $\dfrac{\mathrm d^k x^n}{\mathrm dx^k}=\dfrac{n!}{(n-k)!}x^{n-k}$. This is generalized to non-integer $k$ in fractional calculus.
One approach that works tidily for $x^n$ is motivated by the Laplace transform, and coincides with a generalization you might arrive at while thinking about generalizations like the binomial series (generalizing the binomial theorem) and the Gamma function (generalizing factorial).
This would have you write something like $\dfrac{\mathrm d^i x^n}{\mathrm dx^i}=\dfrac{\Gamma(n+1)}{\Gamma(n+1-i)}x^{n-i}$. If $n$ is a positive integer, this can be written as $\dfrac{n!}{(n-i)(n-1-i)\cdots(-i)\Gamma(-i)}x^{n-i}$ where $\Gamma(-i)\approx -0.155+0.498i$.
I'm not sure how useful this is, but it's at least the sort of operation other people have considered. For example, it was used in this answer by Cye Waldman to Is there a notion of a complex derivative or complex integral?.

3. Ending with $nx^{n-i}$?
You could certainly define your own operation based on the expression. For instance, maybe we define $L(x\mapsto x^n,a)=x\mapsto nx^{n-a}$ for every complex $a$, and extend to polynomials and power series via linearity and similar. Then you can write $L(x\mapsto x^n,i)=x\mapsto nx^{n-i}$, though I can't think of an application/reason to do this.


text:
Q: I can't open/ping any antivirus sites I have a problem with a virus in windows 7, I don't know what kind of virus is infected my OS, I installed kasersky antivirus, and clear all detected viruses. After that I can't open any antivirus sites, can't ping any antivirus sites.
example:
C:\Windows\system32>ping kaspersky.com
Pinging kaspersky.com [38.117.98.231] with 32 bytes of data:
General failure.
General failure.
General failure.
General failure.

Ping statistics for 38.117.98.231:
    Packets: Sent = 4, Received = 0, Lost = 4 (100% loss),

When I ping to other sites, I get reply normally:
example woth pinging to google.com
C:\Windows\system32>ping google.com

Pinging google.com [31.7.160.224] with 32 bytes of data:
Reply from 31.7.160.224: bytes=32 time=2ms TTL=61
Reply from 31.7.160.224: bytes=32 time=2ms TTL=61
Reply from 31.7.160.224: bytes=32 time=1ms TTL=61
Reply from 31.7.160.224: bytes=32 time=1ms TTL=61

Ping statistics for 31.7.160.224:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 1ms, Maximum = 2ms, Average = 1ms

I tryed any antispyware/antimalware softwares, but null results.
Anyone else encountered this problem?

A: Answer found here: http://en.kioskea.net/forum/affich-631539-i-can-t-open-antivirus-sites

The reason is that you may already have an infection which prevents
  such sites from opening to keep your system infected.
Try this:

*

*Boot into safe mode (tapping F8 while booting) with networking.

*Download, install and run Malwarebyte which you can find on this site:
http://en.kioskea.net/telecharger/telecharger-105-malwarebytes-anti-malware

*

*Ensure you make an update.

*Please request a FULL system scan, which may take from 20 minutes to
  hours. Do not interfere no matter how long in takes. The creators of
  Malwarebyte recommend that while the tool is running that you go do
  something else, such as watching a rerun of Gone with the Wind or read
  Tolstoy's War and Peace.

*If Malwarebyte restarts your system, launch it again to finish the
  Full scan.

*When the scan is completed, delete all items found.

*Once your computer is clean and working normally just to be on the
  safe side*

*

*Turn off system restore and wait 30 seconds,

*Turn it back on and create a new restore point.
*This way it gets rid of anything bad that might have gotten saved in a
  restore point and you have a clean restore point to use in the near
  future if needed.

*Do not turn it off until your computer is clean and
  working normally because you might need to use it if something goes
  wrong during the clean-up process.  It is better to go back to an
  infected restore point if something goes wrong then to not be able to
  undo changes that were damaging.

A: Actually the main reason behind this is that the virus has infected your system to a greater extent. It is happening due to that only and these infected programs does not allow you to register to any antivirus site. The best option to get rid of this is to run your system in safe mode and install an antivirus and then make the updates in the system and delete all the unwanted programs from the system. By doing this, you can protect your system. But the best way is obviously to take the required measures in advance and load your system with good http://www.antivirus4u.co.za/>Antivirus Software.

A: I think Sysinternals' AutoRuns can help you to find , stop and delete that virus.
It shows ALL processes, services and programs which starts with Windows
(but you can't see all with MSConfig...).
If you know main processes of your Windows, you can find and delete virus easily.
Download it here.

A: Double check your network settings.
You'll probably find that the DNS server address has been changed to one controlled by the malware writers. They do this so that you can't easily get to the sites you need to clean the infection off your machine.
Go to your ISP's web site and find out what DNS servers (if any) they recommend. Make a note of the IP addresses.
Then open the local area network connection properties dialog, select "Internet Protcol Version 4 (TCP/IPv4)" and then select the "Properties" option.
In the "General" tab of the next dialog there is an option to set the DNS Server. Set this to the IP addresses specified by your ISP or change it to the "Obtain DNS server address automatically option". Click OK, on each dialog to close it.
You should now be able to see all the anti-malware sites.
Do this before and after you've cleaned the system.
You could also try the Google DNS servers at 8.8.8.8 and 8.8.4.4

A: Wondering why previous answer was deleted. Don't you guys' know how Conficker work?
First try to browse this page first, see if you were infected:
http://www.confickerworkinggroup.org/infection_test/cfeyechart.html
Try use this tool to detect.. the rest you could find on Conficker removal tools:
http://www.sophos.com/en-us/products/free-tools/conficker-removal-tool.aspx


text:
Q: Compile error with thrust::device_vector of thrust::complex, possibly due to a wrong implementation I'm actually learning CUDA and thrust, and I'm trying to make a project with .cpp, .hpp files and .cu, .cuh files. Therefore, I have done a first little implementation (see code below), however I have a compile error. Here is the output of my compile error.
Honestly, I don't know exactly what this kind of error means, but I found out that this came from this line:
thrust::device_vector<thrust::complex<T>> deviceVec_;

because when I comment out this line there is no compile error anymore. Therefore, I assume that this is due to the content of the implementation of thrust::device_vector and the fact that I included the .cuh file in the .hpp file and since my main.cpp is handled by g++ the preprocessing will be performed by g++ instead of nvcc.
Content of my main.cpp file:
#include "QGPU.hpp"
int main()
{
     QGPU::GPU<double>  gpu;
     return (0);
}

Content of my .hpp file:
#pragma once

# include "QCUDA.cuh"

namespace QGPU {

 template<typename T>
 class GPU {
 private:
  QCUDA::CUDAGPU<T> cgpu_;
 public:
  GPU();
  virtual ~GPU();

};

template<typename T>
GPU<T>::GPU()
{};

template<typename T>
GPU<T>::~GPU()
{};

};

Content of my .cuh file:
#pragma once

# include <thrust/host_vector.h>
# include <thrust/device_vector.h>
# include <thrust/complex.h>

namespace QCUDA {

 template<typename T>
 class CUDAGPU {
 private:
  thrust::host_vector<thrust::complex<T>> hostVec_;
  thrust::device_vector<thrust::complex<T>> deviceVec_;
 public:
  CUDAGPU();
  virtual ~CUDAGPU();
 };

 template<typename T>
 CUDAGPU<T>::CUDAGPU()
 {};

 template<typename T>
 CUDAGPU<T>::~CUDAGPU()
 {};

};

Thus, my question is:
Is there a way to solve this compile error, and therefore, maintaining this implementation ?
Or I must change my vision on how I should implement a project where .cpp, .hpp files and .cu, .cuh files are mixed together ?
If I must change my implementation, there is a possibility to get a similar example of what would be a good implementation by following my attention ?
NB: I'm actually working with a GTX 1060 with the cuda version:
$nvcc --version
nvcc: NVIDIA (R) Cuda compiler driver
Copyright (c) 2005-2018 NVIDIA Corporation
Built on Wed_Apr_11_23:16:29_CDT_2018
Cuda compilation tools, release 9.2, V9.2.88

A: You need to rename main.cpp to main.cu to make this work. Otherwise you are importing CUDA code into a plain .cpp file, and the host C++ will fail to compile the code.


text:
Q: How to benchmark mongo engine itself, without interfering with a driver? I am optimising a bunch of server machines to be hosting MongoDB. I need to get a feeling of whether the optimisations are effective or not, from the perspective of Mongo engine.
To reduce noise, I would preferably not to use a Mongo driver to eliminate its interference.
How is it feasible to carry out such benchmark?
Could "JS benchmarking harness" be useful for this scenario?

A: For general server optimisation, your best starting point is the Production Notes section in the MongoDB manual. A careful read will help avoid some common mistakes such as not increasing the ulimit settings or not disabling NUMA on Linux servers.
There is also a very detailed section on Security including access control, network exposure, firewalls, and other relevant configuration.

To reduce noise, I would preferably not to use a Mongo driver to eliminate its interference.

You can't avoid using a driver; even the mongo shell is effectively a JavaScript shell sending commands via the C++ driver.  Given there can be some differences in the driver implementations (for example: approaches to connection pooling, timeouts, and defaults), I would suggest choosing whatever driver you expect to be most commonly used in your environment and use that as a reference point for relative performance on your server changes.

Could "JS benchmarking harness" be useful for this scenario?

As noted in the MongoDB documentation page you linked:
This benchRun command is designed as a QA baseline perf measurement tool, not designed
to be a "benchmark".

A good indication of whether your tuning is successful would be to run against a representative workload from your application(s). Even if you've followed best practice for server configuration, applications can still experience performance problems from design issues (poor schema choices, overuse of server-side JavaScript, missing indexes, etc).
I would suggest setting up a monitoring service that supports MongoDB and make sure you capture a reasonable amount of metric history so you can compare the outcome for similar workloads before and after tuning parameters.  A common choice is the free MMS Monitoring service from MongoDB, Inc. There are a number of other admin & monitoring services/tools listed in the Admin UIs section in the documentation.


text:
Q: Is there a difference between Narsil and Andúril? In the movies, we see Elendil in the Prologue of The Lord of the Rings: The Fellowship of the Ring holding the sword Narsil. When Elendil died at the hands of the dark lord Sauron, Narsil was broken at the feet of Sauron. When it was reforged, Elrond calls the sword Andúril. But it seems to me that these 2 swords are just the same.
Why do Aragorn and Elrond call the sword Andúril rather than Narsil? Since Narsil is the original sword.

A: There's an old philosophical problem called the Ship of Theseus, or Theseus's Paradox. It talks about a ship that was preserved by the people of Athens as a cultural relic; over time, they took away the planks that decayed and replaced them with new, identical planks, until every part of the ship had been replaced. The question then rose: Was it still the Ship of Theseus?
There isn't a definite answer either way; it's still a philosophical problem, and a matter for debate. The Narsil/Andúril question is similar.
While it's hard to see on the screen, the text gives us more of a notion about what was done in the reforging:

The Sword of Elendil was forged anew by Elvish smiths, and on its blade was traced a device of seven stars set between the crescent Moon and the rayed Sun, and about them was written many runes; for Aragorn son of Arathorn was going to war upon the marches of Mordor. Very bright was that sword when it was made whole again; the light of the sun shone redly in it, and the light of the moon shone cold, and its edge was hard and keen. And Aragorn gave it a new name and called it Andúril, Flame of the West.

Objects in the Rings mythos, especially those made by Elvish craftsmen, are often portrayed as having some kind of life or identity to them. When Narsil was broken, it was 'killed'; explicitly, its "light [was] extinguished". Andúril was an entirely new blade, made from the substance of Narsil, but with its own identity as the Sword Reforged.

A: In short: Symbolism
I think Tolkien was using the forging of Andúril to amplify the symbolic effect of the Return of the King as a counter point to the rise of Sauron. There is a good bit of reincarnation and subsequent renaming throughout the trilogy, and this is one instance.
It's also worth noting that "Narsil", in Quenya, means "white and red flame", symbolizing the Sun and Moon, or "the enemies of darkness". Andúril means "Flame of the West", meant to more directly oppose the darkness to the East in Mordor.

In response to @NKCampbell's comment, I disagree (in this context). Whether or not the shards of Narsil were forge welded back together or were smelted into a new blank, Andúril is a new sword. As @Werrf says, this is a philosophical question, but it does differ slightly from Theseus's Paradox, as the same steel was used; whereas in the paradox, the ship was eventually made of entirely different material.

Very bright was that sword when it was made whole again

On that, we agree. I don't think it was smelted down. But I still say it's a new sword.
The question here is, "How much does a sword need to change to become a different sword?"
First, it went through a process. It was reforged, and, technically, the molecular structure was changed by the welding, hardening, and heat treating of the steel. Welded steel is strongest at the joints. The sword would feel different in use. It would flex differently. It would sound different on striking. This would be also be true if The Shards were treated as revert and the smelting process was performed again. Also, it was engraved almost ceremoniously. And then it was renamed. As I said, this is a significant thing in Middle-earth.
Second, it can be debated that when a Thing breaks, it's no longer a Thing; it's now a Different Thing.

*

*When you take a plank and run it through a chipper, it's now mulch. Same physical material, but not as good for making furniture.

*Is it really a TV if you can't turn it on, i.e. perform the most basic function of a TV? I call this garbage (until I fix it).

*Better still: if a plank in a table splits, and you mend it with some butterfly inlays, is it the same plank? Seems to me it's now two planks mended together...

*Another place to direct this thought experiment is to the Japanese practice of Kintsugi, in which a broken piece of pottery is mended with gold. It becomes both stronger and more valuable than the original.

Third, and perhaps most important in a literary sense, Narsil was a named weapon. Named weapons are a common trope in the Fantasy genre, and are almost characters. I'd argue that in this context, Narsil has died and reincarnated as Andúril, imbued with a new spirit. It exists for a new purpose (or rather, the same purpose but for a different person). See Gandalf the Grey => Gandalf the White.

A: Because Narsil was a name associated with failure
The sword broke, and at a critical point (which is what happens if you don't properly heat treat it).  And then not long after, its master broke, when Isildur refused to destroy the ring.
While it was symbolically (and probably magically) important to reforge the sword for the new king, it was also important to separate it from its former name, a name with the stigma of breaking attached.


text:
Q: If $\text{Gal}(f)=D_{2017}$ for some $f\in\mathbb{Q}[x]$ then $f$ is solvable
Let $f\in\mathbb{Q}[x]$ and let $E$ be its seperable field over $\mathbb{Q}$. Suppose that $\text{Gal}(E/F)=D_{2017}$. Show that $f$ is solvalbe.

I would like to verify my answer, please.
We know that $f$ is solvable if and only if $G_f=\text{Gal}(E/F)$ is solvable. Consider $H=C_{2017}$. $H\triangleleft G$ because for all $g=a^ib^j\in D_{2017}$ where $0\leq 0<2017, j=0,1$, and for all $h=a^k\in H$ where $0\leq k<2017$, we have that $g^{-1}hg\in H$. According to the cardinals of $G$ and $H$ we have $G\diagup H\cong C_2$ which is commutative.
Also, $C_{2017}\diagup \{1\}\cong C_{2017}$ which is commutative, too. Thus $G_f$ is solvable and $f$ is solvable too.

A: Since every dihedral group $D_n=\langle r,s \rangle$ for $n\ge 3$ is $2$-step solvable, $Gal(E/F)$ is solvable and hence $f$ is solvable. In fact
$$
D_n'=\langle r^2\rangle, \; D_n''=\{id\}.
$$
Another way to show that $D_n$ is solvable, is that $C_n$ is a normal abelian subgroup of $D_n$ with abelian quotient $D_n/C_n\cong C_2$. Since both $C_2,C_n$ are solvable, so is $D_n$.


text:
Q: How do I get all records associated with a record in an aggregate root table For testing purposes, I would like to generate an insert script for all records in all tables associated with a particular record in one of the root tables. For example, I might have a "Participant" table, which has any number of associated entries in the "Documents" table, which in turn has any number of associated entries in the "PrintRequests" table and so on and so forth. I have hundreds of these tables in the database.
Is there any way to select/script out all the records in all tables that are associated with for example ParticipantId = 1? This way, for a representative participant, I can extract all the associated records in all the tables.
One of my ideas was to restore a back up of the full database, modify all foreign key constraints to have cascade delete and then delete everything that is not participantid = 1 and let the database take care of deleting everything that is not related to the participant of interest and then script out the entire database of what remains.
For this, I might have to drop and recreate all the constraints, which I am unsure about how to do across the entire database.
Alternately, are there any other tools that would be able to do this? A migration tool for example that can take a query and only migrate the records and associated child records of that query?

A: While it is entirely possible to build scripts to walk through all the primary key and foreign key constraints and, via liberal use of dynamic SQL, generate these scripts, doing so would be a non-trivial undertaking.  I would strongly suspect that you would be better served using a product like DataBee to generate your data subset.

A: You can script it creating dynamic SQL statements, but I think it is really lots of work. I think you will be faster to just find all the tables with a column "ParticipantId" with something like this
select * from all_tab_columns where column_name = 'PARTICIPANTID'

And then do some fast edit / replace / other sort of script action to generate yourself the delete statements.
Regarding the constraints. This is similar. Getting all the constraints with
SELECT owner, table_name, constraint_name
  FROM dba_constraints
 where table_name in (select table_name from all_tab_columns where column_name = 'PARTICIPANTID')

You switch on and off constraints using
ALTER TABLE <table name> ENABLE/DISABLE constraint <constraint name>;

Maybe this you could do with a loop. Borrowing from this page
begin
  for i in
 (select constraint_name, table_name from user_constraints where table_name in (select table_name from all_tab_columns where column_name = 'PARTICIPANTID')
 ) LOOP
   execute immediate 'alter table '||i.table_name||' disable constraint '||i.constraint_name||'';
  end loop;
end;

I am not sure about your cascading delete thing but the above gives a bit an idea how the delete would look like:
begin
  for i in
 (select constraint_name, table_name from user_constraints where table_name in (select table_name from all_tab_columns where column_name = 'PARTICIPANTID')
 ) LOOP
   execute immediate 'delete from '||i.table_name||' where participantid = ''1'' ';
  end loop;
end;

Hope it helps.


text:
Q: How do I prove the expectation value formula for the momentum operator? I know that according to textbooks $⟨p⟩ = −iℏ∫ψ^{*}(x)\frac{dψ(x)}{dx}dx$, but why? Knowing that $I = ∫|x⟩⟨x|dx$
I get $⟨p⟩ = ⟨ψ|p|ψ⟩ = ∫⟨ψ|p|x⟩⟨x|ψ⟩dx = ∫(−iℏ\frac{dψ(x)}{dx})^{*}ψ(x)dx$,
but also $⟨p⟩ = ⟨ψ|p|ψ⟩ = ∫⟨ψ|x⟩⟨x|p|ψ⟩dx = ∫ψ(x)^{*}(−iℏ\frac{dψ(x)}{dx})dx$.
Now I would expect that $∫(−iℏ\frac{dψ(x)}{dx})^{*}ψ(x)dx = ∫ψ(x)^{*}(−iℏ\frac{dψ(x)}{dx})dx$, but this is not the case.. why?

A: If I've understood your question correctly, you have two definitions of the expectation value of momentum and want to show that they are equivalent. It's easy to do this using integration by parts, given the properties of the wavefunction.
For example, if you start with your "first" definition,
$$\langle p \rangle = \int_{-\infty}^\infty i \hbar \frac{\text{d}\psi^*}{\text{d} x} \psi(x).$$
One can now "shift" the derivative from the first term to the second using integration by parts, since
$$\int_{-\infty}^\infty i \hbar \frac{\text{d}\psi^*}{\text{d} x} \psi(x) = \psi(x) \psi^*(x)\Big|_{-\infty}^\infty - \int_{-\infty}^\infty i \hbar\, \psi^*(x)\frac{\text{d}\psi}{\text{d} x}. $$
Realising that for any "physical" wavefunction $|\psi(x)|^2 \to 0$ as $x\to \pm \infty$, the first term is trivially zero, and so
$$\int_{-\infty}^\infty i \hbar \frac{\text{d}\psi^*}{\text{d} x} \psi(x) = - \int_{-\infty}^\infty i \hbar\, \psi^*(x)\frac{\text{d}\psi}{\text{d} x}. $$
Does this answer your question?


text:
Q: Can I implement an interface in a C# in an .h file? I have an interface that is used by several classes and the interface implementation is the same for all the classes. I would make it a base abstract class, but then it would stop the deriving classes from inhering from another class later on, which I need. So instead of reimplementing the same interface in all the classes, can I somehow implement the interface in one place, like an .h file and include the .h file in the cs file so the class "implements" the interface.
By the way, the interface consists mostly of properties and changed on delegates.

A: EDIT: Scratch all below the line- as per the comments, that's probably not what you want.
Unfortunately mixins are not available as a built-in language feature in C#, other than through some questionable techniques, including post-compile tools like PostSharp.  Some IoC tools can make mixin-like things happen also (see Best implementation of INotifyPropertyChange ever).
To @32bitkid's point, you can write extension methods.  They are not interfaces, but they allow you to apply an implementation of a behavior to a type from outside that type.  For instance, you can write:
public static class IPersonExtensions {
    // Note use of this keyword
    public static Int32 GetAge(this IPerson p) { return DateTime.Now - p.BirthDate; }
}

then use it thus:
var p = new Person( ... );
var pAge = p.GetAge();

Yes, that's how interfaces are normally used- though they get .cs files, not .h files.  You can define the interface in it's own file, just like a class, and then declare the class as implementing the interface.
For example, in IFoo.cs:
public interface IFoo {
  public String Bar { get; set; }
}

and then in ConcreteFoo.cs:
public class ConcreteFoo : IFoo {
  // This property implements IFoo.Bar
  public String Bar { get; set; }
}

(This is an example of an auto-implemented property by the way)
IFoo doesn't even technically need to be in it's own file- it can be in any .cs file.  By convention, it usually is in it's own though.  Also, note the convention of using the I prefix for interfaces.
You might want to read more about this, here for example: http://www.csharp-station.com/Tutorials/Lesson13.aspx

A: I'm a little rusty on my C#, so there may certainly be a C#-specific way of doing this.  However, in a more general sense, you could provide the implementation in its own, standard class file.  For each class that needs to implement the interface, you would still need to declare the interface methods - but instead of having lengthy implementations copied-and-pasted into each, you could have one-line calls to the shared "include" implementation.
(This probably won't be the best solution, but should be a workable one that could at least get you started.)

A: C# does not have a concept of header files. You can't do this easily in C#. If you implement an interface and you want to have the same implementation in another class then the other class needs to derive from the implementing class.
Example:
public interface IFoo
{
    void DoSomething();
}

public class SomeClass : IFoo
{
    public void DoSomething()
    {
    }
}

If you now want to have SomeOtherClass which has the same implementation as SomeClass then you need to derive SomeOtherClass from SomeClass or reimplement it or delegate the call to DoSomething to an instance of SomeClass. Another option would be to use a tool like DynamicProxy which can support mixin styles.

A: You basically need multiple inheritance which C# doesn't support, however you can still make use of an interface implementation in other classes that are already being derived from another class.  One way I've come up with is using partial classes and T4 Text Templates.  It's a slight hack but it's better than copy/pasting the same interface implementation in lots of derived classes.  Below is a simplified example:
IInterface.cs
public interface IInterface
{
    void Foo();
}

InterfaceImpl.cs
public partial class InterfaceImpl : IInterface
{
    public void Foo()
    {
        Console.WriteLine("Foo");
    }
}

BaseClass.cs
using System;

public class BaseClass
{
    public void Bar()
    {
        Console.WriteLine("Bar");
    }
}

DerivedClassA.cs
public partial class DerivedClassA : BaseClass, IInterface
{
    public void FooBar()
    {
        this.Foo();
        this.Bar();
    }
}

DerivedClassAInterfaceImpl.tt
<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ output extension=".cs" #>
<# var codeText = System.IO.File.ReadAllText(this.Host.ResolvePath("InterfaceImpl.cs")).Replace("InterfaceImpl", "DerivedClassA"); #>
<#= codeText #>

DerivedClassB.cs
 public partial class DerivedClassB : BaseClass, IInterface
    {
        public void BarFoo()
        {
            this.Bar();
            this.Foo();
        }
    }

DerivedClassBInterfaceImpl.tt
<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ output extension=".cs" #>
<# var codeText = System.IO.File.ReadAllText(this.Host.ResolvePath("InterfaceImpl.cs")).Replace("InterfaceImpl", "DerivedClassB"); #>
<#= codeText #>

It's a little annoying that this requires creating a tt file for each derived class that wants to use the interface implementation, but it still saves on copy/paste code if InterfaceImpl.cs is more than a few lines of code.  It's also probably possible to just create one tt file and specify the name of all the derived partial classes and generate multiple files.


text:
Q: Compare old and updated fields in Django model I want to compare old and updated field in model. I have did this issue for one field but i want do this for all fields:
class MyUser(User)
    def save(self, **kwargs):
       if self.pk is not None:
         orig = MyUser.objects.get(pk=self.pk)
         orig_field_names = orig._meta.get_all_field_names()
         field_names = self._meta.get_all_field_names()
         # I want do this in loop
         if orig.first_name != self.first_name:
           print 'first_name changed'
           UpdateLog.objects.create(
                user = orig,
                filed_name = self.first_name,
                update_time = datetime.now()
             )
         super(MyUser, self).save(**kwargs)

Thanks in advance

A: Here's my go-to function for comparing fields. Gets a little hairy when dealing with foreign keys, but it's not too bad overall:
def get_changes_between_objects(object1, object2, excludes=[]):
    """
    Finds the changes between the common fields on two objects

    :param object1: The first object
    :param object2: The second object
    :param excludes: A list of field names to exclude
    """
    changes = {}

    # For every field in the model
    for field in object1._meta.fields:
        # Don't process excluded fields or automatically updating fields
        if not field.name in excludes and not isinstance(field, fields.AutoField):
            # If the field isn't a related field (i.e. a foreign key)..
            if not isinstance(field, fields.related.RelatedField):
                old_val = field.value_from_object(object1)
                new_val = field.value_from_object(object2)
                # If the old value doesn't equal the new value, and they're
                # not both equivalent to null (i.e. None and "")
                if old_val != new_val and not(not old_val and not new_val):
                    changes[field.verbose_name] = (old_val, new_val)

            # If the field is a related field..
            elif isinstance(field, fields.related.RelatedField):
                if field.value_from_object(object1) != field.value_from_object(object2):
                    old_pk = field.value_from_object(object1)
                    try:
                        old_val = field.related.parent_model.objects.get(pk=old_pk)
                    except field.related.parent_model.DoesNotExist:
                        old_val = None

                    new_pk = field.value_from_object(object2)
                    try:
                        new_val = field.related.parent_model.objects.get(pk=new_pk)
                    except field.related.parent_model.DoesNotExist:
                        new_val = None

                    changes[field.verbose_name] = (old_val, new_val)

    return changes

Usage:
>>> item = Item.objects.get(pk=1)
>>> item_old = Item.objects.get(pk=1)
>>> print item.my_attribute
'foo'
>>> item.my_attribute = 'bar'
>>> get_changes_between_objects(item, item_old)
{'My Attribute': ('bar', 'foo')}

A: You want a signal.  For quick reference, here's the introductory paragraph or so from that link:

Django includes a "signal dispatcher" which helps decoupled
applications get notified when actions occur elsewhere in the
framework. In a nutshell, signals allow certain senders to notify a
set of receivers that some action has taken place. They're especially
useful when many pieces of code may be interested in the same events.
Django provides a set of built-in signals that let user code get
notified by Django itself of certain actions.

A: Read the docs before vote -1. Catch the signal is the better way to do this thing


text:
Q: Have an error only in production! I'm created project. Works in development mode! Excellent!
DEVELOPMENT:
Typing : ruby lib/scripts/test_sync.rb
And my script works!
PRODUCTION:
Typing : ruby lib/scripts/test_sync.rb
Get Access denied for user 'root'@'localhost' (using password: YES)
Dont know, I did everything. grant previligies, changed password and so on... Coul someone help me, please?
UPD*
# SQLite version 3.x
#   gem install sqlite3-ruby (not necessary on OS X Leopard)
development:
  adapter:  mysql
  host:     localhost
  database: survey_development
  username: root
  password:
  encoding: utf8

# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
  adapter:  mysql
  host:     localhost
  database: survey_development
  username: root
  password:
  encoding: utf8

production:
  adapter:  mysql
  host:     survey
  database: survey_production
  username: survey
  password:
  encoding: utf8

mossad:
  adapter:  mysql
  host:     baza
  database: baza_production
  username: baza_survey
  password:
  encoding: utf8

A: Try adding RAILS_ENV=production

A: Your login/password pair is incorrect for MySql database in database.yml.
EDIT
You should remove your password row if it does not exist:
production:
  adapter:  mysql
  host:     survey
  database: survey_production
  username: survey
  encoding: utf8


text:
Q: No LDPI icon in the latest update of Eclipse Juno ADT I updated to the latest version of Eclipse Juno and I have the Android ADT on it.
When I start a new project, it doesn't give the LDPI icon anymore, and the drawable-ldpi folder is empty.
What is the problem here?
Thanks!

A: Only 10% of the devices are ldpi and this number is decreasing over time. Source: http://developer.android.com/about/dashboards/index.html
It is not required to have images for all the densities, only one is enough. The system will scale it up/down when needed. So the best approach is to have images for the highest density supported (xhdpi or xxhdpi).
I personally only use xhdpi images!


text:
Q: Is there a map which shows all the black holes in our galaxy? I am looking for a map which shows all black holes in the Milky Way.
See this exoplanet map for what I mean.

If it is not existing (yet). Is there at least an online catalogue which summarizes for all black holes which have been discovered so far?


text:
Q: iPhone:Can 3.1.2 built iPhone app installable on 3.0/3.1 devices? I have built an iPhone app with 3.1.2 SDK.

*

*Can it be able to deploy on my iPhone 3.0 or 3.1 device using the same provisional profile using Xcode?

*If i submit that app which built with 3.1.2 SDK, will it be able to install on iPhone 3.0 or 3.1 version users through AppStore?
If not, how can advertise that my app can be installed on iPhone 3.0, 3.1 and 3.1.2 as well during submitting it in AppStore?
Thanks.

A: My understanding is that the version of the SDK that you develop with determines the minimum version of the device that you will deploy to. So, unless you need any of the 3.1, or 3.1.2 features then just deploy to the store using the 3.0 SDK.


text:
Q: Python property setting does not assign the right instance attributes (leading underscores) when assigning via __setattr__ I can't set the right properties of an instance when setting their attributes via setattr in a factory method.
Given the following code where data is a simple dict containing e.g. { "age": "64", ...}
def factory(data):
    obj = MyClass()
    for k, v in data.items():
        setattr(obj, k, v)
    return obj

class MyClass(object):

    def __init__(self):

        self._age = None
        # more...

    @property
    def age(self):
        return self._age

    @age.setter
    def age(self, value):
        some_validation(value)
        self._age = value

    def __setattr__(self, name, value):
        object.__setattr__(self, name, value)

    def __getitem__(self, item):
        return self.__dict__.get(item, None)

    def __getattr__(self, item):
        self.__dict__[item] = None
        return None

    def __str__(self):
        return json.dumps(self, default=lambda o: o.__dict__)

c = factory(data)
print(c)

I always get the following output when printing the created object:
{"_age": "64", ...}

But I need to have
{"age": "64", ...}

Why does the setattr method assign the leading underscore?

A: Some of the things you are trying to achieve get mixed up, like wanting to print __dict__ for a readable representation, but using private attributes for properties. Let's start from scratch and see how we can implement your class correctly.
You are trying to implement a class which attributes can be accessed both as keys and attributes. That is fine and can be accomplished in a more concise way.
class MyClass:
    ...

    def __getitem__(self, item):
        return self.__getattribute__(item)

    def __setitem__(self, key, value):
        return self.__setattr__(key, value)

You also want None to be returned when an attribute does not exist. This is covered by __getattr__ which is called exactly when an attribute does not exist.
    def __getattr__(self, _):
        return None

Then you want to add some validation to some attributes with property. It is indeed the correct way to proceed.
    @property
    def age(self):
        return self._age

    @age.setter
    def age(self, value):
        # some validation here
        self._age = value

And finally you want to be able to have a nice string representation of your instance. We have to be careful for that since we had to add some private attributes that we do not want to print.
What we are going to do is implement a method keys to allow casting to dict. This method will only return keys for attributes which are not private nor methods.
    def keys(self):
        return [k for k in dir(self) if not k.startswith('_') and not callable(self[k])]

    def __str__(self):
        return json.dumps(dict(self))

This does the right thing.
obj = MyClass()

obj.age = 3

print(obj)
# prints: {"age": 3}


text:
Q: Access value of wordpress multidimensional array For one of my projects I created a custom post type and taxonomy chained to it.
I'm trying to access the values of said taxonomy in each of my custom posts, using this code I get a multidimensional array with said values:
<?php
            $specs = wp_get_post_terms($post->ID, 'specializzazioni', array("fields" => "all"));
            print_r($specs);
 ?>

output for example:
         Array
    (
        [0] => WP_Term Object
            (
                [term_id] => 6
                [name] => Chirurgia Toracica
                [slug] => chirurgia-toracica
                [term_group] => 0
                [term_taxonomy_id] => 6
                [taxonomy] => specializzazioni
                [description] =>
                [parent] => 0
                [count] => 1
                [filter] => raw
            )

    [1] => WP_Term Object
        (
            [term_id] => 7
            [name] => Oculistica Pediatrica
            [slug] => oculistica-pediatrica
            [term_group] => 0
            [term_taxonomy_id] => 7
            [taxonomy] => specializzazioni
            [description] =>
            [parent] => 0
            [count] => 2
            [filter] => raw
        )

)

I'm only trying to access the values of [name] and [slug] but I can't seem to find a way to do that.
Using the loop below outputs every value but that's not what I'm looking for
 <?php
foreach($specs as $row => $value){
    foreach($value as $row2 => $value2)
        echo $value2 . "<br/>";
}
?>

I tried using the name and slug keys on every variable but everytime I get a different type of error.

A: Notice that the array contains objects. You should be able to access name and slug for each object like this:
foreach ($specs as $object) {
  echo $object->name . ' ' . $object->slug;
}


text:
Q: Parallel Arrays for toys made by elves c++ I would really like help with this program, as I can't figure out what to do. I've tried searching online for answers or something that would point me in the right direction, but this is sort of difficult for me since I'm just learning how to code. I would greatly appreciate it!

You are to write a program that will help Santa process the work done by his elves. You will be using a data file called elves.dat. There will be one line for each elf. That line will contain the name of the elf and the number of toys the elf made. You are to read from the file and place the values in parallel arrays. You do not know how many elves there are so you must read until the end of file and count. You will need a third parallel array of strings to record a rating for each elf. You should declare arrays with the capacity for 50 components.
The program should read into the arrays. It should look at the number of toys made by each elf and record a rating in a parallel array. The table below determines the ratings. The program should then print out the arrays side by side in neat, labeled columns. It should print out the total number of toys made by the elves, the number of elves who made more than 500 toys, the name of the elf who made the most toys, and the name of the elf who made the least toys. Each calculation should have a function of its own. NO output should be done in functions that do calculations. All output should be done in one output function. Remember to always pass the number of elements in the array with the array to functions.
Toys Made........Rating
500 or more: ***** 5 stars
between 300 and 499: *** 3 stars
between 200 and 299: * 1 star
under 200: - none

Here's the information in elves.dat:
Smiley 662
Curley 88
Clementine 335
Jasper 105
Lucinda 775
Brunhilda 103
Florence 441
Oskar 820
Snowflake 990
Bernard 690
Punch 298
Chuckie 10
Frosty 102
Snowman 311
April 830
Merry 299
Sunshine 331
Buddy 1234
Carol 271
Misty 111
Harold 52
Henry 292
Twinkle 308
Starlight 703
Burr 112
Angelica 444
Bluenose 689
Harry 254
Twinkle 259
Stardust 121
Greensleeves 453
Noel 312
Happy 209
Yukon 534
Snowcap 190
Northpole 598

And here's my code, I feel like a have a very basic understanding, but I know I'm not even close! I would appreciate any help, I really need it.
#include <iostream>
#include <fstream>
#include <cstring>

using namespace std;

int main() {

  ifstream inFile;
  inFile.open("elves.dat");

  string elfName[50];
  int ToysMade[50];
  int count = 0;
  int i;
  //Read file until you've reached the end
  while (!inFile.eof()){
    inFile >> elfName;
    inFile >> ToysMade;
    count++;}
    cout << "Elf: " << elfName <<endl;
    cout << "Toys made: " << ToysMade <<endl;

    inFile.close();
  return 0;
}

A: Based on what you stated: this is how I would design the program. I could have even made it simpler looking by using a struct or class, but I'm gathering you are not that far in your course of training. Even this might be a bit more advanced than what is being asked. You did mention parallel arrays. Instead of arrays I'm using std::vectors in place of it. You can easily swap out the vectors with regular arrays, however the functions for doing the calculations would change since I'm using library functions that work on containers. With raw arrays you would have to do a bunch of for & while loops and comparison checks while also doing bounds checks of those arrays. Your overall program would look similar to this.
#include <string>
#include <vector>
#include <algorithm>
#include <numeric>
#include <iostream>
#include <iomanip>
#include <fstream>

// Typedefs
typedef std::vector<std::string> Strings;
typedef std::vector<unsigned> Values;

unsigned countToys( const Values& toys );
void determineRatings( const Values& toys, Values& ratings );
unsigned count5StarElves( const Values& toys );

std::string getBestElf( const Strings& elves, const Values& toys );
std::string getWorstElf( const Strings& elves, const Values& toys );

void displayStats( const unsigned numElves, const unsigned fiveStarElves,
                   const Strings& elves, const Values& toys, const Values& ratings,
                   const std::string& bestElf, const std::string& worstElf );

int main() {

    // Create Containers Giving 50 available spots.
    Strings elves;
    elves.resize( 50 );
    Values ratings;
    ratings.resize( 50 );
    Values toysMade;
    toysMade.resize( 50 );

    // Create, Open, Read From File & Close It
    unsigned numElves = 0;
    std::ifstream file;
    file.open( "elves.dat" );
    while ( file >> elves[numElves] >> toysMade[numElves] ) {
        numElves++; // Need this to resize containers.
    }
    file.close();

    // Adjust containers to fit number of elves.
    const std::size_t newSize = numElves;
    elves.resize( newSize );
    ratings.resize( newSize );
    toysMade.resize( newSize );

    // Get The Stats -- Counting the total number of elves is called within the display function.
    determineRatings( toysMade, ratings );
    unsigned fiveStarElves = count5StarElves( ratings );
    std::string bestElf  = getBestElf( elves, toysMade );
    std::string worstElf = getWorstElf( elves, toysMade );

    // Display The Results
    displayStats( numElves, fiveStarElves, elves, toysMade, ratings, bestElf, worstElf );

    std::cout << "\nPress any key and enter to quit." << std::endl;
    char c;
    std::cin >> c;

    return 0;
}

unsigned countToys( const Values& toys ) {
    unsigned total = std::accumulate( toys.begin(), toys.end(), 0 );
    return total;
}

void determineRatings( const Values& toys, Values& ratings ) {
    for ( unsigned i = 0; i < toys.size(); i++ ) {
        if ( toys[i] >= 500 ) {
            ratings[i] = 5;
        }

        if ( toys[i] < 500 && toys[i] >= 300 ) {
            ratings[i] = 3;
        }

        if ( toys[i] < 300 && toys[i] >= 200 ) {
            ratings[i] = 1;
        }

        if ( toys[i] < 200 ) {
            ratings[i] = 0;
        }
    }
};

unsigned count5StarElves( const Values& ratings ) {
    unsigned fiveStartCount = 0;
    for ( auto val : ratings ) {
        if ( val == 5 ) {
            fiveStartCount++;
        }
    }

    return fiveStartCount;
}

std::string getBestElf( const Strings& elves, const Values& toys ) {
    auto it = std::max_element( toys.begin(), toys.end() );
    if ( it == toys.end() ) {
        return "";
    }

    // for random access containers with O(1) - constant
    return elves[it - toys.begin()];

    // If using non-random containers use the following with O(n) - linear
    // return std::distance(toys.begin(), it );
}

std::string getWorstElf( const Strings& elves, const Values& toys ) {
    auto it = std::min_element( toys.begin(), toys.end() );
    if ( it == toys.end() ) {
        return "";
    }

    // for random access containers with O(1) - constant
    return elves[it - toys.begin()];

    // If using non-random containers use the following with O(n) - linear
    // return std::distance(toys.begin(), it);
}

void displayStats( const unsigned numElves, const unsigned fiveStarElves,
                   const Strings& elves, const Values& toys, const Values& ratings,
                   const std::string& bestElf, const std::string& worstElf ) {

    std::cout << "***********************************************\n";
    std::cout << "* Welcome To Santa's Workshop:                *\n";
    std::cout << "* We have " << numElves << " working elves.                   *\n";
    std::cout << "* Our Elves made a total of " << countToys( toys ) << " toys today. *\n";
    std::cout << "***********************************************\n\n";
    std::cout << "Here are their stats:\n";
    std::cout << "===============================================\n";

    // Calculate the longest name for proper screen output formatting.
    std::size_t maxLength = 0;
    for ( const auto name : elves ) {
        if ( name.length() > maxLength ) {
            maxLength = name.length();
        }
    }

    std::cout << std::left << std::setw( maxLength + '\t' ) << "Elf Name:" << std::setfill( ' ' ) << "Toys Made:\t\tRating:\n" << std::endl;

    for ( unsigned i = 0; i < numElves; i++ ) {
        std::cout << std::left << std::setw( maxLength + '\t' ) << elves[i] << std::left << std::setfill( ' ' )
            << std::setw( 4 ) << std::left << toys[i] << std::left
            << "\t\t" << ratings[i] << " stars" << std::endl;
    }

    std::cout << "\n\n";

    // Additional Stats:
    std::cout << "There are " << fiveStarElves << " 5 Star Elves!\n";
    std::cout << "The Best Elf is: " << bestElf << std::endl;
    std::cout << "The Worst Elf is: " << worstElf << std::endl;
}

elves.dat
Smiley 662
Curley 88
Clementine 335
Jasper 105
Lucinda 775
Brunhilda 103
Florence 441
Oskar 820
Snowflake 990
Bernard 690
Punch 298
Chuckie 10
Frosty 102
Snowman 311
April 830
Merry 299
Sunshine 331
Buddy 1234
Carol 271
Misty 111
Harold 52
Henry 292
Twinkle 308
Starlight 703
Burr 112
Angelica 444
Bluenose 689
Harry 254
Twinkle 259
Stardust 121
Greensleeves 453
Noel 312
Happy 209
Yukon 534
Snowcap 190
Northpole 598

Edit - If you want to do something a little fancy in the display function. Change the displayStats() function to this:
void displayStats( const unsigned numElves, const unsigned fiveStarElves,
                   const Strings& elves, const Values& toys, const Values& ratings,
                   const std::string& bestElf, const std::string& worstElf ) {

    std::cout << "***********************************************\n";
    std::cout << "* Welcome To Santa's Workshop:                *\n";
    std::cout << "* We have " << numElves << " working elves.                   *\n";
    std::cout << "* Our Elves made a total of " << countToys( toys ) << " toys today. *\n";
    std::cout << "***********************************************\n\n";
    std::cout << "Here are their stats:\n";
    std::cout << "===============================================\n";

    // Calculate the longest name for proper screen output formatting.
    std::size_t maxLength = 0;
    for ( const auto name : elves ) {
        if ( name.length() > maxLength ) {
            maxLength = name.length();
        }
    }

    std::cout << std::left << std::setw( maxLength + '\t' ) << "Elf Name:" << std::setfill( ' ' ) << "Toys Made:\t\tRating:\n" << std::endl;

    // A little bit of magic: (not really) just pretty
    Strings stars;
    std::string str;
    for each (auto star in ratings) {
        if ( star == 0 ) {
            str = std::string( "" );
        }

        if ( star == 1 ) {
            str = std::string( "*" );
        }

        if ( star == 3 ) {
            str = std::string( "***" );
        }

        if ( star == 5 ) {
            str = std::string( "*****" );
        }

        stars.push_back( str );
    }

    for ( unsigned i = 0; i < numElves; i++ ) {
        std::cout << std::left << std::setw( maxLength + '\t' ) << elves[i] << std::left << std::setfill( ' ' )
            << std::setw( 4 ) << std::left << toys[i] << std::left
            << "\t\t" << stars[i] /*ratings[i] << " stars"*/ << std::endl;
    }

    std::cout << "\n\n";

    // Additional Stats:
    std::cout << "There are " << fiveStarElves << " 5 Star Elves!\n";
    std::cout << "The Best Elf is: " << bestElf << std::endl;
    std::cout << "The Worst Elf is: " << worstElf << std::endl;
}


text:
Q: GCDAsyncUDPSocket: Not receiving any data though it is successfully sent I am trying to create a UDP socket and send data to a broadcasting port so that I can receive the same on other devices in the same WiFi network. I am calculating the IP address of broadcasting port as given in the accepted answer here.
After that I have written some connection code which is as below:
self.udpSocket = [[GCDAsyncUdpSocket alloc]initWithDelegate:self delegateQueue:dispatch_get_main_queue() socketQueue:nil];
NSError *error;
[self.udpSocket enableReusePort:YES error:&error];
[self.udpSocket enableBroadcast:YES error:&error];

- (IBAction)sendMessageToBroadcastPort:(id)sender {
 [self.udpSocket sendData:[@"Hi" dataUsingEncoding:NSUTF8StringEncoding] toHost:[self getUDPBroadcastAddress] port:5556 withTimeout:-1 tag:1];
}

I get success in sending the data as the delegate method didSendData: gets called.
Please guide me on what am I missing here.
Thanks!
UPDATE:
Cpde for receiving the data from  the broadcasting port:
- (void)listenForPackets
{
dispatch_queue_t dQueue = dispatch_queue_create("client udp socket", NULL);
udpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dQueue socketQueue:nil];
NSError *error = nil;

if (![udpSocket bindToPort:5556 error:&error]) {
    NSLog(@"Error binding: %@",error);//not connecting to host
    return;
}
if (![udpSocket beginReceiving:&error]) {
    NSLog(@"Error receiving: %@",error);
    return;
}
NSLog(@"Socket Ready");
}

 - (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data
  fromAddress:(NSData *)address
withFilterContext:(id)filterContext
{
NSString *msg = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if (msg)
{
    NSLog(@"RCV: %@", msg);
}
else
{
    NSString *host = nil;
    uint16_t port = 0;
    [GCDAsyncUdpSocket getHost:&host port:&port fromAddress:address];
    NSLog(@"Unknown message from : %@:%hu", host, port);
}
}

The broadcasting IP which I get after calculation is 192.168.2.255
UPDATE 2::
The scenario I am facing is really different and weird. The receiving works sometimes and sometimes it doesn't.
When I installed two apps there were no data received. Only sending was successful. I kept the apps on and after some time the app started receiving data. At some instances it stopped receiving after some time or kept receiving without any issue. What can be the issue?

A: Try like Below :
Create a Socket :
-(void)createClientUdpSocket
{
    dispatch_queue_t dQueue = dispatch_queue_create("client udp socket", NULL);

    sendUdpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue: dQueue socketQueue: nil];
    [sendUdpSocket receiveOnce:nil];
    [sendUdpSocket joinMulticastGroup:[self getIPAddress] error:nil]; // Put your IP Address
    NSLog(@"Ready");
}

Delegate method for Socket.
-(void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data fromAddress:(NSData *)address withFilterContext:(id)filterContext
{
     NSString *ip = [GCDAsyncUdpSocket hostFromAddress:address];
     uint16_t port = [GCDAsyncUdpSocket portFromAddress:address];
     NSString *s = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
     // Continue to wait for a message to receive the next
     NSLog (@ "The server receives the response [%@:% d]%@", ip, port, s);
     [sock receiveOnce:nil];

     dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
     [self sendBackToHost:ip port:port withMessage:s];
   });
}

-(void)sendBackToHost:(NSString *)ip port:(uint16_t)port withMessage:(NSString *)s{

      [sendUdpSocket sendData:yourData toHost:yourIP port:5556 withTimeout:60 tag:200];
       NSLog(@"sent message to server");
}

Hope this will help. Its working for me :)

A: I am answering this question as the scenario I faced is really different and weird. The receiving works sometimes and sometimes it doesn't.
When I installed two apps there were no data received. Only sending was successful. I kept the apps on and after some time the app started receiving data. At some instances it stopped receiving after some time.
Actually I was using a shared internet connection of my mac which is connected to ethernet. I changed my WiFi network to a proper broadband network and since then it works without any issue.
Hope this helps someone with similar scenario :)


text:
Q: Kendo UI Grid not showing JSON data I am facing this problem for quite a while now with the problem that I am unable to bind JSON data that my controller action is passing to the kendo UI Grid, there were few JavaScript issues before but now they are gone but still my grid is not showing any results:
In Model:
public object GetResult(string id)
    {
        var sqlCom = new SqlCommand("SELECT [No],[Desc],[Date],[Height],[Final] FROM [cr_form] WHERE [uId]=@id;", sqlConn);
        sqlCom.Parameters.AddWithValue("@id", id);

        StringBuilder sb = new StringBuilder();
        StringWriter sw = new StringWriter(sb);
        JsonWriter jsonWriter = new JsonTextWriter(sw);
        var rcrds = GETSQLRESULTS(sqlCom);

        try
        {
            int i = 0;
            if (rcrds != null || rcrds.HasRows)
            {
                //jsonWriter.WriteStartObject();
                while (rcrds.Read())
                {
                    jsonWriter.WriteStartObject(); //Changed
                    for (int j = 0; j < rcrds.FieldCount; j++)
                    {
                        jsonWriter.WritePropertyName(rcrds.GetName(j)); // column name
                        jsonWriter.WriteValue(rcrds.GetValue(j)); // value in column
                    }
                    i++;
                    jsonWriter.WriteEndObject(); //Changed
                }
                //jsonWriter.WriteEndObject();

            }

        }

        catch (Exception ex) { }
        return jsonWriter;
    }

In Controller:
    public ActionResult GetRecords()
    {
        var usrObj = new User();
        var jsnRslt = usrObj.GetResult(Session["Id"].ToString());
    //Till here jsnRslt contains this string: "{"No":null,"Desc":"asfasfasfasfasfasfasfasfasfasfasfasf","Date":"2013-03-27T00:00:00","Height":0,"Final":null,"No":null,"Desc":"etwetwetwetwet","Date":"2013-03-27T00:00:00","Height":0,"Final":0,"No":null,"Desc":"asfasfasfskfjklajsfkjasklfjklasjfklajsfkljaklsfjklasjfkljasfkljlasf","Date":"2013-03-27T00:00:00","Height":0,"Final":0,"No":null,"Desc":"askjfkajsfklaskjfkajsfklaskjfkajsfklaskjfkajsfklaskjfkajsfklaskjfkajsfklaskjfkajsfklaskjfkajsfklaskjfkajsfklaskjfkajsfklaskjfkajsfklaskjfkajsfkl","Date":"2013-03-27T00:00:00","Height":0,"Final":0,"No":null,"Desc":"safasfasfasfasfasf","Date":"2013-03-27T00:00:00","Height":0,"Final":0,"No":null,"Desc":"asfasf","Date":"2013-03-27T00:00:00","Height":0,"Final":0,"No":null,"Desc":"asfasfasf","Date":"2013-03-27T00:00:00","Height":2,"Final":0}"

    //After Changes in the Model I am getting it in the required Array format:
    //{"No":null,"Desc":"asfasfasfasfasfasfasfasfasfasfasfasf","Date":"2013-03-27T00:00:00","Height":0,"Final":null}
    //{"No":null,"Desc":"etwetwetwetwet","Date":"2013-03-27T00:00:00","Height":0,"Final":0}
    //{"No":null,"Des...

        return Json(jsnRslt, JsonRequestBehavior.AllowGet);
    }

In View:
<div>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#grid").kendoGrid({
                dataSource: {
                    type: "json",
                    serverPaging: true,
                    pageSize: 5,
                    groupable: true,
                    selectable: "row",
                    transport: { read: { url: "Records", dataType: "json"} }
                },
                height: 400,
                scrollable: true,
                sortable: true,
                filterable: true,
                pageable: true,
                columns: [
                        { field: "No", title: " No" },
                        { field: "Desc", title: "Description" },
                        { field: "Date", title: "Date" },
                        { field: "Height", title: "Height" },
                        { field: "Final", title: "Final" }
                    ],
                dataBound: function () {
                    this.expandRow(this.tbody.find("tr.k-master-row").first());
                }
            });
        });
    </script>
</div>

But after all this all I can see is an empty grid. And no errors in JavaScript console.
Please help

A: The JSON that you return from the server should be array. You currently it seems that you are returning single objects with multiple fields that are the same.
Here is an example how the JSON should look like:
[{"No":null,"Desc":"asfasfasfasfasfasfasfasfasfasfasfasf","Date":"2013-03-27T00:00:00","Height":0,"Final":null},
{"No":null,"Desc":"etwetwetwetwet","Date":"2013-03-27T00:00:00","Height":0,"Final":0},
{"No":null,"Desc":"asfasfasfskfjklajsfkjasklfjklasjfklajsfkljaklsfjklasjfkljasfkljlasf","Date":"2013-03-27T00:00:00","Height":0,"Final":0}]

A: I think  following code will be useful for you and let me know if you have any problem:
    $('#gridName').kendoGrid({
        dataSource: {
            type: "odata",
            transport: {
                read: {
                    contentType: "application/json; charset=utf-8",
                    type: "POST",
                    url: 'YourURL'
                }
            },
            pageSize: 10,
            type: "json"
        },
        scrollable: true,
        sortable: true,
        resizable: true

});

A: Inside you dataSource set data.
 data: @Html.Raw(Json.Encode(Model.RemoteObject)),

RemoteObject is you object containing all data.

A: First I check your tranport read URL. have you trace the controller if it fires the GetRecords command?
transport:
{
  read: {
    //if you don't use area then remove it
    url: "@Url.Action("GetRecords", new { area = "YourAreaName", controller = "YourControllerName" })",
    dataType: "json"
  }
}

if it still doesn't fix your problem, then modify your Controller,
public ActionResult GetRecords([DataSourceRequest] DataSourceRequest request)
{
    var usrObj = new User();
    var jsnRslt = usrObj.GetResult(Session["Id"].ToString());
    return Json(jsnRslt.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}

here's the link to understand the Kendo's ToDataSourceResult


text:
Q: Most general Feynman diagram What is the most general Feynman diagram?
Srednicki, in his Quantum Field Theory book, says:

The most general diagram consists of a product of several connected diagrams. Let $C_I$ stand for a particular connected diagram, including its symmetry factor. A general diagram $D$ can then be expressed as
$$ D = \frac{1}{S_D} \prod_I (C_I)^{n_I}$$
where $n_I$ is an integer that counts the number of $C_I$ 's in $D$, and $S_D$ is the additional symmetry factor for $D$ (that is, the part of the symmetry factor
that is not already accounted for by the symmetry factors already included
in each of the connected diagrams). [see eqn (9.12)]

Can anyone please explain this for me? It would be very helpful if you exemplify this.
I have another question too. Can you give me a reference where phi-cubed theory is treated as I can use it as a reference while reading Srednicki.

A: To explain what Srednicki is doing:
$C_i$ labels the connected diagrams with symmetry factors associated with them (individual diagrams) included, $n_i$ represents the number of diagrams $C_i$ present in the disconnected diagram $D$ and $S_D$ is an extra symmetry factor for the entire disconnected diagram due to interchange of lines between different connected graphs. Note that because we have $n_i$ copies of $C_i$ in our disconnected diagram, not only can we interchange lines in the individual diagrams due to symmetries (which has already been taken into account), but we can also change lines between diagrams of the same type, this contributes to the overall symmetry factor of the diagram. As we have $n_i$ of each $C_i$ we find $S_D = \prod_i n_i!$, so each diagram $D$ can be written as: $$D = \prod_{i}\frac{1}{n_i!}{C_i}^{n_i}$$