text:
Q: Change units of time dimension in NetCDF file from months to months since I currently have multiple NetCDF files with 4 dimensions, (latitude, longitude, time, and depth). Each represents a single year of monthly data. The unit of time is "month", 1-12, and therefore quite useless if I want to merge these files across years to give me a single NetCDF file with a time dimension of size months*years.
The time dimension attributes for a single file:
time  Size:12   *** is unlimited ***
            long_nime: time
            units: month

I used ncrcat of nco to merge.
ncrcat soda3.3.1*sst.nc -O soda3.3.1_1980_2015_sst.nc

This works except that when merged, time values read
#in R
soda.info$var$temp$dim[[3]]$vals
  [1]  1  2  3  4  5  6  7  8  9 10 11 12  1  2  3  4  5  6  7  8  9 10 11 12  1
 [26]  2  3  4  5  6  7  8  9 10 11 12  1  2  3  4  5  6  7  8  9 10 11 12  1  2
 [51]  3  4  5  6  7  8  9 10 11 12  1  2  3  4  5  6  7  8  9 10 11 12  1  2  3
 [76]  4  5  6  7  8  9 10 11 12  1  2  3  4  5  6  7  8  9 10 11 12  1  2  3  4
[101]  5  6  7  8  9 10 11 12  1  2  3  4  5  6  7  8  9 10 11 12  1  2  3  4  5
[126]  6  7  8  9 10 11 12  1  2  3  4  5  6  7  8  9 10 11 12  1  2  3  4  5  6
[151]  7  8  9 10 11 12  1  2  3  4  5  6  7  8  9 10 11 12  1  2  3  4  5  6  7
[176]  8  9 10 11 12  1  2  3  4  5  6  7  8  9 10 11 12  1  2  3  4  5  6  7  8
[201]  9 10 11 12  1  2  3  4  5  6  7  8  9 10 11 12  1  2  3  4  5  6  7  8  9
[226] 10 11 12  1  2  3  4  5  6  7  8  9 10 11 12  1  2  3  4  5  6  7  8  9 10
[251] 11 12  1  2  3  4  5  6  7  8  9 10 11 12  1  2  3  4  5  6  7  8  9 10 11
[276] 12  1  2  3  4  5  6  7  8  9 10 11 12  1  2  3  4  5  6  7  8  9 10 11 12
[301]  1  2  3  4  5  6  7  8  9 10 11 12  1  2  3  4  5  6  7  8  9 10 11 12  1
[326]  2  3  4  5  6  7  8  9 10 11 12  1  2  3  4  5  6  7  8  9 10 11 12  1  2
[351]  3  4  5  6  7  8  9 10 11 12  1  2  3  4  5  6  7  8  9 10 11 12  1  2  3
[376]  4  5  6  7  8  9 10 11 12  1  2  3  4  5  6  7  8  9 10 11 12  1  2  3  4
[401]  5  6  7  8  9 10 11 12  1  2  3  4  5  6  7  8  9 10 11 12  1  2  3  4  5
[426]  6  7  8  9 10 11 12

...which obviously isn't much help if I want to keep track of time.
In the past I've only used NetCDF files with a "months since..." unit. Is there a way to change these rather groundless 'month' units to 'months since...'?

A: Would it suffice to enumerate the months sequentially?
ncap2 -s 'time=array(0,1,$time)' soda3.3.1_1980_2015_sst.nc out.nc

You can also add a "months since ..." unit to time as described in the comment by Chelmy and/or in the NCO manual. I leave that as an exercise for you, gentle reader.


text:
Q: Solving the matrix in Quadratic sieve I am trying to implement the quadratic sieve and I don't understand how to solve the matrix at the end. I will show you what I did and where I got stuck.
So I am trying to factor $149 * 103 = 15347$
I picked B smooth $11$, so my vector primes are $2,3,5,7,11$(I know that I was supposed to actually thieve and pick those $2,17,13,23$ values, but I don't understand this part so I asked a separate question about that here, anyway it's irrelevant to what I am asking now).
Now I started to search for B smooth numbers that satisfy
$a^2 \equiv b^2$
I started from $a = \left\lfloor\sqrt{1534}\right\rfloor = 40$ and the first values I found are

*

*$a = 178^2$, $b = 990  = 2^1 3^2 5^1 7^0 11^1$

*$a = 182^2$, $b = 2430 = 2^1 3^5 5^1 7^0 11^0$

*$a = 219^2$, $b = 1920 = 2^7 3^1 5^1 7^0 11^0$

*$a = 221^2$, $b = 2800 = 2^4 3^0 5^2 7^1 11^0$

First I converted it to vectors and I only care about odd or even powers, so I made it binary.
$\begin{bmatrix}
1& 0& 1& 0& 1\\
1& 1& 1& 0& 0\\
1& 1& 1& 0& 0\\
0& 0& 0& 1& 0
\end{bmatrix}$
Since I want to know what subset equals to {0,0,0,0} I rotate it.
$\begin{bmatrix}
1& 1& 1& 0\\
0& 1& 1& 0\\
1& 1& 1& 0\\
0& 0& 0& 1\\
1& 0& 0& 0
\end{bmatrix}$
Next I calculate the Echelon form.
$\begin{bmatrix}
1& 1& 1& 0\\
0& 1& 1& 0\\
0& 0& 0& 1\\
0& 0& 0& 0\\
0& 0& 0& 0
\end{bmatrix}$
And now I am stuck, how can I understand from my last result if there is such subset and if there is how do I know what it is? If you can please give me a general explanation and also show me how it works with my example.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Connection pool sqlalchemy always return a cached result I use the following code to create connection pooling and run SQL query.
engine = sqlalchemy.create_engine(
                f'mysql+pymysql://{usr}:{pw}@{db_config["host"]}:{db_config["port"]}/'
                f'{sub_db}', pool_size=24, max_overflow=40, poolclass=pool.QueuePool)
connection = engine.connect()
pandas.read_sql(sql=my_query, con=connection)

However, I found that connection I created sometime returns a cached DB return:
E.g. I run SQL function validatePW to validate tokens based on a DB table.  I have two users: A and B with different passwords.  User A's password is 'PW1'.
If I run pandas.read_sql(sql="select validatePW('A', 'PW1')", con=connection), I got a True return which is as expected.  and if I first run pandas.read_sql(sql="select validatePW('B', 'PW1')", con=connection), I will get a False return (B's password is not 'PW1').
Now if I run these two queries sequentially, the results will become funny
pd.read_sql(sql="select validatePW('A', 'PW1')", con=connection)
pd.read_sql(sql="select validatePW('B', 'PW1')", con=connection)

I will get two True return, although I am expecting the second query would return a False.  It seems like connection is returning a cached result from the previous run.  Why is that?  Is there anyway to avoid it? Thanks


text:
Q: Visualization of citation network I am new to mathematica, I want to visualize the citation network using some data, could anyone suggest me which function should I use to visualize the citation network like the following.

A: Please take a look into the following Wolfram Research data resources that have citation network examples:

*

*"High Energy Physics Theory Network"

*"High Energy Physics Phenomenology Network"


text:
Q: Comparing ALAssetGroupType in switch statement Hi I am calling ALAssetsLibrary's
-enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:block failureBlock:failure;

then inside the enumeration block i want to compare the type of group returned and add it to the relevant array. I have tried
^( ALAssetsGroup *group, BOOL *stop )
{
    NSLog(@"Group %@", group );
    ALAssetGroupType assetType = (ALAssetGroupType)[group valueForProperty:ALAssetsGroupPropertyType];
    NSLog( @"Asset type %@", assetType );
    switch( assetType )
    {
        case ALAssetsGroupAplbum :
        NSLog( @"Found ALBUM" );
        [albums addObject:group];
        break;
    }
}

The Initial log traces out "Group ALAssetsGroup - Name:Photo Library, Type:Album, Assets count:177"
The next log is "Asset type 2"
but the third log never get's called.
Any ideas what i am doing wrong?

A: valueForProperty: returns an object. In the case of ALAssetsGroupPropertyType it returns an ALAssetGroupType constant wrapped in an NSNumber. (See docs here.)
So by casting to ALAssetGroupType you're using the object's memory address as your switch value. You need to get the underlying integer value of the NSNumber using intValue:
ALAssetGroupType assetType =
 [[group valueForProperty:ALAssetsGroupPropertyType] intValue];


text:
Q: Find a point on a known line, a set distance from a point on the line as well as off the line I have three points. $P_1(x_1,y_1)$ and $P_2(x_2,y_2)$ and $P_3(x_3,y_3)$ and I am looking for $P_4(x_4,y_4)$.
$P_1$ and $P_2$ are on the same line as $P_4$. I have a known distance along the line which I will call $D_1$. $P_4$ is a distance of $D_1 * T$ away from $P_1$ along this line.
$P_3$ is on the same line as $P_4$, but not the same line as $P_1$ and $P_2$. I have a known distance along this line which is $D_2$. $P_4$ is a distance of $D_2 * T$ away from $P_3$ along this unknown line.
$T$ is an unknown multiplier that is the same for both $D_1$ and $D_2$ to reach $P_4$.
$D_1$ is also known as a direction vector where $D_2$ is only known as a distance.
If someone is able to help me find $P_4$, it would be greatly appreciated.
Clarification
P1, P2 and P4 are all on a straight line, as in if you draw a line from P1 to P4, it will also pass through P2.
P3 and P4 also form a straight line where P4 is D2 * T away from P4.
D1 is a distance which is also known as a direction vector because it is along the straight line which includes P1, P2 and P4. As in P2 - P1 is a direction vector D1 and Pythagorean theorem lets us find the distance of said vector. I was just trying to give available information for whichever would be most useful.
Example
This is what I have tried, although it is basic and only works when the distance from P3 to P4 is equal to the distance from P3 to P1. Also of note, D1 is used in its vector form.
P4 = P1 + D1 * |P1-P3| / D2
And this works perfectly when |P1-P3| = |P4-P3| but that only covers a very small range of possible scenarios.
Picture!

Thanks for looking!

A: I am happy that there is actually a unique solution.
The way I am imagining this is that we have two objects initially --- the vector $\mathbf{P_1P_2}$ and the circle with centre $P_3$ and radius $d_1$ and they are both sitting in the plane, $\Pi$.
Now what happens is we continuously enlarge both the vector and circle in a linear way. Depending on the situation we can start at an enlargement factor of $T=1$ and enlarge or start at $T=1$ and shrink.
So you have a vector $\mathbf{v}(T)$ and a circle $\mathcal{C}(T)$.
Now there are a few different cases that need to be teased out... I am going to assume that $d_2<|\mathbf{d_1}|$.
The 'top' of vector $\mathbf{v}(t)$ sits at $\mathbf{P_1}+T\,\mathbf{P_1P_2}$. At some point in their simultaneous enlargement the 'top' of the vector will lie on the circle and the distance from this to the centre will equal the radius of the circle $Td_2$:
$$\sqrt{(Tx_2+(1-T)x_1-x_3)^2+(Ty_2+(1-T)y_1-y_3)^2}=Td_2.$$
Squaring both sides gives a quadratic in $T$.
There will be two solutions $T_1$ and $T_2$. One of them, say $T_1$, will be negative and will come from
$$\begin{align}
\text{distance from }\mathbf{v}(T_1)\text{ to }P_3\text{ is }T_1d_2,
\end{align}$$
which has no solutions but we will get an extraneous solution when we square the right hand side.


text:
Q: Why is rendering this SVG map crashing my browser? I'm trying to make a drought map with D3 (and topojson), using this shapefile.
I've converted it to both GeoJSON and topojson, but in either case, trying to render causes the browser to hang and CPU for that tab to hit 100% or higher.
I can render larger files, like all US counties, and I can render the file using Mapnik or TileMill. But in the browser, it dies.
Here's the relevant code.
var map = d3.select('#map').append('svg')
    .style('width', width)
    .style('height', height);

var albers = d3.geo.albersUsa();

var path = d3.geo.path()
    .projection(albers);

d3.json(urls.drought, function(err, data) {

    var drought = window.drought = topojson.feature(data, data.objects.usdm130521);

    map.selectAll('path')
        .data(drought.features)
      .enter().append('path')
        .attr('d', path);
});

A: Figured this out. As the USDM site says, "The files have been projected to the USA Contiguous Albers Equal Area Conic projection."
It turns out, this is a problem, though I don't fully understand it. I converted it to EPSG: 4326 using ogr2ogr:
$ ogr2ogr -t_srs EPSG:4326 usdm130521-projected.shp usdm130521.shp

And it rendered. Quick, too.
Mike Bostock wrote more about projecting topojson here.


text:
Q: Size of generic structure I need to find out a size of a generic structure (I can not do it like sizeof(T) or using Marshal.SizeOf(...) 0> gives me an error)
So I wrote:
public static class HelperMethods
{
    static HelperMethods()
    {
        SizeOfType = createSizeOfFunc();
    }

    public static int SizeOf<T>()
    {
        return SizeOfType(typeof(T));
    }

    public static readonly Func<Type, int> SizeOfType = null;

    private static Func<Type, int> createSizeOfFunc()
    {
        var dm = new DynamicMethod("SizeOfType", typeof(int), new Type[] { typeof(Type) });

        ILGenerator il = dm.GetILGenerator();
        il.Emit(OpCodes.Ldarg_0);
        il.Emit(OpCodes.Sizeof); //needs to be il.Emit(OpCodes.Sizeof, typeof(something))
        il.Emit(OpCodes.Ret);

        var func = (Func<Type, int>)dm.CreateDelegate(typeof(Func<Type, int>));
        return func;
    }
}

A diffuclty is that il.Emit(OpCodes.Sizeof) needs an argument which I can not pass it during the method (SizeOfType) creation. How can I pass a parameter which is on stack to il.Emit(OpCodes.Sizeof) using IL ? (or a different solution but I want to cache a function (delegate) not a result what is proposed in the 2nd answer)

A: Computing size is something that is fraught with problems because you need to know what is meaningful in the context you are using it. I'd assume there is a good reason for Marshal.SizeOf to throw when the argument is a generic struct, but I don't know what it is.
With that caveat, this code seems to work and gives similar results to Marshal.SizeOf for non-generic structs. It generates a new dynamic method that gets the size via the sizeof IL opcode for the type. It then caches the result (since generating a dynamic method is some what expensive) for future use.
public class A { int x,y,z; }
public struct B { int x,y,z,w,a,b; }
public struct C<T> { Guid g; T b,c,d,e,f; }

public class Program
{
    public static void Main(string[] args)
    {
        Console.WriteLine(IntPtr.Size); // on x86 == 4
        Console.WriteLine(SizeHelper.SizeOf(typeof(C<double>))); // prints 56 on x86
        Console.WriteLine(SizeHelper.SizeOf(typeof(C<int>))); // prints 36 on x86
    }
}

static class SizeHelper
{
    private static Dictionary<Type, int> sizes = new Dictionary<Type, int>();

    public static int SizeOf(Type type)
    {
        int size;
        if (sizes.TryGetValue(type, out size))
        {
            return size;
        }

        size = SizeOfType(type);
        sizes.Add(type, size);
        return size;
    }

    private static int SizeOfType(Type type)
    {
        var dm = new DynamicMethod("SizeOfType", typeof(int), new Type[] { });
        ILGenerator il = dm.GetILGenerator();
        il.Emit(OpCodes.Sizeof, type);
        il.Emit(OpCodes.Ret);
        return (int)dm.Invoke(null, null);
    }
}

Edit
As far as I can tell there is no way to make non-generic delegate that you can cache. The SizeOf opcode requires a metadata token. It does not take a value from the evaluation stack.
Actually the code below works as well. I'm not sure why Marshal.SizeOf(Type) throws an argument exception when the type is generic structure but Marshal.SizeOf(Object) does not.
    public static int SizeOf<T>() where T : struct
    {
        return Marshal.SizeOf(default(T));
    }

A: It would appear that your aim is to resolve the argument Type from your functions return type Func<Type, int> at compile time. This information is not known at compile time and there is no apparent way to resolve this information using reflection at runtime.
I do not see what benefit returning the the dynamic method serves instead of invoking the dynamic method and returning the result immediately. Given that you have not given any context I would propose the obvious solution, return the value immediately. If your concerns lie with performance then simply cache the results in a dictionary.
public static class GlobalExtensions
{

    public static int SizeOf<T>()
    {
        return SizeOf(typeof (T));
    }

    public static int SizeOf(this Type type)
    {
        var dynamicMethod = new DynamicMethod("SizeOf", typeof(int), Type.EmptyTypes);
        var generator = dynamicMethod.GetILGenerator();

        generator.Emit(OpCodes.Sizeof, type);
        generator.Emit(OpCodes.Ret);

        var function = (Func<int>) dynamicMethod.CreateDelegate(typeof(Func<int>));
        return function();
    }
}

Using an extension method leverages some nice syntax. You can now proceed to obtain the size of a generic structure or class using the following code:
var size = TypeExtensions.SizeOf<Example<int>>();

//alternative syntax...
size = typeof (Example<int>).SizeOf();

A: Now there is possibility for the unmanaged types in unsafe context to do this, if that is sufficient.
    private unsafe int MySizeOf<T>() where T : unmanaged
    {
        return sizeof(T);
    }

A: Taking the above thinking one step further, I arrived at:
public static class TypeSize<T>
{
    public readonly static int Size;

    static TypeSize()
    {
        var dm = new DynamicMethod("SizeOfType", typeof(int), new Type[] { });
        ILGenerator il = dm.GetILGenerator();
        il.Emit(OpCodes.Sizeof, typeof(T));
        il.Emit(OpCodes.Ret);
        Size = (int)dm.Invoke(null, null);
    }
}

...which I believe is the most efficient solution to the problem.


text:
Q: How to generate patterns by a list of integers I have a list of integers {3,4,2,2}.
This list will give patterns {x_,_,y_,y_,_,_,z_,z_,w_,w_,x_} and {0,0,0,1,1,1,1,0,0,1,1}.
Notice that I want to assign successive 0,1 with the same symbol.
How to make this?
*edit
Compare the patterns
{x_,_,y_,y_,_,_,z_,z_,w_,w_,x_}
{0, 0, 0,1, 1,1, 1,0,  0,1, 1 }
{1, _, 2,2, _,_, 3,3,  4,4, 1 }

Suppose I have symbols {x_,y_,z_,w_} (you may use {a_,b_,c_,d_,...}).
To transform lst={3,4,2,2} to {x_,_,y_,y_,_,_,z_,z_,w_,w_,x_},
begin with {x_,_,_,_,_,_,_,_,_,_,_}.
Then put y_ at positions lst[[1]] and lst[[1]]+1.
Then put z_ at positions lst[[1]]+lst[[2]] and lst[[1]]+lst[[2]]+1.
Then put w_ at positions lst[[1]]+lst[[2]]+lst[[3]] and lst[[1]]+lst[[2]]+lst[[3]]+1.
And finally put x_ at the last position.

A: Like others I cannot follow the {x_,_,y_,y_,_,_,z_,z_,w_,w_,x_} part but for the integer sequence this problem is related to: How to apply or map a list of functions to a list of data?
Any of those solutions should be adaptable but for this particular application I like TomD's method the best.  It is both concise and very fast.
f[pat : {__Integer}, rep_List] /; Min[pat] > 0 :=
  Join @@ ConstantArray @@@ Partition[Riffle[pat, rep, {1, -1, 2}], 2]

f[{3, 4, 2, 2}, {0, 1}]

{0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1}

Here is one that is a bit shorter and faster still:
f2[p : {__Integer}, r_List] /; Min[p] > 0 :=
  Inner[ConstantArray, PadRight[r, Length @ p, r], p, Join]

f2[{3, 4, 2, 2}, {0, 1}]

{0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1}

In response to your updated question you could use this:
lst = {3, 4, 2, 2};

ReplacePart[
 ConstantArray[_, Tr@lst],
 Prepend[
  {{#}, {# + 1}} -> (Pattern[#, _] &@Unique[]) & /@ Accumulate@lst,
  {{1}, {-1}} -> x_
 ]
]

{x_, _, $1_, $1_, _, _, $2_, $2_, $3_, $3_, x_}

This generates as many Unique symbols as required to fill out the list.
I still think this is distinct from the integer sequence result and should be split to a separate question.  I also echo m_goldberg's question: "How do you intend to use the pattern?" as there may be another approach.

A: One part of the question is easy -- constructing a sequence of ones and zeros according to a pattern given by a control list of integers:
binaryPattern[controlList : {_Integer ..}] :=
   Flatten@MapIndexed[
      If[EvenQ @@ #2, ConstantArray[1, #1], ConstantArray[0, #1]] &, controlList]

binaryPattern[{3, 4, 2, 2}]

{0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1}

binaryPattern[{1, 2, 3, 4}]

{0, 1, 1, 0, 0, 0, 1, 1, 1, 1}

About the other part, I haven't a clue of what the OP has in mind.
Edit
Slightly modifying the function Mr. Wizard defined in his comment to this answer, I present a function that produces sequences of digits from any base from two to ten. I confess I can think of no use case for this extended version.
nAryPattern[controlList : {__Integer}, base_Integer: 2] /; 11 > base > 1 :=
   Join @@ MapIndexed[ConstantArray[Mod[#2[[1]] - 1, base], #] & controlList]

Table[nAryPattern[Range[5], base], {base, 2, 5}]

{
{0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0},
{0, 1, 1, 2, 2, 2, 0, 0, 0, 0, 1, 1, 1, 1, 1},
{0, 1, 1, 2, 2, 2, 3, 3, 3, 3, 0, 0, 0, 0, 0},
{0, 1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4}
}


text:
Q: Node.js/Express - Render error when page not found I have the following controller/route definition in Node.js (using Express and Mongoose). What would be the leanest most appropriate way to handle Error when the user requests a page that does not exist?
  app.get('/page/:pagetitle', function(req, res) {
      Page.findOne({ title: req.params.pagetitle}, function(error, page) {
          res.render('pages/page_show.ejs',
            { locals: {
                title: 'ClrTouch | ' + page.title,
                page:page
            }
          });
      });
  });

It currently breaks my app. I believe because I'm not doing anything with the error i'm just passing it to the view like a success?
TypeError: Cannot read property 'title' of null

Thanks much.

A: Check out the express error-pages example. The principle is to register your app routes first, then you register a catch all 404 handler for all other requests that do not map to a route. Finally, a 500 handler is registered, as follows:
// "app.router" positions our routes
// specifically above the middleware
// assigned below

app.use(app.router);

// Since this is the last non-error-handling
// middleware use()d, we assume 404, as nothing else
// responded.

app.use(function(req, res, next){
  // the status option, or res.statusCode = 404
  // are equivalent, however with the option we
  // get the "status" local available as well
  res.render('404', { status: 404, url: req.url });
});

// error-handling middleware, take the same form
// as regular middleware, however they require an
// arity of 4, aka the signature (err, req, res, next).
// when connect has an error, it will invoke ONLY error-handling
// middleware.

// If we were to next() here any remaining non-error-handling
// middleware would then be executed, or if we next(err) to
// continue passing the error, only error-handling middleware
// would remain being executed, however here
// we simply respond with an error page.

app.use(function(err, req, res, next){
  // we may use properties of the error object
  // here and next(err) appropriately, or if
  // we possibly recovered from the error, simply next().
  res.render('500', {
      status: err.status || 500
    , error: err
  });
});

A: One of the major problems with Node.JS is that there is no clean error catching. The conventional way is usually for every callback function, the first argument is the not null if there is an error, so for example:
function( error, page ){
   if( error != null ){
       showErrorPage( error, req, res );
       return;
   }
   ...Page exists...
}

Things can get ugly after a while with too many callbacks, and I recommend using something like async, so that if there is one error, it goes directly to an error callback.
EDIT: You can also use express error handling.


text:
Q: Getting ID3 tags from Streaming URL I am trying to make a Stream Music player application that you can play the mp3s from your dropbox account on stream. But DropboxAPI doesnt give you ID3 information as metadata . So i need to find a way to get the ID3 informations like artist and song name so i can list the files on the screen.
I tried MediaMetadataRetriever class , but it always gave Illegel argument exception for URI, and i tried also different URLs from different websites ,still result is the same.
So can you suggest an alternative way to get the ID3 tags of a Mp3 file from a stream URL.
Thank you in advance for your help


text:
Q: Creating private function inside directive Is it possible to create a private function inside a directive? I need to do a rather complex process inside a directive to fill the directive's template.
Something like this (HTML):
<textarea the-result="data">
</textarea>

Javascript:
angular
.module("MyModule")
.directive("theResult", [function () {
    return {
        scope: {
            theResult: "="
            // calculatestuff = function(d){ // ... } can't put it here (error)
        },
        template: ' ... '
            + '{{calculatestuff(theResult.someproperties)}}'
            + ' ... '
    }
}])

Where can I put calculatestuff?

A: Notice that directive(directiveName, directiveFunction) uses only what directiveFunction returns. You can do whatever you want inside this function, like, for instance, define other function :
angular
.module("MyModule")
.directive("theResult", [function () {
    var calculateStuff = function (d) {
        // ...
    };

    return {
        // ...
    }
}]);

But of course, calculateStuff won't exist anymore during the $digest cycles and is not link to the scope, so you won't be able to call it inside your template. If this is really what you want to do, contemplate to put your function in the scope, during the linking phase :
angular
.module("MyModule")
.directive("theResult", [function () {
    return {
        scope: {
            theResult: "="
        },
        template: ' ... '
            + '{{calculatestuff(theResult.someproperties)}}'
            + ' ... ',
        link : function ($scope) {
            $scope.calculateStuff = function (d) {
                // ...
            };
        }
    }
}]);

Since you use an isolated scope, this function won't be accesible from outside the directive.


text:
Q: How do i remove labels from MS Charts Pie chart? the following image shows labels on a pie chart
Image of my PIE chart
As you can see the legend labels are on the pie chart and chart is not clear.

*

*How do I remove those label from the pie chart surface but not from the chart screen?

*How do I make the pies chart bigger in this case bigger diameter?

*As I change the size of pie chart, is it possible to change the size of all the other charts?
thanks

A: Youc can do like this
ChartPie.Series[i]["PieLabelStyle"] = "Disabled";

A: I'm not sure if I understand your fist question, do you mean you want to remove label form chart surface but still display the legend? If that so you could set Points.Label to be empty string and set Points.LegendText to be the label text.
Such the sample code below (You could adapt it to be fit your code, if it needed.):
chart1.Series[0].Points[0].Label = "";
chart1.Series[0].Points[0].LegendText = "2012";

chart1.Series[0].Points[1].Label = "";
chart1.Series[0].Points[1].LegendText = "2013";

Where my chart1 has only one series (Series[0]) with two piece of pie (Points[0] and Points[1])
The size of pie will be changed following the size of Chart, so if you want it to be bigger, then you have to set the size of chart.
Size size = new System.Drawing.Size(800, 600);
chart1.Size = size;

This will be the same for other chart types.


text:
Q: Prestashop _PS_MODE_DEV_ and WebService I am in a particular situation.
I use the prestashop webservice with a cron to update my prestashop database and synchronize with my management software.
The problem is that i have to set  _PS_MODE_DEV_ to OFF for many reasons, and in particular for some errors that prestashop fix setting _PS_MODE_DEV_ to OFF.
For example a checkout error:
http://www.prestashop.com/forums/topic/344514-solved-unable-to-save-account-parsererror-one-page-checkout/page-2
BUT if a set _PS_MODE_DEV_ to OFF, my WebService stop working.
How can i solve it ?
Thanks.

A: I end up on a dirty solution found on https://www.e-connecteur.fr/content/comment-afficher-les-erreurs-du-webservice-prestashop (French).
The solution consists in turning _PS_DEV_MODE_ on only for the api by detecting the request url, and replacing a line in defines.inc.php
if (_PS_MODE_DEV_ === true OR substr($_SERVER['REQUEST_URI'], 0, 4) == '/api')


text:
Q: close one specific GNOME Terminal command I run a loop like this (duration one hour):
#!/bin/bash
gnome-terminal --geometry=50x30 --working-directory=/$HOME/TEST --title terminal1 -e  ' sh -c "./FirstAPP; exec bash"'
while true; do
    if [ ! pgrep SecondAPP ]; then
        gnome-terminal --geometry=50x30 --working-directory=/$HOME/TEST --title terminal2 -e  ' sh -c "./SecondAPP; exec bash"'
        for ((i=0; i<3600; i+=5)); do
            sleep 5
            if [ ! pgrep SecondAPP ]; then
                break
            fi
        done
        killall -9 SecondAPP > /dev/null 2>&1
    # Iwant here a command that closes the gnome-terminal "terminal2"
    fi
    sleep 5
done

I run this loop and I noticed that in the terminal2 the process got killed but the terminal stays open. Is there a flag or something to close that terminal2?
Or is my implementation wrong?
PS. I am a newbie in Ubuntu, I looked up closing specific terminal, however I dont think it apllies to my case.

A: You are killing the program SeondApp, but you are not killing the terminal it is running in. The two are separate things. For example, this is the process tree of running gedit in a terminal:
$ gedit &
[1] 13064
$ pstree -s 13064
systemd───systemd───gnome-terminal-───bash───gedit───4*[{gedit}]

Ignore the systemd, that's the init process, everything running on your machine is a child of systemd. Then, what you see there is that gnome-terminal    has launched bash which then runs gedit. If you now kill gedit, that won't affect its parents. However, if you kill one of the parents, that will also kill the child.
Normally, what you would do is to use $!, a special variable that holds the PID of the last process launched to the background. Unfortunately, that doesn't with gnome-terminal which seems to have some sort of complicated launching procedure:
$ gnome-terminal &
[1] 23861
$ ps aux | grep 23861
terdon   24341  0.0  0.0   8684  2348 pts/11   S+   10:59   0:00 grep --color 23861
$ pgrep gnome-terminal
23866

As you can see above, gnome-terminal seem to re-launch itself after launching and uses a different PID. No idea why, but another good reason to use a different terminal.
So, since the standard approach won't work, we need a workaround. What you can do is use kill -$PID which will kil all processes in the process group (from man kill):
-n  where n is larger than 1.  All processes in process  group  n  are
    signaled.   When  an argument of the form '-n' is given, and it is
    meant to denote a process group, either a signal must be specified
    first,  or  the argument must be preceded by a '--' option, other‐
    wise it will be taken as the signal to send.

Putting all this together, here's a working version of your script:
#!/bin/bash
gnome-terminal --geometry=50x30 --working-directory=/$HOME/TEST --title terminal1 \
               -e  ' sh -c "./FirstAPP; exec bash"'
while true; do
    if ! pgrep SecondAPP; then
        gnome-terminal --geometry=50x30 --working-directory=/$HOME/TEST \
            --title terminal2 -e  'SecondAPP' &
        for ((i=0; i<3600; i+=5)); do
          sleep 5
          if ! pgrep SecondAPP; then
            break
          fi
        done
        ## Now, get the PID of SecondAPP
        pid=$(pgrep SecondAPP)
        ## Using -$pid will kill all process in the process group of $pid, so
        ## it will kill SecondAPP and its parent process, the terminal.
        kill -- -$pid
    fi
    sleep 5
done

Note that I also remove the [ ] around ! pgrep since that was wrong syntax.

I don't see why you are launching terminals at all though. Here's the same idea, without terminals:
#!/bin/bash

$HOME/TEST/FirstAPP
while true; do
    if ! pgrep SecondAPP; then
      #$HOME/TEST/SecondAPP &
      SecondAPP &
      pid=$!
        for ((i=0; i<3600; i+=5)); do
          sleep 5
          if ! pgrep SecondAPP; then
            break
          fi
        done
        kill $pid
    fi
    sleep 5
done

Finally, this feels like a strange way of doing things. You might want to ask a new question, explain what you are trying to do and why and we can see if we can find a simpler approach for whatever it is you need.


text:
Q: How is this JAX-RS webservice working? I'm going over few pieces of code and came across something like this
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces({ MediaType.APPLICATION_JSON , MediaType.APPLICATION_XML })
public Response getMedia(
        @HeaderParam("X-META") String metaToken,
        @QueryParam("provider") String provider, MultivaluedMap<String, String> formContext ,
        @Context UriInfo uriInfo) {
    Map<String, String> context = APIUtils.buildContext(formContext);
    return getMediaInternal(metaToken, provider, context, uriInfo);
}

I know that Annotated vars are injected by jersey but I'm clueless as how the formContext is being injected. It's not annotated. What all values are put in here by jersey ? All the post parameters ? Whats a general rule to deduce whats being populated when not annotated ? Any pointers to reference material or a brief description of whats happening here is helpful

A: According to the Jersey User Guide, it seems like jersey will inject the MultiValuedMap<> type on a @POST request because form parameters are part of the message entity. This is the example:
Example 3.13. Obtaining general map of form parameters

@POST
@Consumes("application/x-www-form-urlencoded")
public void post(MultivaluedMap<String, String> formParams) {
    // Store the message
}


text:
Q: No of pairs of elements whose XOR satisfies a condition We are given a set of $n$ non-negative integers. We need to find the number of pairs of integers from this set whose $XOR$ is $ = K$.
My approach is to sort the integers which takes $O(NlogN)$. Then for each element $a_i$ find $a_i\oplus K$. Make a binary search for the result. If it exists increment the counter. This can be done in a total of $O(NlogN)$.
Now, I want to extend the question to find number of such pairs whose $XOR$ is $\le K$. Obviously, an algorithm better than $O(N^2)$ is needed.

A: Let's make the problem a little more general and have two sets of input numbers $A$ and $B$, and ask for the number of pairs $(a,b)\in A\times B$ such that $a \oplus b \le K$.
If $K=0$ then the answer is just $|A\cap B|$. Otherwise let $K=2^p+Q$ with $Q<2^p$. (This is just finding the most significant set bit in $K$).
Then partition both $A$ and $B$ into subsets according to the quotient $\lfloor a/2^p \rfloor$ for each number $a$. Whenever there's both a subset $A_i$ and a subset $B_i$ with the same quotient, that gives us $|A_i|\times|B_i|$ pairs that xor to something less than $K$ -- indeed, less than $2^p$.
On the other hand, we can also pair up the partitions such that the subset of $A$ corresponding to the quotient $x$ is matched up to the subset of $B$ corresponding to the quotient $x\oplus 1$. When we xor numbers from two such subsets together we get something between $2^p$ and $2^{p+1}$, which will be $\le K$ if the xor of the remainders is $\le Q$. Count the numbers of relevant pairs between the two partitions recursively.
If we start by setting $A=B=$ the input set, this algorithm gives the number of ordered pairs that xor to something $\le K$. We can get the number of unordered pairs instead by noting $(a,a)$ is a qualifying pair for every input number $a$ -- and these $n$ pairs are counted exactly once, whereas everything else was counted exactly twice. So to get the number of unordered pairs, add $n$ and divide by two at the very end. (Or subtract $n$ if you don't want to count $a\oplus a$ as "pairs" at all).

Time complexity. If we sort the set of input numbers once and for all at the beginning, the order will be preserved each time we take remainders for a recursive invocation of the algorithm, so the partitioning in each step takes linear time. Each of the $n$ input numbers ends up in at most one recursive call for each $p$, and there are at most $\log K$ levels in the recursion, so the total time complexity in $O(n\log n + n\log K)$.
It feels like it should be possible to prove that this running time is actually linear in the size of the the input in bits (rather than the number of input numbers), but the details of how to dispose of the $\log K$ factor are a bit murky if $K$ is larger than most but not all of the input numbers. Perhaps it isn't true.


text:
Q: What is this inside an erb template [Rails] I'm seeing code like this inside of an erb template:
<% hook :admin_footer_scripts do -%>

What exactly is hook? is it a standard method within ActionView?

A: It's probably a helper method defined in your application. Look in app/helpers/application.rb or in the app/helpers/ directory for a ruby file named like the controller which renders that view

A: Just from what it looks like I'd say it's a way to allow the controller to add code the the page. But bgj is right. Look in your helper files.


text:
Q: Saving Image via Web Service to SQL and Retrieving It

I have created a Web Service that is intended to receive an image from a 3rd party, which will then gets imported into a SQL table.After that, I retrieve the image and save it to a directory from an Azure Database at my end.
Everything works and I receive no errors, except when I retrieve the image into a 'test' picturebox, I get a 'Red X' for the image which signify's an error with the image.
Is anyone able to look at my code and see what I am doing wrong? This is the first time for me doing this kind of stuff.
Web Service:
Public Function Wunelli_SendImage(ByVal PolicyRef As String, ByVal ImagePath As String) Implements FreshCloud.Wunelli_SendImage
    Using cn As New SqlConnection(sqlConn)
        'SqlConnection.ClearAllPools()
        Using cmd As New SqlCommand("INSERT INTO [dbo].[Autosaint_Wunelli_Engineer_Images] VALUES(@policyref,GETDATE(),@photo)", cn)
            Try
                With cmd
                    .Parameters.AddWithValue("@policyref", "LYJX01PC01")

                    Using MS As New MemoryStream(), BM As New Bitmap(ImagePath)
                        BM.Save(MS, System.Drawing.Imaging.ImageFormat.Jpeg)
                        Dim data As Byte() = MS.GetBuffer()
                        Dim p As New SqlParameter("@photo", SqlDbType.Image)
                        p.Value = data
                        .Parameters.Add(p)
                    End Using

                    .Connection.Open()

                    Return cmd.ExecuteNonQuery()

                    .Connection.Close()
                End With
            Catch ex As Exception
                MsgBox(ex.Message & " " & ex.StackTrace)
            End Try
        End Using
    End Using
End Function

WPF Test Harness to Retrieve Image:
Try
    Using cn As New SqlConnection(sqlConn)
        'SqlConnection.ClearAllPools()
        Using cmd As New SqlCommand("SELECT [Image] From [dbo].[Autosaint_Wunelli_Engineer_Images] WHERE [PolicyRef] = 'LYJX01PC01'", cn)
            Try
                With cmd
                    .Connection.Open()
                    Dim imageData As Byte() = DirectCast(cmd.ExecuteScalar(), Byte())

                    If Not imageData Is Nothing Then
                        Using ms As New MemoryStream(imageData, 0, imageData.Length)
                            ms.Write(imageData, 0, imageData.Length)
                            PictureBox1.BackgroundImage = Image.FromStream(ms, True)
                        End Using
                    End If

                    .Connection.Close()

                End With

            Catch ex As Exception
                MsgBox(ex.Message & " " & ex.StackTrace)
            End Try
        End Using
    End Using
Catch ex As Exception
    MsgBox(ex.Message & " " & ex.StackTrace)
End Try

A: From the Image.FromStream docs:

You must keep the stream open for the lifetime of the Image.

So, change this:
Using ms As New MemoryStream(imageData, 0, imageData.Length)

to
Dim ms As New MemoryStream(imageData, 0, imageData.Length)

and remove the End Using, so that the stream is not disposed, and it should work OK.

A: Regarding the Wunelli_SendImage method:

*

*Don't use Parameters.AddWithValue. Instead, create the parameter explicitly and give it a datatype, just like with @photo.

*Do not use the IMAGE datatype if using SQL Server 2005 or newer, either in the DB or in this app code via SqlDbType.Image. Instead, use VARBINARY(MAX) in the DB and here use SqlParameter("@photo", SqlDbType.VarBinary, -1) where -1 equates to MAX.

*You don't need to create the MemoryStream or Bitmap objects. Instead, use p.Value = File.ReadAllBytes(ImagePath) and not waste memory, or at least get rid of some unnecessary steps.

*The INSERT statement should include the field names:
INSERT INTO [dbo].[Autosaint_Wunelli_Engineer_Images] ([PolicyRef], [Date], [Image]) VALUES (@policyref, GETDATE(), @photo);


text:
Q: Running a vba method from python with long path in Windows 10 Scenario
In an attempt to execute method main from module of example.xlsm from python file convertOds.py, I am experiencing slight difficulties. The path to the excel file is "too long" as it is longer than 218 characters. Now I could work around it and make a temp folder at c:/temp but then I lose some generality, e.g. what if the pc it runs on has no c: drive. So I am trying to run the excel method from a deep path regardless.
Code execution steps
The code is executed by opening Anaconda, browsing to the directory of the example.xlsm, the convertOds.py is located in the same directory as the example.xlsm file. So for example:
E:
cd "E:\long path of more than 218 characters/"
python convertOds.py

Code
The convertOds.py consists of:

import xlwings as xw

if __name__ == '__main__':
    file = r'E:\long path of more than 218 characters/example.xlsm'
    wb = xw.Book(file)
    macro = wb.macro("main")
    macro()

Error
The code yields the following error message when I execute it from anaconda with python 3.7:

File ">", line 8, in Open
    pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Excel', 'Cannot open the file because the file path is more than 218 characters. Try shortening the path or filename.', 'xlmain11.chm', 0, -2146827284), None)

So the first and second thing I did was enable long paths at regedit and gpedit.msc and reboot, according to the following procedure:
# 1.1 Press: start>Type: run>Type: gpedit.msc <enter>>Go to: Computer Configuration\Administrative Templates\System\Filesystem
# 1.2 And enable: "Enable Win32 long paths".
# 2. Then also enable long paths in regedit:
# 2.1 Press: start>Type: regedit<enter>>HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem
# 2.2 And enable: LongPathsEnabled

However that still results in the error described above.
Question
Is there a way to execute a method main from module1 of an example.xlsm from python even if it has a long path >260?


text:
Q: SQL Query to find two values attached to a single user via an ID Hopefully, the title makes sense.
I've got a Postgres SQL DB. I'd like to search my data and find all users that have two Instagram handles attached to them (these IG handles will share one ID that is linked to the user).
I've got a rough idea but I've only been able to do this in Trevor.IO and I'd like to have more experience running SQL properly through something like DBeaver.
Thanks

A: If you had a normalized table which applies users to instagram handles, it would be something like this:
SELECT
    user
FROM
    instagram_handle_table
GROUP BY user
HAVING COUNT(*) > 2


text:
Q: NAT with iptables: need help understanding i am trying to learn NAT with iptables but i ran into some confusions.
i am having two virtual machines with ips 18.43 lets say B and 18.42 C running webservers on port 80.
i need to NAT every traffic coming on B:80 to C:80 (Do not want to use any other techinique other than NAT)
rule on B with ip-forward on and Default Policy of every chain is to ACCEPT
iptables -t nat -A PREROUTING -p tcp -d 10.10.18.43 --dport 80 -j  DNAT --to 10.10.18.42:80

When i make request from A(my machine 11.46) to B:80 i can see the following on tcpdump
of Machine B
12:24:43.488944 IP 10.10.11.46.43149 > 10.10.18.43.http: Flags [S], seq 3856561847, win 14600, options [mss 1460,sackOK,TS val 2554127 ecr 0,nop,wscale 5], length 0
12:24:43.488986 IP 10.10.11.46.43149 > 10.10.18.42.http: Flags [S], seq 3856561847, win 14600, options [mss 1460,sackOK,TS val 2554127 ecr 0,nop,wscale 5], length 0
12:24:44.488106 IP 10.10.11.46.43149 > 10.10.18.43.http: Flags [S], seq 3856561847, win 14600, options [mss 1460,sackOK,TS val 2554377 ecr 0,nop,wscale 5], length 0
12:24:44.488138 IP 10.10.11.46.43149 > 10.10.18.42.http: Flags [S], seq 3856561847, win 14600, options [mss 1460,sackOK,TS val 2554377 ecr 0,nop,wscale 5], length 0
12:24:46.492250 IP 10.10.11.46.43149 > 10.10.18.43.http: Flags [S], seq 3856561847, win 14600, options [mss 1460,sackOK,TS val 2554878 ecr 0,nop,wscale 5], length 0
12:24:46.492283 IP 10.10.11.46.43149 > 10.10.18.42.http: Flags [S], seq 3856561847, win 14600, options [mss 1460,sackOK,TS val 2554878 ecr 0,nop,wscale 5], length 0

Also on the Machine C i am getting following on tcpdump
 12:24:43.497050 IP 10.10.11.46.43149 > 10.10.18.42.http: Flags [S], seq 3856561847, win 14600, options [mss 1460,sackOK,TS val 2554127 ecr 0,nop,wscale 5], length 0
 12:24:43.497116 IP 10.10.18.42.http > 10.10.11.46.43149: Flags [S.], seq 450030769, ack 3856561848, win 14480, options [mss 1460,sackOK,TS val 2097931 ecr 2554127,nop,wscale 7], length 0
 12:24:44.496174 IP 10.10.11.46.43149 > 10.10.18.42.http: Flags [S], seq 3856561847, win 14600, options [mss 1460,sackOK,TS val 2554377 ecr 0,nop,wscale 5], length 0
 12:24:44.496227 IP 10.10.18.42.http > 10.10.11.46.43149: Flags [S.], seq 450030769, ack 3856561848, win 14480, options [mss 1460,sackOK,TS val 2098181 ecr 2554127,nop,wscale 7], length 0
 12:24:44.970715 IP 10.10.18.42.http > 10.10.11.46.43149: Flags [S.], seq 450030769, ack 3856561848, win 14480, options [mss 1460,sackOK,TS val 2098300 ecr 2554127,nop,wscale 7], length 0.
 12:24:46.500288 IP 10.10.11.46.43149 > 10.10.18.42.http: Flags [S], seq 3856561847, win 14600, options [mss 1460,sackOK,TS val 2554878 ecr 0,nop,wscale 5], length 0
 12:24:46.500336 IP 10.10.18.42.http > 10.10.11.46.43149: Flags [S.], seq 450030769, ack 3856561848, win 14480, options [mss 1460,sackOK,TS val 2098682 ecr 2554127,nop,wscale 7], length 0
 12:24:46.970717 IP 10.10.18.42.http > 10.10.11.46.43149: Flags [S.], seq 450030769, ack 3856561848, win 14480, options [mss 1460,sackOK,TS val 2098800 ecr 2554127,nop,wscale 7], length 0

But i am not getting any Reply back to Machine A.,If my interpretation is correct on machine C packets are coming as source ip 11.46(A) and 18.42(C) is replying to A but why are the packets not reaching A.Do i need more rules on B to make this work.
Update
added SNAT
SNAT       tcp  --  anywhere             anywhere             to:10.10.18.43:80

Tcpdump on machine B:
   15:13:38.816289 IP 10.10.11.46.44423 > 10.10.18.43.http: Flags [P.], seq 2436344770:2436345215, ack 4133534960, win 892, options [nop,nop,TS val 5087771 ecr 4627759], length 445
15:13:38.816332 IP 10.10.18.43.http > 10.10.18.42.http: Flags [P.], seq 2436344770:2436345215, ack 4133534960, win 892, options [nop,nop,TS val 5087771 ecr 4627759], length 445
15:13:38.817173 IP 10.10.18.42.http > 10.10.18.43.http: Flags [P.], seq 1:159, ack 445, win 231, options [nop,nop,TS val 4631763 ecr 5087771], length 158
15:13:38.817206 IP 10.10.18.43.http > 10.10.11.46.44423: Flags [P.], seq 1:159, ack 445, win 231, options [nop,nop,TS val 4631763 ecr 5087771], length 158
15:13:38.818819 IP 10.10.11.46.44423 > 10.10.18.43.http: Flags [.], ack 159, win 926, options [nop,nop,TS val 5087772 ecr 4631763], length 0
15:13:38.818830 IP 10.10.18.43.http > 10.10.18.42.http: Flags [.], ack 159, win 926, options [nop,nop,TS val 5087772 ecr 4631763], length 0

tcpdump on machine C:
15:13:38.824622 IP 10.10.18.43.http > 10.10.18.42.http: Flags [P.], seq 2436344770:2436345215, ack 4133534960, win 892, options [nop,nop,TS val 5087771 ecr 4627759], length 445
15:13:38.824880 IP 10.10.18.42.http > 10.10.18.43.http: Flags [P.], seq 1:159, ack 445, win 231, options [nop,nop,TS val 4631763 ecr 5087771], length 158
15:13:38.826811 IP 10.10.18.43.http > 10.10.18.42.http: Flags [.], ack 159, win 926, options [nop,nop,TS val 5087772 ecr 4631763], length 0

A: iptables -t nat -A PREROUTING -p tcp -d 10.10.18.43 --dport 80 -j  DNAT --to 10.10.18.42:80
As khaled specified machine A was confused with reply from C and Rejected all the packets from C.
SNAT ing source ip fixed this
iptables -t nat -A POSTROUTING -p tcp -o eth0 -j SNAT --to 10.10.18.43

A: You did not tell us exactly how these machines are connected and whether they are attached to a single subnet or not. However, I can assume at least that machines B and C are in the same subnet and machine A is in different one.
Your setup will not work this way. You will not receive any response back to your machine A because the server C is replying back directly to machine A and not through NATing box (server B in this case).
Machine A will get confused as it is sending to machine B and receiving response back from machine C.
In order to make it work, you need to do the NATing on the gateway of machines B and C.


text:
Q: Convert Rtf, Excel, Pdf, or Html file formats to image I'm working on a feature for a .NET 4 WPF/WCF/EF 4/SQL 2008 application that supports adding/editing Rtf or Excel content. We're using 3rd party components from Telerik and GrapeCity to support Rtf and Excel editing inside our product.
Among other pertinent fields, the "Entry" entity is simple and includes an RtfContent varchar(max), ExcelContent varbinary(max), and IsRtf (bit). IsRtf indicates if the Entry uses Rtf (true) or Excel (false). They are mutually exclusive.
Using the 3rd party controls, I can "export" the Rtf and Excel data as Pdf, Html, or each as Rtf and Xlsx.
We're wanting to include the Rtf or Excel content into a report, and we're using Data Dynamics Reporting package. I'm stumped on how or even if we can accommodate this request since Data Dynamics doesn't offer support for Rtf, Excel, Html, or Pdf. They do however, offer support for Tiff (and some other image formats).
I'm not sure if this would be a trivial conversion, but it may be the only way to include this content in a Data Dynamics Report.
Is it possible to convert any of those formats to a Tiff image? Or would it be possible to somehow "capture" the content of one of the 3rd party controls as a Tiff?
I can't say that I like the thought of performing conversions like this, but I'm running out of ideas.
Any thoughts?

A: This question addresses converting PDF to different images in C# and would probably work for you.
https://stackoverflow.com/questions/711942/convert-pdf-file-to-jpg-asp-net


text:
Q: ComboBoxItem Binding Error on opening combobox (wpf) I am opening my combobox once it gets focus using combobox.isDropDownOpen
I am getting the following binding error in the console

System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.ItemsControl', AncestorLevel='1''. BindingExpression:Path=VerticalContentAlignment; DataItem=null; target element is 'ComboBoxItem' (Name=''); target property is 'VerticalContentAlignment' (type 'VerticalAlignment')

here is the code:
private void combo_GotFocus(object sender, RoutedEventArgs e)
{
    placeholder.Visibility = Visibility.Collapsed;

    combo.IsDropDownOpen = true;
}

private void combo_LostFocus(object sender, RoutedEventArgs e)
{
    if (combo.Text.Equals(""))
    {
        placeholder.Visibility = Visibility.Visible;
    }

}

A: These kind of binding errors are harmless. Please refer to the following link for more information.
Resolving harmless binding errors in WPF: https://weblogs.asp.net/akjoshi/resolving-un-harmful-binding-errors-in-wpf


text:
Q: jMonkeyEngine 3.1 apk not installed I have a lot of problems with running jME project on android. Firs problem: jME SDK does not support latest version of Android SDK (it does not have sdk/tools/ant folder). I have found an older SDK version, but still it not working. jME creates MyGame-debug-unaligned.apk and MyGame-release-unsigned.apk, but both of them can't be installed on Android device (App not installed message). If I try to run app directly from jME SDK this i got in log:
C:\Users\Bublik\GoogleDrive\jMEprojects\Fuck\nbproject\mobile-impl.xml:10: The following error occurred while executing this line:
C:\Program Files\Android\sdk\tools\ant\build.xml:958: The following error occurred while executing this line:
C:\Program Files\Android\sdk\tools\ant\build.xml:969: The following error occurred while executing this line:
C:\Program Files\Android\sdk\tools\ant\build.xml:312:
java.lang.InternalError: Could not obtain X500Principal access
    at sun.security.x509.X500Name.<clinit>(X500Name.java:1399)
    at com.android.sdklib.internal.build.SignedJarBuilder.writeSignatureBlock(SignedJarBuilder.java:384)


text:
Q: I am trying to figure out how this works. In a site master from VS template (Web Forms), I read the following:

<asp:ScriptManager runat="server">

      <Scripts>

            <asp:ScriptReference Name="MsAjaxBundle" />
            <asp:ScriptReference Name="jquery" />
            <asp:ScriptReference Name="bootstrap" />
            <asp:ScriptReference Name="respond" />
            <asp:ScriptReference Name="WebForms.js" Assembly="System.Web" Path="~/Scripts/WebForms/WebForms.js" />
            <asp:ScriptReference Name="WebUIValidation.js" Assembly="System.Web" Path="~/Scripts/WebForms/WebUIValidation.js" />
            <asp:ScriptReference Name="MenuStandards.js" Assembly="System.Web" Path="~/Scripts/WebForms/MenuStandards.js" />
            <asp:ScriptReference Name="GridView.js" Assembly="System.Web" Path="~/Scripts/WebForms/GridView.js" />
            <asp:ScriptReference Name="DetailsView.js" Assembly="System.Web" Path="~/Scripts/WebForms/DetailsView.js" />
            <asp:ScriptReference Name="TreeView.js" Assembly="System.Web" Path="~/Scripts/WebForms/TreeView.js" />
            <asp:ScriptReference Name="WebParts.js" Assembly="System.Web" Path="~/Scripts/WebForms/WebParts.js" />
            <asp:ScriptReference Name="Focus.js" Assembly="System.Web" Path="~/Scripts/WebForms/Focus.js" />
            <asp:ScriptReference Name="WebFormsBundle" />
            <%--Site Scripts
       --%>

      </Scripts>

    </asp:ScriptManager>

Now some of the scripts have just names, others have names and paths + assembly.
How does the application figure out the paths of those only with names and why is there this difference with the others. Also what is Assembly needed for?

A: If you expand the References node of your web project in the Solution Explorer or you open the Manage NuGet Packages tab and filter the installed packages with "AspNet.ScriptManager." you'll see references such as AspNet.ScriptManager.jQuery and Microsoft.AspNet.ScriptManager.MSAjax. Those packages ship with the default VS template and their job is to add ScriptMappings in the PreApplicationStart method of the application. For example, the description of the AspNet.ScriptManager.jQuery package reads as follows:

This package contains the AspNet.ScriptManager.jQuery assembly that
  will automatically  register jQuery x.y.z with the ScriptManager as
  "jquery".

So, those are the names used by the ScriptManager.
And here is a sample of the ScriptMapping definitions added by those packages:
string str = "x.y.z";
ScriptManager.ScriptResourceMapping.AddDefinition("jquery", new ScriptResourceDefinition
{
    Path = "~/Scripts/jquery-" + str + ".min.js",
    DebugPath = "~/Scripts/jquery-" + str + ".js",
    CdnPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-" + str + ".min.js",
    CdnDebugPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-" + str + ".js",
    CdnSupportsSecureConnection = true,
    LoadSuccessExpression = "window.jQuery"
});

In ASP.NET 4.5 the Microsoft Ajax script files (MicrosoftAjaxCore etc) and the WebForms scripts (GridView.js etc) were decoupled so they can be served from your application Scripts folder rather than being loaded up from System.Web. The reason both the Assembly and the Path attributes are present is because ScriptManager special cases these scripts when it tries to load them, so special arrangements with ScriptManager code had to be done to make this work. Basically when the ScriptManager tries to load up these scripts, it can load them up from System.Web or the path attribute and eventually in this case, the ScriptManager dedupes the script references and serves the scripts from the path attribute.


text:
Q: Updating a table with information Oracle Apex I am trying to make an application where users can enter data into a page filled with fields. Based off that information, a table will be updated with the information they enter. The problem is the table cant be updated as you need to start a SQL query with SELECT or WITH. Any idea on how to get around this? ex:
 UPDATE temptable
 SET temp_value = 10

A: From the error message it looks like you're putting the update statement in the source for a report - that raises this type of error message.
I suggest you use the wizard to create a page of the type "Report with form". APEX will then generate everything for you, no manual update statements needed - it saves you a ton of time and the code is rock solid.
If you do want to write the update statement yourself, then that should be done in a "Page Process" with processing point "After Submit".


text:
Q: How to exclude a pattern that starts with a phrase, but the pattern may contain substring of the phrase? With this example,
whether or not apple
apple
not apple

How could I find either apple or not apple and exclude whether or not apple?
My attempt was to use negative lookbehind like
(?!whether or not)(([Nn]ot)?\s*apple)

but this finds all as

*

*whether or not apple

*apple

*not apple

A: As your consuming pattern starts with an optional pattern, you need to account for these two scenarios and implement two separate lookbehinds:
(?<!\bwhether or )(?<!\bwhether or not )(?:\bnot )?\bapple\b

See the regex demo. Details:

*

*(?<!\bwhether or ) - no whether or  allowed immediately on the left

*(?<!\bwhether or not )  - no whether or not  allowed immediately on the left

*(?:\bnot )? - an optional sequence of not word and a space

*\bapple\b - a whole word apple.

Another approach is to match the string you want to skip and skip it:
\bwhether\s+or\s+not\s+apple\b(*SKIP)(*F)|(?:\bnot\s+)?\bapple\b

See this regex demo. Here, \bwhether\s+or\s+not\s+apple\b matches the whether or not apple and (*SKIP)(*F) drop the match, skips to the position of the failure and restarts a new match search.

A: The pattern you are looking for is ^(?:not\s)?apple
Python
import re

re.match(r"^(?:not\s)?apple", "apple")  # matches
re.match(r"^(?:not\s)?apple", "not apple")  # matches
re.match(r"^(?:not\s)?apple", "whether or not apple")  # does not match

JavaScript
/^(?:not\s)?apple/.test("apple"); // matches
/^(?:not\s)?apple/.test("not apple"); // matches
/^(?:not\s)?apple/.test("whether or not apple"); // does not match


text:
Q: PyQT6/PySide6: How to make a QWidget always on top of screen? I am making a floating clock based on PySide6, its main part is as follows
How can I make this program always on top of the screen, even in full screen mode?
The self.setWindowFlags(Qt.WindowStaysOnTopHint) method doesn't seem to work.
import sys

from PySide6.QtCore import QPoint, Qt, QTime, QTimer
from PySide6.QtGui import QAction, QFont, QMouseEvent
from PySide6.QtWidgets import QApplication, QLabel, QMenu, QVBoxLayout, QWidget

class Clock(QWidget):

    def __init__(self, parent=None) -> None:
        super().__init__(parent)

        self.left = 1100
        self.top = 800
        self.width = 320
        self.height = 60
        # UI
        self.initUI()

    def initUI(self) -> None:

        # geometry of main window
        self.setGeometry(self.left, self.top, self.width, self.height)

        # hide frame
        self.setWindowFlags(Qt.WindowStaysOnTopHint)
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setAttribute(Qt.WA_TranslucentBackground)

        # font
        font = QFont()
        font.setFamily("Arial")
        font.setPointSize(50)

        # label object
        self.label = QLabel()
        self.label.setAlignment(Qt.AlignCenter)
        self.label.setFont(font)

        # layout
        layout = QVBoxLayout(self, spacing=0)

        layout.addWidget(self.label)  # add label
        self.setLayout(layout)

        # timer object
        timer = QTimer(self)
        timer.timeout.connect(self.showTime)
        timer.start(1000)  # update the timer per second
        self.show()

    def showTime(self) -> None:

        current_time = QTime.currentTime()  # get the current time
        label_time = current_time.toString('hh:mm')  # convert timer to string
        self.label.setText(label_time)  # show it to the label

if __name__ == '__main__':

    App = QApplication(sys.argv)
    clock = Clock()
    clock.show()  # show all the widgets
    App.exit(App.exec())  # start the app

A: You are using the wrong method for setting the flags individually. You should use this method instead: setWindowFlag NOT setWindowFlags (without the "s" at the end). This will solve Your issue:
self.setWindowFlag(Qt.WindowStaysOnTopHint, True)
self.setWindowFlag(Qt.FramelessWindowHint, True)

To use setWindowFlags (with the "s" at the end) You should combine the flags with the bitwise OR.
Here is the (C++) Qt-example for that https://doc.qt.io/qt-6/qtwidgets-widgets-windowflags-example.html


text:
Q: How to GET data from mongoDB ATLAS and display in React App I am new to MERN stack and been working on a project that uses different driver information entered from the user and display that information back to the user in a table. I have successfully connected to MongoDB Atlas and also can enter data using my front end but I can't seem to figure out how to retrieve the data back to the front end. Can y'all help me fetch the data back and how I can present it in a tabular format.
Thanks in advance.
//driver model
onst mongoose = require('mongoose');
const DriverSchema = new mongoose.Schema({
    name:{type: String, required:true},
    email:{type: String, required:true},
    phone:{type: Number, required:true},
    address:{type:String, required:true},
    country:{type: String, required:true}
});

const DriverModel = mongoose.model("drivers", DriverSchema)
module.exports = DriverModel;

//routes
const router= require('express').Router();
let Driver = require('../models/driver');

router.route('/getDrivers').get((req, res) =>{
    Driver.find()
    .then(drivers => res.json(drivers))
    .catch(err => res.status(400).json('Error: '+ err));

}
)

router.route('/createDrivers').post((req, res) => {
    const name = req.body.name;
    const email = req.body.email;
    const phone = req.body.phone;
    const address = req.body.address;
    const country =req.body.country;
    const newDriver = new Driver({name, email, phone, address, country});

    newDriver.save()
      .then(() => res.json('Driver added!'))
      .catch(err => res.status(400).json('Error: ' + err));
  });

  router.route('/:id').get((req,res)=> {
      Driver.findById(req.params.id)
      .then(drivers => res.json(drivers))
      .catch(err => res.status(400).json('Error: ' + err));
  })

  router.route('/:id').delete((req, res) => {
    Driver.findByIdAndDelete(req.params.id)
      .then(() => res.json('Driver deleted.'))
      .catch(err => res.status(400).json('Error: ' + err));
  });

  router.route('/update/:id').post((req, res) => {
    Driver.findById(req.params.id)
      .then(driver => {
        driver.name = req.body.name;
        driver.email = req.body.email;
        driver.phone = req.body.phone;
        driver.address = req.body.address;
        driver.country =req.body.country;

        driver.save()
          .then(() => res.json('Driver updated!'))
          .catch(err => res.status(400).json('Error: ' + err));
      })
      .catch(err => res.status(400).json('Error: ' + err));
  });

  module.exports = router;

//frontend
import React from 'react';
import Sidebar from '../../components/sidebar/Sidebar';
import Navbar from '../../components/navbar/Navbar';
import { useEffect, useState } from 'react';
import "./dbtrial.scss" ;
import Axios from "axios";
function Dbtrial() {

    const [listOfDrivers, setListOfDrivers]= useState([]);
    const [name, setName] = useState("");
    const [email, setEmail] = useState("");
    const [phone, setPhone] = useState(0);
    const [address, setAddress] = useState("");
    const [country, setCountry] = useState("");

    useEffect(() => {
      const fetchDrivers= async () =>{
        try{
          const response = await fetch("http://localhost:3001/driver/getDrivers")
          if(!response.ok) throw Error('Did not recieve expected data');
          const listDrivers = await response.json();
          console.log(listDrivers);
          setListOfDrivers(listDrivers);
          setFetchError(null);
        } catch(err){
          setFetchError(err.message)
        }
      }
      setTimeout(() => {
        (async () => await fetchDrivers())();
      }, 2000)
      //(async () => await fetchDrivers())();
    }, [])

    const createDrivers = () =>{
      Axios.post("http://localhost:3001/createDrivers", {
        name,
        email,
        phone,
        address,
        country,
      }).then((response) =>{
        setListOfDrivers([...listOfDrivers,
        {
          name, email, phone, address,
          country,
        },
      ]);
        //alert("Driver added!");
      });
    }

    return (

            <Sidebar />

                <Navbar />

                    Name
                    <input type="text" placeholder="name"  onChange={(event) => {
                      setName(event.target.value);
                      }} />

                    Email
                    <input type="email" placeholder="email"  onChange={(event)=> {setEmail(event.target.value);}}/>

                    Phonenumber
                    <input type="text" placeholder="0923668881 "  onChange={(event) => {setPhone(event.target.value);}}/>

                    Address
                    <input type="text" placeholder="Addis Ababa" onChange={(event)=> {setAddress(event.target.value);}}/>

                    Country
                    <input type="text" placeholder="country" onChange={(event) => {setCountry(event.target.value);}}/>
                    <button type="submit" onClick={createDrivers}>Send</button>

    )
}

export default Dbtrial

A: On your backend, your router functions don't seem to use
res.send

Where you are doing res.json, you can do something like
res.status(200).send(responseData)

So in router.routes.findById' then callback, instead of:
.then(drivers =>
   res.json(drivers))

You can have
.then(drivers =>
   res.status(200).send(JSON.stringify(drivers)) //maybe you don't need to use JSON.stringify here

In your frontend, I'm not sure what response.data will be defined after your api call. To be sure what properties the response has, you can console.dir(response.data), console.dir(response.json()) and check the result in the browser console. (Not too familiar with axios) If the result is your driver array, you can do like are already doing with setDriverList to set the state, but probably with the result of, or a part of the result of response.data or response.data.devices or something like that.
So I would do something like
//...api call
.then((response) => {
    if(response.status === 200){
        setDriverList(response.data.drivers) //or response.data or whatever
    }
})


text:
Q: How to compare two mediation models?
I ran a mediation study using three dispositional measures, each measured with a scale. The order of scales was in line with my assumed model, so A --> B --> C.
Using SPSS and PROCESS the results support the notion that B mediates the association of A --> C and there seems to be full mediation.
Now, to protect this finding against possible criticism I also tested an alternative mediation model using the exact same scales but in a different order: A --> C --> B. Also this model looks good but there is not full mediation.
I would like to compare these two models but I am puzzled how to do that. I found two suggested approaches by Mackinnon & Dwyer (1993).
A) refer to the total effect that is mediated
B) refer to the ratio of the indirect to direct effect.
For B) PROCESS already provides the numbers:
Model 1
Ratio of indirect to direct effect of X on Y
            Effect    Boot SE   BootLLCI   BootULCI
mean_SCC   -16,6985    88,0316 -2091,0335    -8,2910

Model 2
Ratio of indirect to direct effect of X on Y
             Effect    Boot SE   BootLLCI   BootULCI
mean_INC      ,0975      ,0467      ,0164      ,2032

The numbers are  pretty different (I guess they are unstandardized) and I am wondering whether I can use them to make the comparison of interest. What do you think?

Alternatively, do I have to justify/compare at all?


text:
Q: Update Java code during runtime about a year ago I stumbled across a nice feature in Java that I cannot for the life of me find again.
Through some magic interface it was apparently possible to declare some classes or functions replaceable during runtime.
I found a nice example guide of someone who ran a simple little program that printed a certain message, he then updated the program using a method I cannot remember anymore and all of a sudden the program had replaced that old print function with a new one.
I've tried looking through the Java API to spark my memory as well as googling but without success. Can anyone here help?

A: Various app containers can do this.
Basically you'd need to reload the class in a new ClassLoader (unless you're talking about doing this under the debugger, in which case there are completely different APIs available).
In my opinion, this kind of thing is rarely worth the hassle: designing everything so that it can be reloaded is considerably harder than designing it so it can be completely restarted in a new process. It's also easier to be sure exactly what code is running if there's only ever one version loaded in the process.
It's a neat thing to be able to demo, but for most applications it's not worth it. All in my opinion, of course :)
Note that one notable exception is the ability to reload web UI layers without restarting the container: that can make life much easier.

A: The HotSwap technology was added to Java 1.4 and enable class file replacement at run-time. The feature is provide through the redefineClasses method of the instrumentation package. I think you can also do that through the JPDA interface.
Here is also a reference to what I believe is the research paper that describe the HotSwap mechanism first:

*

*Towards Flexible and Safe Technology for Runtime Evolution of Java  Language Applications
Otherwise you can use Classloader, as the other mentionned, but it only provides dynamic class loading, not replacement. The same class loaded twice will be considered as two different types. Combined with interface and/or a bit of reflection, it can however provide ways to update the application at run-time.
Here is a reference to an awesome paper about class loader, and there usage:

*

*Dynamic Class Loading in the Java Virtual Machine
I won't expand on whether this is good or bad, because it was not your question, but I think it's great to have support for run-time software evolution -- too bad that JSR-117 never made it!

A: This is typically the kind of functionality I gladly leave to infrastructure as it is difficult to get right and easy to get wrong. As Jon mentioned above, most applications do not need it and for those that need it infrastructure is available.
Most application servers allow hot deployment nowadays, and equally most application servers are embeddable and allow them to be stripped down to remove features you do not need.
If it mainly for development, you should look a JRebel which provides this functionality transparently. I've heard they are working on a runtime solution, but I do  not know if it is ready for primetime yet.
If you are really motivated to get this to work, then consider using OSGi. It has a steep learning curve, but once you grok it, it does most things right and works very well. I found the pax tools a good starting point but the eclipse toolchain also has good support for it.


text:
Q: Microsoft Exchange Web service :GetUserAvailability exception :System.ArgumentException: An item with the same key has already been added         try

        {

            results = this.exchangeService.GetUserAvailability(attendees, new TimeWindow(startTime, endTime), AvailabilityData.FreeBusy);

         }

        catch (Exception ex)

        {

            string attendeesString = string.Empty;

            foreach (AttendeeInfo item in attendees)

            {

                attendeesString += item.SmtpAddress + "; ";

            }

            LogData logData = MethodLogUtilityForExchange.GetLogDataGetAttendeesAvailabilityDebug(attendeesString, startTime, endTime, ex);

            LogUtility.LogException(logData, "EWS GetAttendeesAvailability Exception", ex, LogCategory.MethodInformation);

            throw;

        }

Exception stack trace :
ExceptionSystem.ArgumentException: An item with the same key has already been added.
at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
at Microsoft.Exchange.WebServices.Data.ExchangeServiceBase.SaveHttpResponseHeaders(WebHeaderCollection headers)
at Microsoft.Exchange.WebServices.Data.SimpleServiceRequestBase.ReadResponse(HttpWebResponse response)
at Microsoft.Exchange.WebServices.Data.GetUserAvailabilityRequest.Execute()
at Microsoft.Exchange.WebServices.Data.ExchangeService.GetUserAvailability(IEnumerable`1 attendees, TimeWindow timeWindow, AvailabilityData requestedData)
at Intel.Exchange.WebServices.Extension.ExchangeServiceManager.GetAttendeesAvailability(List`1 attendees, DateTime startTime, DateTime endTime)
Can you help in understanding the issue ? we are not handling any Dictionary explicitly here. but still we see the Dictionary key error. Not sure What would have gone wrong.

A: You might not be using any Dictionary, but apparently EWS is in its HTTP response processing.  It almost looks like EWS has returned a duplicate response header.  You might have to get a Fiddler trace or some such to see that.  One thing to check (altho how this would cause this error is beyond me): do each of the 'attendees' have a different SMTP address?  Just a shot in the dark.


text:
Q: Mergesort recursion error i coded this mergesort code in python.The function merge is working well when i am calling it seperately,its sorting two different sorted lists.But when i am using it in real merge sort recursion problem,it is not doing its intended work.I am uploading my code please help me regarding this issue
def merge(list,p,q,r):

    list1=[]
    list2=[]
    list3=[]
    i=0
    j=0
    for a in list[:q+1]:
        list1.append(a)
    list1.append(99999999999)

    for b in list[q+1:]:
        list2.append(b)
    list2.append(9999999999999999999999999)
    for k in range(len(list)):
        if list1[i]<list2[j]:
            list3.insert(k,list1[i])
            i=i+1
        else:
            list3.insert(k,list2[j])
            j=j+1
        return list3

def mergesort(list,p,r):

    if p<r:

      q=(p+r)/2
      mergesort(list,p,q)
      mergesort(list,q+1,r)
      merge(list,p,q,r)

list=[1,5,7,8,2,4,6,9]

mergesort(list,0,7)

print list

There is no intendation error
the output is :
[1, 5, 7, 8, 2, 4, 6, 9]

its printing the same as the list
not sorting it

A: you are not modifing list inside your function 'merge'
You either need to modify the list or return new list , you are doing neither
You can return list3 from merge function
and modify mergesort as:
def mergesort(list,p,r):
    if p<r:
      q=(p+r)/2
      mergesort(list,p,q)
      mergesort(list,q+1,r)
      list =merge(list,p,q,r)

Hi made it work:
Use
 def merge(list,p,q,r):

    list1=[]
    list2=[]
    list3=[]
    i=0
    j=0
    for a in list[:q+1]:
        list1.append(a)
    list1.append(99999999999)

    for b in list[q+1:]:
        list2.append(b)
    list2.append(9999999999999999999999999)
    for k in range(len(list)):
        if list1[i]<list2[j]:
            list3.insert(k,list1[i])
            i=i+1
        else:
            list3.insert(k,list2[j])
            j=j+1
    return list3

def mergesort(list,p,r):

    if p<r:

      q=(p+r)/2
      mergesort(list,p,q)
      mergesort(list,q+1,r)
      list = merge(list,p,q,r)
      return list

list=[1,5,7,8,2,4,6,9]

list = mergesort(list,0,7)

print list


text:
Q: Remove or hide time row from the kendo scheduler in angular 8 how to remove or hide the Time-Row from the Scheduler in angular 8.
here is the code with sample date in stackblitz:
https://stackblitz.com/edit/angular-brn2en-rtbgjt
I want to remove or hide the second row: "11:00 AM"

A:
I want to remove or hide the second row: "11:00 AM"

To achieve your above requirement, you can try to apply following CSS styles to Kendo UI for Angular Scheduler.
div.k-scheduler-timeline-month-view>div:nth-child(1)>div.k-scheduler-times>table.k-scheduler-table tr:last-child {
  display: none;
}

div.k-scheduler-header-wrap table.k-scheduler-table tr:last-child {
  display: none;
}

Test Result


text:
Q: SQL running a count(*) and count(*) group by returns differnet number of rows This is strange, lets say I have a table called dbo.internetquotes in SQL server.
I want to get the total number of quotes in a month and break it down by a column called quotetype.
I run the query:
select count(*) from dbo.internetquotes
where quotedate between '2014/03/01' and '2014/04/01';

and it returns 20k.
Now I run the query
select count(*), quotetype from dbo.internetquotes
where quotedate between '2014/03/01' and '2014/04/01'
group by quotetype;

And it returns the count per quotetype.  However, when i sum up the counts from the second query the number does not equal 20k (slightly less).  My thought was perhaps there are nulls in the column quotetypes but running a select * where quotetype = null returns 0 rows.
What is the reason for the discrepancies?

A: When anything does not match with aggregation, just think about three values - TRUE, FALSE, UNKNOWN.
You are probably dropping out the NULLS (UNKNOWN) when aggregating.
Also, please use > and < when dealing with dates.
Bad habits to kick : mis-handling date / range queries
-- 1 - Skip nulls
select
    count(*) as Total
from
    dbo.internetquotes
where
    quotedate >= '20140301' and
    quotedate < '20140401' and
    quotetype is not null

-- 2 - Skip nulls
select
    quotetype, count(*) as total
from
    dbo.internetquotes
where
    quotedate >= '20140301' and
    quotedate < '20140401' and
    quotetype is not null
group by
    quotetype;

These two queries should have the same counts.  Good luck.
Just use Adventure Works and try these queries
-- 31465
select count(*) from [Sales].[SalesOrderHeader]

-- Group by person
select SalesPersonID, count(*) as total
into #temp
from [Sales].[SalesOrderHeader]
group  by SalesPersonID

-- 18 rows for a total count of 31465
select sum(total) as grand from #temp

The nulls will be group by and show up as a row.  I never discounted that.  But the date issue could drop data.  I champion that!

A: I'm thinking about it for a moment, I think you have duplicated rows or duplicated quotedate.
Can you run something like :
select count(distinct quotedate) from dbo.internetquotes
where quotedate between '2014/03/01' and '2014/04/01';

To compare with sum(counts) of 2nd query.


text:
Q: Bad request encountered with RestSharp JSON POST request I am using RestSharp to make a POST request containing a JSON body.  But I get a Bad request error.
Because I have [] and "" in my JSON I have decided to use Newtonsoft.Json   . Before using this I couldn't even see a JSON request being formed.
I am willing to try MS httpwebrequest as an alternative.
restClient = new RestClient();

restRequest = new RestRequest(ApiUrl, Method.POST, DataFormat.Json);

var myObject = "{ \"target\" : \"[5,5]\", \"lastseen\" : \"1555459984\" }";

var json = JsonConvert.SerializeObject(myObject);
restRequest.AddParameter("application/json", ParameterType.RequestBody);

restRequest.AddJsonBody(json);

Please note that I am trying to convert a JSON curl to C#.  Please see below:
curl -H 'Content-Type: application/json' -X POST -d '{ "target" : [5, 5],  "lastseen" : "1555459984", "previousTargets" : [ [1, 0], [2, 2], [2, 3] ] }' http://santized/santized/santized

A: You appear to be over serializing the data to be sent.
Consider creating an object and then passing it to AddJsonBody.
//...

restClient = new RestClient();

restRequest = new RestRequest(ApiUrl, Method.POST, DataFormat.Json);

var myObject = new {
    target = new []{ 5, 5 },
    lastseen = "1555459984",
    previousTargets = new []{
        new [] { 1, 0 },
        new [] { 2, 2 },
        new [] { 2, 3 }
    }
};

restRequest.AddJsonBody(myObject); //this will serialize the object and set header

//...

AddJsonBody sets content type to application/json and serializes the object to a JSON string.

A: Why not just this?
restClient = new RestClient();

restRequest = new RestRequest(ApiUrl, Method.POST, DataFormat.Json);

var myObject = "{ \"target\" : \"[5,5]\", \"lastseen\" : \"1555459984\" }";

restRequest.AddParameter("application/json", ParameterType.RequestBody);

restRequest.AddJsonBody(json);

Removed the line where you are serializing a json string.

A: You could also use:
public class RootObject
{
    public string target { get; set; }
    public string lastseen { get; set; }
}

restClient = new RestClient();

restRequest = new RestRequest(ApiUrl, Method.POST, DataFormat.Json);

RootObject myObject = new RootObject();
myObject.target = "[5,5]";
myObject.lastseen = "1555459984";
var json = JsonConvert.SerializeObject(myObject);

restRequest.AddParameter("application/json", ParameterType.RequestBody);

restRequest.AddJsonBody(json);

A: you could do this example:
  public static IRestRequest PostInformationAndPassToken(JsonObject tokenString, string path, string whatistobePosted)
    {
        IRestRequest request = new RestRequest(path, Method.POST);
        request.AddHeader("Authorization", $"Bearer {tokenString["Token"]}");
        request.AddHeader("cache-control", "no-cache");
        request.AddHeader("Content-Type", "application/json");
        request.AddParameter(whatistobePosted, ParameterType.RequestBody);
        return request;
    }


text:
Q: Make DataTables totals row immune to sorting/filtering I am using jquery datatable. I also add total in last tr. When I search any data by date range or datatable default search my total not showing. How can I fix it with search result total?
This is my script
$.fn.dataTable.ext.search.push(
                function (settings, data, dataIndex) {
                    var min = $('#datepicker_from').datepicker("getDate");
                    var max = $('#datepicker_to').datepicker("getDate");
                    var startDate = new Date(data[1]);
                    if (min == null && max == null) {
                        return true;
                    }
                    if (min == null && startDate <= max) {
                        return true;
                    }
                    if (max == null && startDate >= min) {
                        return true;
                    }
                    if (startDate <= max && startDate >= min) {
                        return true;
                    }
                    return false;
                }
            );

            $("#datepicker_from").datepicker({
                onSelect: function () {
                    table.draw();
                },
                changeMonth: true,
                changeYear: true,
                autoclose: true,
                todayHighlight: true

            });
            $("#datepicker_to").datepicker({
                onSelect: function () {
                    table.draw();
                }, changeMonth: true,
                changeYear: true,
                autoclose: true,
                todayHighlight: true

            });
            var table = $('#datatable').DataTable();

            // Event listener to the two range filtering inputs to redraw on input
            $('#datepicker_from, #datepicker_to').change(function () {
                table.draw();
            });

A: Considering, you didn't share certain prerequisites, I'll allow myself to make up my own example.
So, as being said, optimal solution of your problem would be to place your totals into
 row, so they're not getting affected neither by filtering nor by sorting:

//source data
const srcData = [
  {item: 'apple', order: '12/03/2019', cost: 15},
  {item: 'pear', order: '24/10/2018', cost: 24},
  {item: 'banana', order: '13/02/2019', cost: 14},
  {item: 'plum', order: '11/12/2018', cost: 26}
];
//DataTable initialization
const dataTable = $('#mytable').DataTable({
  dom: 't',
  data: srcData,
  columns: [
    {title: 'Item', data: 'item'},
    {title: 'Order date', data: 'order'},
    {title: 'Cost', data: 'cost'}
  ],
  drawCallback: () => {
 //append tfoot and populate it with total cost
 $('#mytable tfoot').remove();
 $('#mytable').append(`<tfoot><td colspan="3" style="text-align:right"><b>Total cost:</b> ${$('#mytable').DataTable().column(2, {search:'applied'}).data().toArray().reduce((sum, item) => sum+=item, 0)}</td></tfoot>`);
  }
});
//custom date range filter
$.fn.DataTable.ext.search.push((settings, row) => (new Date(row[1].split('/').reverse()) >= new Date($('#startdate').val().split('/')) || $('#startdate').val() == '') &&
 (new Date(row[1].split('/').reverse()) <= new Date($('#enddate').val().split('/')) || $('#enddate').val() == ''));
//bind 'from' / 'to' inputs
$('input[type="date"]').on('change', function(){
  if($(this).attr('id') == 'startdate') $('#enddate').attr('min', $(this).val());
  else if ($(this).attr('id') == 'enddate') $('#startdate').attr('max', $(this).val());
  dataTable.draw();
});
<!doctype html>

  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">

  from:
  <input type="date" id="startdate"></input>
  to:
  <input type="date" id="enddate"></input>

However, if, for some reason, you wish to keep your totals as a regular row on the bottom of
, you may change drawCallback to append totals row upon each redraw to secure totals row persistence, or attach id attribute to it and pass totals row through your custom filter.
If former is preferred, you may simply change drawCallback option (back to my example) for:
  drawCallback: () => {
    //append row to tbody and populate it with total cost
    $('#mytable #totals').remove();
    $('#mytable tbody').append(`<td id="totals" colspan="3" style="text-align:right"><b>Total cost:</b> ${$('#mytable').DataTable().column(2, {search:'applied'}).data().toArray().reduce((sum, item) => sum+=item, 0)}</td>`);
  }

If latter option is more suitable for you, and you construct your totals row with id="totals", the filter (again, back to my example) would look like (pay attention to the last row):
//custom date range filter
$.fn.DataTable.ext.search.push((settings, row, index) => (new Date(row[1].split('/').reverse()) >= new Date($('#startdate').val().split('/')) || $('#startdate').val() == '') &&
    (new Date(row[1].split('/').reverse()) <= new Date($('#enddate').val().split('/')) || $('#enddate').val() == ''))
    || $(dataTable.row(index).node()).is('#totals');


text:
Q: How to include excerpt in ul from different pages with the same parent - Wordpress I wish to get the title, the excerpt and some meta from three different pages that all have the same parent.
I do not wish to specify wich three pages to show but rather show the three that was last edited/published.
I aim to display the content as three blocks on a horizontal line.
As I was unable to get the code to work:

<?php query_posts("posts_per_page=1&post_type=page&post_parent=4"); the_post(); ?>

<img src="<?php echo get_post_meta($post->ID, "image", true); ?>" alt="<?php the_title(); ?>" />

<?php the_title(); ?>

<?php the_excerpt(); ?>

Thank you Dan, this still does not work though. The excrept of the first page does not show (the title shows and the meta also). Tried the code below with the same result except that the second time the content is displayed, the excerpt of the first page shows.
<?php get_header(); the_post(); ?>

<?php
$categoriesCF = get_post_meta($post->ID, "categories", true);
$allCategories = explode(",", $categoriesCF);
foreach ($allCategories as $category) {
$pieces = explode("|", $category);
$link = get_permalink($pieces[1]);
echo "
";
echo "
" . $pieces[0] . "
";
query_posts("posts_per_page=-1&post_type=page&post_parent=$pieces[1]");
while (have_posts()) : the_post(); ?>
<a href="<?php the_permalink(); ?>" class="product-jump" title="<?php the_title(); ?>" data-large="<?php get_post_meta($post->ID, "image", true); ?>">
<?php echo "ID, "image", true) . "' />"; ?>
<?php the_title(); ?>
<?php the_excerpt(); ?>
<?php endwhile; wp_reset_query();
echo "
";
};
?>

<?php get_sidebar(); ?>
<?php get_footer(); ?>`

A: Change posts_per_page to 3 and use orderby=date&order=DESC to get the 3 most recent.
If you are displaying this on a page that already shows some other post/page/posts/pages, use get_posts instead of query_posts.
The WordPress codex has full documentation and examples for all of these things:
http://codex.wordpress.org/Function_Reference/query_posts
http://codex.wordpress.org/Function_Reference/get_posts


text:
Q: String concatination for dynamically adding classes in View I am listing previously used shipping addresses for user to select. I`m dynamically adding classes

    <% @shipping_addresses.each do |address| %>
      <ul class=<%= "shipping_address_#{address.id}" %> >

<%= address['name'] %>

<%= address['street'] %>

<%= address['city'] %>

<%= address['country'] %>

<%= address['zip'] %>

<%= address['phone'] %>

    <% end %>

Problem is, that now I am trying to add a col-lg-3 bootstrap class to my ul`s, and it doesn`t work when I write it like this:
<ul class=<%= "shipping_address_#{address.id} col-lg-3" %> >

I get this output:

I also tried several different options and they don`t work.
Can anyone help?
Thank you

A: The actual html you are outputting is

And your browser is interpreting this as best it can. The quotation marks in your template never make it to the actual html because they're not actually part of the string.
You could do something like
<ul class="<%= "shipping_address_#{address.id} col-lg-3" %>" >

Although in my opinion you're now past the point where ERB gets difficult to read - you may wish to refactor this into a helper.


text:
Q: URL with trailing slash breaks layout - how can I fix this without using base tag? I am developing a website, and I have set up the following htaccess rules
RewriteEngine On
#RewriteRule ^([0-9]+)?$ index.php?page=$1
#RewriteRule ^([0-9]+)/([0-9]+)?$ index.php?page=$1&post=$2
RewriteRule ^([A-Za-z0-9-]+)?$ index.php?pagename=$1
RewriteRule ^([A-Za-z0-9-]+)/([A-Za-z0-9-]+)?$ index.php?pagename=$1&post=$2

This ensures that instead of http://www.mysite.com/index.php?page=2 showing the page
I get to use the friendlier method of http://www.mysite.com/about-us
* note I have not included a trailing slash.
In the page my css files are included as:
<link href="css/style.css" rel="stylesheet" type="text/css" />

and located at www.mysite.com/css/style.css
And this works well, however if I want to include a trailing slash (i.e. http://www.mysite.com/about-us/)
Then my css files do not load and I get an error where the Firefox source browser says:
The requested URL http://www.mysite.com/about-us/css/style.css was not found on this server.
This is because the page is determining about-us to be a directory instead of a page.
I am not keen to use the basehref tag like <base href="http://www.mysite.com/" />
Are there any other options?

A: Relative URLs are resolved from a base URL that is the URL of the document the relative URL is used in if not specified otherwise.
Now to fix this incorrect reference, you have two options:

*

*change the base URL using the BASE element,

*change the reference

*

*by adjusting the relative URL path to the base URL path, or

*by using just an absolute URL path, or

*by using an absolute URL.

Since you don't want to use the BASE element, you will probably need to adjust the URL you are using to reference the external resource.
The simplest would be to use the absolute URL path /css/style.css instead so that it is independent from the actual base URL path.


text:
Q: How to find the maximum on 3 or more arrays at each index So I am basically trying to get the maximum (minimum, or any similar opration for that matter) on 3 parallel numpy arrays for an image processing application.
The thing is, for given arrays:
a = [1, 2, 34, 5]
b = [3, 5, 6, 1]
c = [4, 62, 12, 6]

I want to obtain a similar array like:
maxArray = [4, 62, 34, 6]

in which each element is the maximum for the common index in the arrays.
There is an obvious approach with classic and naïve programming techniques but I am interesed in a vectorized way, since I just can't wrap my head around it.
Am I maybe thinking of this the wrong way? You tell me. Thanks before hand!

A: It will depend on the number and size of the arrays, but typically using functools.reduce together with np.maximum will be one of your best options, because it avoids array stacking which is comparatively expensive since it involves a full copy of all sub-arrays, but does use vectorized functions on the arrays we are given:
from functools import reduce
import numpy as np

# make example
N = 1000,
a,b,c,d,e = (np.random.random(N) for _ in "abcde")

# my proposal
def f_pp():
    return reduce(np.maximum,(a,b,c,d,e))

# @yatu's
def f_yatu():
    return np.max((a,b,c,d,e),0)

# @rusu_ro1 1st
def f_rr_1():
    return [max(x) for x in zip(a, b, c, d, e)]

# 2nd
def f_rr_2():
    return list(map(max, zip(a, b, c, d, e)))

# rusu_ro1 modified by pp 1st
def f_rr_pp_1():
    return [*map(max,a,b,c,d,e)]

# 2nd
def f_rr_pp_2():
    return np.fromiter(map(max,a,b,c,d,e),float,1000)

# timings and check
all_funcs = {k:v for (k,v) in globals().items() if k.startswith('f_')}
for k,v in all_funcs.items():
print(k,timeit(v,number=1000),'correct',np.all(f_pp()==v()))

Sample run:
# f_pp 0.012913539074361324 correct True
# f_yatu 0.025256304070353508 correct True
# f_rr_1 0.8206795542500913 correct True
# f_rr_2 0.7683364972472191 correct True
# f_rr_pp_1 0.7669085101224482 correct True
# f_rr_pp_2 0.7993066972121596 correct True

A: you can use:
1) applying max buil-in function over elements with common index in the arrays using zip inside a list comprehension:
[max(e) for e in zip(a, b, c)]

2) similar with :
list(map(max, zip(a, b, c)))

output:
[4, 62, 34, 6]

3) or @yatu suggestion:
np.max([a,b,c], axis=0)

output:
array([ 4, 62, 34,  6])


text:
Q: What are function epilogues and prologues? While reading some calling convention in some CPU architecture I read something like
"epilogue and prologue", when a function is called from another function.
What is a function prologue or epilogue?

A: Wikipedia FTW: https://en.wikipedia.org/wiki/Function_prologue
This seemed to explain it fairly well, in my opinion. If there is anything that is unclear, let me know and I can try and clear things up.

A: The epilogue and prologue of a function are simply the set of instructions that 'set up' the context for the function when it's called and clean up when it returns.
The prologue typically performs such tasks as:

*

*saves any registers that the function might use (that are required by the platform's standard to be preserved across function calls)

*allocates storage on the stack that the function might require for local variables

*sets up any pointer (or other linkage) to parameters that might be passed on the stack

The epilogue generally only needs to restore any save registers and restore the stack pointer such that any memory reserved by the function for its own use is 'freed'.
The exact mechanisms that might be used in a prologue/epilogue are Dependant on the CPU architecture, the platforms standard, the arguments and return values of the function, and the particular calling convention the function might be using.


text:
Q: Uneven line spacing in Beamer title page I have a custom title page for a Beamer presentation using the metropolis theme. Trying to set up two columns results in uneven line spacing in the right column.

Here's the MWE:
\documentclass[aspectratio=43,9pt]{beamer}
\usetheme[numbering=fraction,titleformat section=allsmallcaps]{metropolis}

\setlength{\leftmargini}{2ex}
\setbeamertemplate{itemize items}[circle]

\newcommand{\detail}[1]{%
  {\usebeamercolor[fg]{institute}#1}
}

\title[April 2020]{Terraform}
\subtitle{Module Architecture Proposition}
\date{Thursday, June 11th}
\author{Joey Dumont}
\institute[\textsc{Group}]{Group\\%
Branch\\%
Org%
}

\begin{document}

\begin{frame}[plain,noframenumbering,fragile]
  \begin{columns}[t]
    \column{0.45\textwidth}
    \insertauthor\par
    \vspace{-0.25em}{\scriptsize\detail{\texttt{<joey.dumont@org.ca>}}}\\
    \vspace{1em}
    \usebeamertemplate*{date}

    \column{0.45\textwidth}
    \usebeamertemplate*{institute}
  \end{columns}

\end{frame}

\end{document}

Any idea why this happens, and how I can fix it?