text:
Q: Significance of Static variable in a Trigger Can anyone help me in understanding the significance of having a Static variable in Trigger with any real time example.
For Example
Trigger on Account(after Insert,after Update)
{
   Static String testVariable = 'Hello' // Why do we declare Static in a trigger what is the significance?
}

I understand the significance of it in a class. A static variable defined in a class serves as a common variable which is shared across all the objects of the class.

A: static in a trigger is an allowed keyword, most likely as a way of simplifying the compiler logic, but has no effect when used in a trigger. Static variables are not persisted in a trigger, only in classes.

A: Here I got a thread on Stack Exchange that states the same query. I suppose that will be nice if you go through this one:
Static variables defined in a trigger

A: Static variables in triggers are allowed by the syntax of Apex, but in my 4.5 years on the Salesforce platform, I have not found a practical use for them.
The reason is that static variables defined in a trigger behave differently than static variables defined in an Apex class do. It's more accurate to say that Triggers behave differently than regular Apex Classes
The documentation page Static and Instance Method, Variables, and Initialization Code covers the differences between static vars in classes, and static vars in triggers pretty well.
Probably the most important bit in regards to your question here is the following paragraph from that page:

A static variable defined in a trigger doesn't retain its value between different trigger contexts within the same transaction, such as between before insert and after insert invocations. Instead, define the static variables in a class so that the trigger can access these class member variables and check their static values.

Going further, a static variable defined in a trigger (because we can't currently define a static{ ... } block inside a trigger) is re-declared and re-initialized each time the trigger is executed. Combine that with the fact that Salesforce breaks trigger executions into batches of (at most) 200 records, and the result is that variables declared static in a trigger, in addition to not being retained between different trigger events like before insert and after insert, are not retained between separate trigger batches if you're performing DML on more than 200 records of a single object at once.
You can verify this for yourself by adding the following snippet to any trigger
// I assume this is either an insert or update trigger
Static List<SObject> encountered;

// If static vars in triggers are persisted across contexts, this if would
//   prevent us from overwriting our existing list with a new (empty) one.
if(encountered == null){
    encountered = new List<SObject>();
}

encountered.addAll(trigger.new);

system.debug('Number of records in trigger static variable: ' + encountered.size());

And then looking at the execution log after executing the following as anonymous apex
// In this example, I added the trigger snippet to a Contract trigger.
// You'll need to adjust this to create appropriate records for whatever trigger
//   you added the snippet to.
// Also, probably a good idea to do this in a sandbox environment (as opposed to production)
Account acct = [SELECT Id FROM Account WHERE RecordType.Name = 'Billing' LIMIT 1];
List<Contract> contracts = new List<Contract>();
for(Integer i = 0; i < 210; i++){
    contracts.add(new Contract(
        AccountId = acct.Id
    ));
}

insert contracts;

// In your debug log, you should see
// 'Number of records in trigger static variable: 200'
// and then later on...
// 'Number of records in trigger static variable: 10'
// These may be repeated, depending on if your trigger handles both the 'before' and
//   'after' events, but it will never result in seeing '210' (or anything
//   greater than 200)

So the end result is that static variables defined inside of a trigger are useless.


text:
Q: How to edit each line of file and write to file after each edit I have a file that is very large. I need to rearrange something in the file but the file is too large to load into memory. I was thinking of ways to achieve this goal and what I came up with was just editing the file line by line. So what I need to do is read the file, remove certain columns, and then write the file. As I mentioned before, the file is very large so I need to write the file as the script runs. I will give an example data set and the code that I am using
Here is an example dataset
{'CHROM': {0: 'chr1', 1: 'chr1'}, 'POS': {0: 10397, 1: 12719}, 'ID': {0: '.', 1: '.'}, 'REF': {0: 'CCCCTAA', 1: 'G'}, 'ALT': {0: 'C', 1: 'C'}, 'QUAL': {0: 943.64, 1: 255.34}, 'FILTER': {0: 'VQSRTrancheINDEL99.00to100.00', 1: 'VQSRTrancheSNP99.80to100.00'}, 'INFO': {0: 'AC=1;AF=0.5;AN=2;BaseQRankSum=1.07;ClippingRankSum=-0.322;DP=11;ExcessHet=0.2139;FS=1.056;InbreedingCoeff=0.1828;MQ=27.81;MQ0=0;MQRankSum=1.59;NEGATIVE_TRAIN_SITE;QD=25.5;ReadPosRankSum=0.572;SOR=0.922;VQSLOD=-2.735;culprit=DP', 1: 'AC=1;AF=0.5;AN=2;BaseQRankSum=-0.922;ClippingRankSum=-0.198;DP=7;ExcessHet=0.0067;FS=0;InbreedingCoeff=0.4331;MQ=24.5;MQ0=0;MQRankSum=-1.495;QD=17.02;ReadPosRankSum=1.5;SOR=3.126;VQSLOD=-28.96;culprit=MQ'}, 'FORMAT': {0: 'GT:AD:DP:GQ:PL', 1: 'GT:AB:AD:DP:GQ:PL'}, 'CGND-HDA-03201': {0: '0/1:5,6:11:99:224,0,156', 1: '0/1:0.29:2,5:7:42:126,0,42'}, 'CGND-HDA-03202': {0: '0/1:5,6:11:99:224,0,156', 1: '0/1:0.29:2,5:7:42:126,0,42'}}

Here is the code that I am using
n = 0
for line in open(input, "r+"):
    li=line.strip()
    if li.startswith("#"):
        n = n+1
    if not li.startswith("#"):
        test = li.split("\t")
        test2 = (f"{test[0]}\t{test[1]}\t{test[9:]}")
        with open("output.txt","w") as out:
            out.write(test2, sep='\t')

I have a few problems here

*

*the output contain on one single line, the last line that was read. For example, the file contains one line like this
chr1    1021791 ['0/1:0.56:22,17:39:99:414,0,623', '0/1:0.56:22,17:39:99:414,0,623']

*I don't want the output to have any bracket. I need the output to look more like this
chr1    1021791 0/1:0.56:22,17:39:99:414,0,623     0/1:0.56:22,17:39:99:414,0,623

*I need the ouput file to be tab delimited
Is there a way I can continuously write to a file after each line is edited?
The original file does contain #'s that I didn't show here, so the part of the script that ignores lines with #'s is required
I know this can easily be done using bash but I am looking for a solution using python.

A: seperator should be \n instead of \t while writing to the file. Also opening file in w mode inside the for loop overrides the previous contents of the file.
import ast
n = 0
with open("output.txt","w") as out:
    for line in open(input, "r+"):
        li=line.strip()
        if li.startswith("#"):
            n = n+1
        elif not li.startswith("#"):
            test = li.split("\t")
            new_test = ast.literal_eval(str(test[9:]))
            test2 = (f"{test[0]}\t{test[1]}\t{new_test[0]}\t{new_test[1]}\n")
            out.write(test2)

A: Prakash Dahal solution works great. After playing with the data a bit more, I realized that test[9:] will likely be a large number of extracted values so I wouldn't want to have to list each of the newvalue's in test2 = (f"{test[0]}\t{test[1]}\t{new_test[0]}\t{new_test[1]}\n")
Since new_test = test[9:] is a list, I combine the list to make a tab-delimited string. This results in the overall desired output
n = 0
with open("output.txt","w") as out:
    for line in open(input, "r+"):
        li=line.strip()
        if li.startswith("#"):
         n = n+1
        elif not li.startswith("#"):
            test = li.split("\t")
            new_test = test[9:]
            new_test = '\t'.join(new_test)
            test2 = (f"{test[0]}\t{test[1]}\t{new_test}\n")
            out.write(test2)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Typescript: TS2322 with Generics classes Typescript gives me a hard time with generics. When compiling this project, I get a TS2322 error at return new TransformedBase(); (you can c/c this project in the Typescript playground, it works)
For more context, we have a lot of project using a Core project. The goal is to mutualize all we can into Core, and use Angular injection to change the behaviour in each app.
Since TB extends TransformedBase, and I'm returning a new TransformedBase() why is Typescript refusing to compile?
Thank you
// Projet 'Core'
class Base {
    a: string;
}

class TransformedBase {
    z: string;
}

class BaseTransformer<B extends Base, TB extends TransformedBase> {
    transform(source: B): TB {
        return new TransformedBase();
    }
}

class GenericService<B extends Base, TB extends TransformedBase> {
    private transformer: BaseTransformer<B, TB>;
    constructor(transformer: BaseTransformer<B, TB>) {
        // transformer is injected
        this.transformer = transformer;
    }

    doWork(source: B): TB {
        return this.transformer.transform(source)
    }
}

// One of the project which use Core
// import Base from 'core/Base'
// import TransformedBase from 'core/TransformedBase'
// import BaseClass from 'core/BaseClass'

class Better extends Base {
    b: string;
}

class TransformedBetter extends TransformedBase {
    w: string;

    constructor(transformedBase: TransformedBase) {
        super();
        // Do something
        this.w = `Hello ${transformedBase.z}`;
    }
}

class BetterTransformer extends BaseTransformer<Better, TransformedBetter> {
    transform(source: Better): TransformedBetter {
        super.transform(source);
        return new TransformedBetter(super.transform(source));
    }
}

A: If all you know is that TB extends TransformedBase then TB is a subtype of TransformedBase.  So every TB is a TransformedBase, but not every TransformedBase is necessarily a TB. So the implementation of transform() in BaseTransformer is incorrect. You'd need to return a new instance of TB but you don't have any constructor for it.
I'd suggest not even having an implementation for BaseTransformer, since it's pretty useless.  Maybe BaseTransformer should be an abstract class or interface instead.
Hope that helps; good luck!


text:
Q: Gifting specific apps from within an app A client has asked us to create an app for iOS that gifts other apps to their customers. I.e. a customer downloads the app, in which some paid App Store app are offered for free. The fee is paid by our client.
Essentially, it should work pretty much like Apple's 12 days of Christmas app.
I can't find any way to achieve this. There apparently is no way to forward an app's purchase to another Apple ID.
Did I miss any obvious API or SDK to make this possible? Or can't this be done?

A: This can't be done for paid apps.  If you control all apps you can make the apps free with in app purchase and then use another app to "gift the in app purchase". You would have to fully implement the gifting mechanism through your servers.


text:
Q: Django restframework generics.ListCreateAPIView returns list like objects class UserProfileView(generics.ListCreateAPIView):
    permission_classes = (
    permissions.IsAuthenticated,
    )
    serializer_class = UserProfileSerializer

    def list(self,request):
        queryset = UserProfile.objects.filter(user=request.user.id)
        serializer = UserProfileSerializer(queryset, many=True)
        return Response(serializer.data)

I've got out pull like this
[
  {
    "id": 1,
    "firstname": "exp",
    "lastname": "exp"
  }
]

I wanted like this,How can i do that and i don't know why it's returning list like object, How can i fix this
{
    "id": 1,
    "firstname": "exp",
    "lastname": "exp",
}

A: ListCreateAPIView is designed to return list of objects.
Representation like this
{
    "id": 1,
    "firstname": "exp",
    "lastname": "exp",
}

Means you want an object, not list of objects, which means you need to get desired object by using RetrieveAPIView
There are no RetrieveCreateAPIView, but you can easily make with RetrieveModelMixin
Like this
from rest_framework import mixins, generics

class UserProfileView(mixins.RetrieveModelMixin, generics.CreateAPIView):
    permission_classes = (
        permissions.IsAuthenticated,
    )
    serializer_class = UserProfileSerializer

    # Custom get_object method which is gets from request
    # instead of queryset
    def get_object(self, queryset=None):
        return UserProfile.objects.get(user=self.request.user)

    # You can look this up in RetrieveAPIView
    def get(self, request, *args, **kwargs):
        return self.retrieve(request, *args, **kwargs)

Update
You need to overload get_object method, by default get_object will look in passed url parameters and try to get object from provided queryest. It is made like this to be generic for CRUDL usage. After that returned value from get_object is used to instantiate serializer_class.  But in your case you need to just return current user in request. See updated answer. All this info can be understood if you look up retrieve method relaisation. For developer it is essential skill to know how to read source code.


text:
Q: Proving inequality for all real $a$ and $b$. I am trying to prove the following two inequalities
My first intuition was to take the natural log of both sides, then simplify them to get an obvious statement regarding a and b. But I can't reduce the natural log of the right hand-side of the inequality (because of the addition operator).
I'm feeling really stumped and dumb, so a hint would be great!

A: for the first one:
dividing by $$e^{a+2b}\ne 0$$ and we get
$$3\le e^{2(a-b)}+\frac{2}{e^{a-b}}$$
substituting $$z=e^{a-b}$$ then we get
$$3\le z^2+\frac{2}{z}$$
can you finish?
and this is equivalent to $$0\le (z+2)(z-2)^2$$ which is true. For your send question:
we get the general case : $$\frac{a^n+b^n}{2}\geq \left(\frac{a+b}{2}\right)^n$$

A: The first inequality:
By AM-GM
$$\frac{e^{3a}+2e^{3b}}{3}\geq\sqrt[3]{e^{3a}\left(e^{3b}\right)^2}=e^{a+2b}$$
The second inequality it's Jensen for $f(x)=x^{2018}$:
$$\frac{a^{2018}+b^{2018}}{2}\geq\left(\frac{a+b}{2}\right)^{2018}.$$

A: If we divide first one with $e^{a+2b}$ we get $$3\leq (e^{a-b})^2+2e^{b-a}$$
Now let $x=e^{a-b}$ so we have to prove $$3\leq x^2+{2\over x}$$
which is true by inequality between arithmetic and geometric mean:
$$ x^2+{1\over x}+{1\over x} \geq 3\cdot \sqrt[3]{x^2{1\over x}{1\over x}}=3$$

A: *

*Use AM-GM on $e^{3a},e^{3b},e^{3b}$ so that $$\frac{e^{3a}+2e^{3b}}{3} \ge e^{a}e^{2b}$$

*Use Jensen's inequality on $x\mapsto x^{2018}$, which is a convex function (since it has a positive second derivative except at $x=0$).
\begin{align}
\left(\frac{a+b}{2}\right)^{2018} &\le \frac12 a^{2018}+\frac12 b^{2018} \\
(a+b)^{2018} &\le 2^{2017} a^{2018} + 2^{2017} b^{2018}
\end{align}

Since OP starts by taking log, but none of the existing answers use log, I'll continue OP's work.

*

*Take log on both sides to get

\begin{align}
e^{a+2b} &\le \frac13 e^{3a} + \frac23 e^{3b} \\
\iff a+2b &\le \log \left( \frac13 e^{3a} + \frac23 e^{3b} \right) \\
\iff \frac13 \log e^{3a} + \frac23 \log e^{3b} &\le \log \left( \frac13 e^{3a} + \frac23 e^{3b} \right) \\
\iff \frac13 f(e^{3a}) + \frac23 f(e^{3b}) &\le f \left( \frac13 e^{3a} + \frac23 e^{3b} \right),
\end{align}
which is Jensen's inequality for the concave function $f: x \mapsto \log x$.


text:
Q: JAX-RS Jersey JSON preserve null using annotations How do I have JAXB preserve nulls when receiving a JSON sting that contains a null or "" value.
String:{"id":null,"fname":"John","region":""}
returns Object:
 Person {
    Integer id = 0
    String fname = "John"
    Region regions = 0 }

I would like it to return null instead of 0
Here is what I have so far:
@Provider
public class JAXBContextResolver implements ContextResolver<JAXBContext> {
    private JAXBContext context;
    private Class<?>[] types = {Person.class};

    public JAXBContextResolver() throws Exception {
        this.context = new JSONJAXBContext(JSONConfiguration.natural().build(), types);
    }

    public JAXBContext getContext(Class<?> objectType) {
        for (Class<?> c : types) {
            if (c.equals(objectType)) {
                return context;
            }
        }
        return null;
    }
}

Person.class is annotated with @XmlRootElement I've tried looking into Jackson annotations but have had no success.

A: Note:  I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB (JSR-222) expert group.
Below is an example of how this can be done with MOXy.
Person
MOXy will unmarshal the Person object as you want without specifying any metadata.  To have the output JSON contain null values, you can use the @XmlElement(nillable=true) annotation (see Binding to JSON & XML - Handling Null).
package forum8748537;

import javax.xml.bind.annotation.*;

@XmlAccessorType(XmlAccessType.FIELD)
public class Person {

    @XmlElement(nillable=true)
    Integer id;

    @XmlElement(nillable=true)
    String fname;

    @XmlElement(nillable=true)
    Region regions;

}

jaxb.properties
To specify MOXy as your JAXB (JSR-222) provider you need to add a file called jaxb.properties in the same package as your domain classes with the following entry (see Specifying EclipseLink MOXy as Your JAXB Provider).
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory

Demo
package forum8748537;

import java.io.StringReader;
import java.util.*;

import javax.xml.bind.*;
import javax.xml.transform.stream.StreamSource;

public class Demo {

    public static void main(String[] args) throws Exception {
        Map<String, Object> properties = new HashMap<String, Object>(2);
        properties.put("eclipselink.media-type", "application/json");
        properties.put("eclipselink.json.include-root", false);
        JAXBContext jc = JAXBContext.newInstance(new Class[] {Person.class}, properties);

        StringReader json = new StringReader("{\"id\":null,\"fname\":\"John\",\"region\":\"\"}");
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        Person person = unmarshaller.unmarshal(new StreamSource(json), Person.class).getValue();

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(person, System.out);
    }

}

Output
{
   "id" : null,
   "fname" : "John",
   "regions" : null
}

Using MOXy in a JAX-RS Application
For an example of using MOXy in a JAX-RS application see:

*

*MOXy as Your JAX-RS JSON Provider - Server Side

*MOXy as Your JAX-RS JSON Provider - Client Side

A: As of JSON-B JSR-367 (JAX-RS 2.1 JSR-370), the following annotation works instead of @XmlElement.
@JsonbProperty(nillable = true)


text:
Q: Vertically align Bootstrap badge inside heading When I use a Bootstrap badge inside of heading such as h1,h2,h3 the vertical alignment is off. The badge aligns towards the bottom of the heading text. I'd like the badge to align vertically centered with the heading text.
HTML

badge Heading 1

badge Heading 2

badge Heading 3

CSS
h1,h2,h3 {
  vertical-align:middle;
}

h1>.badge, h2>.badge, h3>.badge {
  vertical-align:middle;
}

Result..
See this Bootply: http://bootply.com/88526

How can I get this to align on center vertically?

A: In Bootstrap 4, the vertical alignment issue is no longer a problem since the badge will inherit the size of the containing heading..

badge Heading 1

badge Heading 2

badge Heading 3

However, the align-middle class be used to vertically align badges outside of the heading.

  badge Heading 1

  badge Heading 2

  badge Heading 3

Demo: https://www.codeply.com/go/rE0z3665zh

A: Always hated this problem.
A little hacky but this works:
h1 { font-size: 2em; }
h2 { font-size: 1.6em; }
h3 { font-size: 1.4em; }
h1,h2,h3 {
    vertical-align:middle;
}

  h1>.badge, h2>.badge, h3>.badge {
    vertical-align:middle;
    margin-top: -0.5em;
}

Defined the heading font-sizes for demo purposes


text:
Q: How to fill inputs when editing an article in flask I have a list of articles.

After I press Edit, I am redirected to another page containing in the url the id of the article that wants to be edited.
Edit

This is where I am redirected:

And I want the inputs to be filled with the title and the body text of the respective article.
This is my backend function:
@app.route('/edit_article/<string:id>', methods=['POST', 'GET'])
def edit_article(id):
    conn = mysql.connect()
    cursor = conn.cursor()

    result = cursor.execute("SELECT * from articles where id=%s", [id])
    data = cursor.fetchone()

    if result < 0:
        flash("Article does not exist!")

    cursor.close()
    conn.close()

    return render_template("edit_article.html", data=data)

How can I use data to fill those inputs? Please help. Thank you.
I will put also the edit_article.html
{% extends 'layout.html' %}

{% block body %}

Bucket List App

        <form class="form-addArticle">
        Title
        <input type="name" name="inputTitle" id="inputTitle" class="form-control" placeholder="Title" required autofocus>
        Body
        <input type="text" name="inputBody" id="inputBody" class="form-control" placeholder="Body" required autofocus>

        <button id="btnEditArticle" class="btn btn-lg btn-primary" type="button">Update article</button>
      </form>

{% endblock %}

A: You can just need to add value="{{ ... }}" to your inputs:
<input type="name" value="{{ data[0] }}" name="inputTitle" id="inputTitle" class="form-control" placeholder="Title" required autofocus>
<input type="text" value="{{ data[1] }}" name="inputBody" id="inputBody" class="form-control" placeholder="Body" required autofocus>

But it's recommended to name the values:
name, text = cursor.fetchone()
return render_template("edit_article.html", name=name, text=text)

and then
<input type="name" value="{{ name }}" name="inputTitle" id="inputTitle" class="form-control" placeholder="Title" required autofocus>
<input type="text" value="{{ text }}" name="inputBody" id="inputBody" class="form-control" placeholder="Body" required autofocus>

But I'd personally recommend WTForms module instead of rendering forms manually - it can for example help to validate your inputs properly.


text:
Q: rolling median stiil leave one NaN value I have a dataframe as follows:
    3348    3349    3350    3351    3352    3353    3354    3355    3356    3357    ... 40287   40288   40289   40290   40291   40292   40293   40294   40295   40296
U1  231.7   232.4   232.1   232.1   214 232.3   218.5   217.3   231.7   217.1   ... 223.9   231.5   222.8   234.6   230.7   230.8   227.3   232.3   229.4   NaN
U2  NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... 221.2   227.2   218.8   234.6   227 232.2   230.5   232.1   233.7   226.1
U3  NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... 225.3   228.3   223.1   234.5   227 233.6   231 234.2   233.4   225.8
U4  NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... 225.2   230.6   NaN 235.5   228.3   232.4   230.6   231.1   230.5   227.3
U5  230.3   231.4   230.4   230.4   220.4   232.8   219 217.9   230.2   220.4   ... 224.9   228.9   223.7   231.9   227.1   232.4   231.5   231.1   230 225.9
... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
U92 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... 229.3   235.3   227.3   230.8   234 231.6   228.5   229.5   227.3   234.6
U93 238.8   238.3   239.2   239.4   227.3   238.9   239.3   232.2   238.6   227.7   ... NaN 237.5   229 237.1   NaN 232.1   223.2   NaN 227.9   235.1
U94 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... 231.9   236 232.9   238.3   234.4   NaN 232.9   230.9   229 234.5
U95 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... 233.9   237.5   233.6   236.6   NaN 235.2   234.8   236.6   230 235.5
U96 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN

There are several NaN values and I did a data cleaning using pandas's rolling() method as follows:
X = X.fillna(X.rolling(12, min_periods=1).median())

I want to replace the NaN with a rolling median of window size 12 and at least 1 valid values should be present in the window.
Ans the result is :

3348    3349    3350    3351    3352    3353    3354    3355    3356    3357    ... 40287   40288   40289   40290   40291   40292   40293   40294   40295   40296
U1  231.7   232.4   232.1   232.1   214 232.3   218.5   217.3   231.7   217.1   ... 223.9   231.5   222.8   234.6   230.7   230.8   227.3   232.3   229.4   NaN
U2  231.7   232.4   232.1   232.1   214 232.3   218.5   217.3   231.7   217.1   ... 221.2   227.2   218.8   234.6   227 232.2   230.5   232.1   233.7   226.1
U3  231.7   232.4   232.1   232.1   214 232.3   218.5   217.3   231.7   217.1   ... 225.3   228.3   223.1   234.5   227 233.6   231 234.2   233.4   225.8
U4  231.7   232.4   232.1   232.1   214 232.3   218.5   217.3   231.7   217.1   ... 225.2   230.6   222.8   235.5   228.3   232.4   230.6   231.1   230.5   227.3
U5  230.3   231.4   230.4   230.4   220.4   232.8   219 217.9   230.2   220.4   ... 224.9   228.9   223.7   231.9   227.1   232.4   231.5   231.1   230 225.9
... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
U92 237.1   237.3   237.4   237.5   231.3   238.9   240.2   230.5   237 236.1   ... 229.3   235.3   227.3   230.8   234 231.6   228.5   229.5   227.3   234.6
U93 238.8   238.3   239.2   239.4   227.3   238.9   239.3   232.2   238.6   227.7   ... 228.3   237.5   229 237.1   234 232.1   223.2   231.65  227.9   235.1
U94 237.95  237.8   238.3   238.45  229.3   238.9   239.75  231.35  237.8   231.9   ... 231.9   236 232.9   238.3   234.4   232.1   232.9   230.9   229 234.5
U95 238.8   238.3   239.2   239.4   227.3   238.9   239.3   232.2   238.6   227.7   ... 233.9   237.5   233.6   236.6   234.3   235.2   234.8   236.6   230 235.5
U96 238.8   238.3   239.2   239.4   227.3   238.9   239.3   232.2   238.6   227.7   ... 231.05  236.5   230.9   236.6   234.3   232.1   229.4   231.35  228.8   234.7

As can be seen that all NaNs are replached by a moving median of window size 12. But there is still one NaN at the top right corner. It seems that this specific NaN is always there, whatever I tune the window_size and min_period paramters of the rolling() function.
Why is this and how can I get rid of the NaN value on the top right corner?

A: You can just add another step:
X = X.fillna(X[40296].median(), axis 1, inplace=True)

I am using the median of the Column titled 40296, in this example, but you could use any value you deem appropriate.


text:
Q: Comparing a single value to multiple values from arrays in python My code looks like this:
import requests
import re
import mechanize
import urllib
import json

htmltext = urllib.urlopen("https://www.binance.com/api/v1/klines?symbol=BCDBTC&interval=4h")

data = json.load(htmltext)

current_price= data[len(data)-1][4]
last_prices= (data[len(data)-2][4],data[len(data)-3][4],data[len(data)-4][4],data[len(data)-5][4],data[len(data)-6][4])
last_volumes= (data[len(data)-2][5],data[len(data)-3][5],data[len(data)-4][5],data[len(data)-5][5],data[len(data)-6][5])
current_volume= data[len(data)-1][5]

print current_price
print last_prices
if current_price > last_prices:
    print "the current price is greater than the last 5"
print current_volume
print last_volumes
if current_volume > last_volumes:
    print "the current volume is higher than the last 5"

But my output is this:
0.00495600
(u'0.00492500', u'0.00366300', u'0.00332800', u'0.00333800', u'0.00308000')
the current price is greater than the last 5
938.01000000
(u'29687.32500000', u'14740.03800000', u'9366.77400000', u'10324.83200000', u'44953.53400000')
the current volume is higher than the last 5

The problem here is the current volume is certainly not greater than the last 5 but it's still printing it out regardless
I'm grabbing data from here
https://www.binance.com/tradeDetail.html?symbol=BCD_BTC

A: First, your data are not all converted to numbers, many of them are in string format. To convert them all to floating point numbers, you can use this formula:
data = [[float(x) for x in row] for row in data]

Next, in the if statement, you are comparing a number with a sequence of numbers. What you want is to compare this number with the largest in the sequence:
if current_price > max(last_prices):
    print "the current price is greater than the last 5"

Putting it all together:
# code to obtain data is the same

PRICE = 4
VOLUME = 5
LAST_ROW = -1

data = [[float(x) for x in row] for row in data]

current_price = data[LAST_ROW][PRICE]
current_volume = data[LAST_ROW][VOLUME]
last_prices = tuple(row[PRICE] for row in data[-6:-1])
last_volumes = tuple(row[VOLUME] for row in data[-6:-1])

print 'current_price =', current_price
print 'current_volume =', current_volume
print 'last_prices =', last_prices
print 'last_volumes =', last_volumes

if current_price > max(last_prices):
    print "the current price is greater than the last 5"

if current_volume > max(last_volumes):
    print "the current volume is higher than the last 5"


text:
Q: How can I print the contents of a js file to the screen from a URL? I have an application that will check if a javascript file exists on our CDN and I would like to display the contents of that file in the browser window.  I have all the nuts and bolts figured out, I just need to display the contents of the javascript file when I put in the URL where it exists.
Thanks in advance.

A: I believe you can output a javascript file to a webpage by just making sure any html elements are escaped. You can use the htmleditformat() function to do this when you output the value.
For example:
<cfhttp url="#jsurl#"  />
<cfoutput><pre>#htmleditformat(cfhttp.filecontent)#</pre></cfoutput>

Other options just using the js address directly are to 1) link to the js file if you just want to be able to see it in the window, or 2) show the js file in an iframe

A: I'm not quite sure what you're asking:

*

*"I need to open a javascript file in a web browser"
A. this is OS dependant, you call the binary that's registered for .htm files with parameters pointing it's initial destination to that .js file.

*"I have a web app and want to dynamically display the contents of remote files formatted as text"
A. Use a  block and fill it with GetWebResourceUrl().

*"I am writing a standalone app and want to display remote files as text"
A. If you are writing a standalone, why do you want to display the contents of a js file via a browser? Use your local API, or launch the default text viewer with a local temp copy.


text:
Q: Select all records within month and year When I tried to select records for specific month and year when I search I found half a solution
mysql: select all entries from a particular month using PHP
select *
from thetable
where monthname(date_field) = 'February'

then i modify it following
select *
from payments
where monthname(date) = 'February' and EXTRACT(date )='2011';

but it show error what is correct way to select mounth and year
in my table i store date as     2011-2-4

A: it seems that your column is not in a Date data type, so the best way you can do is to convert it first to DATE using STR_TO_DATE
SELECT  *
FROM    Payments
WHERE   MONTHNAME(STR_TO_DATE(date,'%Y-%c-%e')) = 'FEBRUARY' AND
        YEAR(STR_TO_DATE(date,'%Y-%c-%e')) = 2011

A: Try this:
select * from payments p
where year(p.date) = 2011 and monthname(p.date) = 'February'


text:
Q: Row and column average in dynamic pivot In SQL Server 2008, I have a table tblStock with 3 columns:
PartCode (NVARCHAR (50))
StockQty (INT)
Location (NVARCHAR(50))

Some example data below:

I want to get the following output,

I have written the following query to get the above output, Avg value is not being returned properly:
IF OBJECT_ID('tempdb..#tblStock') IS NOT NULL /*Then it exists*/
    DROP TABLE #tblStock

SELECT *
INTO #tblStock
FROM
    (SELECT 'A' PartCode,  10 StockQty, 'WHs-A' Location
     UNION ALL
     SELECT 'B',   22,  'WHs-A'
     UNION ALL
     SELECT 'A',   1,   'WHs-B'
     UNION ALL
     SELECT 'C',   20,  'WHs-A'
     UNION ALL
     SELECT 'D',   39,  'WHs-F'
     UNION ALL
     SELECT 'E',   3,   'WHs-D'
     UNION ALL
     SELECT 'F',   7,   'WHs-A'
     UNION ALL
     SELECT 'A',   9,   'WHs-C'
     UNION ALL
     SELECT 'D',   2,   'WHs-A'
     UNION ALL
     SELECT 'F',   54,  'WHs-E') TAB

SELECT * FROM #tblStock

DECLARE @cols NVARCHAR (MAX)
SELECT @cols = COALESCE (@cols + ',[' + Location + ']', '[' + Location + ']')
               FROM (SELECT DISTINCT Location FROM #tblStock) PV
               ORDER BY Location
-- Since we need Total in last column, we append it at last
SELECT @cols += ',[AVG]'

-- Variable to replace NULL with zero
DECLARE @NulltoZeroCols NVARCHAR (MAX)
SELECT @NullToZeroCols = SUBSTRING((SELECT ',ISNULL(['+Location+'],0) AS ['+Location+']'
FROM (SELECT DISTINCT Location FROM #tblStock)TAB
ORDER BY Location FOR XML PATH('')),2,8000)
SELECT @NullToZeroCols += ',ISNULL([AVG],0) AS [AVG]'

DECLARE @query NVARCHAR(MAX)
SET @query = 'SELECT PartCode,' + @NulltoZeroCols + ' FROM
             (
                 SELECT
                 ISNULL(CAST(PartCode AS VARCHAR(30)),''AVG'')PartCode,
                 AVG(StockQty) StockQty  ,
                 ISNULL(Location,''AVG'')Location
                 FROM #tblStock
                 GROUP BY Location,PartCode
                 WITH CUBE
             ) x
             PIVOT
             (
                 AVG(StockQty)
                 FOR Location IN (' + @cols + ')
            ) p
            ORDER BY CASE WHEN (PartCode=''AVG'') THEN 1 ELSE 0 END,PartCode'

EXEC SP_EXECUTESQL @query

Can anyone know the solution for this issue?

A: I obtain your desired result changing your SET query with this.
I think you need to add the RIGHT JOIN to list every PartCode and Location (else AVG function could not count correctly the number of items). I added ISNULL to AVG(StockQty) too.
Moreover you should cast average as numeric.
SET @query = 'SELECT PartCode,' + @NulltoZeroCols + ' FROM
             (SELECT
                 ISNULL(CAST(X.PC AS VARCHAR(30)),''AVG'') PartCode,
                 AVG(CAST(ISNULL(StockQty,0) AS NUMERIC(10,2))) StockQty,
                 ISNULL(Y.LC,''AVG'') Location
                 FROM #tblStock
                 RIGHT JOIN (SELECT DISTINCT PartCode AS PC FROM #tblStock)  X
                          CROSS JOIN  (SELECT DISTINCT Location AS LC FROM #tblStock) Y
                  ON Y.LC = #tblStock.LOCATION AND X.PC=#tblStock.PARTCODE
                 GROUP BY  Y.LC, X.PC
                 WITH CUBE
             ) x
             PIVOT
             (
                 AVG(StockQty)
                 FOR Location IN (' + @cols + ')
            ) p
            ORDER BY CASE WHEN (PartCode=''AVG'') THEN 1 ELSE 0 END,PartCode'

Output:
PartCode                       WHs-A                                   WHs-B                                   WHs-C                                   WHs-D                                   WHs-E                                   WHs-F                                   AVG
------------------------------ --------------------------------------- --------------------------------------- --------------------------------------- --------------------------------------- --------------------------------------- --------------------------------------- ---------------------------------------
A                              10.000000                               1.000000                                9.000000                                0.000000                                0.000000                                0.000000                                3.333333
B                              22.000000                               0.000000                                0.000000                                0.000000                                0.000000                                0.000000                                3.666666
C                              20.000000                               0.000000                                0.000000                                0.000000                                0.000000                                0.000000                                3.333333
D                              2.000000                                0.000000                                0.000000                                0.000000                                0.000000                                39.000000                               6.833333
E                              0.000000                                0.000000                                0.000000                                3.000000                                0.000000                                0.000000                                0.500000
F                              7.000000                                0.000000                                0.000000                                0.000000                                54.000000                               0.000000                                10.166666
AVG                            10.166666                               0.166666                                1.500000                                0.500000                                9.000000                                6.500000                                4.638888


text:
Q: ArrayList with different types for T I want to have a list that have different but similar types.
For example, I want to put a list of different validator classes in one list.
Eg:
ArrayList<T> validators = new ArrayList<T>();
validators.add(new StringValidator());
validators.add(new IntegerValidator());

Is this possible to do?

A: If you just want to add, then
ArrayList<Validator> validators = new ArrayList<Validator>();
validators.add(new StringValidator());
validators.add(new IntegerValidator());

is perfectly fine. But if you want your subclass type to be referred by superclass type, then
Use ArrayList< ? extends Validator> validators = new ArrayList<Validator>(); where all your validators extendsValidator` if you want to refer to subclasses of Validator using the superclass reference. Read about generics wildcard operator here

A: Yes, if the validators share a superclass you can supply that as the type.
List<Validator> validators = new ArrayList<Validator>();
validators.add(new StringValidator());
validators.add(new IntegerValidator());

Many of the answers here specify the first type as <? extends Validator> but that's unnecessary. It would allow you to specify the second type as a Validator subclass, i.e.
List<? extends Validator> validators = new ArrayList<ValidatorSubClass>();

A: Here is a complete example of how you can do it:
First, define an interface:
public interface Validator {
    void validate();
}

Then, create an implementation:
public class IntegerValidator implements Validator {

    public void validate() {
        // Validate
    }
}

The String validator implementation:
public class StringValidator implements Validator {
    public void validate() {
        // Validate
    }
}

Here is the client code:
public class Test {

    public static void main(String[] args) {
        List<Validator> v = new ArrayList<Validator>();
        v.add(new StringValidator());
        v.add(new IntegerValidator());

        for (Validator validator : v) {
            validator.validate();
        }
    }
}

A: create a super class named Validator,and let StringValidator and IntegerValidator extends(or implement)Validator, then you can init your ArrayList like this:
ArrayList<Validator> validators = new ArrayList<Validator>();
validators.add(new StringValidator());
validators.add(new IntegerValidator());

A: yes, you can always do:
ArrayList<object> validators = new ArrayList<object>();
validators.add(new StringValidator());
validators.add(new IntegerValidator());

and in your case also
ArrayList<Validator> validators = new ArrayList<Validator>();
validators.add(new StringValidator());
validators.add(new IntegerValidator());

you see, when you state what's T then only the class you declared or extended classes can be put in the ArrayList. so when you state a common parent such as Validator then you can add botch StringValidator and IntegerValidator to the ArrayList

A: According to the Generics tutorial, you can use
List<? extends Validator> validators = new ArrayList<>();
validators.add(new StringValidator());
validators.add(new IntegerValidator());

where StringValidator and IntegerValidator extend Validator.


text:
Q: Why has my neighbor city stopped taking garbage? I have two cities. 1st is the main. 2nd is for garbage export. It was not difficult to start garbage exporting. I just created road connection and placed garbage processing plant in the 2nd and a 2x2 garbage area. I was exporting up to 80 garbage successfully, but then export was broken. When I'm cliking on "Neighbor deals", I get "There are currently no neighbor deals available" and can't do nothing. Also I still can't import/export Power (I've already built powerlines connection).
I have a nice city with 7000 population and it will begin die in few months if I would not start exporting garbage again. But now I don't know how.

A: There are several things that can cause a deal to be canceled:

*

*The Customer (the one with the trash) does not have a minimum amount of money in the bank.
Something like twice the cities TOTAL budget for a month. If you're out of money, your only option is loading from where you saved the city last, or taking out a loan. I have had this kill cities before.

*Service Provider (the one burning the trash) does not have enough capacity.
Note that when you are playing as the Customer, the Service Provider's info is locked in: the capacity for each month and the total trash collected DO NOT CHANGE no matter how many months you play as the Customer. This means there's no chance the Service Provider's land fills are full, but rather that the customer is making too much trash each month for the Service Provider to take.

*The connection is broken.
Simple enough, the roads/powerlines/pipes have been demolished due to a mis-click or disaster or something.
In any of these cases, the deal is canceled automatically. You will have to open both cities, check that everything is OK, THEN re-initiate the deal. Also, I believe you sometimes have to run a month in either city for any correction you've made (such as building more landfill) to be recognized, and allow you to restart the deal.


text:
Q: How to collect data usage information from the internet to iPhone with Xamarin / monotouch I'm needing to collect information from internet data usage on the iphone, the below code in C # I'm using only returns 0 values.
I'm using the right class?
have some reference I need to add in Xamarin?
appears in mono 3 types of classes, Coincidentally the "MacOsIPv4InterfaceStatistics" interface always returns the fixed value 0.
https://github.com/mono/mono/blob/master/mcs/class/System/System.Net.NetworkInformation/IPv4InterfaceStatistics.cs
Win32IPv4InterfaceStatistics
LinuxIPv4InterfaceStatistics
MacOsIPv4InterfaceStatistics

using System;
using System.Net;
using System.Net.NetworkInformation;
using System.Runtime.InteropServices;
using System.Threading;
using MonoTouch.ObjCRuntime;

namespace Taximetro { public delegate void Update();

public static class ControleUso
{
    public static long controller;

    public static long BytesReceivedWiFi;
    public static long BytesSentWiFi;

    public static long BytesReceived3G;
    public static long BytesSent3G;

    public static Update UpdateMethod;

    public static void DoWork()
    {
        foreach (var netint in NetworkInterface.GetAllNetworkInterfaces()) {
            var stats = netint.GetIPv4Statistics ();

            //WiFi
            //if (netint.Name.StartsWith ("en")) {
                BytesReceivedWiFi += stats.BytesReceived;
                BytesSentWiFi += stats.BytesSent;
            //}

            //3G
            if (netint.Name.StartsWith ("pdp_ip")) {
                BytesReceived3G += stats.BytesReceived;
                BytesSent3G += stats.BytesSent;
            }
        }
        controller++;
        if (UpdateMethod != null) {
            UpdateMethod ();
        }
        Thread.Sleep (1000);
    }
}

}

A: Notice that data is uint and not long, which means it will overflow every 4GB of data.
Edit: After some Googling around I noticed that this data is reset on iOS reboot. Just some heads ups to anyone who might use this.
public enum InterfaceTypes
{
    Wifi,
    Cellular
}

public class DataUsage
{
    [DllImport ("libc")]
    static extern int getifaddrs (out IntPtr ifap);

    [DllImport ("libc")]
    static extern void freeifaddrs (IntPtr ifap);

    const int AF_LINK = 18;

    struct ifaddrs
    {
        public IntPtr ifa_next;
        public string ifa_name;
        public uint ifa_flags;
        public IntPtr ifa_addr;
        public IntPtr ifa_netmask;
        public IntPtr ifa_dstaddr;
        public IntPtr ifa_data;
    }

    public InterfaceTypes InterfaceType {
        get;
        private set;
    }

    public uint BytesSent {
        get;
        private set;
    }

    public uint BytesReceived {
        get;
        private set;
    }

    public static List<DataUsage> GetAllNetworkInterfacesUsage ()
    {
        IntPtr ifap;
        if (getifaddrs (out ifap) != 0)
            throw new SystemException ("getifaddrs() failed");

        List<DataUsage> usages = new List<DataUsage> ();
        try {
            IntPtr next = ifap;
            while (next != IntPtr.Zero) {
                ifaddrs addr = (ifaddrs)Marshal.PtrToStructure (next, typeof(ifaddrs));
                next = addr.ifa_next;
                string name = addr.ifa_name;
                if (addr.ifa_addr != IntPtr.Zero) {
                    if (Marshal.ReadByte (addr.ifa_addr, 1) == AF_LINK) {
                        if (!name.StartsWith ("en") && !name.StartsWith ("pdp_ip"))
                            continue;
                        usages.Add (new DataUsage () {
                            InterfaceType = name.StartsWith ("en") ? InterfaceTypes.Wifi : InterfaceTypes.Cellular,
                            BytesReceived = (uint)Marshal.ReadInt32 (addr.ifa_data, 40),
                            BytesSent = (uint)Marshal.ReadInt32 (addr.ifa_data, 44)
                        });
                    }
                }
            }

        } finally {
            freeifaddrs (ifap);
        }
        return usages;
    }
}


text:
Q: Custom properties for reports in SSRS I have a customized report sitemap for SSRS (which is a report itself) and currently put custom options in the report description. I then use those options in the sitemap to filter reports accordingly.
I was wondering if I could add columns to the ReportServer.dbo.Catalog table?
Or is there a way to add custom properties to the report settings (as in picture)?

A: Altering the Catalog table in the SSRS database would more than likely break SSRS. At a minimum, it would stop you from being able to upgrade to another version in the future without a whole lot of pain.
If you really need to add custom properties to the report catalog, host your reports in SharePoint. That way, you can add additional fields to the report list it creates all day long, and you won't break a thing.
I have done this, it's nice. I have added a new field to hold the technical description of the report, leaving the canned description field for the business description. With SharePoint, you can all sorts of additional fields, for all types of data. If you know anything about the SharePoint database, you can query that too to pull the addition data into whatever you need.
This may not be the answer you want since the move to SharePoint may not be an option for you, but it is a viable option none the less.


text:
Q: Requirejs Optimize project to single file With a Build configuration as below, Why am i seeing all the files in source directory + minified application file when i run the deploy command specified below. I only need a single js file that will kickoff my backbone application
Build Config
({
    appDir: "../",
    baseUrl: 'Comment',
    dir: './deploy',
    optimize: 'uglify',
    paths: {
        text: '../../amd/plugins/text',
        CommentView: 'views/feedback',
        Feedback: 'models/feedback',
        templates: 'templates'
    },
    modules: [
        {
            name: "app"
        }
    ]
})

App.js
require.config({
    urlArgs: "bust=" + (new Date()).getTime(),
    baseUrl: 'scripts/apps/feedback',
    paths: {
        text: '../../amd/plugins/text',
        CommentView: 'views/feedback',
        Feedback: 'models/feedback',
        templates: 'templates'
    }
});

require(["Feedback", "CommentView"], function (feedbackModel, commentView) {
});

Optimization Command
node amd/plugins/r.js -o apps/feedback/build.config.js

A: By default, the requirejs optimizer does not remove modules from the output.  Check the contents of your built app.js, I would guess that it has all of your modules in it.  The individual modules shouldn't cause any problems and won't be used, but if you really went to get rid of them, try setting removeCombined: true in your build config.


text:
Q: c++ learning the order of map entry If I have a map with keys as strings. How can I know which string is in which place in the map? For example, 'cats' is the first entry and 'dogs' are the second entry. How will I know that dogs are the second entry in the map? Should I go through the map and search/check the order or is there any easier way?

A: You can find() the element, and then compute the distance between the element and the map's begin().  Since this is a map, the complexity of distance will be O(n) with the number of elements in the map.  I doubt you'd see much performance improvement versus simply looping the map and counting, but I'd prefer to not write such hand-written loops.
But this smells like an XY Problem.  Why would you need the position of an element in a map?

A: You can't do that anyway better, and here's two reasons for that:
a) std::map has a tree inside that, so initially leaves of tree don't have linear order, only a partial order (of course you can compare two keys, but you can't do that for a general binary tree - that's the reason for complication).
b) std::map has bidirectional iterator, so you can't have effective iterator arithmetics. You could do that like this:
typedef map<string, int> MyMapT;
MyMapT data;
// ...
auto it = data.find("dog");
if (it == data.end()) {
  // don't have such a key
}
auto position = distance(data.begin(), data.end());

Unfortunately, that's not the best way to do that, because distance function works in O(n) time for bidirectional iterators. Again, that's because of tree structure inside the std::map.


text:
Q: error: cannot find symbol method GetApplicationContext() I had this error: "error: cannot find symbol method GetApplicationContext()" when I'm creating Fragments for Android app.
public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void simple(View v){

        Intent intent = new Intent(intent.GetApplicationContext(), SimpleFragmentActivity.class);
        startActivity(intent);
    }
}

A: intent.GetApplicationContext()

getApplicationContext is not a method of the Intent class but of context.
Change
  Intent intent = new Intent(intent.GetApplicationContext(), SimpleFragmentActivity.class);

with
  Intent intent = new Intent(getApplicationContext(), SimpleFragmentActivity.class);

or simply
Intent intent = new Intent(this, SimpleFragmentActivity.class);

where this refers to this object, the Activity, that extends ContextWrapper


text:
Q: Slash command response not parse correctly My question is related to Slack's Slash commands.
I am trying to echo response back to invoking channel.
e.g I have integerated a test command like
/test hello

and I want response as:
Hello
Wold

but I am currently getting it as (in my slack channel):
{"text":"hello\nworld"}

This is my PHP code:
$payload = '{"text":"hello\nworld"}';
echo $payload;

Note I don't want to just echo like this:
echo "hello\nworld";

Thanks in advance :)
Maybe useful in giving answer:-
Sample wrong response actual:

Slack slash command API url:
https://api.slack.com/slash-commands

A: If you had carefully read the docs (which you linked), you would have noticed that it says:

NOTE: If you are responding with JSON instead of plain text, the content-type header of the response must match the disposition of your content, application/json.

It looks like you're just outputting JSON without sending the correct Content-Type header, so Slack thinks it's plain text and displays your JSON as plain text.
Also, consider using json_encode instead of manually writing JSON.


text:
Q: hibernate.cfg.xml is not getting created even when i run mvn hibernate3:hbm2cfgxml When I run mvn hibernate3:hbm2cfgxml it does not generate hibernate.cfg.xml file.
However it generates pojos and daos but does not generate hibernate.cfg.xml file.
Following is my pom.xml.
<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 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.myhadoop.app</groupId>
<artifactId>my-app-hadoop</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>my-app-hadoop</name>
<url>http://maven.apache.org</url>

<dependencies>
<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>3.8.1</version>
  <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.apache.hadoop</groupId>
    <artifactId>hadoop-core</artifactId>
    <version>1.0.3</version>
</dependency>

<dependency>
    <groupId>org.hibernate </groupId>
    <artifactId>hibernate-core</artifactId>
    <version>4.1.6.Final</version>
</dependency>

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>servlet-api</artifactId>
    <version>3.0-alpha-1</version>
</dependency>

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-simple</artifactId>
    <version>1.6.6</version>
</dependency>

<dependency>
    <groupId>javassist</groupId>
    <artifactId>javassist</artifactId>
    <version>3.12.1.GA </version>
</dependency>
</dependencies>
<repositories>
<repository>
    <id>jBoss-Repository</id>
    <url>https://repository.jboss.org/nexus/content/groups/public/</url>
    <releases>
       <enabled>true</enabled>
    </releases>
    <snapshots>
      <enabled>false</enabled>
    </snapshots>
 </repository>
 <repository>
    <id>mirrors.ibiblio</id>
    <url>http://mirrors.ibiblio.org/maven/mule/dependencies/maven2/</url>
    <releases>
       <enabled>true</enabled>
    </releases>
    <snapshots>
      <enabled>false</enabled>
    </snapshots>
 </repository>
 </repositories>
 <build>
<plugins>
    <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>hibernate3-maven-plugin</artifactId>
        <version>2.2</version>
        <configuration>
            <components>
                <component>
                    <name>hbm2ddl</name>
                         <implementation>jdbcconfiguration</implementation>
                </component>
                <component>
                    <name>hbm2hbmxml</name>
                    <implementation>jdbcconfiguration</implementation>
                    <outputDirectory>src/main/java/org/dbmxml</outputDirectory>
                </component>
                <component>
                    <name>hbm2dao</name>
                    <implementation>jdbcconfiguration</implementation>
                    <outputDirectory>src/main/java</outputDirectory>
                </component>
                <component>
                    <name>hbm2java</name>
                    <implementation>jdbcconfiguration</implementation>
                    <outputDirectory>src/main/java</outputDirectory>
                </component>

                <component>
                    <name>hbm2doc</name>
                    <implementation>jdbcconfiguration</implementation>
                    <outputDirectory>src/hbm2doc</outputDirectory>
                </component>

                <component>
                    <name>hbm2ddl</name>
                    <implementation>jdbcconfiguration</implementation>
                    <outputDirectory>src/hbm2ddl</outputDirectory>
                </component>
            </components>

            <componentProperties>
                <drop>true</drop>
                <packagename>org.hbm2dao</packagename>
                <configurationfile>/src/main/resources/hibernate.cfg.xml</configurationfile>
                <propertyFile>/src/main/resources/database.properties</propertyFile>
            </componentProperties>
        </configuration>
        <dependencies>
            <dependency>
                <groupId>com.oracle</groupId>
                <artifactId>ojdbc</artifactId>
                <version>6</version>
                <scope>system</scope>
                <systemPath>D:/apps/oracle11g/product/11.2.0/dbhome_1/jdbc/lib/ojdbc6.jar</systemPath>
        </dependency>
    </dependencies>
  </plugin>
</plugins>

What needs to be added in pom.xml so that I can generate hibernate.cfg.xml file.

A: Based on the documentation you need to create a part like the following:
<component>
  <name>hbm2cfgxml</name>
  <implementation>...</implementation>
  ...
</component>

A: Also, in addition to above answer, I think you have duplicate declaration of "hbm2ddl" component in your POM.
You can refer this:
http://hop2croft.wordpress.com/2011/05/08/creating-java-domain-objects-with-the-maven-hibernate-plugin/#highlighter_819265
and
https://forum.hibernate.org/viewtopic.php?f=6&t=1008209&view=previous


text:
Q: Suppose $(a,b)=1$, then $(2a+b,a+2b)=1\text{ or }3$. Suppose $(a,b)=1$.  Let $d=(2a+b,a+2b)$.
Then $d=(2a+b)u+(a+2b)v=a(2u+v)+b(2v+u)$ where $u,v \in \mathbb{Z}$.
Since $(a,b)=1$, then $a(2u+v)+b(2v+u)=1$.
I'm not sure if I'm going in the right direction to solve this problem.

A: Hint:
Let $d=(a+2b,2a+b)$, so $d|3a$ since $d|2(2a+b)-(a+2b)$ and
$d|3b$
since $d|2(a+2b)-(2a+b)$.
Therefore $d|(3a,3b)$.

A: Hint $\ $ Specialize the method below:  $\rm\,(x,y)\mapsto (2x+y,x+2y) =: (X,Y)\,$ has   $\, \det = 3,\,$ i.e.
$\qquad\begin{pmatrix} 2 & \rm 1 \\\\ \rm 1 & \rm 2 \end{pmatrix}\ \begin{pmatrix} x \\\\ \rm y \end{pmatrix}\ =\ \begin{pmatrix} X \\\\ \rm Y\end{pmatrix}\ \ \ \Rightarrow\ \ \ \begin{array} \rm\ 3\ x\ \ \ =\ \ \ \rm 2\ X \ - \ Y \\\\ \rm 3\ y\ =\ \rm\  - X + 2\ Y \end{array} $
Theorem  $\ $ If $\rm\,(x,y)\overset{A}\mapsto (X,Y)\,$ is linear then $\: \rm\gcd(x,y)\mid \gcd(X,Y)\mid \Delta \gcd(x,y),\,\ \Delta = \det A$
Proof $\ $ Inverting the linear map $\rm\,A\,$ by Cramer's Rule (multiplying by the adjugate) yields
$$\rm \begin{eqnarray} a\ x\, +\, b\ y &=&\rm X\\ \\ \rm c\ x\, +\, d\ y &\ =\ &\rm Y\end{eqnarray}
\quad\Rightarrow\quad \begin{array} \rm\Delta\ x\ \ \ =\ \ \ \rm d\ X\, -\, b\ Y \\\\ \rm\Delta\ y\ =\ \rm -c\ X\, +\, a\ Y \end{array}\ ,\quad\ \Delta\ =\ ad-bc\qquad $$
Hence, by RHS system, $\rm\ n\ |\ X,Y\ \Rightarrow\ n\ |\ \Delta\:x,\:\Delta\:y\ \Rightarrow\ n\ |\ gcd(\Delta\:x,\Delta\:y)\ =\ \Delta\ gcd(x,y)\:.$
In particular $\rm\ n = \gcd(X,Y) \mid \Delta\, \gcd(x,y).\ $
Further, by LHS system $\rm\,n\mid x,y\ \Rightarrow\ n\mid X,Y\ \Rightarrow\ n\mid\gcd(X,Y).$
In particular $\rm\ n = gcd(x,y)\mid \gcd(X,Y).\ \ \ $  QED

A: Direct manipulation of gcd
$\gcd(a+2b,2a+b) = \gcd(a+2b,(2a+b)-2(a+2b)) = \gcd(a+2b,-3b)$
$ | \gcd(a+2b,3) \gcd(a+2b,b) | 3 \gcd((a+2b)-2(b),b) = 3 \gcd(a,b) = 3$

A: Let $$d=\gcd(a+2b, 2a+b).$$
$$\Rightarrow d|a+2b, d|2a+b.$$
$$\rightarrow d|2(a+2b), d| 2a+b.$$
Now use this result that if $d=\gcd(a, b), d|a, d|b\ \text{then}\ d|a\pm b$.
So,
$$d|2a+4b-2a-b.$$
$$\Rightarrow d|3b.$$
Also $$\Rightarrow d|3a.$$
$$\therefore d|(3a, 3b) \Rightarrow d= 1\ \text{or} \ 3. (\because (a, b)=1.)$$


text:
Q: Can I use $(this) in a jquery.data() call? I would like to store the default value of an element in that element's jQuery.data() collection.  Since I can't do this...
$("#myElement").data('defaultValue', $(this).html());

... because $(this) does not give me a reference to #myElement, what is the most efficient way to do this?  I'm trying to avoid selecting the element twice like this:
$("#myElement").data('defaultValue', $("#myElement").html());

A: There's no sane way really other than to save the jQuery object in a temporary variable:
var $element = $("#myElement");
$element.data('defaultValue', $element.html());

An altenative which is just one expression, but IMHO is much worse:
$("#myElement").each(function() { $(this).data('defaultValue', $(this).html()); });

A: Ehhh.
You could try to hack around it:
$("#myElement").each(function(){$(this).data('defaultValue', $(this).html());});

UGLY
Or do like the other posts:
var $element = $("#myElement");
$element.data('defaultValue', $element.html());

A: var el = $("#myElement");
el.data('defaultValue', el.html());

A: var myElement = $("#myElement");
myElement.data('defaultValue', myElement.html());

A: If you are a performance freak, you could save nano seconds by saving a reference to #myElement:
var $myElement = $("#myElement");
$myElement.data('defaultValue', $myElement.html());


text:
Q: Measuring CMRR of op-amp circuit I am trying to calculate the CMRR of following circuit. I am aware that similar circuit has been posted here before but I have read through them and they don't answer my question.

Based on my research so far, this circuit is one of the way to measure the CMRR of op-amp assuming that the resistor values for \${R}_{1a}\$, \${R}_{1b}\$, \${R}_{2a}\$,\${R}_{2b}\$ match perfectly.
In this circuit, i assume that the common mode input \${V}_{CM}\$ is \$ {V}_{IN} \frac{{R}_{2b}}{({R}_{1b} + {R}_{2b})} \$
And I learnt that the \$ CMRR = \frac{Differential-mode-Gain}{Common-mode-gain} \$. So, normally, i would find the common mode gain \$ {A}_{CM} \$ and differential mode gain \$ {A}_{DM} \$ separately.
However, i noticed, in  most of the online sites, they simply measure the \$ \frac{{V}_{out}}{{V}_{in}} \$ and considered it as \$CMRR\$
My Question is: Why is the \$ \frac{{V}_{out}}{{V}_{in}} \$ of this circuit is equivalent to the \$ CMRR \$ of the circuit?
Can someone point me in the right direction?
EDIT 1:
I have added some link to the similar questions per @MarcusMuller request.
operational amplifier CMRR measurement
This question was asking what is the correct common mode input voltage. I am well are that it is \$ {V}_{IN} \frac{{R}_{2b}}{({R}_{1b} + {R}_{2b})} \$ so it doesn't help me.
Op Amp CMRR problem
This question was asking about his particular issue regarding common mode gain.

A: To put it shortly, even if you had perfect resistors (and resistors aren't perfectly matched, so this won't even remotely work), the formula as stated is wrong.
You need to vary the input voltage and observe the variation of the output voltage; the ratio of these two differences would then be the CMRR.
Again, it's not \$\text{CMRR}=\frac{V_{out}}{V_{in}}\$; it'd be \$\text{CMRR}=\frac{\Delta V_{out}}{\Delta V_{in}}\$, because that's how much a variation of common mode input gets amplified (that's literally just the definition of amplification applied to CM input).
And again, that assumes that your resistors are all perfectly matched, which they aren't. The best resistors I can buy are 0.01% accurate, which means the differential gain isn't exactly 1, but has some unknown error, and that sadly doesn't cancel, and at CMRR > 60 dB (which is pretty boring compared to what modern opamps offer), that error by far outshines our CM amplification. You'd hence need to measure that error, too, which, again, is pretty hard, because your measurement process needs to change the system much less than the CMRR, and measuring voltages does actually draw a bit of current.

A: The Op-Amp has an internal CMRR far better than any R tolerance.  Yet the R tolerance error defines the output for ideal parts leaving only the Acm to have some value. Thus the CMRR of the circuit is simply \$V_o = A_{dm} * V_{dm} (=0) + A_{cm} * V_{cm}  , ~~~or ~~ A_{cm}=V_o/V_{cm}\$.
Let the worst-case R tolerance error =X% for all 4 parts, thus degrades the Op Amp's CMRR = Adm/Acm = 4 * X%  and thus the DM gain makes the CMRR even worse which demands precision-matched R ratio components and similarly matched wire impedance or STP cable for EMC concerns.  I'll let you prove this as it was not part of your question.


text:
Q: Distinguishing between terms of different domains What I am trying to do:
I am trying to take a list of terms and distinguish which domain they are coming from. For example "intestine" would be from the anatomical domain while the term "cancer" would be from the disease domain. I am getting these terms from different ontologies such as DOID and FMA (they can be found at bioportal.bioontology.org)
The problem:
I am having a hard time realizing the best way to implement this. Currently I am naively taking the terms from the ontologies DOID and FMA and taking difference of any term that is in the FMA list which we know is anatomical from the DOID list (which contains terms that may be anatomical such as colon carcinoma, colon being anatomical and carcinoma being disease).
Thoughts:
I was thinking that I can get root words, prefixes, and postfixes, for the different term domains and try and match it to the terms in the list. Another idea is to take more information from their ontology such as meta data or something and use this to distinguish between the terms.
Any ideas are welcome.

A: The naive approach - what precision and recall is it getting you? If you setup a test case now, then you can track your progress as you apply more sophisticated methods.
I don't know what initial set you are dealing with - but one thing to try is to get your hands on annotated documents(maybe use mechanical turk). The documents need to be tagged as the domains you're looking for - anatomical or disease.
then count and divide will tell you how likely a word you encounter is to belong to a domain. With that the next step and be to tweak some weights.
Another approach (going in a whole other direction) is using WordNet. I don't know if it will be useful for exactly your purposes, but its a massive ontology - so it might help.
Python has bindings to use Wordnet via nltk.
from nltk.corpus import wordnet as wn
wn.synsets('cancer')
gives output = [Synset('cancer.n.01'), Synset('cancer.n.02'), Synset('cancer.n.03'), Synset('cancer.n.04'), Synset('cancer.n.05')]
http://wordnetweb.princeton.edu/perl/webwn
Let us know how it works out.

A: As a first run, you'll probably have the best luck with bigrams. As an initial hypothesis, diseases are usually noun phrases, and usually have a very English-specific structure where NP -> N N, like "liver cancer", which means roughly the same thing as "cancer of the liver." Doctors tend not to use the latter, while the former should be caught with bigrams quite well.
Use the two ontologies you have there as starting points to train some kind of bigram model. Like Rcynic suggested, you can count them up and derive probabilities. A Naive Bayes classifier would work nicely here. The features are the bigrams; classes are anatomy or disease. sklearn has Naive Bayes built in. The "naive" part means, in this case, that all your bigrams are independent of each other. This assumption is fundamentally false, but it works well in a lot of circumstances, so we pretend it's true.
This won't work perfectly. As it's your first pass, you should be prepared to probe the output to understand how it derived the answer it came upon and find cases that failed on. When you find trends of errors, tweak your model, and try again.
I wouldn't recommend WordNet here. It wasn't written by doctors, and since what you're doing relies on precise medical terminology, it's probably going to add bizarre meanings. Consider, from nltk.corpus.wordnet:
>>> livers = reader.synsets("liver")
>>> pprint([l.definition() for l in livers])
[u'large and complicated reddish-brown glandular organ located in the upper right portion of the abdominal cavity; secretes bile and functions in metabolism of protein and carbohydrate and fat; synthesizes substances involved in the clotting of the blood; synthesizes vitamin A; detoxifies poisonous substances and breaks down worn-out erythrocytes',
u'liver of an animal used as meat',
u'a person who has a special life style',
u'someone who lives in a place',
u'having a reddish-brown color']

Only one of these is really of interest to you. As a null hypothesis, there's an 80% chance WordNet will add noise, not knowledge.


text:
Q: PL/SQL Triggers in Oracle
I have the following tables shown in the image. I need to create a trigger that inserts data into an AUDIT table from the PAYMENT table including information about the payment like- who made the payment (pay_from), Oracle user who processed the payment, appointment id (apt_id) and patient who made the payment (patient_id).
From the image above, the PAYMENT table has a relationship with the APPOINTMENT table which in turn has a relationship with PATIENT table.
My question is, how can I add "patient_id" from the APPOINTMENT table into my AUDIT table using the trigger?
This is my code:
CREATE OR REPLACE TRIGGER PAYMENT_AUDIT_TRIGGER
AFTER INSERT ON PAYMENT
FOR EACH ROW
BEGIN
INSERT
INTO AUDIT_LOG VALUES
(
 AUDIT_LOG_AUDIT_ID_SEQ.NEXTVAL,
 :new.PATIENT_ID,
 :new.APT_ID,
 USER,
 SYSDATE,
 :new.PAY_FROM
);
END;

A: This is easy in Oracle because it has both before and after triggers. The difference between them is, as may well be guessed, when they execute -- just before the operation or after the operation.
A before trigger is useful for intercepting the input stream for more sophisticated data testing and/or modifying some of the data (such as generating the key value from a sequence in INSERT operations). By "just before", I mean that all defined integrity checking is performed first -- type checking, check constraints, referential constraints, etc. So you can know that the data has already passed all those checks.
An after trigger is useful for logging the operation that just occurred. If there is any error condition that prevents the operation from finishing, even though it may have passed the initial system checking and the additional checking that may have taken place by the before trigger, the after trigger will not execute. A handy feature of this trigger is that the row presented to it will be exactly the row that was inserted/updated/deleted. That means any generated key value will be there for the after INSERT trigger.
This description is for Oracle and other systems that have both types of triggers. SQL Server only has the after trigger although it has recently extended the instead of trigger to work with tables -- in effect, making it a before trigger, although there are differences with "normal" triggers so users should read the documentation to be aware of these differences.


text:
Q: Filtering is not working on Array of objects in AngularJS I have list of products as array of object. Want to display that based on highest views count. I tried to use "orderBy" service. But it's not filtering from my attached array of object. Any suggestion about how to do that?

vm.products = [
      {
        title : 'ABC',
        imgSrc: '../../images/product1.png',
        viewsCount: '183',
        clicksCount: '34'
      },
      {
        title : 'DEF',
        imgSrc: '../../images/product1.png',
        viewsCount: '158',
        clicksCount: '30'
      },
      {
        title : 'GHI',
        imgSrc: '../../images/product1.png',
        viewsCount: '86',
        clicksCount: '32'
      },
      {
        title : 'JKL',
        imgSrc: '../../images/product1.png',
        viewsCount: '47',
        clicksCount: '20'
      },
      {
        title : 'MNO',
        imgSrc: '../../images/product1.png',
        viewsCount: '62',
        clicksCount: '22'
      }
    ];
<md-list>
 <md-list-item layout="row" layout-align="space-between center"
  ng-repeat="product in vm.products | orderBy:'product.viewsCount'"
    ng-click="vm.latestSelectedIndex = $index; vm.selectProduct(product)"
  ng-show="!$first">

{{product.title}}

{{product.viewsCount}}

 Views

 </md-list-item>
</md-list>

A: You dont have to mention products, just use the fieldName
<md-list-item layout="row" layout-align="space-between center"
        ng-repeat="product in vm.products | orderBy:'viewsCount'"

EDIT:
Also the property viewsCount is a string, you need to parse it as a number/float value as follows.
angular.forEach(vm.products, function (detail) {
  detail.viewsCount = parseFloat(detail.viewsCount);
});

DEMO

 var app = angular.module('mainApp', ['ngMaterial'])
 app.controller('productsController',function(){
vm =this;
vm.products = [
      {
        title : 'ABC',
        imgSrc: '../../images/product1.png',
        viewsCount: '183',
        clicksCount: '34'
      },
      {
        title : 'DEF',
        imgSrc: '../../images/product1.png',
        viewsCount: '158',
        clicksCount: '30'
      },
      {
        title : 'GHI',
        imgSrc: '../../images/product1.png',
        viewsCount: '86',
        clicksCount: '32'
      },
      {
        title : 'JKL',
        imgSrc: '../../images/product1.png',
        viewsCount: '47',
        clicksCount: '20'
      },
      {
        title : 'MNO',
        imgSrc: '../../images/product1.png',
        viewsCount: '62',
        clicksCount: '22'
      }
    ];

angular.forEach(vm.products, function (detail) {
  detail.viewsCount = parseFloat(detail.viewsCount);
});
    });
 <link rel="stylesheet" href="//rawgit.com/angular/bower-material/master/angular-material.css" />

<md-list>
 <md-list-item layout="row" layout-align="space-between center" ng-repeat="product in vm.products | orderBy:'viewsCount'"
    ng-click="vm.latestSelectedIndex = $index; vm.selectProduct(product)"
  ng-show="!$first">

{{product.title}}

{{product.viewsCount}}

 Views

 </md-list-item>
</md-list>


text:
Q: Handling malformed Querystring in `Page_Load` I'd like to open up a modal error box with a message and a button redirecting the user from Page_Load event when the incoming Querystring does not contain a required attribute, or if it's malformed.
I've defined a jQuery function for opening the dialog, but when I try to register it through RegisterStartupScript or RegisterClientScriptBlock, it does not show up.
function showErrorPopup() {
    $('#errorDialog').dialog({
        autoOpen: false,
        height: 120,
        width: 500,
        draggable: false,
        resizable: false,
        modal: true,
        title: "Error!",
        open: function (type, data) {
            $(this).parent().appendTo("form");
        },
        close: function (type, data) {
            $('#addNoteButton').hide();
        }
    });
    $('#errorDialog').dialog("open");
    $('#addNoteButton').hide();
}

And on Page_Load:
string cID = Page.Request["c"];
int contractID = 0;
if (cID != null)
{
    try
    {
        contractID = Convert.ToInt32(cID);
        Contract contract = FacadeFactory.ProjectsFacade.GetContract(contractID);
        TFSContract source = TFS.GetTFSContract(contract);
        Contract = source;
    }
    catch (Exception)
    {
        errMessage.Text = "Zakázka s tímto číslem neexistuje!";
        ScriptManager.RegisterClientScriptBlock(this, typeof(Page), UniqueID, script, true);
        return;
    }

}
else
{
    errMessage.Text = "Zakázka s tímto číslem neexistuje!";
    ScriptManager.RegisterClientScriptBlock(this.Page, typeof(Page), this.UniqueID, script, true);
    return;
}

Can somebody please tell me how this can be achieved?


text:
Q: % of Queue and % of Cluster difference in yarn ui for MR/TEZ/SPARK jobs run While debugging the TEZ/SPARK/MR jobs I can see the below jobs details in YARN UI.

does any one please help me with % of Queue & % of Cluster stats, since it showing 1815% usage ?

A: % of cluster is stat, that is telling you how much resources does your job take from cluster.
% of queue tells you, how much of Absolute Configured Capacity does your query take.
Example:
your cluster has 1000GB of memory and two queues.
QueueA has Absolute configured capacity of 1%, with max capacity of 100%.
QueueB has Absolute configured capacity of 99% with max capacity of 100%.
If you run query in queueA, you are guaranteed you get at least 10GB of memory, but depending on the cluster load, you can get up to 1000GB of memory.
That would mean that when you run query in queueA and you get 20GB of memory, you will be using 200% of the queue, but 2% of the cluster.


text:
Q: How to get Specific column of a table in webAPI method I have a MVC4 application with a WebApi method which is getting entire table data from database. Now i want to extract only two columns from it. How can I do it?
I know that arrays will be used to do so but don't know the syntax in .net.
This is my WebAPi function which is getting the entire table data from the SQL server database:
namespace BRDCEP_MIS.Areas.BRDCEP.Controllers
{
    public class WebApiController : ApiController
    {

        //api get method.

        //[Route("WebApi/GetPscTargets")]

        public HttpResponseMessage Get() {
            using (ApplicationDbContext db = new ApplicationDbContext())
            {

                List<PscDistrictTargets> xx = new List<PscDistrictTargets>();
                xx = db.PscDistrictTargetss.ToList();
                //xx.ID = Convert.ToString(DATA);
                HttpResponseMessage response = new HttpResponseMessage();
                response = Request.CreateResponse(HttpStatusCode.OK, xx);
                return response;
            }

        }

    }
}

A: You can use the Select method and do a projection on only those properties you needed to an an object of your DTO/view model to represent this data, in your LINQ query.
So create a DTO class to represent the data you want with only those properties,
public class MyDto
{
    public int TargetId { set; get; }
    public string TargetName { set; get; }
}

Now update your LINQ query use the Select method to get only those properties and project those our dto object.
var items = db.PscDistrictTargetss
              .Select(f => new MyDto { TargetName = f.Name,
                                       TargetId = f.Id})
              .ToList();
return Request.CreateResponse(HttpStatusCode.OK, items );

Assuming PscDistrictTargets entity class has a Name and Id property. Update that part based on your actual property names.


text:
Q: JavaScript alert function behaviour In ASP.NET, I am preventing default postback action when user presses enter while textbox control has focus. See  the following piece of code
      $("#TextBox1").keydown(function(e)
        {
            if(e.keyCode == 13)
            {
                //alert("Hello");
                return false;
            }
        });

This code works fine. But if I uncomment the alert function call then page post does not stop.
My question is why alert call is creating a problem?

A: I missed that you were using keydown. To prevent form submission, I'd  use a submit handler instead, in this case working with your keydown handler and probably a blur handler as well (to reset the flag):
var cancelFlag = false;

$('#TextBox1')
    .keydown(function(e) {
        cancelFlag = e.keyCode == 13;
    })
    .blur(function() {
        cancelFlag = false;
    });

$('#theform').submit(function() {
    if (cancelFlag) {
        alert("Hello!");
    }
    return cancelFlag;
});

(Or you can call e.preventDefault(); instead of returning false, either works.) You'll need to do testing to ensure the flag gets cleared in every situation you want it to be cleared in.

Alternately, make the alert asynchronous:
$("#TextBox1").keydown(function(e)
{
    if(e.keyCode == 13)
    {
        setTimeout(function()
        {
            alert("Hello");
        }, 10);
        return false;
    }
});

That lets the event stack unwind before putting up the alert. But I'm not at all sure you can reliably (cross-browser and OS) prevent a form submission by cancelling the default action of a keydown. You said it was working, and if it works in your target browsers, great, but...

A: The return false will not execute until the alert box has been dismissed.
By then your form has long since posted.

A: if you really wanted this type of behaviour you could use event.preventDefault():
$("#TextBox1").keydown(function(e)
        {
            if(e.keyCode == 13)
            {
                e.preventDefault();
                alert("Hello");
            }
        });

A: Try this one
 $("#TextBox1").keydown(function(e)
        {
            if(e.keyCode == 13)
            {
               e.preventDefault();
            }
        });

A: You should use e.preventDefault instead.
  $("#TextBox1").keydown(function(e)
  {
      if(e.keyCode == 13)
      {
          e.preventDefault(); // won't trigger default behavior

          alert("Hello"); // will work
      }
  });


text:
Q: Does Huggingface's T5 Model Vocabulary include English-only version? Does anyone know if HuggingFace's T5 model (small) comes with mono-language vocabulary? The T5 paper by Google indicates that their vocabulary is trained on English and 3 other languages. Is there a version of this vocabulary that contains English only vocabulary?

A: When looking at the publicly available model card definition, the HuggingFace T5-small also seems to contain the necessary translation tasks, which makes it a multi-lingual model. Note that the summarization task should still be English-only, so depending on your task, this might not matter too much.


text:
Q: Prove that $f'(a)=\lim_{n\to\infty}\frac{f(b_n)-f(a_n)}{b_n-a_n}$ under some conditions
Prove that $f'(a)=\lim_{n\to\infty}\frac{f(b_n)-f(a_n)}{b_n-a_n}$, with $f: (k_1,k_2)\to\Bbb R$ differentiable at $a\in (k_1,k_2)$, $\lim b_n=\lim a_n=a$, and $a_n<a<b_n$.

My attempt: Im trying to write the above equality as a particular case of this other equality that hold by any interior point $a$
$$f'(a)=\lim_{h\to 0}\frac{f(a+h)-f(a-h)}{2h}$$
Because $a_n<a<b_n$ then I can write
$$f'(a)=\lim_{n\to\infty}\frac{f(b_n)-f(a_n)}{b_n-a_n}=\lim_{n\to\infty}\frac{f(h_n+a)-f(a-j_n)}{h_n+j_n}$$
Where $h_n=b_n-a>0$ and $j_n=a-a_n>0$, where these two new sequences tends monotonically to zero.
Now my problem: my thought is that $h_n$ and $j_n$ are particular sequences then I can build a sequence $k_n$ such that $j_n$ and $h_n$ are subsequences so I can write:
$$\{h_n:n\in\Bbb N\}\subset\{k_n:n\in\Bbb N\}\text{ and }\{j_n:n\in\Bbb N\}\subset\{k_n:n\in\Bbb N\}$$
(I can build this $k_n$ by example doing $k_{2n}=h_n$ and $k_{2n-1}=j_n$) and then I have the desired expression
$$f'(a)=\lim_{n\to\infty}\frac{f(b_n)-f(a_n)}{b_n-a_n}=\lim_{n\to\infty}\frac{f(k_n+a)-f(a-k_n)}{2k_n}$$
My question:

*

*Is this proof right? In particular Im unsure of the implicit statement "if the limit exist for $k_n$ then it must exist too for the particular case with $h_n$ and $j_n$". The use of two sequences, $h_n$ and $j_n$ in the limit make me unsure about the validity of this manipulation and assumption.

*There is a simpler/different way to prove the same?
Thank you in advance.

A: Since $f'(a)$ exists we have $$f(a_{n}) = f(a) + (a_{n} - a)f'(a) + (a_{n} - a)\eta_{n}$$ where $\eta_{n} \to 0$ as $n \to \infty$. Similarly $$f(b_{n}) = f(a) + (b_{n} - a)f'(a) + (b_{n} - a)\mu_{n}$$ where $\mu_{n} \to 0$ as $n \to \infty$. Then we have $$f(b_{n}) - f(a_{n}) = (b_{n} - a_{n})f'(a) + (b_{n} - a)\mu_{n} - (a_{n} - a)\eta_{n}$$ and hence $$\left|\frac{f(b_{n}) - f(a_{n})}{b_{n} - a_{n}} - f'(a)\right| \leq \frac{|b_{n} - a|}{|b_{n} - a_{n}|}\cdot|\mu_{n}| + \frac{|a_{n} - a|}{|b_{n} - a_{n}|}\cdot|\eta_{n}|$$ and since $a_{n} < a < b_{n}$ it follows that the RHS of the above equation is less than $|\mu_{n}| + |\eta_{n}|$ and hence both LHS and RHS tend to $0$ as $n \to \infty$.

Your proof has a problem because you seem to assume that $b_{n} - a = a - a_{n}$. This is not necessary.

It is possible to remove the constraint $a_{n} < a < b_{n}$ provided we assume that $b_{n} \neq a_{n}$ and $f'$ is continuous at $a$.


text:
Q: optimized bsort in C I was looking at wikipedia's bsort page and I tried to implement the two optimized versions that are in pseudo code in C, but the results don't seem to add up. Here's my code:
Implementation 1:
#include <stdio.h>

#define SWAP(a, b) (a ^= b ^= a ^= b)

void tbsort(int a[], int n)
{
        int i, swapped;

        do {
            swapped = 0;
            for (i = 1; i <= n - 1; i++) {
                    if (a[i - 1] > a[i]) {
                            SWAP(a[i - 1], a[i]);
                            swapped = 1;
                    }
            }
            n -= 1;
        } while (!swapped);

        for (i = 0; i < 10; i++)
            printf("%d ->", a[i]);
        putchar('\n');
}

int main(int argc, char **argv)
{
        int a[10] = { 20, 22, 13, 0, 10, 11, 12, 13, 9, 3};

        tbsort(a, sizeof(a)/sizeof(int));

        return 0;
}

Implementation 2:
#include <stdio.h>

#define SWAP(a, b) (a ^= b ^= a ^=b)

void tbsort(int a[], int n)
{
        do {
            int i, newn = 0;

            for (i = 1; i <= n-1; i++) {
                if (a[i-1] > a[i]) {
                    SWAP(a[i-1], a[i]);
                    newn = i;
                }
            }
            n = newn;
        } while (!n);

        {
        int i;
        for (i = 0; i < 10; i++)
            printf("%d ->", a[i]);
        putchar('\n');
        }
}

int main(int argc, char **argv)
{
        int a[10] = { 20, 22, 13, 0, 10, 11, 12, 13, 9, 3};

        tbsort(a, sizeof(a)/sizeof(int));

        return 0;
}

Here is the output:

implementation1: 20 ->0 ->0 ->0 ->0 ->0 ->0 ->0 ->0 ->22 ->
implementation2: 20 ->0 ->0 ->0 ->0 ->0 ->0 ->0 ->0 ->22 ->

Could you help me understand what could be wrong?

A: There are two problems:

*

*The macro SWAP looks cool, however you shall never use it like that again. Let's try some code first:
#include <stdio.h>

int main(int argc, char **argv)
{
    #define SWAP(a, b) (a ^= b ^= a ^= b)

    int x[] = { 1, 2, };
    SWAP(x[0], x[1]);
    printf("%d %d\n", x[0], x[1]);

    int a = 1;
    int b = 2;
    SWAP(a, b);
    printf("%d %d\n", a, b);

    return 0;
}

I guess you may amazingly find it generate outputs unexpected. The reason is that your SWAP actually relies on specific undefined behaviors: the sequence of fetching values from memory and also writing back to memory (however in this case it's because of the manner of fetching values) on statements like a ^= b ^= c ^= d;.
To solve this you just need something like:
#define SWAP(a, b) ({ int tmp = a; a = b; b = tmp; })

However it's strongly recommended to write it a function. If you worry about efficiency of function calls, just use the inline modifier.

*Your algorithm logic seems not okay. To be specific, replace these lines:
} while (!swapped);  /* in implementation 1 */
} while (!n);        /* in implementation 2 */

with
} while (swapped);  /* in implementation 1 */
} while (n);        /* in implementation 2 */

The reason, is that you need to keep on swapping until there's no item swapped.
EDITED:
I'm explaining my example above using some detailed information.
First of all, I claimed that it's undefined behavior that:

the sequence of fetching values from memory and also writing back to memory on statements like a ^= b ^= c ^= d;

because I didn't find related specifications in the standard(ISO/IEC 9899:2011). However if anyone finds some evidence that supports/opposes this, please let me know. :)
Now let's have some code. Below is the related parts of assembly generated by gcc for my code example:
# int a = 1;
# int b = 2;
# a ^= b ^= a ^= b;
movl    $1, -4(%rbp)    # initialize a
movl    $2, -8(%rbp)    # initialize b
movl    -8(%rbp), %eax  # loads b into eax
xorl    %eax, -4(%rbp)  # a ^= eax
movl    -4(%rbp), %eax  # loads a into eax
xorl    %eax, -8(%rbp)  # b ^= eax
movl    -8(%rbp), %eax  # loads b into eax
xorl    %eax, -4(%rbp)  # a ^= eax

# int x[] = { 1, 2, };
# x[0] ^= x[1] ^= x[0] ^= x[1];
movl    $1, -16(%rbp)   # initialize x[0]
movl    $2, -12(%rbp)   # initialize x[1]
movl    -16(%rbp), %edx # loads x[0] into edx
movl    -12(%rbp), %ecx # loads x[1] into ecx
movl    -16(%rbp), %esi # loads x[0] into esi
movl    -12(%rbp), %eax # loads x[1] into eax
xorl    %esi, %eax      # eax = x[0] ^ x[1]
movl    %eax, -16(%rbp) # writes eax into x[0]
movl    -16(%rbp), %eax # loads (new)x[0] into eax
xorl    %ecx, %eax      # eax = x[1] ^ (new)x[0]
movl    %eax, -12(%rbp) # writes eax into x[1]
movl    -12(%rbp), %eax # loads (new)x[1] into eax
xorl    %edx, %eax      # eax = (new)x[1] ^ (old)x[0]
movl    %eax, -16(%rbp) # writes eax into x[0]

You could easily see the last but one line uses the old value of x[0], which leads to the unexpected results.
I'm using gcc 4.8.2.
EDITED:
Also #define SWAP(a, b) ({ a ^= b; b ^= a; a ^= b; }) is totally fine.

A: My guess would be that SWAP() isn't working, since the data is corrupted.
I guess it's possible that SWAP() works fine, since both 0 and 22 occur in the input, though. Still, it's definitely a source of confusion and possible bugs and badness, so it should be the first thing you fix in this program. Just do a plain old ordinary swap with a temporary variable:
const int tmp = a[i - 1];
a[i - 1] = a[i];
a[i] = tmp;

That XOR trickery might be useful somewhere, but it's not here.


text:
Q: Connect to Informix using Microsoft Visual C++ I'm trying to connect to Informix on HP-UX through Microsoft Visual C++ 2010. Any help with ODBC or another way of connecting to Informix will be appreciated.
It's a data form that needs to query, add, update and delete data from various Informix tables.

A: At first on client machine you must install client. You can download it from IBM site and its name is like: clientsdk.3.70.TC5DE.WIN.zip. Choose newest and install it. Configure client using setnet32 (Menu Start/IBM Informix Client SDK/setnet32). Then configure ODBC source. When asked for driver use "IBM Informix ODBC Driver". There on Connection tab you have to fill some data (host, port, database etc ). You will also see "Apply & Test Connection" button. Use it. If it works you can start programming.

A: Following Informix drivers are supported, and it can be used from Visual Studio including VS2010.
ODBC Driver.
.NET Driver.
OLE DB driver.
ESQL/C
Please let me know what specific information you are looking for.

A: The .NET driver has the most trivial setup among these drivers.
Assuming you have already done client server connectivity setup on your system by using SetNet32.

Then you may need to add reference to the .net provider binary (IBM.Data.Informix.dll) to your VS project, that is all needed as part of setup.
This binary is located at bin\netf<.net framework version>

For example:C:\CSDK\bin\netf40\

A sample connection string: "Database=MyDb1;UID=myuser;PWD=MyPassword;Server=MyServerInst";

    If you are using C/C++ application then ODBC driver may be a better choice.
    These are the two most common usages of ODBC driver.
    Using ODBC driver directly
    Using ODBC driver through a driver manager.

    Here is the instruction to use Informix ODBC driver directly.
    (If you want to use by using driver manager then change the include and library accordingly from the instruction).

    1) Create VS 2010 C++ Console Application Project
    File -> New Project
    Visual C++
    Win32 Console Application.
    Create an Empty Project
    <Give Project Name>
    <Press OK>
    <Application Option Check Mark 'Empty Project'>
    <Press Finish Button>

    2) Setup Informix ODBC driver reference to the project
{

    From the Solution Explorer Right Click on the Project Name
    From the pop-up menu that appear, select Property
    From the dialog box do the following setting.

    Configuration Properties :
    General
    Select appropriate value for 'Character Set'
    If you are not using Unicode API then make sure you have selected
    Use Multi Byte Character Set

    C/C++:
    General
    Additional Include Directories
    (Give the include directory location)
    C:\CSDK\incl\cli

    Linker
    General
    Additional Library Directories
    (Give the LIB directory location)
    C:\CSDK\lib

    Linker:
    Command Line
    Additional Options
    (Specify the Informix ODBC driver library)
    iclit09b.lib
}

Your project is ready to use Informix ODBC driver to connect any Informix Dynamic Servers.

////////////////////////////////////////////////
    Here is a very simple ODBC code
////////////////////////////////////////////////
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

//#ifdef WIN32 || WIN64
#ifdef WIN32
#include <io.h>
#include <windows.h>
#include <conio.h>
#endif

#ifdef USE_DRIVER_MANAGER
#include "sql.h"
#include "sqlext.h"
#else
#include <infxcli.h>
#endif

void GetDiagRec(SQLRETURN rc, SQLSMALLINT htype, SQLHANDLE hndl, char *szFunTag );

int main( int argc, char *argv[] )
{
    SQLHENV         henv=NULL;
    SQLHDBC         hdbc=NULL;
    SQLRETURN       rc = 0;

    SQLCHAR         ConnStrIn[1024]=
        "DRIVER={IBM INFORMIX ODBC DRIVER};SERVER=MyServerInst;DATABASE=MyDatabase;HOST=HpHost.ibm.com;PROTOCOL=onsoctcp;SERVICE=5550;UID=MyUser;PWD=PasswordForMyUser;";

    rc = SQLAllocHandle( SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv );
    rc = SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3,0);
    rc = SQLAllocHandle( SQL_HANDLE_DBC, henv, &hdbc );

    printf( "\n ConnStr=[%s]\n", ConnStrIn);

    rc = SQLDriverConnect( hdbc, NULL, ConnStrIn, SQL_NTS, NULL, 0, NULL, SQL_DRIVER_NOPROMPT );
    if (rc != SQL_SUCCESS)
    {
        GetDiagRec(rc, SQL_HANDLE_DBC, hdbc, "SQLDriverConnect" );
        exit(1);
    }

    // Do Some Work Here
     printf( "\n Connection Success! \n", ConnStrIn);

    rc = SQLDisconnect(hdbc);
    rc = SQLFreeHandle(SQL_HANDLE_DBC,hdbc);
    rc = SQLFreeHandle(SQL_HANDLE_ENV,henv);

    return(0);
}

void GetDiagRec(SQLRETURN rc, SQLSMALLINT htype, SQLHANDLE hndl, char *szFunTag )
{
    SQLCHAR message[SQL_MAX_MESSAGE_LENGTH + 1];
    SQLCHAR sqlstate[SQL_SQLSTATE_SIZE + 1];
    SQLINTEGER sqlcode;
    SQLSMALLINT length;

    if ( szFunTag == NULL )
    {
        szFunTag = "---";
    }

    printf  ( "\n %s: %d : ", szFunTag, rc);

    if (rc >= 0)
    {
       printf  ( " OK [rc=%d]", rc);
    }
    else
    {
        int i=1;

        printf  ( " FAILED: %i", rc);
       //Get diagnostic record
       while (SQLGetDiagRec(htype,
                            hndl,
                            i,
                            sqlstate,
                            &sqlcode,
                            message,
                            SQL_MAX_MESSAGE_LENGTH + 1,
                            &length) == SQL_SUCCESS)
       {
         printf  ( "\n SQLSTATE          = %s", sqlstate);

         printf( "\n Native Error Code = %ld", sqlcode);

         printf  ( "\n %s", message);
         i++;
       }
       printf  ( "\n-------------------------\n");
    }
}