text:
Q: How can I 'accumulate' a raw stream in Node.js? At the moment I concatenate everything into a string as follows
var body = '';
res.on('data', function(chunk){
    body += chunk;
});

How can I preserve and accumulate the raw stream so I can pass raw bytes to functions that are expecting bytes and not String?

A: First off, check that these functions actually need the bytes all in one go.  They really should accept 'data' events so that you can just pass on the buffers in the order you receive them.
Anyway, here's a bruteforce way to concatenate all data chunk buffers without decoding them:
var bodyparts = [];
var bodylength = 0;
res.on('data', function(chunk){
    bodyparts.push(chunk);
    bodylength += chunk.length;
});
res.on('end', function(){
    var body = new Buffer(bodylength);
    var bodyPos=0;
    for (var i=0; i < bodyparts.length; i++) {
        bodyparts[i].copy(body, bodyPos, 0, bodyparts[i].length);
        bodyPos += bodyparts[i].length;
    }
    doStuffWith(body); // yay
});

A: Better use Buffer.concat - much simpler. Available in Node v0.8+.
var chunks = [];
res.on('data', function(chunk) { chunks.push(chunk); });
res.on('end', function() {
    var body = Buffer.concat(chunks);
    // Do work with body.
});

A: Alternately, you can also use a node.js library like bl or concat-stream:
'use strict'
let http = require('http')
let bl = require('bl')
http.get(url, function (response) {
  response.pipe(bl(function (err, data) {
    if (err)
      return console.error(err)
    console.log(data)
  }))
})


text:
Q: How can a template argument after variardic arguments be inferred? I have the following template function:
template <typename...Args, typename Func>
void call(const char *name, Args...args, Func f)
{
        f(3);
}

When I try to use it, like
    call("test", 1, 2, 3, [=](int i) { std::cout<< i; });

The compiler complains that it cannot infer the template argument Func.
How can this problem be solved, knowing that args can be any type except a function pointer.

A: From 14.1p11:

A template parameter pack of a function template shall not be followed
  by another template parameter unless that template parameter can be deduced from the parameter-type-list
  of the function template or has a default argument (14.8.2).

If you want to keep the callable as the last argument, you can use forward_as_tuple:
template <typename...Args, typename Func>
void call(const char *name, std::tuple<Args...> args, Func f)
{
        f(3);
}

call("test", std::forward_as_tuple(1, 2, 3), [=](int i) { std::cout<< i; });

We can actually do better by synthesizing the tuple to contain the callable as well:
#include <tuple>

template<typename... Args_F>
void call_impl(const char *name, std::tuple<Args_F... &&> args_f) {
   auto &&f = std::get<sizeof...(Args_F) - 1>(args_f);
   f(3);
}

template<typename...ArgsF>
void call(const char *name, ArgsF &&...args_f) {
   call_impl(name, std::tuple<ArgsF &&...>(std::forward<ArgsF>(args_f)...));
}

A: Write get_last, which extracts the last element of a parameter pack.
Call it f.  Call f.
As an example,
template<typename T0>
auto get_last( T0&& t0 )->decltype(std::forward<T0>(t0))
{
  return std::forward<T0>(t0);
}
template<typename T0, typename... Ts>
auto get_last( T0&& t0, Ts&&... ts )->decltype(get_last(std::forward<Ts>(ts)...))
{
  return get_last(std::forward<Ts>(ts)...);
}

if you don't care about overload resolution, just calling get_last and treating it like a functor might be enough:
template <typename...Args>
void call(const char *name, Args...&& args)
{
    auto&& f = get_last(std::forward<Args>(args)...);
    f(3);
}

The next step up would be to do some SFINAE enable_if magic in order to make the call fail to match if you don't pass a valid functor last: however, this is probably overkill.
To detect if the f(3) will work, a simple traits class:
// trivial traits class:
template<typename T>
struct is_type:std::true_type {};

template<typename Functor, typename=void>
struct can_be_called_with_3:std::false_type {}

template<typename Functor>
struct can_be_called_with_3<Functor,
  typename std::enable_if<
    std::is_type< decltype(
      std::declval<Functor>(3)
    ) >::value
  >::type
>:std::true_type {}

which is pretty silly.  A fancier traits class would have to be used if your requirements for the passed in type are more complex (say, you want it to be called with the arguments).
Then you augment call with:
template <typename...Args>
auto call(const char *name, Args...&& args)
  -> typename std::enable_if<
       can_be_called_with_3< decltype( get_last(std::forward<Args>(args)... ) ) >::value
     >::type
{ /* body unchanged */ }

which is pretty obtuse.

A: if you want to vhave a pack of arguments as template you cannot write this in a way you already did:
template <typename...Args, typename Func>
void call(const char *name, Args...args, Func f)
{
        f(3);
}

But you can pack them in a std::tuple:
template <typename...Args, typename Func>
void call(const char *name, std::tuple<Args...> args, Func f)
{
        f(3);
}

call("test", std::forward_as_tuple(1, 2, 3), [=](int i) { std::cout<< i; });

redpajama_set_name: RedPajamaStackExchange


text:
Q: [SQL Server]Implicit conversion from data type nvarchar(max) to varbinary(max) is not allowed. Use the CONVERT function to run this query That is my code
DB::statement(DB::raw('EXECUTE dbo.SP_WS_CUST_MAIN ?,?,?,?,?,?,?'),
    [ $USER_ID, $CUST_PYMT_MTHD, $CUST_CMMNT, $CUST_NAME, $ANDROID_LOCATION,
      DB::raw("CONVERT(VARBINARY(MAX), $value)") , $WEEKDAY]
);

How can convert nvarchar(max) to varbinary(max)?

A: I can think of three possibilities. The simplest would be to create a shell stored procedure (say dbo.SP_WS_CUST_MAIN_VC) that simply accepts the parameters, including $value as a varchar(max), then does the conversion of $value to a varbinary(max) and calls the target stored procedure. This ensures proper quoting with the parameter replacement.
The second (and most hazardous) is to embed the CONVERT into the parameters directly, opening yourself to all sorts of SQL Injection ugliness.
The third would be to create a UDF that accepts a varchar(max) and returns a varbinary(max), and embed that into the base EXECUTE call, e.g.:
DB::statement(DB::raw('EXECUTE dbo.SP_WS_CUST_MAIN ?,?,?,?,?,dbo.castAsVarbinary(?),?'),
    [ $USER_ID, $CUST_PYMT_MTHD, $CUST_CMMNT, $CUST_NAME, $ANDROID_LOCATION,
      DB::raw("CONVERT(VARBINARY(MAX), $value)") , $WEEKDAY]
);

Any of these would work, but (1) and (3) should also be secure.


text:
Q: Resolving dependencies using restore and build I have several questions related to project.json, dependencies and the use of dotnet restore :

*

*Where are located the packages when doing dotnet restore according to dependencies declared in project.json?

*I have seen that one can dotnet restore --packages "myPackagesPath thus specifying where to locate its packages, but how can `dotnet build' knows where to fetch the dependencies afterwards? I have not seen any part of the project.json that specifies it.

*is project.json the way to go when creating new project in dotnet core?

A: 1: depending on your OS, it is in $USERDIR/.nuget/packages/
2: sorry, no idea on this one
3: yes, try it by doing: dotnet new it'll create a project.json


text:
Q: WYSIWYG Editor isn´t working after using a Subdomain for JavaScript I made 3 subdomains for the Media, JS and Skin Path to improve the site loading speed.
After switching the unsercure URL paths in Backend under Configuration > Web > unserucre from
{{unsecure_base_url}}js/
to
http://js.myDomain.de/js/
the
WYSIWYG Editor in the Backend isnt working.
It Shows all Icons but when I click to enable the HTML view of a CMS page only an empty page without html code opens in a seperate window.
JS is working fine at the frontend. If I reset my changes the WYSIWYG Editor starts working agiain.
Any Ideas for a magento newbie?

A: Undo your changes in System > Configuration > Web, then in the top left corner change the scope from "Default Config" to the next entry.  Now enter the new URL again and save, it will only affect the frontend.  This is because the admin gets it's web settings from the "Default Config" scope but not any other scope.


text:
Q: Jython with eclipse Java imports unresolved I am new to Jython. Started developing with PyDev and eclipse. Created a PyDev project with a .py file. Added a jar to its classpath; but I am getting Unresolved Import for the Java classes. For the other classes which are a part of the .jar I added import is working fine (OmdWorkRepoSecure). But only for the other Java native imports like, RuntimeException or String, its saying Unresolved Import.
from org.omd.util import OmdWorkRepoSecure // working fine
...
from java.lang import RuntimeException // saying Unresolved Import
I think somewhere I am missing the Java related paths, but not sure where I can fix this. Any help is appreciated.


text:
Q: Allternate to get contens by hitting a url? when i hit url i get:
//#DWR-REPLY
if (window.dwr) dwr.engine._remoteHandleBatchException({ name:'org.directwebremoting.extend.ServerException', message:'The specified call count is not a number: null' });
else if (window.parent.dwr) window.parent.dwr.engine._remoteHandleBatchException({ name:'org.directwebremoting.extend.ServerException', message:'The specified call count is not a number: null' });


text:
Q: regexkitlite match? i would like to get everything inbetween &v= and "> using a regex expression,
NSString *YouTubeRegex =  @"/amp;v=([^(\">)]+)/";

But that regex is not returning any matches ? i know the coding is correct just not the regex expression any help ?
Thanks

A: Assuming the regex engine is Perl-like:
"/&v=(.*)>/"

should do the trick.

A: Try this :
/amp;v=(.+?)">/

http://www.rubular.com/r/Lqb63CsN2p


text:
Q: delphi adoquery filter with listbox items this is final but already not filter
anyone has idea about my filter problem
begin
adoquery1.SQL.CLEAR;
adoquery1.SQL.Add('select * FROM gunsonu ');
adoquery1.SQL.Add('where TARIH like :TRH');
adoquery1.Parameters.ParamByName('TRH').Value:=(PlannerDatePicker1.text);

for i := 0 to form3.ListBox1.Items.Count-1 do
adoquery1.SQL.Add(' and VLIM <> '+QuotedStr(form3.ListBox1.items[i]));
end;
adoquery1.Open;
frxReport1.ShowReport(true);

A: The best way to set up queries from a Delphi app against an MS Sql Server isn't to keep modifying code in the app that constructs the query until running it returns the results you're hoping for.  One of the problems with the Delphi rapid compile/run cycle is that it encourages trial and error, which is
no substitute for getting things working properly.
It's better to separate the SQL-constructing task from the coding one for two reasons:

*

*The Sql Server client-side utilities (e.g. Sql Server Management Studio or the old ISql/W "Query Analyzer") are better tools for the Sql-construction task, they have access to the server's execution plan, profiler, etc.  But if you don't have one of those available, over the years, Delphi has included some kind of "Data Explorer" utility to run queries against a variety of servers - in recent XE versions, there's a Firedac one under FireDac | Explorer from the IDE menu.

*Using one of those tools, you have the Sql query which is actually sent to the server right on the screen in front of you.  A frequent source of error when trying to set the Sql up in Delphi code, especially for a beginner, is that the Sql query sent to the server isn't necessarily what you assume it is.  Judging by the examples that appear in qs on SO, they're frequently riddled with syntactic or semantic errors, especially when the Sql is supposed to contain quotation marks (the Delphi IDE's Watch and Evaluate windows don't provide a good form for viewing Sql).  Creating the query in a Sql querying tool, you get the chance to see exactly what the query is, and to get feedback from the tool regarding syntax errors, etc.

*It's easier using those tools to experiment with the best way to parameterize your query.
What's the point of 3?  Well, one thing is that parameterized queries are generally better optimized by the server than an ad hoc one, though admittedly not all queries can be expressed in a parameterized form  (e.g. you can't parameterize which column or table you're querying against).  The other thing is that it helps minimise your exposure to Sql-Injection (see https://en.wikipedia.org/wiki/SQL_injection).
Once you've got your query working as you're expecting in a client-side Sql tool like those above is the time to write the code to execute it from your Delphi app, not before.


text:
Q: Geopandas geoseries area - units? I have a GeoPandas DataFrame. I apply a couple of functions to the GeoDataFrame.

*

*Buffer - https://geopandas.org/en/stable/docs/reference/api/geopandas.GeoSeries.buffer.html
This creates a set of points around the coordinates / geometry.
import geopandas
from shapely.geometry import Point, LineString, Polygon

s = geopandas.GeoSeries(
    [
        Polygon([(0, 0), (1, 1), (0, 1)]),
        Polygon([(10, 0), (10, 5), (0, 0)]),
        Polygon([(0, 0), (2, 2), (2, 0)]),
        LineString([(0, 0), (1, 1), (0, 1)]),
        Point(0, 1)
    ]
)

s.buffer(0.2)

*Now, I'd like to measure the area of the buffered geometry using: https://geopandas.org/en/stable/docs/reference/api/geopandas.GeoSeries.area.html
s.area
The crs info of the DataFrame is:
<Derived Projected CRS: ESRI:102003>
Name: USA_Contiguous_Albers_Equal_Area_Conic
Axis Info [cartesian]:
- E[east]: Easting (metre)
- N[north]: Northing (metre)
Area of Use:
- name: United States (USA) - CONUS onshore - Alabama; Arizona; Arkansas; California; Colorado; Connecticut; Delaware; Florida; Georgia; Idaho; Illinois; Indiana; Iowa; Kansas; Kentucky; Louisiana; Maine; Maryland; Massachusetts; Michigan; Minnesota; Mississippi; Missouri; Montana; Nebraska; Nevada; New Hampshire; New Jersey; New Mexico; New York; North Carolina; North Dakota; Ohio; Oklahoma; Oregon; Pennsylvania; Rhode Island; South Carolina; South Dakota; Tennessee; Texas; Utah; Vermont; Virginia; Washington; West Virginia; Wisconsin; Wyoming.
- bounds: (-124.79, 24.41, -66.91, 49.38)
Coordinate Operation:
- name: USA_Contiguous_Albers_Equal_Area_Conic
- method: Albers Equal Area
Datum: North American Datum 1983
- Ellipsoid: GRS 1980
- Prime Meridian: Greenwich

My question is: what is the units of the area calculated?

A: The units of area would be metre^2. The units are reported in the CRS.
Presumably, the actual shapefile has very large values (e.g. in the ~1e6 range). See e.g. this question: Interpreting GeoPandas Polygon coordinates


text:
Q: In RUP: What RUP roles are responsilbe for creating the Software Architecture Document? Based on the different views documented in SAD which RUP roles should should be responsible for creating the SAD? I thought from the beginning that the SAD was only for a technical audience but from what i can see in RUP it is more than that so it seems like it is not only the Software Architect that should be involved.

A: Well, according to RUP's documentation, it's the Software Architect.
Quoting the Artifact:  Software Architecture Document online reference:

Responsibility
A software architect is responsible
  for producing the Software
  Architecture Document, which captures
  the most important design decisions in
  multiple architectural views.
The software architect establishes the
  overall structure for each
  architectural view: the decomposition
  of the view, the grouping of elements,
  and the interfaces between these major
  groupings. Therefore, in contrast with
  the other roles, the software
  architect's view is one of breadth, as
  opposed to depth.
The software architect is also
  responsible for maintaining the
  architectural integrity of the system
  through the development process by:

*

*Approving all changes to architecturally significant elements,
  such as major interfaces, described in
  the Software Architecture Document.

*Being part of the "change-control board" decisions to resolve problems
  that impact the software architecture.

A: Well,
Do not think "roles" as job titles...
If you work in a traditonal enviroment, generally there is a guy who is job title is also "Software Architect"...If you work in an agile  enviroment generally you can not find a job title like "software architect" in team...So the important thing is who knows and who gives the important decisons about architecture: Who fills the role of the architect not title....
In an healty enviromement[ traditional or agile] one guy can not give all decisons, so SAD is a workproduct of all team in practice because all teams  members sometimes play the role of "architect"...


text:
Q: Partition of a set induced by an equivalence relation Let $X = \{1, 2, 3, 4, 5\} × \{1, 2, 3, 4, 5\}$ and define $R$ on $X$ by $(x_1, y_1)R(x_2, y_2)$ if $x_1 + y_1 = x_2 + y_2$.
Determine the partition of $X$ induced by $R$.
I have already shown that this is an equivalence relation. I am trying to figure out what this means when it says, the partition of $X$ induced by $R$.
The way that I understand it, $x+y = \{2,3,...,10\}$. So would I be listing the equivalence classes of each possible value that $x+y$? I am very confused about this. Any help would be appreciated.

A: Given some set $X$ and $R$ an equivalence relation on it, what is partitionned is what is called technically the quotient set noted $X/R$ of $X$ by $R$, that is the set of all distinct equivalence classes which can be generated from any element of $X$ with the relation of equivalence.
Consider $R$ as being represented by some binary graph also noted $R$, some subset of $X\times X$. $(x,y)\in R$ meaning $x$ and $y$ are equivalent modulo $R$. For $R$ to be an equivalence on $X$ it has to be represented by an equivalence graph:
(1) $R$ is reflexive  $\forall x\in X\ (x,x)\in R$
otherwise stated the diagonal of $X\times X$ belongs also to $R$.
(2) $R$ is symmetrical, i.e. it does not differ from its symetrical graph noted $R^{-1}=\{(y,x)\ s.t.\ (x,y)\in R\}$ otherwise stated $(x,y)\in R \iff (y,x)\in R$.
(3) $R$ is transitive, $R=R\circ R$ the compound graph being defined by $R\circ R=\{(x,z)\ s.t.\ (\exists y)[(x,y)\in R \wedge (y,z)\in R]\}$ otherwise stated $(x,y)\in R \wedge (y,z)\in R \Rightarrow (x,z)\in R$
Now consider one element of $X$ and consider its image $R(\{x\})$ noted
$R(x)$ for short i.e. the set of all elements corresponding to $x$ by the relation: $R(x)=\{y\in X \ s.t.\ (x,y)\in R\}$. It is some cut in the graph $R$ for some  fixed $x$ abscissa along $y$ ordinates which is called the class of equivalence of $x$ and is also noted $[x]_R$. $x$ is said to be one representant of the class $[x]_R$ which is a subset of $X$. Now the quotient set $X/R$ is nothing else than the union of all these equivalence classes $X=\bigcup_{x\in X} R(x)$. By construction it is easy to show that two distinct equivalence classes have no element in common: if $x$ and $y$ are not equivalent then $[x]_R\cap [y]_R=\emptyset$. Hence the quotient set $E/R$ can be seen as a disjoint union, i.e. a partition of $X$ into equivalence classes.
What you have to do in your particular example is to find for each ordered pair $x\in X$ its equivalence class $[x]_R$ i.e. the set of all other ordered pairs (including $x$ itself) equivalent to $x$. Then select among these classes only those which are distinct. By symetry you can generate all the equivalence classes considering only half of your elements in $X$ as representants.
$(1,1)\quad [(1,1)]_{R}=\{(1,1)\}$
$(1,2)\quad [(1,2)]_{R}=\{(1,2),(2,1)\}$
$(1,3)\quad [(1,3)]_{R}=\{(1,3),(3,1),(2,2)\}$
$(1,4)\quad [(1,4)]_{R}=\{(1,4),(4,1),(2,3),(3,2)\}$
$(1,5)\quad [(1,5)]_{R}=\{(1,5),(5,1),(2,4),(4,2),(3,3)\}$
$(2,5)\quad [(2,5)]_{R}=\{(2,5),(5,2),(3,4),(4,3)\}$
$(3,5)\quad [(3,5)]_{R}=\{(3,5),(5,3),(4,4)\}$
$(4,5)\quad [(4,5)]_{R}=\{(4,5),(5,4)\}$
$(5,5)\quad [(5,5)]_{R}=\{(5,5)\}$

A: If $X$ is set then a partition of $X$ is a collection $(S_i)_{i \in I}$ of non-empty subsets $S_i \subseteq X$ such that $X = \bigcup_{i \in I} S_i$ and these subsets are pairwise disjoint, i.e. $S_i \cap S_j = \emptyset$ for $i \neq j$. In other words, each element of $X$ is contained in exactly one of the $S_i$.
If $(S_i)_{i \in I}$ is a partition of $X$ then this induces an equivalence relation on $X$ via $x \sim y$ if and only if $x$ and $y$ are contained in the same $S_i$.
On the other hand every equivalence relation on $X$ also induces a partition of $X$ via the correspondings equivalence classes (because every elment of $X$ is contained in exactly one equivalence class.)
These two constructions are inverse of each other, so equivalence relations on $X$ are, in the above way, the same as partitions of $X$.
So the exercise is to give the equivalence classes of $X = \{1, \dotsc, 5\} \times \{1, \dotsc 5\}$ with respect to the equivalence relation $(x_1, y_1) \sim (x_2, y_2) \iff x_1+y_1 = x_2+y_2$. For example, the equivalence class of $(2,3)$ is $\{(1,4),(2,3),(3,2),(4,1)\}$.

A: Yes, you want to list the equivalence classes.  The set of equivalence classes is the partition induced by the equivalence relation.

A: Yes, you are on the right track. An equivalence class is a subset of $X$ that only contains elements that are equivalent to each other under $R$. In this way we can partition (group together elements of) $X$ into disjoint subsets that are each an equivalence class, grouping together equivalent elements of $X$.
In your case each equivalence class  contains elements of $X$ whose components add up to the same number. You already found the possible sums: $\{x+y| (x,y) \in X\} = \{2,3,4,5,6,7,8,9,10\}$
So one subset defined by the partition of $X$ induced by $R$ is the subset of all $(x,y) \in X$ such that $x+y =2$: $\{(x,y) \in X | x+ y = 2\}$
So you are being asked to find a subset of $X$ for each $n \in \{2,3,4,5,6,7,8,9,10\}$: $\{(x,y) \in X| x+y = n\}$
Together, the definitions of each subset (you could define each subset by just listing the elements contained within it) describes the partition.


text:
Q: Running single junit test in gradle passes but fails when entire test is run I have an unusual issue dealing with a particular junit test within gradle.  When I run the test as follows it passes
gradlew test --tests com.compsci.ic.xbrl.SchemaRefTest
However when I run
gradlew test
it fails with the following stacktrace
java.lang.IllegalStateException: Undeclared namespace prefix in DOM input: link
    at net.sf.saxon.dom.NodeWrapper.getURI(NodeWrapper.java:531)
    at net.sf.saxon.dom.NodeWrapper.getNameCode(NodeWrapper.java:412)
    at net.sf.saxon.om.Navigator.copy(Navigator.java:523)
    at net.sf.saxon.dom.NodeWrapper.copy(NodeWrapper.java:827)
    at net.sf.saxon.om.Navigator.copy(Navigator.java:516)
    at net.sf.saxon.dom.NodeWrapper.copy(NodeWrapper.java:827)
    at net.sf.saxon.om.StrippedNode.copy(StrippedNode.java:448)
    at net.sf.saxon.instruct.CopyOf.processLeavingTail(CopyOf.java:397)
    at net.sf.saxon.instruct.Template.applyLeavingTail(Template.java:175)
    at net.sf.saxon.instruct.ApplyTemplates.applyTemplates(ApplyTemplates.java:343)
    at net.sf.saxon.Controller.transformDocument(Controller.java:1735)
    at net.sf.saxon.Controller.transform(Controller.java:1559)
    at org.custommonkey.xmlunit.Transform.transformTo(Transform.java:211)
    at org.custommonkey.xmlunit.Transform.getResultDocument(Transform.java:233)
    at org.custommonkey.xmlunit.XMLUnit.stripWhiteSpaceUsingXSLT(XMLUnit.java:514)
    at org.custommonkey.xmlunit.XMLUnit.getWhitespaceStrippedDocument(XMLUnit.java:507)
    at org.custommonkey.xmlunit.Diff.getWhitespaceManipulatedDocument(Diff.java:182)
    at org.custommonkey.xmlunit.Diff.getManipulatedDocument(Diff.java:203)
    at org.custommonkey.xmlunit.Diff.<init>(Diff.java:155)
    at org.custommonkey.xmlunit.Diff.<init>(Diff.java:145)
    at org.custommonkey.xmlunit.Diff.<init>(Diff.java:109)
    at org.custommonkey.xmlunit.Diff.<init>(Diff.java:101)
    at org.custommonkey.xmlunit.Diff.<init>(Diff.java:93)
    at org.custommonkey.xmlunit.XMLAssert.assertXMLEqual(XMLAssert.java:228)
    at org.custommonkey.xmlunit.XMLAssert.assertXMLEqual(XMLAssert.java:179)
    at com.compsci.ic.xbrl.SchemaRefTest.testSerialize(SchemaRefTest.java:34)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.runTestClass(JUnitTestClassExecuter.java:114)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.execute(JUnitTestClassExecuter.java:57)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassProcessor.processTestClass(JUnitTestClassProcessor.java:66)
    at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:51)
    at sun.reflect.GeneratedMethodAccessor43.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:32)
    at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
    at com.sun.proxy.$Proxy1.processTestClass(Unknown Source)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:108)
    at sun.reflect.GeneratedMethodAccessor42.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:146)
    at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:128)
    at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:404)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
    at java.lang.Thread.run(Thread.java:748)

This test runs fine in ant so I've checked all dependencies between ant and gradle and they all seem to match.  Any additional suggestions would be greatly appreciated
Here is the source code of the test
package com.compsci.ic.xbrl;

import java.io.IOException;
import java.net.URI;

import org.custommonkey.xmlunit.XMLAssert;
import org.custommonkey.xmlunit.XMLUnit;
import org.junit.Test;
import org.xml.sax.SAXException;

import com.compsci.ic.xbrl.xstream.URIConverter;
import com.thoughtworks.xstream.XStream;

public class SchemaRefTest {
    @Test
    public void testSerialize() throws SAXException, IOException {
        SchemaRef ref = new SchemaRef();

        ref.setHref(URI.create("http://example.com"));

        XStream xstream = new XStream();

        xstream.registerConverter(new URIConverter());
        xstream.processAnnotations(SchemaRef.class);

        XMLUnit.getTestDocumentBuilderFactory().setNamespaceAware(false);
        XMLUnit.getControlDocumentBuilderFactory().setNamespaceAware(false);

        XMLAssert.assertXMLEqual(
            "<link:schemaRef xlink:type='simple' xlink:href='http://example.com'/>",
            xstream.toXML(ref));
    }
}

A: My guess is that another test is being dirty and bleeding into this test. Things like System Properties or mutable static variables are likely causes. Those static XMLUnit mutator methods have a code smell to me
You could try the following which will give each test a "clean" jvm. Note this will slow things down
apply plugin: 'java'
test {
    forkEvery = 1
}

See Test.setForkEvery(...)
This is obviously a hack and it's best to find the offending test and fix it to clean up after itself in @After or @AfterTest. If you can't find the "dirty" test you could always initialize the "polluted" statics in  @Before or @BeforeTest of the failing test

A: I fixed it by adding the following to the test
XMLUnit.setIgnoreWhitespace(false);

Seems that XMLAssert is outdated and will have to overhaul these tests in the future to get everything current.  For now I am in good shape.


text:
Q: Why is my querystring being modified by Chrome Mobile on iPhone and Kindle Fire's Silk browser? I have a portal application with the following url https://pv.xxxxx.org/Y/Students.aspx, at least that is how it appears in any of my web browsers on my PC. On my Kindle Fire HD (Silk) or iPhone  (Chrome) it is showing up like
https://pv.xxxxx.org/(F(gXjx4o3HVBTt2dUj-0_fg8JrTaBqvjZUE7WjynRNoYUKpUo3YFpP6KD92KXl6XSeJE633w9eetXNHJhE_bXBrMe8wcd9FKivh16Ibrz4a06dZd4UAxyHTxK2euBM8gRlqzEmgLnQmy830rW2UtMwfmuNJQVwsvyz72EaLNgTkf01))/Y/Students.aspx
As soon as I click on any link in the web forms application the system just logs me out. I have coded pretty heavy error handling into the system so it sends me an email and logs to the database and event logs if anything goes wrong and I am getting nothing. I cannot reproduce the problem since it is only happening on those two mobile devices(that I have access to), and I cannot run a debugger on it.
Some other information it does not do bad things to my url in Safari on the iPhone. I do use the querystring to pass variables but not when you first load the application and this is after the end user, in this case me, has been authenticated and is on the landing page.
So my questions are why is it being modified, can I make it stop, if not how can I fix it? I have been struggling to find any mention of the problem let alone a solution through googling.

A: My portal application is running asp.net 4.0, I cannot get to 4.5 because I am running a windows 2003 server and it will not let me install it. So this problem is not relative to anyone who is running 4.5 or later. In the browsers I mentioned above they are taking my forms based authentication and setting it to Cookieless mode. I assume, although I don't know for sure, but the addition to the Querystring is the authentication token.
In order to fix the problem so that my end users don't have to mess around with their cookie settings, I updated my web.config with the following code:
<authentication mode="Forms" >
  <forms loginUrl="~/Account/LogOn" timeout="2880" cookieless="UseCookies" />
</authentication>

The key component of that code snippet is:
cookieless="UseCookies"

Once I updated the Web.Config the addition to the Querystring vanished and I was able to observe the creation of the .aspxauth authentication token using chrome's developer tools.
I added the explanation for completeness purposes here is where I ended up finding the answer:
FormsAuthentication On ASPNET Sites With The Google Chrome Browser On iOS
Thank you Mr. Scott Hanselman.


text:
Q: Call to grep in command substitution fails I am trying to make a grep call in a command substitution in bash like so:
status=$(dpkg -s elasticsearch | grep "Status")

But when I run this in a script called elk.sh, I get the following output:
./elk.sh: 47: ./elk.sh:  grep: not found

It seems that when I use command substitutions, grep is not found. But when I call it normaly in my script, it is working as usual.
Do you have any idea of what could be wrong?
EDIT: as my code is not sensitive, I am sharing it here, since it may help you to understand what is wrong.
Note that file elk.sh returns:
elk.sh: POSIX shell script, UTF-8 Unicode text executable

Here is the code:
#!/bin/sh

pInfo() {
    if [ "$#" -ne 1 ]; then
        echo "Invalid arguments: pInfo needs one string as argument."
        exit 1
    fi
    echo "\033[32m[INFO]\033[0m $1"
}

pError() {
    if [ "$#" -ne 1 ]; then
        echo "Invalid arguments: pError needs one string as arguments."
        exit 1
    fi
    echo "\033[31m[ERROR]\033[0m $1"
}

install_elk() {
    wget "https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-6.4.2.deb" -q --show-progress
    sudo dpkg -i "elasticsearch-6.4.2.deb"
    sudo apt-get install -f
    sudo rm -rRf "elasticsearch-6.4.2.deb"
}

which grep
echo $PATH
pInfo "Verifying ElasticSearch installation."
status=$(dpkg -s elasticsearch | grep Status)
if [ "$?" -ne 0 ] || [ -z "$status" ]; then
    pError "ElasticSearch is not installed."
    pInfo "Start the installation ? (y/n)"
    read answer
    if [ "$answer" != "y" ] && [ "$answer" != "n" ]; then
        pError "Invalid answer. Just type 'y' (yes) or 'n' (no)."
        exit 1
    fi
    if [ "$answer" = "y" ]; then
        pInfo "Installing ElasticSearch..."
        install_elk
    else
        pInfo "Not installing ElasticSearch."
        exit 2
    fi
fi

pInfo "ElasticSearch installed."

ps ax | grep -v grep | grep "elasticsearch" > /dev/null
if [ "$?" -eq 1 ]; then
    pInfo "ElasticSearch not running. Starting..."
    if [ ! -z "$(ps -p 1 | grep "systemd")" ]; then
        pInfo "System running systemd."
        sudo systemctl start elasticsearch.service
    else
        pInfo "System running init."
        sudo -i service elasticsearch start
    fi
fi

pInfo "ElasticSearch started."

exit 0

A call to elk.sh gives the following output:
$ ./elk.sh
/bin/grep
/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games
[INFO] Verifying ElasticSearch installation
[INFO] ElasticSearch installed
./elk.sh: 49: ./elk.sh:  grep: not found
[INFO] ElasticSearch not running. Starting...
[INFO] System running systemd.
[INFO] ElasticSearch started.

EDIT: I found the issue: rewriting the line like so:
status=$(dpkg -s elasticsearch |grep "Status")

makes the commands works just fine. I just needed to remove the whitespace between the pipe and the grep command.


text:
Q: ember-simple-auth cookieExpirationTime not working I need to implement a "remember me" feature in my application.
I am using the built-in devise authenticator and have the following as my Session Store:
// app/session-stores/application.js
import CookieStore from 'ember-simple-auth/session-stores/cookie';

export default CookieStore.extend({
  cookieName: 'myapp-session-cookie'
});

I have a login-form component with the following:
rememberMe: false,
setExpirationTime() {
  const expirationTime = this.get('rememberMe') ? (14 * 24 * 60 * 60) : null;
  this.set('session.store.cookieExpirationTime', expirationTime);
},

actions: {
  authenticateWithDevise() {
    this.setExpirationTime();
    let { identification, password } = this.getProperties('identification', 'password');
    this.get('session').authenticate('authenticator:devise', identification, password).then(() => {
      this.sendAction('onLoggedIn');
    }).catch((reason) => {
      this.set('errorMessage', reason.errors[0]);
    });
  }
}

and of course in the corresponding template I have:
<form role="form" {{action "authenticateWithDevise" on="submit"}}>
  {{input type="email" value=identification placeholder="Email" class="icon-email"}}
  {{input type="password" value=password placeholder="Password" class="icon-lock"}}
  {{input id='remember_me' type='checkbox' checked=rememberMe}}
</form>

What happens is session is never remembered, no matter whether cookieExpirationTime was set or null.
My question is: should I also implement something else on the server side? I'm currently using devise's rememberable. Also, I've tried searching both here and on github but can only find conversations and code that seems obsolete, like this:
https://github.com/simplabs/ember-simple-auth/pull/451
Can somebody please shed some light? Thanks!


text:
Q: Get the entire document innerhtml Is there a way to get the innerhtml for the entire page, including html, head, body and so on.
I am only able to call page.getDocument().getBody().getInnerHTML() ... there is no page.getDocument().getInnerHTML() ... shouldn't there be ?

A: There is no such api for Ui4j but you could use the following example to get innerhtml of the entire page.
import static com.ui4j.api.browser.BrowserFactory.getWebKit;

import com.ui4j.api.browser.Page;

public class Main {

    public static void main(String[] args) {
        Page page = getWebKit().navigate("https://bing.com");
        String html = (String) page.executeScript("document.documentElement.innerHTML");
        System.out.println(html);
    }
}


text:
Q: Centroid of the Region bounded by the functions: $y = x, x = \frac{64}{y^2}$, and $y = 8$. Can someone help and teach me how to solve this problem?

Find the centroid of the region bounded by the graphs of $$\begin{align}
&y = x\\
&x = \frac{64}{y^2}\\
&y = 8
\end{align}$$

I'm having trouble solving this problem, please help. Thank you!
I currently don't know how to solve this problem, if someone would show a step-by-step solution would be very much appreciated!

A: HINT
We can find the $x$ and $y$ coordianates of the centroid separately. There are several formulae that we can use:
$$\sum m_i x_i=\bar x\sum m_i$$
$$\sum m_i y_i=\bar y\sum m_i$$
$$\bar x=\frac{\int_a^bxy ~dx}{\int_a^b y ~dx}$$
$$\bar y=\frac{\int_a^b\frac{1}{2}y^2dx}{\int_a^b y ~dx}$$
If that doesn't help, or if you have any questions, I will be happy to elaborate.


text:
Q: Hasura 2.0, is there a way to use wildcards? Hello everyone I am having some issues with the way I used to query my data before updating to Hasura 2.0 (I am currently on Beta 1), so Before 2.0 if you sent a null value to a query it would act as a wildcard * , now that I updated to 2.0 all query variables must have non-null values, is there anyway I could get around this?
A small query will serve as an example:
query get_student_organization($authorId: Int, $gradeId: Int, $groupId: Int, $schoolId: Int) {
  validation: student_organization(where: {author_id: {_eq: $authorId}, escuela_id: {_eq: $schoolId}, grado_id: {_eq: $gradeId}, grupo_id: {_eq: $groupId}}) {
    id
  }
}

so if I send it with only
{"authorId": 5455}

I expect all other variables to act as wildcards.
Any help is welcome :)

A: you can simply send your whole where object from your front-end!
That way you can simply omit the null variables at all. For this, you need to tweak your query a little bit.
query get_student_organization($wh_frontend: student_organization_bool_exp!) {
  validation: student_organization(where: $wh_frontedn) {
    id
  }
}

In the variables section, add your non-null variables only:

{
  "where_fe": {
    "authorId": 5455
  }
}

so this time your haven't sent the schoolId, groupId and gradeId which serves your need for a wild-card.


text:
Q: How to call a jar applet file in html I have copied a very simple applet (just a written message) in java and created a jar file. I called the jar file with the following code but when I opened the file in a browser nothing's appearing (apart from the header). What beginners mistake am I making?
<html>
    <head>
        Chess App
    </head>
    <body>
        <applet code="Main.class" archive="JavaChessGradeApplet.jar" width=640 height=480></applet>
    </body>
    </head>
</html>


text:
Q: how to use select with like condition for search some words with out Priority status i create a store procedure that get a Sentence and separate words with % instead of ' '
create proc Mysp_SearchIn_Comments
@text nvarchar(max)
as
set @text = REPLACE(@text ,' ', '%')

select text from tblMediaComments
where Text like
'%'+@text+'%'

it good But the problem is when i search something like : 'bad boy'
 , the results is that comments contain boy after bad
 , i need also show comments when bad after boy
i need an advance search such as google algorithm !
Thanks.

A: You need Full Text Search.
It does most of the fancy search functionality for you.
(Source MSDN)
Comparing LIKE to Full-Text Search
In contrast to full-text search, the LIKE Transact-SQL predicate works on character patterns only. Also, you cannot use the LIKE predicate to query formatted binary data. Furthermore, a LIKE query against a large amount of unstructured text data is much slower than an equivalent full-text query against the same data. A LIKE query against millions of rows of text data can take minutes to return; whereas a full-text query can take only seconds or less against the same data, depending on the number of rows that are returned.
Take a look at this...
MSDN Full-Text Search

A: In this case you need to use dynamic sql.
DECLARE @text NVARCHAR(max) = 'bad after boy'
    ,@sql NVARCHAR(max)

SET @text = '''%' + REPLACE(@text, ' ', '%'' or [Text] like ''%') + '%''';
SET @sql = 'select text from tblMediaComments where [Text] like ' + @text;

EXEC @sql

Query will looks like this:
select text from tblMediaComments where [Text] like '%bad%' or [Text] like '%after%' or [Text] like '%boy%'


text:
Q: What kind of Windows-based "process accounting" software is available? Linux has pacct and kernel-based processing.  What equivalents are available for Windows?  I am aware (and use/recommend) of Process Explorer, but that only tracks real-time stats, with non-portable graphs for a single process.  I want to be able to track CPU, Memory, I/O for all of my processes on Windows 7.

A: Windows Performance Monitor does have the ability to do what you're looking for, just not with realtime graphing. Since you tagged this windows-7 you have access to the full tool for this.

*

*Open "Performance Monitor"

*Expand "Data Collector Sets"

*Expand "User Defined"

*Right-click, select New

*Use "Manually Defined"

*Select "Performance Counter" but nothing else.

*Add the relevant process-level monitors you need

*

*Click Add.

*Find "Process"

*Look for the items you need

*In the "Instances" dropdown, select "" for everything, and click Add.

*Repeat as needed.

*Click Finished when done.

*Right-click on the monitor you just created, and go to Properties.

*Go to the "Stop Condition" tab to specify how long you want to monitor.

*To start monitoring, right-click on the monitor and select start. Stop the same way if you want to stop it before the stop-condition.

To view the report once monitoring is complete, it will be under Reports.
That'll get you started.

A: http://msdn.microsoft.com/en-us/performance/cc709422
look at the "wpr"
can be kinda hardcore....

A: Depending on how detailed you need to get either Perfmon or Windows Perfomance analyzer (from the performance toolkit) can provide these details.  In general it's best to have some sort of reason for this type of analysis on a desktop, for the server environment you can use all of the above as well as windows system resource manager to do accounting.


text:
Q: in _asarray_tuplesafe result[:] = [tuple(x) for x in values] my function is like this :
def computer_daily_returns(df):
    daily_returns = df.copy()
    daily_returns[1:] = (df[1:] / df[:-1].values) - 1
    **daily_returns.ix[0, :] = 0**
    return daily_returns

and will generate a df like below:
                GOOG      AAPL       GLD       XOM
2010-01-04  0.000000  0.000000  0.000000  0.000000
2010-01-05 -0.004404  0.001689 -0.000911  0.003873
2010-01-06 -0.025209 -0.015881  0.016500  0.008642
2010-01-07 -0.023280 -0.001857 -0.006188 -0.003213
2010-01-08  0.013331  0.006629  0.004963 -0.003991
2010-01-11 -0.001512 -0.008812  0.013289  0.011250
2010-01-12 -0.017684 -0.011376 -0.020913 -0.005029

when i was trying to use
allocs = spo.minimize(sharpe_ratio, guess_allocs, args=(normed,) bla bla bla..

it gave me
ValueError("Objective function must return a scalar")

sharpe_ratio is a function and contains computer_daily_returns function.
after i delete daily_returns.ix[0, :] = 0 everything is working fine ..


text:
Q: Storing data and not outputting with Intended Format I'm storing some data from a spreadsheet which works properly after a Debug.Print
The data being stored is a long number starting with a single or more 0.
I've tried using the below few different code segments and none of them are outputting what I want...
.Cells(LR + 1, index).value = "00049875142"
OUTPUT: 49875142
.Cells(LR + 1, index).value2 = "0008789875949898451142"
OUTPUT: 8.78988E+18
QUESTION: How can i get the output to add the leading 0 in the string when unloading my data back into the spreadsheet?

A: Make sure the cell is formatted as text before storing value to it.
.Cells(LR + 1, index).NumberFormat = "@"
.Cells(LR + 1, index).value = "00049875142"

It will be more efficient though to not set format for each cell at a time, but do for the range before looping through and setting the values.

A: You can either add leading zeroes with a custom number format (which doesn't seem to be standard across multiple cells) or input the data as text.
.Cells(LR + 1, index).value = "'00049875142"
 'more loops
.Cells(LR + 1, index).value2 = "'0008789875949898451142"

The second needs to be input as text in any event since it is larger than 15 digits and the 15 digit precision rule will truncate off important data.
.Cells(LR + 1, index).numberformat  ="00000000000"
.Cells(LR + 1, index).value = 49875142
 'more loops
.Cells(LR + 1, index).numberformat  ="@"
.Cells(LR + 1, index).value2 = "0008789875949898451142"


text:
Q: Regex - Match @function[args1|args2] I have an issue to match a certain pattern in Regex

*

*Case 1 : @Function[]

*Case 2 : @Function[args1|args2]

*Case 3 : @Function

I want this result

*

*Case 1 : 1-Function 2-

*Case 2 : 1-Function 2-args1|args2

*Case 3 : 1-Function 2-

I match the two first pattern with \@(.?*)\[(.?*)\] but not the third.
Thank you for your time.
Aubin

A: \@([^[\]]+)(?:\[(.*?)\])?

(btw you made a mistake while writing your regex here I guess, as you wrote: .?*)
Edit: forgot the second capturing group.
Edit2: as for the reason the previous didn't work, the lazy operator of the first group made sure to get the smallest match. So the second part was tested while the first matched "" (nothing), and was a success too as it has a ? operator.


text:
Q: Is it better to use a MOSFET with a gate driver IC or a MOSFET with a lower VGS,on? I am building an RGBW controller for my room. I will be using an ESP32 with four MOSFETs for each channel. I want to know which is best for fast switching. Do I need to use a MOSFET driver IC such as the ICL7667 with IRFZ44n or is it better to use a lower VGS MOSFET such as the AO3400, or something entirely different?
I'm open for suggestions.
What are the cons and pros for both, since it's only one time investment cost is not the issue?
I will make the PCB, so I prefer SMD components.

A: You cannot design ANY switch properly without specifying the load impedance R, C, L.  tR and f rate.
Your switch RdsOn only needs to be < 1% of this load R for efficiency and cool operation with our large heatsink. But cost of FET may become a factor.
Vgs should be be 3x Vgsth for old std 2~4V thresold FETs or Vgs = 12V and only >2~2.5x for low Vth =1V FETs e.g. 3.3V. So your uC levels can consider these options for drivers if a boost is needed in Vgs.  But remember that Coss increases as RdsOn decreases, which with cable L affects resonant frequency, so switch rise time, Q, and rep rate needs to be specified also.
For Visual RBW controls, you do not need a very fast rep rate compared to a 1MHz SMPS.  Maybe 20kHz with PWM ??
When in doubt, datasheet specs for Vgs @ RdsOn ought to be observed for desired low loss and Coss & L cable to load R, ESR, or incremental R for resonance and series Q values.  E.g. LED R ~= 0.5/P. Thus 100W = 5 milliohms , 1 W = 0.5 Ohm.  And thus choose a switch that is near 1% of this for cool operation. More Ron demands attention to heat sink 1W/sq.in. of Cu area attached to SMD switch or as specified by datasheet.
For EMI reduction, consider a CM choke and X,Y cap as a PI filter to strip. This can be a Toroid or SMD choke. Use an AM radio to determine if you have EMI.
Bottom line:  Compare Ron / R(LED) for loss ratio then decide on FET choices and then Vgs. The P rating of LEDs depends on array voltage and is irrelevant to this.  Current and impedance ratio of switch is primary concern. Thus actual load tends to use only a small ratio of rated FET current at max heat sink rating.

A:
which is best for fast switching do I need to use MOSFET driver IC such as ICL766 with IRFZ44n or is it better to use lower VGS MOSFET such as AO3400

You don't want fast switching to drive LED strips! If the FET switches in a couple tens of nanoseconds, you will send very high di/dt currents into your wires which will radiate electromagnetic interference and essentially act like a broadband radio jammer. Remember a signal with 10ns edges has bandwidth extending to hundreds of MHz...
On the contrary, you want slow edges, like 0.5µs - 1µs. This increases switching losses, but your PWM frequency is going to be low anyway, so switching losses, which are proportional to frequency, will be low too. Let's check the math:
Conduction losses = RdsON * I^2 * DutyCycle
For 2 amps and a duty cycle of 1 (100%) a FET with RdsON of 40 mOhms dissipates 0.16W -- you can use a FET with lower RdsON if you want.
Switching losses = V * I * SwitchingTime * Frequency
For 12V, 2A, 500ns, 10kHz losses will be 0.12W.
Note these losses are already a bit high for a SOT23 FET. I'd use a SO8 single or dual FET instead, they have better dissipation and they're pretty cheap.
Say you want to switch an AO3400 in T=500ns, total gate charge is Qg=7nC so gate drive current will be roughly Qg/T = 14mA. For this you don't need a specialized gate drive IC.

*

*If you have 5V available, you can use a 74HCT logic gate as voltage translator between your 3V3 micro and a 5V "logic level" MOSFET. It's cheap and it'll work.

*If you only have 3V3 available and no 5V, and you don't want to bother with a separate 5V supply, then it makes sense to use a FET that is compatible with 3V3 drive. Depending on the gate drive current required, and the output drive capability of your micro, you might want to add a logic gate as a buffer too. 74LVC for example.


text:
Q: How to convert DER formatted public key file to PEM form I need to use the PEM formatted public key for some purpose, but not finding the command which can convert DER formatted public key to PEM formatted public key.
The command I have used -
openssl rsa -in user_id_rsa.pub -inform DER -outform PEM -out pubkey.pem
Actually the command expect private key as a input.
But I got the below error -

unable to load Private Key 139901900170912:error:0D0680A8:asn1
  encoding routines:ASN1_CHECK_TLEN:wrong tag:tasn_dec.c:1337:
  139901900170912:error:0D08303A:asn1 encoding
  routines:ASN1_TEMPLATE_NOEXP_D2I:nested asn1 error:tasn_dec.c:677:
  139901900170912:error:0D0680A8:asn1 encoding
  routines:ASN1_CHECK_TLEN:wrong tag:tasn_dec.c:1337:
  139901900170912:error:0D07803A:asn1 encoding
  routines:ASN1_ITEM_EX_D2I:nested asn1 error:tasn_dec.c:388:Type=RSA

My expected output should be in this format-

-----BEGIN RSA PUBLIC KEY-----
KEY CONTENT
  -----END RSA PUBLIC KEY-----

Has anyone tried the same?

A: You should add -pubin for public key inputs.
openssl rsa -pubin -in user_id_rsa.pub -inform DER -outform PEM -out pubkey.pem

EDIT: To handle PEM RSA PUBLIC KEY format, specify -RSAPublicKey_in -RSAPublicKey_out instead.
openssl rsa -RSAPublicKey_in -in user_id_rsa.pub -inform DER -outform PEM -out pubkey.pem -RSAPublicKey_out

If you want to convert OpenSSH public key to PEM RSA PUBLIC KEY, just use ssh-keygen.
ssh-keygen -f user_id_rsa.pub -e -m PEM > pubkey.pem


text:
Q: Git bare repo - /refs/head/master deleted - How to get last commit id? I have a bare repository.
For unknown reasons the /refs/head/master file got deleted.
Because I don't know the id of the latest commit, I wonder how can I recover it so that I can recreate the master file (holding the id).

A: Use git reflog to find where your HEAD has been.
Note the hash of the appropriate commit and do git branch master <hash>


text:
Q: Google Analytics - Track subdomain AND no subdomain? (xyz.domain.com & domain.com) When I added the filters to Google Analytics (https://support.google.com/analytics/answer/7476333) to show the full hostname with the subdomain, no traffic was showing up when testing it out on just the primary domain (without www).
What's the proper way to set up filters so that it tracks subdomains and domains without a subdomain?

A: There is only one filter listed on the linked page. It is a commonly used filter and does not exclude data. It simply prepends the hostname to the requestURI in the GA reports.
If you are trying to track a subdomain of the primary domain and the primary domain, having tracking for the same Property on both with the cookieDomain set to auto (which it is by default)and the filter applied should be all that is needed.
If you are trying to track a primary domain and subdomains of a different domain, then if you are are trying to preserve referral and session data across the two, then you will need tracking for the same Property on the primary and subdomains, configured for cross domain tracking setup as per the article and the filter applied.
One weird issue I have come across (and it happens really randomly without rhyme or reason), is a view not reporting data, until the Save button on the view settings page has been clicked.
Usually the three most common issues i see are:
1) Tracking for the same property as the primary domain not being installed on the subdomain(s)
2) Tracking for multiple Properties being installed, setup with incorrect configuration for multiple trackers.. which can cause all hits from all trackers to get sent to just one Property instead of all Properties
3) Incorrect filters applied or incorrect filter order. Filters run in the order they are applied/added to a view. The order of the filters, needs to be set in the Filter table for the particular view.
Example of incorrect filters -
a View with a hostname filter to include only the Primary domain hostname, that also has the above filter applied, will not show any data for the subdomain(s) only the primary domain.


text:
Q: Unclear passage of a theorem concerning compact operators (Schauder fixed point theorem) I'm looking at this proof of Schauder theorem  and I am struggling with a passage. This is my problem:
Let  $X$ be a Banach space, $K \subset X$ a convex, close and bounded set and $F:K \rightarrow K$ a compact operator.
$F$ compact and $K$ bounded imply that   $ \:\overline{F(K)} \subset K$ is a compact set. So, fixed $\epsilon >0, $there exist $\{v_1,...,v_{n_\epsilon}\}$ such that $F(K) \subset\overline{F(K)} \subset \bigcup_{i=1}^{n_\epsilon}B(v_i, \epsilon)$.
I call $E_\epsilon$ the vector space generated by $v_1,...,v_{n_\epsilon}$ and for $u\in F(K)$ I consider
$G_\epsilon(u)=\sum_{k=1}^{n_\epsilon} \lambda_i(u) v_i$ with $\lambda_i\in (0,1)$ and such that $ \sum_{k=1}^{n_\epsilon} \lambda_i(u) =1 $ for every $u$.
Clearly $G_\epsilon\in E_\epsilon$ and then  I have that $G_\epsilon(u)\in M:= co(v_1,...,v_n)$ (the convex hull of $ \{ v_1,...,v_n \} $).
$\textbf{The claim is this}$: if $u\in F(u)$ then $G_\epsilon(u) \in E_\epsilon \cap K$.
In order to prove that it is said: $G_\epsilon(u) \in E_\epsilon \cup F(K) \subset E_\epsilon \cup K$.
$\textbf{My problem:}$ The thing that I don't understand is why $G_\epsilon \in F(K)$.
I would have concluded in this way:  $G\epsilon\in M$, which is the smallest convex set containg the elements $v_i\in K$. Since $K$ is convex I have directly that $G_\epsilon(u)\in M\subset K$.
  Is it correct?
Many thanks for the help.

A: I think we can argue as follows.
Let's fix $\epsilon > 0.$ Since $\overline{F(K)}$ is compact, there is a finite set
$$
W_\epsilon := \{w_1,\ldots,w_{n_\epsilon}\} \subseteq \overline{F(K)}
$$
such that
$$
\overline{F(K)} \subseteq \bigcup_{j=1}^{n_\epsilon}B(w_j,\frac{\epsilon}{2}).
$$
Moreover, for a fixed index $j\in\{1,\ldots,n_\epsilon\},$ since $w_j\in\overline{F(K)},$ there is a $v_j\in F(K)$ such that
$$
\|v_j - w_j\| < \frac{\epsilon}{2}.
$$
This implies
$$
B(w_j,\frac{\epsilon}{2}) \subseteq B(v_j,\epsilon).
$$
Thus, we have the finite set
$$
V_\epsilon := \{v_1,\ldots,v_{n_\epsilon}\} \subseteq F(K)
$$
with
$$
\overline{F(K)} \subseteq \bigcup_{j=1}^{n_\epsilon}B(w_j,\frac{\epsilon}{2}) \subseteq \bigcup_{j=1}^{n_\epsilon}B(v_j,\epsilon).
$$
If we use this particular set $V_\epsilon,$ we can further argue that
$$
G_\epsilon(u) = \sum_{j=1}^{n_\epsilon} \lambda_j(u)v_j
$$
is a convex combination of elements of $F(K),$ and since $F(K)$ is convex (since $K$ is convex, and $F$ is linear), we must have
$$
G_\epsilon(u)\in F(K),
$$
as desired.


text:
Q: Lock application orientation to landscape and sensor only I understand how to lock the application into landscape mode using android:screenOrientation= "lanscape" but how can I lock it to use both landscape and sensor orientations, which allows me to switch between the landscape views and skip out the portrait views. I found somewhere there is an option for sensorLandscape orientation mode but don't know how to set this in the manifest.

A: Unfortunately, sensorLandscape is a newly added manifest option only available for Android 2.3. Link here. Perhaps you could add android:configChanges="orientation" to your activity, and in your onConfigurationChanged method, handle the changes only if you're at a 90 or 270 degree orientation?


text:
Q: boxfuse app can't connect to RDS database I am using boxfuse to deploy a dropwizard (0.9.1) app on AWS.
I was able to deploy the dev version and my app is working as expected when using the VirtualBox environment.
I am now trying to deply it to AWS without much success.  Everything is going as expected until what's below.
Do I need to put anything special in my boxfuse.yml file?
I'm using the one I used when deploying to the VirtualBox environment.
Do I need to create anything prior in my AWS account?
Any ideas what I could be doing wrong?  I searched around and couldn't find much of anything to try?
i-e482a13c => DEBUG [2016-04-17 02:06:42,949] org.hibernate.boot.registry.selector.internal.StrategySelectorImpl: Registering named strategy selector [org.hibernate.dialect.Dialect] : [MySQL5InnoDB] -> [org.hibernate.dialect.MySQL5InnoDBDialect] (replacing [org.hibernate.dialect.MySQL5InnoDBDialect])
i-e482a13c => DEBUG [2016-04-17 02:06:43,021] org.hibernate.service.spi.ServiceBinding: Overriding existing service binding [org.hibernate.secure.spi.JaccService]
i-e482a13c => DEBUG [2016-04-17 02:06:43,021] org.hibernate.cfg.Configuration: Preparing to build session factory with filters : {}
i-e482a13c => ERROR [2016-04-17 02:06:44,067] org.apache.tomcat.jdbc.pool.ConnectionPool: Unable to create initial connections of pool.
i-e482a13c => ! sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
i-e482a13c => ! at sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:141) ~[na:1.8.0-8u74]
i-e482a13c => ! at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:126) ~[na:1.8.0-8u74]
i-e482a13c => ! at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:280) ~[na:1.8.0-8u74]
i-e482a13c => ! at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:382) ~[na:1.8.0-8u74]
i-e482a13c => ! ... 57 common frames omitted
i-e482a13c => ! Causing: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
i-e482a13c => ! at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:387) ~[na:1.8.0-8u74]
i-e482a13c => ! at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292) ~[na:1.8.0-8u74]
i-e482a13c => ! at sun.security.validator.Validator.validate(Validator.java:260) ~[na:1.8.0-8u74]
i-e482a13c => ! at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:324) ~[na:1.8.0-8u74]
i-e482a13c => ! at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:229) ~[na:1.8.0-8u74]
i-e482a13c => ! at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:124) ~[na:1.8.0-8u74]
i-e482a13c => ! at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1491) ~[na:1.8.0-8u74]
i-e482a13c => ! ... 51 common frames omitted
i-e482a13c => ! Causing: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
i-e482a13c => ! at sun.security.ssl.Alerts.getSSLException(Alerts.java:192) ~[na:1.8.0-8u74]
i-e482a13c => ! at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1949) ~[na:1.8.0-8u74]
i-e482a13c => ! at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:302) ~[na:1.8.0-8u74]
i-e482a13c => ! at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:296) ~[na:1.8.0-8u74]
i-e482a13c => ! at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1509) ~[na:1.8.0-8u74]
i-e482a13c => ! at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:216) ~[na:1.8.0-8u74]
i-e482a13c => ! at sun.security.ssl.Handshaker.processLoop(Handshaker.java:979) ~[na:1.8.0-8u74]
i-e482a13c => ! at sun.security.ssl.Handshaker.process_record(Handshaker.java:914) ~[na:1.8.0-8u74]
i-e482a13c => ! at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1062) ~[na:1.8.0-8u74]
i-e482a13c => ! at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1375) ~[na:1.8.0-8u74]
i-e482a13c => ! at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1403) ~[na:1.8.0-8u74]
i-e482a13c => ! at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1387) ~[na:1.8.0-8u74]
i-e482a13c => ! at com.mysql.jdbc.ExportControlled.transformSocketToSSLSocket(ExportControlled.java:149) ~[payload.jar:na]
i-e482a13c => ! ... 43 common frames omitted
i-e482a13c => ! Causing: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
i-e482a13c => !
i-e482a13c => ! The last packet successfully received from the server was 634 milliseconds ago.  The last packet sent successfully to the server was 631 milliseconds ago.
i-e482a13c => ! at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0-8u74]
i-e482a13c => ! at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:1.8.0-8u74]
i-e482a13c => ! at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.8.0-8u74]
i-e482a13c => ! at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[na:1.8.0-8u74]
i-e482a13c => ! at com.mysql.jdbc.Util.handleNewInstance(Util.java:404) ~[payload.jar:na]
i-e482a13c => ! at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:981) ~[payload.jar:na]
i-e482a13c => ! at com.mysql.jdbc.ExportControlled.transformSocketToSSLSocket(ExportControlled.java:164) ~[payload.jar:na]
i-e482a13c => ! at com.mysql.jdbc.MysqlIO.negotiateSSLConnection(MysqlIO.java:4801) ~[payload.jar:na]
i-e482a13c => ! at com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(MysqlIO.java:1643) ~[payload.jar:na]
i-e482a13c => ! at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1215) ~[payload.jar:na]
i-e482a13c => ! at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2255) ~[payload.jar:na]
i-e482a13c => ! at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2286) ~[payload.jar:na]
i-e482a13c => ! at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2085) ~[payload.jar:na]
i-e482a13c => ! at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:795) ~[payload.jar:na]
i-e482a13c => ! at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:44) ~[payload.jar:na]
i-e482a13c => ! at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0-8u74]
i-e482a13c => ! at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:1.8.0-8u74]
i-e482a13c => ! at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.8.0-8u74]
i-e482a13c => ! at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[na:1.8.0-8u74]
i-e482a13c => ! at com.mysql.jdbc.Util.handleNewInstance(Util.java:404) ~[payload.jar:na]
i-e482a13c => ! at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:400) ~[payload.jar:na]
i-e482a13c => ! at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:327) ~[payload.jar:na]
i-e482a13c => ! at org.apache.tomcat.jdbc.pool.PooledConnection.connectUsingDriver(PooledConnection.java:307) ~[payload.jar:na]
i-e482a13c => ! at org.apache.tomcat.jdbc.pool.PooledConnection.connect(PooledConnection.java:200) ~[payload.jar:na]
i-e482a13c => ! at org.apache.tomcat.jdbc.pool.ConnectionPool.createConnection(ConnectionPool.java:708) [payload.jar:na]
i-e482a13c => ! at org.apache.tomcat.jdbc.pool.ConnectionPool.borrowConnection(ConnectionPool.java:642) [payload.jar:na]
i-e482a13c => ! at org.apache.tomcat.jdbc.pool.ConnectionPool.init(ConnectionPool.java:464) [payload.jar:na]
i-e482a13c => ! at org.apache.tomcat.jdbc.pool.ConnectionPool.<init>(ConnectionPool.java:141) [payload.jar:na]
i-e482a13c => ! at org.apache.tomcat.jdbc.pool.DataSourceProxy.pCreatePool(DataSourceProxy.java:115) [payload.jar:na]
i-e482a13c => ! at org.apache.tomcat.jdbc.pool.DataSourceProxy.createPool(DataSourceProxy.java:102) [payload.jar:na]
i-e482a13c => ! at org.apache.tomcat.jdbc.pool.DataSourceProxy.getConnection(DataSourceProxy.java:126) [payload.jar:na]
i-e482a13c => ! at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:139) [payload.jar:na]
i-e482a13c => ! at org.hibernate.engine.jdbc.internal.JdbcServicesImpl$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcServicesImpl.java:279) [payload.jar:na]
i-e482a13c => ! at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:124) [payload.jar:na]
i-e482a13c => ! at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:111) [payload.jar:na]
i-e482a13c => ! at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:234) [payload.jar:na]
i-e482a13c => ! at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:206) [payload.jar:na]
i-e482a13c => ! at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1887) [payload.jar:na]
i-e482a13c => ! at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1845) [payload.jar:na]
i-e482a13c => ! at io.dropwizard.hibernate.SessionFactoryFactory.buildSessionFactory(SessionFactoryFactory.java:96) [payload.jar:na]
i-e482a13c => ! at io.dropwizard.hibernate.SessionFactoryFactory.build(SessionFactoryFactory.java:49) [payload.jar:na]
i-e482a13c => ! at io.dropwizard.hibernate.SessionFactoryFactory.build(SessionFactoryFactory.java:39) [payload.jar:na]
i-e482a13c => ! at io.dropwizard.hibernate.HibernateBundle.run(HibernateBundle.java:56) [payload.jar:na]
i-e482a13c => ! at io.dropwizard.hibernate.HibernateBundle.run(HibernateBundle.java:14) [payload.jar:na]
i-e482a13c => ! at io.dropwizard.setup.Bootstrap.run(Bootstrap.java:199) [payload.jar:na]
i-e482a13c => ! at io.dropwizard.cli.EnvironmentCommand.run(EnvironmentCommand.java:39) [payload.jar:na]
i-e482a13c => ! at io.dropwizard.cli.ConfiguredCommand.run(ConfiguredCommand.java:77) [payload.jar:na]
i-e482a13c => ! at io.dropwizard.cli.Cli.run(Cli.java:70) [payload.jar:na]
i-e482a13c => ! at io.dropwizard.Application.run(Application.java:80) [payload.jar:na]
i-e482a13c => ! at com.vertware.dms.DMSService.main(DMSService.java:65) [payload.jar:na]
i-e482a13c => WARN  [2016-04-17 02:06:44,078] org.hibernate.engine.jdbc.internal.JdbcServicesImpl: HHH000342: Could not obtain connection to query metadata : Communications link failure
i-e482a13c =>
i-e482a13c => The last packet successfully received from the server was 634 milliseconds ago.  The last packet sent successfully to the server was 631 milliseconds ago.
i-e482a13c => INFO  [2016-04-17 02:06:44,088] org.hibernate.dialect.Dialect: HHH000400: Using dialect: org.hibernate.dialect.MySQLInnoDBDialect
i-e482a13c => INFO  [2016-04-17 02:06:44,104] org.hibernate.engine.jdbc.internal.LobCreatorBuilder: HHH000422: Disabling contextual LOB creation as connection was null

A: The error message indicates an SSL certificate error. The default Boxfuse root certificates keystore does however include the RDS root certificate. Did you by any chance ship your own cacerts file which does not include that root certificate?


text:
Q: Java socks 4 proxy issue I've setup java to use SOCK4 by utilizing reflection call java.net.SocksSocketImpl#setV4.  My connection works fine with Socks5 but with Socks 4 i'm getting a number of Socket Exceptions.   For example:
java.net.SocketException: Malformed reply from SOCKS server
    at java.net.SocksSocketImpl.readSocksReply(Unknown Source)
    at java.net.SocksSocketImpl.connectV4(Unknown Source)
    at java.net.SocksSocketImpl.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)

Any ideas?


text:
Q: Module not found error in Anaconda terminal Can somebody please explain why this is happening?
(base) C:\Users\Harry\Desktop>pip show numpy
Name: numpy
Version: 1.17.4
Summary: NumPy is the fundamental package for array computing with Python.
Home-page: https://www.numpy.org
Author: Travis E. Oliphant et al.
Author-email: None
License: BSD
Location: c:\users\harry\anaconda3\lib\site-packages
Requires:
Required-by: tensorflow-hub, tensorflow-gpu, tensorboard, tables, statsmodels, seaborn, scikit-learn, resampy, PyWavelets, pytest-arraydiff, pyclustering, patsy, pandas, opt-einsum, numexpr, numba, mkl-random, mkl-fft, matplotlib, librosa, langid, Keras, Keras-Preprocessing, Keras-Applications, imageio, h5py, Bottleneck, bokeh, bkcharts, audiosegment, astropy

(base) C:\Users\Harry\Desktop>script.py
Traceback (most recent call last):
  File "C:\Users\Harry\Desktop\script.py", line 1, in <module>
    import numpy as np
ModuleNotFoundError: No module named 'numpy'

numpy is installed as you can see, but python can't import it. Why is this?


text:
Q: Incremental progress on nested stored procedure (Postgres) I have three Postgres stored procedures that are being ran sequentially (i.e. SP1 will call SP2 which then calls SP3). while proc'ing these nested stored procedures I noticed that I do not see the results from SP1 only until the last stored procedure has completed (SP3).
Is there a way to have the results of these procedures be produced at the time of execution rather than waiting for all of them to be complete?
Thanks!
Some code for reference:
create or replace procedure sp1()
as $$

declare

begin

    drop table if exists seq_test;
    create table seq_test (
        step        varchar,
        status      varchar,
        time_log    timestamp not null default now()
    );

    insert into seq_test values ('1','running','now');
    raise notice 'step 1 beginning';

    -- does something

    insert into seq_test values ('1','complete','now');
    raise notice 'step 1 complete';

    call sp2();

end;
$$
language plpgsql;

--------------

create or replace procedure sp2()
as $$

declare

begin

    insert into seq_test values ('2','running','now');
    raise notice 'step 2 beginning';

    -- does something else

    insert into seq_test values ('2','complete','now');
    raise notice 'step 2 complete';

    call sp3();

end;
$$
language plpgsql;

--------------

create or replace procedure sp3()
as $$

declare

begin

    insert into seq_test values ('3','running','now');
    raise notice 'step 3 beginning';

    -- does something else

    insert into seq_test values ('3','complete','now');
    raise notice 'step 3 complete';

end;
$$
language plpgsql;

--------------------------------------------------

call sp1();

In the above script, if hypothetically each SP takes 1 minute to complete, despite records being inserted into seq_test throughout the entire 3 minute runtime I wont actually be able to observe these records until every SP has completed.

A: You don't see the results, because data modifications only become visible when the transaction that made them has ended. This is guaranteed by the default READ COMMITTED transaction isolation level, and there is no way in PostgreSQL to get "dirty reads".
By default, CALL sp1() will run in a single transaction, which explains what you observe.
You can change that behavior by explicitly calling COMMIT AND CHAIN inside your stored procedures. That will commit the work up to this point and start a new transaction. But consider the consequences: if execution encounters an error, the transaction will be rolled back (undone). A COMMIT in the middle of your procedure can then result in only part of the work being done. This may be exactly what you need, but often it is undesirable.


text:
Q: Path for Paperclip missing.png using paperclip's default/standard configuration, a model without an image will result in having a path http://localhost:3000/avatars/thumb/missing.png
I am using paperclip with S3, and I would like to use a missing.png from my storage.
Is there a way to set the path for the missing.png via s3?
I am aware of the :default_url but it doesnt seem to work with the s3 information that other images use

A: 'default_url' is the  url to use when an image is nil.
One other scenario would be that url for your attachment exists but it just doesn't exists at the location or s3, in that case the Frontend tries to find the file but returns the error as unable to find the file.
So the solution here could be you replace all your missing url file with some asset file via javascript like this : jQuery/JavaScript to replace broken images


text:
Q: Can a scala self-type be satisfied via delegation? Suppose I have (and this is rather contrived)
trait DbConnection {
  val dbName: String
  val dbHost: String
}

class Query {
  self: DbConnection =>

  def doQuery(sql: String) {
    // connect using dbName, dbHost
    // perform query
  }
}

class HasADbConnection(override val dbName: String,
                       override val dbHost: String) extends DbConnection {
  self =>

  def doSomething() {
    doSomethingElseFirst()
  }

  def doSomethingElseFirst() = {
    val query = new Query() with DbConnection {
      override val dbName = self.dbName
      override val dbHost = self.dbHost
    }
    query.doQuery("")
  }
}

Is there a way to avoid the redundant "override val dbName = self.dbName, override val dbHost = self.dbHost" in the new Query() creation, and instead indicate that the new Query object should inherit from / delegate to the HasADbConnection instance for these fields?
I realize it may be more appropriate for Query to take a DbConnection as a constructor argument.  I'm interested though in other ways of satisfying the Query self-type.  Perhaps there is no way of propagating the HasADbconnection fields onto the new Query instance, which is a completely valid answer.

A: Not sure exactly what you are trying to do, but this seems like a possible match to your intent:
trait C extends B {
    def myA = new A() with C {  // Note that this could be "with B" rather than "with C" and it would still work.
        val name: String = C.this.name // explicit type not actually required - String type can be inferred.
    }
}

then, for example:
scala> val myC = new C() { val name = "myC-name" }
myC: C = $anon$1@7f830771

scala> val anA = myC.myA
anA: A with C = C$$anon$1@249c38d5

scala> val aName = anA.name
aName: String = myC-name

Hopefully that can at least help guide your eventual solution. Might be able to give further help if you clarify what you want to do (or why you want to do it) further.
EDIT - after update to question:
I suggest you may be thinking about this the wrong way. I would not like tying the Query class down to knowing how to forge a connection. Rather, either pass a ready-made connection as a parameter to your call that uses the connection, or (as shown below) set up the Query class to supply a function from a connection to a result, then call that function using a connection established elsewhere.
Here is a how I would think about solving this (note that this example doesn't create an actual DB connection per se, I just take your DbConnection type at face value - really you have actually defined a 'DbConnConfig' type):
trait DbConnection {
  val dbName: String
  val dbHost: String
}

class Query(sql: String) {
  def doQuery: DbConnection => String = { conn: DbConnection =>
    // No need here to know how to: connect using dbName, dbHost
    // perform query, using provided connection:
    s"${conn.dbName}-${sql}-${conn.dbHost}" // <- Dummy implementation only here, so you can, for example, try it out in the REPL.
  }
}

class HasADbConnection(override val dbName: String,
                       override val dbHost: String) extends DbConnection {

  // You can create your actual connection here...
  val conn = makeConnection

  def doSomething(query: Query) = {
    // ... or here, according to your program's needs.
    val conn = makeConnection
    query.doQuery(conn)
  }

  def makeConnection = this // Not a real implementation, just a quick cheat for this example.
}

In reality, doQuery (which could be named better) should have a type of DbConnection => ResultSet or similar. Example usage:
scala> val hasConn = new HasADbConnection("myDb", "myHost")
hasConn: HasADbConnection = HasADbConnection@6c1e5d2f

scala> hasConn.doSomething(new Query("@"))
res2: String = myDb-@-myHost


text:
Q: how to reset servlet data after a session end? Suppose I have the following snippet of code:
    public class ApplyOfferCalculation extends HttpServlet {

        private RequestDispatcher rd;
        static int totaldiscount = 0;
        StringBuilder totalofferids = new StringBuilder();
        Map map = new HashMap();
        static int count = 0;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
}
}

Now i want to reset the class level variables after a session end.
How to do it?

A: Let the servlet container do its job, and do not try to store state in a Servlet. Using non-final static variables is highly discouragable.
If you need variables at the session level, then use the session for it, but keep the servlet free from stateful behaviour, as they are by definition stateless.


text:
Q: Deleting a common number from an integer list in swi prolog I use swi-prolog. How can you delete a common number from an integer list? for example, if the list is X=[11,12,13,14,15] and i need to delete 10 from it, so the list will become X=[1,2,3,4,5].
Help required.Thanks.

A: You can try
substract(N, L1, L2) :-
    maplist(sub(N), L1, L2).

sub(N, V1, V2) :-
    V2 is V1 - N.


text:
Q: multiple public classes in java I was trying to write a Java program with more than 1 public class and it gave me the following error:
Class [classname] is public,should be declared in a separate file named
[classname].java

Can't seem to find a convincing answer as to why this is happening.

A: You can not declare more than one public class in one .java file. Separate your classes to different .java files.
Class1.java
public class Class1 {

}

Class2.java
public class Class2 {

}

This restriction implies that there must be at most one such type per
  compilation unit. This restriction makes it easy for a compiler for
  the Java programming language or an implementation of the Java virtual
  machine to find a named class within a package; for example, the
  source code for a public type wet.sprocket.Toad would be found in a
  file Toad.java in the directory wet/sprocket, and the corresponding
  object code would be found in the file Toad.class in the same
  directory.

Similar questions:

*

*Why only 1 public class in Java file

*source file can't have more than one public class

A: Every public class must be declared in it's own .java source file.

A: The class name is the same as the file name. If you have more than one class in a file, it creates a conflict which causes errors. So each class should be in a separate file with the file name same as the class name.


text:
Q: Problems with vmstart after upgrade from vwmare fusion 4 to 5 After upgrading from vmware fusion 4 to 5 i get an errormessage when starting my VMs

"This virtual machine appears to be in use"
  if this virutal machine is not in use, press Take Ownership ....

Was there any layout change in the .vmx file or what is causing the problem ?

A: Just delete any files with the .lck extension.  You should be able to start your machine after that.


text:
Q: Restrict all restful routes without repeating for each resource declaration I am working on a Rails API (Rails 4.2.0.beta4), and in turn since the client will be responsible for generating the new and edit forms, my RESTful controllers will only need 5 actions. Rather than having to do something like this:
resources :media, except: [:new, :edit]
resources :media_collections, except: [:new, :edit]
etc...

Is there some way I could define all of my resources inside a block that has except: [:new, :edit] stated in one spot or something? Seems crazy to have to append that to ever resource declaration, right?

A: You can create a method that abstracts this. I would create a new module for this, and use extend to make the methods available in routes.rb
module ApiResource
  def api_resources(name, options = {}, &block)
    resources name, options.merge({:except => [:new, :edit]}, &block)
  end
end

# in routes.rb:

MyApp::Application.routes.draw do
  extend ApiResource

  api_resources :media
  api_resources :media_collections

  # ...

end


text:
Q: Postgresql json-generation from dynamic SQL Is there any way of using the json-functions, such as json_agg when you're using dynamic SQL?
The documentation leads to think that ref cursors should be used when returning multiple rows. But then iterating over ref cursors appear to involve fetch/loop etc or is there a way of doing some sort of json_agg from (select * from my_ref_cursor)?
Of course there is the option of ref cursor + loop + concating json rows one at a time but that doesn't sound very effective.
Thanks in advance,
  Nik


text:
Q: Connect Four game - understanding how array keeps always the same length I'm a self learner, please bear with me.
So I'm following this tutorial on how to code a connect4 game and there's two things I'm definitely not getting
1 - every time I click on a cell I call the changeColor() and push to an empty array that specific cell. I dont get how the array always keeps only one cell.. it always has same length. Shouldn't it be adding each cell I click on to the array?
2 - in the stylesheet I defined that every cell would have the background color of white and when applying a if/ else condition as "if the cell is white then do something" the person in the tutorial defined in the js file once again that each cell has to have the background color of white in order for this condition to work
This does not make much sense to me because if its already defined in the stylesheet why does it not work unless I define it again in the js file?
Any help is much appreciated :)
codepen : https://codepen.io/mullerz/pen/WNremXo?editors=1111
tableCell.forEach(el => {
    el.addEventListener("click", changeColor);

    el.style.backgroundColor = 'white'
})

function changeColor(e){
    let column = e.target.cellIndex;
    let row = [];
    for(let i = tableRow.length-1 ; i > -1; i--){

        if (tableRow[i].children[column].style.backgroundColor == 'white'){
          row.push(tableRow[i].children[column])

          console.log(row)

            if (currentPlayer === 1){
                row[0].style.backgroundColor = 'red';
                playerTurn.style.color = player1Color;
                return currentPlayer = 2;
            }
            else{
                row[0].style.backgroundColor = 'yellow';
                playerTurn.style.color = player2Color;
                return currentPlayer = 1;
            }
        }

    }

}

A: *

*Variables in JavaScript are scoped. You are defining let row = [] every time the functions is called thats why the array is always empty at the start.
If you would move the variable declaration outside the function block it would not be redeclared everytime the function is run.

*Because of if (tableRow[i].children[column].style.backgroundColor == 'white')
It seems to me the background color is used to check if the field was not selected before. But this is a bad practice and shouldnt be done.

A: Starting with 2.
A cell has the class slot, which sets the background colour to white, but the element itself also has a style object as a property, but this object has nothing set.
When rendering the style, the browser does so from broadest to narrowest (then !important things). Style classes are broader than style applied directly to an element. For example if you have this css:
.notred
{
  color: black;
}

And this element:

this text would be red

The element's text will be red, despite the class saying it should be black.
Your code is using a check on the element's style property to make sure the cell is empty, so it has to set the style property otherwise the value is an empty string. In fact, you could change the code so that it checks for an empty string in the property rather than setting each background.
Back to 1:
The row is in fact a column. The code looks at each row in the table, checking the column number for the cell that was clicked. If the background colour of the cell in that row & column is white then it's added to the row array. This way the last cell that's added to row is the first available cell in that column.
The row variable is redeclared each time the function is called, so it is empty each time the function is called. When a function is called all variables that are declared in it are set back to their initial values. Beware global variables, because that doesn't happen with them.
If you fill up a column with red and yellow, then click on the column again, you should get an index out of range error, because the row will be empty.


text:
Q: Tested VueJS file problems I have this simple file and using http-server it does not work. Please help. NOTE that I have a proper  of the HTML page .
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <title>VueTester</title>

{{ message }}

A: Ok if i understand you right, you just have a simple HTML-file and want to use vue in it.
In this case you just have to reorganize your code like this and it should work:

{{ message }}

If i missunderstood you just tell me and I try to edit it.


text:
Q: Zuul path - SpringBoot detects it although not configured I followed the sample from the Spring Cloud docu and have now configured in my application.yml
server:
  port: 18081
  servlet:
    context-path: /myPath/services
zuul:
  # don't add per default all services automatically to the Zuul server
  ignoredServices: '*'
  routes:
    mytest:
      #path: /checkPath/**
      url: http://mytest.server.local/api/

and a configured Filter:
public class PreFilter extends ZuulFilter {

  @Override
  public String filterType() {
    return "pre";
  }

  @Override
  public int filterOrder() {
    return 1;
  }

  @Override
  public boolean shouldFilter() {
    return true;
  }

  @Override
  public Object run() {
    RequestContext ctx = RequestContext.getCurrentContext();
    HttpServletRequest request = ctx.getRequest();

    System.out.println("Request Method : " + request.getMethod() + " Request URL : " + request.getRequestURL().toString());
    return null;
  }
}

When I test with
http://localhost:18081/myPath/services/mytest/test

I would expect that this works only if path is configured. If I leave it as above (uncommented) I get from ZuulPreFilter that it was hit. I wouldn't expect it since the path shouldn't be found. Is there a misunderstanding or do I miss something in my config? Why is the path hit at all because .../checkPath2/... won't be detected?


text:
Q: How to loop a function through columns in a data frame and add to new columns I'll create some test data:
import numpy as np
import pandas as pd
test_df = pd.DataFrame(np.random.randn(10,4), columns=['a','b','c','d'])

The function I'm trying to pass over the column variables is:
def standard(x):
    return (x - x.mean()) / x.std()

What I then want to do is run the function standard over each of the column variables using a for loop and add new columns to the data frame with the standardised data.
However, aside from making simple for loops I've not really done anything like this before. So any pointers would be much appreciated.

A: you can apply your function to every column like this:
std_df = test_df.apply(standard,axis = 1)]

You can concatinate this to your original frame like this:
big_df = pd.concat([ test_df, std_df], axis = 1)

To simplify you can run both of these together:
test_df = pd.concat([ test_df, test_df.apply(standard,axis = 1)], axis = 1)

A: you can do it like this:
for column in test_df:
    print(standard(test_df[column]))

A: In case you want to use one line, here does applying the function on original/source dataframe, then lambda function will do the trick(by passing an anonymous function as an argument to apply()):
test_df.apply(lambda x: (x - x.mean()) / x.std(), axis =1)

Out:

           a         b            c          d
0     -0.381437   0.090135    -1.038400   1.329702
1     -0.722698   0.902806    0.817258    -0.997366
2     -0.521621   1.375428    -0.912505   0.058698
3     0.161679    0.900105    0.363529    -1.425313
4     -0.605061   0.527289    -1.045744   1.123515
5     -1.271155   0.481572    -0.253487   1.043071
6     -0.473747   -0.471403   -0.553750   1.498901
7     0.161580    1.335381    -0.935835   -0.561127
8     1.355149    -0.372754   0.029416    -1.011811
9     -1.065852   1.253947    0.276011    -0.464105

For the : "How to loop a function through columns in a dataframe and add to new columns" you can use pandas.DataFrame.join to join the source dataframe test_dfwith the new columns standardized form columns that will have the new name :

test_df.join(test_df.apply(lambda x: (x - x.mean()) / x.std(), axis =1), rsuffix='_std')

          a          b            c          d           a_std       b_std        c_std      d_std
0     -0.142156   0.239129    -0.673335   1.241366    -0.381437   0.090135    -1.038400   1.329702
1     -0.726785   0.668620    0.595182    -0.962573   -0.722698   0.902806    0.817258    -0.997366
2     -1.212991   0.384315    -1.542113   -0.724365   -0.521621   1.375428    -0.912505   0.058698
3     0.366151    0.897416    0.511373    -0.775619   0.161679    0.900105    0.363529    -1.425313
4     -0.248543   0.830104    -0.668326   1.398053    -0.605061   0.527289    -1.045744   1.123515
5     -1.001275   0.695089    -0.016333   1.238530    -1.271155   0.481572    -0.253487   1.043071
6     -0.850323   -0.848182   -0.923375   0.950963    -0.473747   -0.471403   -0.553750   1.498901
7     0.337371    0.688291    0.009287    0.121310    0.161580    1.335381    -0.935835   -0.561127
8     1.976673    -0.953941   -0.271841   -2.037817   1.355149    -0.372754   0.029416    -1.011811
9     -1.795365   0.058748    -0.722873   -1.314415   -1.065852   1.253947    0.276011    -0.464105

pandas.Series.apply
pandas.DataFrame.apply


text:
Q: Minimum one element from the array exist in another array I would like to check if minumum one element from an array exists in another array. Here is the SQL code for reference:
CREATE TEMP FUNCTION is_array_in_array(subset ARRAY<string>, main ARRAY<string>)
AS ((SELECT min(a in UNNEST(main)) FROM UNNEST(subset) as a));

What would be the best implementation in PySpark?

A: You can check whether the arrays overlap (docs):
import pyspark.sql.functions as F

df2 = df.withColumn('is_array_in_array', F.arrays_overlap('subset_col', 'main_col'))


text:
Q: Getting data to show in ListView DataTemplate This is probably something simple I'm missing, but I have a ListView with an ItemTemplate and DataTemplate:
                         <ListView Name="IngredientsListBox">
                            <ListView.ItemTemplate>
                                <DataTemplate>
                                    <TextBlock Text="{Binding IngredientName}" />
                                </DataTemplate>
                            </ListView.ItemTemplate>
                        </ListView>

and data passed to it in the code behind:
protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        base.OnNavigatedTo(e);

        var selectedRecipe = e.Parameter as Recipe;
        if (selectedRecipe != null)
        {

            _ingredientViewModel = new IngredientViewModel(selectedRecipe);
            IngredientsListBox.DataContext = _ingredientViewModel.Ingredients;
        }
    }

When I run the code, _ingredientViewModel.Ingredients shows the three ingredients passed to it from the data source, but they're not displaying on the XAML page. Any thoughts?

A: Ignore my original answer if you read it. The ItemsSource isn't being set anywhere. Instead of setting IngredientsListBox.DataContext, set IngredientsListBox.ItemsSource


text:
Q: Showing error while importing Sceneform Assets I get this error While import Sceneform asset. I've added the
dependencies {
    classpath 'com.google.ar.sceneform:plugin:1.15.0
}

in the Project level gradle file this also
dependencies {
implementation "com.google.ar.sceneform.ux:sceneform-ux:1.15.0"
}

I searched alot but getting this error

A: You should import the models manually using this format in the project gradle
  apply plugin: 'com.google.ar.sceneform.plugin'

sceneform.asset('sampledata/models/andy.obj', // 'Source Asset Path' specified during import.
        'default',                            // 'Material Path' specified during import.
        'sampledata/models/andy.sfa',         // '.sfa Output Path' specified during import.
        'src/main/res/raw/andy')              // '.sfb Output Path' specified during import.

As shown here: https://developers.google.com/sceneform/develop/import-assets


text:
Q: How to see if element is in my list I am trying to find out if there is an way to see how many of an object (count) from one list is in another list.
I have a class Card.
class Card(object):
    def __init__(self, number):
        self.number = number

    def __eq__(self, other):
        return self.number == other.number

    def getNumber(self, card):
        return card.number

I have a class Deck which contains a list of Cards.
class Deck(object):
    def __init__(self):
        self.cards = []
        for i in range(11):
            for j in range(i):
                self.cards.append(Card(i))

I want to see if a I can get the count of a Card in the Deck.
deck = Deck()
The deck contains 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 6 6 6 6 6 6 7 7 7 7 7 7 7 8 8 8 8 8 8 8 8 9 9 9 9 9 9 9 9 9 10 10 10 10 10 10 10 10 10 10

cards = [Card(6), Card(5), Card(3)]
The cards are 6 5 3

I want to know how many 6's, 5's and 3's there are in the deck.

A: To tally an individual card, use list.count():
for card in cards:
    print(deck.cards.count(card))

To tally them all, use collections.Counter():
>>> from collections import Counter
>>> Counter(deck.cards)
Counter({Card(10): 10, Card(9): 9, Card(8): 8, Card(7): 7,
         Card(6): 6, Card(5): 5, Card(4): 4, Card(3): 3,
         Card(2): 2, Card(1): 1})

For the counter to work, you'll need to make minor modifications to your Card class by adding __hash__() and __repr__() methods:
class Card(object):
    def __init__(self, number):
        self.number = number

    def __eq__(self, other):
        return self.number == other.number

    def __hash__(self):
        return hash(self.number)

    def getNumber(self, card):
        return card.number

    def __repr__(self):
        return 'Card(%r)' % self.number

A: You can try:
print "Count for 6's: ", ListName.count(6)

Similarly for 5 and 3:
print "Count for 5's: ", ListName.count(5)
print "Count for 3's: ", ListName.count(3)

A: I think you can try in this way
>>> from collections import Counter
>>> deck1
['1', '2', '2', '3', '3', '3', '4', '4', '4', '4', '5', '5', '5', '5', '5',
'6', '6', '6', '6', '6', '6', '7', '7', '7', '7', '7', '7', '7', '8', '8',
'8', '8', '8', '8', '8', '8', '9', '9', '9', '9', '9', '9', '9', '9', '9',
'10', '10', '10', '10', '10', '10', '10', '10', '10', '10']
>>> Counter(deck1)
Counter({'10': 10, '9': 9, '8': 8, '7': 7, '6': 6, '5': 5, '4': 4, '3': 3,
'2': 2, '1': 1})