Speeding up my query using sql server 2008.Alternative to cross apply

Question: I have a function that is performing very slow.I am working a database that I need to migrate data and I have NO control over!.
Ideally I would like to use a view directly since this function is called by a view ,but I could only seem to be able to do it by calling a function.
===
A view should return whatever is in the dummytable by orderNo.If an orderNo has a paymenttype of "Interest" than the balance should be interest,if "tax" should be tax
In real life I will have 200000 rows and more,by using cross apply it seems to slow down quite a lot.
Is there a better way to get the data rather than using CrossApply?
Noddy Sample here(data and datatypes are just fictious for semplicity of the example)
CREATE DATABASE DummyDB
GO

use DummyDB
IF object_id(N'DummyTable', 'U') IS NOT NULL
DROP TABLE DummyTable
GO
CREATE TABLE DummyTable
(
Id int,
OrderNo varchar(255),
PaymentType varchar(255),
Credit varchar(255),
Debit varchar(255),
Balance varchar(255)
)
GO
INSERT INTO [dbo].[DummyTable]([Id], [OrderNo], [PaymentType], [Credit], [Debit], [Balance])
SELECT 1, N'200', N'Interest', N'10', N'5', N'5' UNION ALL
SELECT 2, N'201', N'Deposit', N'400', N'30', N'370' UNION ALL
SELECT 3, N'202', N'Tax', N'20', N'10', N'10' UNION ALL
SELECT 4, N'202', N'Tax', N'50', N'10', N'10'

--my sample attempt not performing

    use DummyDB
    select * from DummyTable

    Declare @OrderNo int
    set @OrderNo=202

    SELECT
    Tax=tx.Tax,
    Interest=tx1.Interest,
    Deposit=tx2.Deposit
    FROM DummyTable T1
    CROSS APPLY(SELECT
               Tax=sum(cast(T2.Balance as money))
               FROM DummyTable T2
               WHERE T2.OrderNo=@OrderNo
               AND  PaymentType='Tax')as tx
    CROSS APPLY(select
               Interest=sum(cast(T2.Balance as money))
               FROM DummyTable T2
               WHERE T2.OrderNo=@OrderNo
               AND  PaymentType='Interest')as tx1
    CROSS APPLY(select
               Deposit=sum(cast(T2.Balance as money))
               FROM DummyTable T2
               WHERE T2.OrderNo=@OrderNo
               AND  PaymentType='Deposit')as tx2

    WHERE T1.OrderNo=@OrderNo

    Any Suggestion of using something more efficient than cross apply?

    Many thanks

Answer: This will do almost the same as your sample query. It will give you one row with the result where your query will repeat the values for all rows that match @OrderNo.
select sum(case when T1.PaymentType = 'Tax' then cast(T1.Balance as money) else 0 end) as Tax,
       sum(case when T1.PaymentType = 'Interest' then cast(T1.Balance as money) else 0 end) as Interest,
       sum(case when T1.PaymentType = 'Deposit' then cast(T1.Balance as money) else 0 end) as Deposit
from DummyTable as T1
where T1.OrderNo = @OrderNo

BTW, you should make sure that the data type for OrderNo in the table is the same as the variable @OrderNo. It looks like you are dealing with integers so you should change the table. If that is not possible for you then you need to change @OrderNo to varchar(255) if you want to use an index on OrderNo.


Relating number of iterations to n

Question: n = length of list with more than n > 0.
index = 0
step = 1
while index < n:
    index = index + step
    step = step + 1
return
How many times will the loop iterate relative to n?
I have calculated the number of iterations based on n for the first 21 items, and I am failing to see a pattern. I
(n,#iterations) (1,1), (2,2), (3,2), (4,3), (5,3), (6,3), (7,4), (8,4), (9,4), (10,4)
I am looking for a way to determine the number of loop iterations given a number n.
Answer: Each pass through the loop, index becomes the next triangular number:  $1,3,6,10,15\dots$  On the $k^{\text{th}}$ pass, it is $\frac 12k(k+1)$  You are looking to solve $n=\frac 12k(k+1)$ for $k$ and round up.  It is a quadratic equation.
Answer: What if you had this code?

index = 0
step = 1
while forever:
    index = index + step
    step = step + 1
    print index
return

It would output: 1, 3, 6, 10, 15, ...
Lets call the sequence members above $s_i$ where $i$ is an index running from $1$ to $\infty$. So essentially you have to find a position in the above list such that in your code $n \le s_i$
If $n=1$, then this happens for $s_1$
If $n=2$, then this happens for $s_2$
If $n=3$, then this happens for $s_2$
If $n=4$, then this happens for $s_3$
Which is all consistent with what you found. So the key is to find an expression for $s_i$. I'll work out the case where $i$ is even, and let you work out the odd:
If $i$ is even then we're adding terms like $1 + 2 + 3 + 4$ for example. Group these as $(1+4) + (2+3) = 5 + 5 = 10$. You can do this in general and you'll have $i/2$ groups each adding to $i+1$ so $s_i = \frac{i}{2}(i+1)$. The argument for the odd case is similar.
Now using this information can you figure out how many steps will be required for length $n$? You'll probably have to use a floor or ceiling function.
Comment: What i'm trying to find is the Ω run time of the worst case behaviour of this algorithm. I thought being able to explicitly express the run time of the loop in relation to n would help with this. Although I am not sure, now... very confused.
Comment: The run time is proportional to the number of times you transverse the loop, so you're on the right track. The other answer made the next step more explicit, so try to apply that.
Comment: Okay thanks! Sorry for asking so many questions. I am slightly confused when you say "if n = 2, then this happens for s_2" isn't s_2 = 3, how would 2 >= 3?
Comment: Oh youre right i did it wrong
Comment: Okay sorry should have been n<=s_i
Comment: could I also say that for n = 4 it happens for s_3?
Comment: Yes Right again.

Relating number of iterations to n


Spring @Cacheable for methods with same signature

Question: I have a Spring bean that has a couple of finders with the same signature, like this:
<code>@Cacheable
public Player findById(int id) {
    // query player by id
    return player;
}

@Cacheable
public Player findByRank(int rank) {
    // query player by rank
    return  player;
}
</code>
The @Cacheable annotation treats both methods equal so this messes up the cache. Is there a way to tell Spring that the keys for those methods are not the same?
Answer: Maybe you can try this? Not sure whether it works..
<code>@Cacheable(value = "playerId")
public Player findById(int id) {
    // query player by id
    return player;
}

@Cacheable(value = "playerRank")
public Player findByRank(int rank) {
    // query player by rank
    return  player;
}
</code>
Comment: Yes, that works! I was hoping for a fool-proof solution, but this solves the problem for now.


In Bayonetta, how can you kill Umbran crows?

Question: So I'm staring at an Umbran crow right now, but I can't hit it. This is in chapter IV in a rainy square, while protecting Cervesa. Run at it, jump at it, shoot at it, I don't target the crow and can't hit it. What's the easiest technique to killing them?
Comment: You grab them, not kill them.
Answer: Found the problem by accident after running in circles 57 times. If you approach it from one direction, it flies away from you, making it really hard to catch. If you approach from the exact opposite direction, it flies right towards you, making it an easy kill. Solved!
Comment: If this solved your issue, don't forget to accept your own answer.


Storing jQuery objects using Object Literal pattern

Question: Is it possible to store jQuery objects inside Object Literal pattern? In my case inside config.
var myApp = {
    config: {
        disabledElem: $('.disable')
    },

    init: function () {
        someFunction(this.config.disabledElem);
    }
};

$(function () {
    myApp.init();
});

Comment: did you try it? what is the problem you faced?
Comment: as long as the jquery and element has already been loaded by the time this `myApp` is initialized, it will work.
Answer: Yes, you can absolutely store a reference as a value in an object literal.
Perhaps some of your confusion is how you are accessing this value in your init function.
Try something like this instead:
init: function () {
    someFunction(myApp.config.disabledElem);
}

Comment: `this` inside init method is already referring to myApp object
Comment: @A.Wolff but it's not clear from the question how the init function is being invoked so it's not clear what `this` will be during invocation
Comment: @Jonathan.Brink and how can I call the stored object inside the `config` ? For e.g. `disabledInput: disabledElem.closest('input')`
Comment: @Gabriel you mean the dom node? `$('.disable').get(0)`
Comment: @Jonathan.Brink Yes, the DOM node. Currently I have duplicated nodes:
`config: {
        form__internet: $('.form__internet'),
        fi__parent: $('.form__internet').closest('.fieldTypeINPUT')
}`
Comment: When I use it with `this`, `fi__parent: this.closest('.fieldTypeINPUT')`I get the `Cannot read property 'closest' of undefined` error.


How to mix multiple parent class constructors with val in child class

Question: Suppose I have a class Parent that has four fields A, B, C and D, such that C and D are optionally passed or initialized with default implementations:
open class Parent(val a: A, val b: B, val c: C, val d: D) {
    constructor(a: A, b: B, c: C): this(a, b, c, DImpl()){}
    constructor(a: A, b: B): this(a, b, CImpl(), DImpl()){}
}

I need to extend this class and add another field to the child class:
class Child: Parent {
     val e: E // How do I initialize this?
}

Passing a val to a secondary constructor doesn't work, and neither does using the init{} block.
Passing a val to the primary constructor could work, but then I lose the delegation to the secondary constructors in the Parent class - I need to use all the Parent constructor with all the params or duplicate the secondary constructors, leaking implementation details to the Child class.
This should be simple, am I missing something here?
Answer: If you do need to use secondary constructors, and can't use default values as suggested by @Ingo Kegel, you can initialize the e field just like you would do this in Java, by assigning the parameter value to the property:
class Child: Parent {
    val e: E

    constructor(a: A, b: B, c: C, d: D, e: E) : super(a, b, c, d) {
        this.e = e
    }
}

Comment: Actually, I can and will use both, but your answer hit the nail on the head for me. It turns out that the answer IS simple, I was just missing that (obvious in retrospect) piece of the Kotlin syntax.
Answer: You can use default values instead of secondary constructors:
open class Parent(val a: A, val b: B, val c: C = CImpl(), val d: D = DImpl())
class Child(a: A, b: B, val e: E): Parent(a, b)


Why are destructured environment variables undefined in Next.js?

Question: In my Next.js app I've created a .env file with a variable named API_KEY.
Destructuring the value results in undefined, as shown here:
const { API_KEY } = process.env; // = undefined
const key = process.env.API_KEY; // = 'value'

Can someone please explain why process.env isn't populated with the correct value here?
Comment: Remove the  ```{}``` and try again. ```{}``` are used when there are multiple imports
Comment: @HimanshuSaxena This doesn't explain why node result is undefined. This is es6 usage - using destructuring and otherwise works on everything else.
Comment: Can you show the actual code you tried? I mean you used some console.log, right? Or how do you know the api_key is undefined? Can you create minimal example which proves this?
Comment: Both lines should work the same. How exactly are you running this script? In what environment? How do you load the `.env` file? Are you using a transpiler/build pipeline?
Comment: @Bergi I am using Next.js. My console.log is in my react component.
Answer: From the docs:

Note: In order to keep server-only secrets safe, Next.js replaces process.env.* with the correct values at build time. This means that process.env is not a standard JavaScript object, so you're not able to use object destructuring.

and for client-side React components

The value will be inlined into JavaScript sent to the browser because of the NEXT_PUBLIC_ prefix. This inlining occurs at build time, so your various NEXT_PUBLIC_ envs need to be set when the project is built.


Separate code in ASP.NET

Question: Dear Stackoverflowers,
I am trying to build a simple web application in ASP.NET where I have a textbox and a button and when the button is pressed I should count the number of UPPERCASE-characters. I was thinking of trying to use a RegularExpression but i dont know how to separate it.
Now i have a .cs file that looks like this:
public static class TextAnalyzer
{
    public static int GetNumberOfCapitals(string text)
    {

    }
}

And a aspx.cs file that looks like this and is connected to my button.
protected void Button1_Click(object sender, EventArgs e)
    {
     //   Regex caps = new Regex("");
    }

Where do i put the regular expression? in aspx.cs or .cs? And at the samt time you can give me some other tips, im an absolute beginner and this is my first web page! Thanks in advance.
Answer: Why not call .ToCharArray on the string and use a bit of linq to count all characters where .IsUpper is true.
Answer: Something like this:
var NumOfUpper = (from c in text.ToCharArray()
                 where Char.IsUpper(c)
                 select c).ToList().Count();

Answer: Your code in the button-click event could look like this:
int capitals = TextAnalyzer.GetNumberOfCapitals(textBox1.Text);
//do something with 'capitals'

The code in the event could be like this:
public static int GetNumberOfCapitals(string text)
{
    return text.ToArray().Count(c => c.ToString() == c.ToString().ToUpper());
}

Answer: Here is sample console application which you can adapt for you web needs:
static void Main()
{
    Regex capitalLetters = new Regex("[A-Z]");
    string sampleString = "This is NOT a HellO WoRlD sample Applicati0N. OK?";

    var matches = capitalLetters.Matches(sampleString);

    Console.WriteLine("Matches count: {0}", matches.Count);

    Console.WriteLine("Press ENTER");
    Console.ReadLine();
}

This uses regular expression to count the number of upper case characters

Separate code in ASP.NET


How can I return and parse document returned from the Firebase server to the client?

Question: Foreword: I'm an iOS programmer diving into Node/JS. I created a https.onCall function as I need to perform multiple reads + writes. In the final update promise, I'd ideally like to return the data in a form that could be decoded into a DocumentSnapshot (as this is easily converted into a model), but I'm happy to just do what best practice is as well.
This is what the relevant piece of code looks like:
return group.ref.set({
  members: admin.firestore.FieldValue.arrayUnion(user)
}, { merge: true }).then(result => {
   // The additional `get` seems necessary because the completion block doesn't contain the updated document's data
   return group.ref.get().then(doc => {
     return doc
  })
})

I also tried returning return group.ref.get(), but both failed to parse on the iOS side:
// This fails to cast
guard let document = result?.data as? DocumentSnapshot else { return }

I was thinking this would be an alternative I can make work:
...
return {
  id: doc.id,
  data: doc.data()
}

And then manually decoding the JSON on the iOS side. But this feels very heavy-handed, and so I'm hoping someone can illuminate me with a more straightforward solution.
Answer: Callable functions do not receive or deliver strongly typed data.  Everything is boiled down to JSON, which is converted to the relevant low-level types on either end.
If you want to deliver a DocumentSnapshot from a callable function, you should minimally call its data() method to get a plain JavaScript object that is easily serialized, which is what your alternative is doing just fine.  Personally, I don't see this as "heavy-handed".  This is very typical data exchange between systems that don't share a sophisticated type serialization system.
Comment: Thanks, I needed the validation this is the right approach. Re heavy-handed: considering there are methods to get a document with a given reference, and using said document to easily initialize your own custom object, I was curious if there was a way to hook into those decoding methods. Worst case I can take a look at the source and implement a wrapper around my http request though. Appreciate your speedy reply!
Comment: For posterity, I did find a Firebase method exists to decode objects that can be reused: `Firestore.Decoder().decode(Model.self, from: data)`


How to open ConfusionMatrixChart from matlab workspace

Question: I have run a few models and I do not save any Confusion Matrix info. But, I have save entire matlab workspace. I need help to view Confusion Matrix chart.
I would like to view it like this

It seems when I double click at the confusion matrix chart it only open Property Inspector
Comment: I'm confused by this question. You *have* the matrix stored, as you mention in the text and show in the image. It's called `cm` in your workspace. What do you mean by "open" it? If you've got a single .mat file with all workspace variables, `my_workspace.cm` will be your matrix (if `my_workspace = load('my_workspace.mat')`).
Comment: @Adriaan I have no problem loading the whole workspace. The issue is when open the `my_workspace.cm` , its only appear the property inspector and not the matrix. I was looking for the matrix value, am I missing something?
Comment: It's a chart, which will open the property inspector. Calling `my_workspace.cm` in the command line will, presumably, result in a list similar to that of a figure handle. I don't know the specifics of this type of chart, but somewhere in that list should be your data.
Comment: Thanks @Adriaan, I think I got it , we need to call out _NormalizedValues_ which are stored within the chart.
Answer: You need to call NormalizedValues from ConfusionMatrixChart stored in workspace
Example:
ConfusionMatrix = cm.NormalizedValues

Comment: As a note especially for future questions where the code is much more relevant: Please [edit] your post to add code and data as text ([using code formatting](https://stackoverflow.com/editing-help#code)), not images. Images: A) don't allow us to copy-&-paste the code/errors/data for testing; B) don't permit searching based on the code/error/data contents; and [many more reasons](https://meta.stackoverflow.com/a/285557). Images should only be used, in addition to text in code format, if having the image adds something significant that is not conveyed by just the text code/error/data.


OpenGL old-style diffuse shading producing unexpected effects

Question: Question:
What is going wrong with the shape of the contours of constant illumination in the below picture ?
Detail:
Although Lambertian shading might be ill-regarded because it exposes the hard edges of our low-poly models, and because it models only "matte" surfaces, which it supposes reflect light equally in all directions (in particular, independent of the direction to the camera), yet I understand that it is considered a reasonably accurate approximation to how a single (hence no shadows, no illumination from light bouncing off surfaces and hitting other surfaces, no ambient occlusion etc) planar matte surface might look in space, say, illuminated by several lights which are either effectively infinitely far away (like the sun), or else nearby.
I would like to make the physically correct choice to have the surface normal vector constant across the surface of my triangle, that is, I do not want to use any of the various tricks that make the mesh look smoother, by averaging vertex normals over the triangles sharing the vertex, etc.
I believe that the intensity of incident light should decrease as the inverse square of the distance to the light (and therefore be effectively constant, for lights effectively infinitely far away, like the sun) ? But I am not sure. In any case, I would like to ignore this possible effect for now.
I would also like to ignore specular effects, whether produced by raising to some power, the cosine of the angle between the surface normal and the direction to the light, as in Blinn and Phong, or by more physically accurate models.
In spite of all these simplifications, I believe that I still must interpolate across the triangle, since the direction from the point on the triangle to the light source varies with that point (given that my light is not infinitely far away, but rather is quite close to the model). My understanding is that in world coordinates, it is mathematically correct to interpolate that cosine linearly between the 3 vertices, using for instance Barycentric coordinates.
My understanding of perspective projections is that linear interpolation in the world space becomes hyperbolic interpolation, after the perspective projection and w-divide transform coordinates into normalised device coordinates (NDCs). The GPU automatically uses such hyperbolic interpolation, for occlusion testing with the z-buffer, I believe. That is, it measures the reciprocal z at each vertex, and then for each pixel interior to the triangle, it linearly interpolates between those reciprocals, and takes the reciprocal of the result, to get a correct z value. Similarly, any quantity that varies linearly across the triangle in world-space must be treated the same way, once in NDCs.
In the picture below, I have a square made from two triangles joined along the top-left to bottom-right diagonal, lying in a horizontal plane. The camera is above the square, looking down on it, via a reversed-z, infinite far-plane, perspective projection matrix. I have a light source close to the plane of the square but just above it, and (as we look at it) off the bottom-right corner of the image. As expected, the bottom-right corner of the square is brighter than the top-left corner. Also as expected (if we look very carefully) we see faint Mach bands, due to the quantisation of colour and the characteristics of our eyes / brain.

I would expect the Mach bands to form concentric circles, being the level sets of the cosine mentioned above. Even without any explicit attenuation of intensity due to the distance to the light (see above). However, they do not, or if they do, then the centre of the circle is much farther away than the light source, and is different for the two triangles. It seems as if maybe something has gone wrong with the interpolation. Perhaps it is being done linearly instead of hyperbolically ? Even though Blinn explained this potential error in 1992:
Hyperbolic Interpolation - Jim Blinn
I am using the very old-fashioned, deprecated, (Immediate-mode ? Fixed Function ?) style of OpenGL. I am given to understand that by using the modern type of OpenGL, with shaders etc, I could specify the lighting more or less exactly as I would like. But I am trying to find out whether the model described above is achievable in the old-fashioned OpenGL. It seems as if it ought to be, since even that kind of OpenGL was capable of techniques fancier than Lambertian shading, for instance, specular lights.
Here are some of my settings:
<code>GLfloat light0_position[] = {800.0f, 0.0f, -(float)screendistmm + 800.0f, 1.0f};
GLfloat light0_diffuse[] = {1.0f, 1.0f, 1.0f, 1.0f};
GLfloat light0_specular[] = {1.0f, 1.0f, 1.0f, 1.0f};

glLightfv(GL_LIGHT0, GL_POSITION, light0_position);
glLightfv(GL_LIGHT0, GL_DIFFUSE, light0_diffuse);
glLightfv(GL_LIGHT0, GL_SPECULAR, light0_specular);

glShadeModel(GL_SMOOTH);

glEnable(GL_LIGHT0);

glEnable(GL_RESCALE_NORMAL);
glEnable(GL_NORMALIZE);

// Enable gamma-correction:
glEnable(GL_FRAMEBUFFER_SRGB);

glEnable(GL_LIGHTING);

glBegin(GL_TRIANGLE_FAN);

     GLfloat colour[] = {1.0f, 0.5f, 0.5f, 1.0f};
     glMaterialfv(GL_FRONT, GL_DIFFUSE, colour);
     glNormal3f(0.0f, 1.0f, 0.0f);

     glVertex4f(-500.0f, -200.0f, -500.0f - (float)screendistmm, 1.0f);
     glVertex4f(-500.0f, -200.0f, 500.0f - (float)screendistmm, 1.0f);
     glVertex4f(500.0f, -200.0f, 500.0f - (float)screendistmm, 1.0f);
     glVertex4f(500.0f, -200.0f, -500.0f - (float)screendistmm, 1.0f);

glEnd();
</code>
Comment: I am not familiar with deprecated opengl so I can't comment on that part. Ignoring the specifics of opengl for a directional light you should get a constant colour and for a point light you should get the radial attenuation you're looking for.
Comment: Maybe it's using Gouraud shading instead of Phong shading which causes said issue.
Comment: Immediate mode rendering is like a box of chocolates, you never know what your gonna get.
Comment: Thank you - that is reassuring ! The "wrong-looking" attenuation in the image above makes the top-left to bottom-right diagonal of the square, which is a "seam" between two triangles, brighter than it ought to be. I feel that excessive brightness along mesh seams is an error that I've seen before.
Answer: As far as I remember, without a fragment shader the shading is only evaluated at vertices then interpolated. Try subdividing the mesh.


Template typedef of a template

Question:
Possible Duplicate:
C++ template typedef

I am trying to derive a template type of another template by pre-specializing of another template:
template<unsigned a, unsigned b, unsigned c>
struct test
{
    enum
    {
        TEST_X = a,
        TEST_Y = b,
        TEST_Z = c,
    };
};

template<unsigned c>
typedef test<0, 1, c> test01;

However, on GCC 4.4.5, I am getting this error: error: template declaration of 'typedef' on the second type (test01).
Guidance would be highly appreciated, as I don't understand what is wrong with my code.
Comment: I know this is a duplicate, but I can't find it. EDIT: Aha, [here](http://stackoverflow.com/questions/2795023/c-template-typedef).
Comment: When you look at the duplicate, note that in that particular case the user did not want to use inheritance, even if that was a common pattern for C++98 compilers: `template  struct test01 : test<0,1,c> {}` There is a slight difference, as you are adding inheritance to the mix and that has some pitfalls (beware: do not delete the type through pointers to `test<0,1,N>` as that will cause UB, always destroy at the `test01` level)
Comment: Please use the search next time
Answer: This syntax isn't allowed by C++03. The nearest work-around is:
template<unsigned c>
struct test01
{
    typedef test<0, 1, c> type;
};

typedef test01<2>::type my_type;

In C++0x, we can do this:
template<unsigned c>
using test01 = test<0, 1, c>;

Comment: It's so sad that templatetypedefs are illegal. ;-)
Comment: Damn you C++03!!! and damn you C++0x for not coming already! Thank you for clarifying this.
Comment: @templatetypedef: Then what are you doing here? ;)
Comment: @templatetypedef : I knew you were illegal; thanks for admitting so :P
Answer: Just for the sake of listing an alternative:
template <typename C>
struct test01 : test<0, 1, C> { };

test01<4> my_test014;

This does create new, distinct types and not simply aliases for instantiations of the base template :-(.
Comment: Sadly it doesn't guard against: `test<0, 1, 2>* x = new test01<2>(); delete x; // oops, UB!`.
Comment: @GMan: obviously true if you don't bother to put a `virtual` destructor in `test<>` (same old issue as derivation from Standard containers, and practically irrelevant in my experience and coding style, but everyone lives by the concerns that seem significant to them...)
Comment: Since I am doing mostly template meta-programming, this is fine by me. However, I do understand the difference.
Comment: Does not work for #include
template
struct MyShared : public std::shared_ptr{};
Comment: @Cobala: it I was inclined to put as much effort and detail into this comment as you did for yours, I'd just say "you're wrong", but to be more constructive ;-P... here's [an ideone example](http://ideone.com/7yN8hO) proving it "works", but more seriously you probably want to add a convenience function or two - e.g. at least constructor forwarding ala `using std::shared_ptr::shared_ptr;` inside `MyShared`.  Cheers.

Template typedef of a template


regular expression for finding and replacing variable URL strings in XML

Question: I'm having some difficulty figuring out a regular expression for stripping part of the string within a particular XML tag and replacing it. I have a number of URL paths with variable parts, so I need to find everything between a certain string and the last slash in the URL. For example, I might have tags and URLS that look like this:

<bpoc:resourceMetadataLoc>http://app01/media/images/I//1951-1960_Embark_Object_Photos/1957.59.jpg</bpoc:resourceMetadataLoc>

or

<bpoc:resourceMetadataLoc>http://app01/media/images/CONTEMPORARY/1986-2005/1991.2.jpg</bpoc:resourceMetadataLoc>

The output should look like

<bpoc:resourceMetadataLoc>http://app01/media/Previews/1957.59.jpg</bpoc:resourceMetadataLoc>

This is about as far as I got, but it captures the last slash in the string, and not the second-to-last slash:

(<bpoc:resourceMetadataLoc>http://app01/media/images)+(.*[/])

That regex will capture the following:

<bpoc:resourceMetadataLoc>http://app01/media/images/I//1951-1960_Embark_Object_Photos/1957.59.jpg</

What would I need to add to the regex to exclude the </bpoc:resourceMetadataLoc> bit from the query and then capture everything prior to the last slash in the URL?
Comment: +1 for a well-posed regex question!
Answer: Because this is XML, there can't be a (non-escaped) < or > in the URL itself. You can use this to your advantage:
<bpoc:resourceMetadataLoc>http://app01/media/images[^<]*/([^<]*)

This should capture the last segment (e.g. "1957.59.jpg") of the URL. It works by greedily matching everything up to the start of the end-of-tag (the first [^<]*), then backtracking to match the nearest (i.e. last) /, then capturing everything after that slash (the ([^<]*)) into group 1 so that you can use it during the replacement step.
Comment: Hi @Cameron: Thanks so much for your response! You're my personal hero for the day. Since the replacement string is consistent, I ended up with the following: FIND: http://app01/media/images[^<]*/

replace with:

http://app01/media/Previews
Comment: @Isara: No problem :-) Side tip: You can surround the URLs in your comment with backticks to give them code-formatting so they aren't auto-converted into links.
Comment: clearly I'm not a coder. Markdown and regex makes my head hurt! ;)


tensorflow: how to implement this complex mask operation

Question: I have a tensor t1(rank 2) with shape [batch_size, data_size] as below:
|---------------|--------------|--------------|
|      1.0      |     2.0      |     3.0      |
|---------------|--------------|--------------|
|      4.0      |     5.0      |     6.0      |
|---------------|--------------|--------------|
|      7.0      |     8.0      |     9.0      |
|---------------|--------------|--------------|

and a indicator tensor t2(rank 1) with shape [batch_size] like this:
|---------------|--------------|--------------|
|      2        |     1        |     3        |
|---------------|--------------|--------------|

i want to implement a function(t1, t2) to output:
|---------------|--------------|--------------|
|      1.0      |     2.0      |     0.0      |
|---------------|--------------|--------------|
|      4.0      |     0.0      |     0.0      |
|---------------|--------------|--------------|
|      7.0      |     8.0      |     9.0      |
|---------------|--------------|--------------|

it looks like multiplying t1 with a mask defined by t2, but i cannot figure out how to implement that.
Answer: I think you are looking for tf.sequence_mask. See here. This basically implements creating the mask you are wondering about. Usage as follows:
mask = tf.sequence_mask(t2, dtype=tf.float32)
result = t1 * mask

If dtype is not given this would create a boolean mask which would likely result in problems when trying to multiply with t1, which is why we specifically ask for float32.
In case the maximum element in t2 can be smaller than data_size, you should use
mask = tf.sequence_mask(t2, maxlen=data_size, dtype=tf.float32)

to prevent a shape mismatch between t1 and mask.


Error while installing DaVinci Resolve version 17.4.6 on Ubuntu 20.04.4

Question: I got an error while installing DaVinci Resolve 17.4.6 on Ubuntu 20.04. After running MakeResolveDeb 1.6.0 I got this error.
MakeResolveDeb 1.6.0
Detected DaVinci Resolve version 17.4.6
Checking for tar...found!
Checking for fakeroot...found!
Checking for dpkg-deb...found!
Using Resolve 17 conversion process
Extracting archive
Found 2876 objects
Adding BlackmagicRAWPlayer
Adding BlackmagicRAWSpeedTest
Creating Debian package
**dpkg-deb: error: control directory has bad permissions 777 (must be >=0755 and <=0775)**
[DONE] errors reported 1

Answer: I've finally figured out how to make this work repeatedly on Ubuntu 22.04.2 LTS without workarounds.
You need to first update your Nvidia drivers directly from Nvidia.
There are a bunch of dependencies missing from Ubuntu 22.04.2 LTS that prevent Resolve's installation. Here's how fix that.
First, run:
sudo apt install libfuse2

Then:
sudo apt install libapr1
sudo apt install libaprutil1
sudo apt install libxcb-composite0

Then:
sudo apt install libxcb-cursor0
sudo apt install libxcb-damage0
sudo apt install libxcb-xinerama0
sudo apt install libxcb-xinput0

Then open a console in your unzipped resolve folder and install as normal.
This works without black screens or other errors.
Comment: Did you know that you don't need to run `sudo apt install` over and over again if you need to install multiple packages? You can just list multiple packages, like this: `sudo apt install package1 package2 package3` and so on. Also, it's important to always run `sudo apt update` and `sudo apt upgrade` to ensure the system is up-to-date before attempting to install new packages.
Comment: Finally, the advice *"You need to first update your Nvidia drivers directly from Nvidia"* - is really not recommended. The drivers that are posted on Nvidia's website are not tested  to work with Ubuntu. Installing Nvidia drivers this way also sidesteps your package manager. This makes it likely that problems will arise in the future when other updates break dependencies. Having installed the driver this way may have caused the original problem to begin with.


go build does not compile local changes into main

Question: I am relatively new to go, and I am having some trouble with the go build system.
GO Environment:
(base) ngadre-mbp:github.com ngadre$ go version
go version go1.14.5 darwin/amd64

(base) ngadre-mbp:github.com ngadre$ go env
GO111MODULE=""
GOARCH="amd64"
GOBIN=""
GOCACHE="/Users/ngadre/Library/Caches/go-build"
GOENV="/Users/ngadre/Library/Application Support/go/env"
GOEXE=""
GOFLAGS=""
GOHOSTARCH="amd64"
GOHOSTOS="darwin"
GOINSECURE=""
GONOPROXY=""
GONOSUMDB=""
GOOS="darwin"
GOPATH="/Users/ngadre/Desktop/Workspace/go"
GOPRIVATE=""
GOPROXY="https://proxy.golang.org,direct"
GOROOT="/usr/local/go"
GOSUMDB="sum.golang.org"
GOTMPDIR=""
GOTOOLDIR="/usr/local/go/pkg/tool/darwin_amd64"
GCCGO="gccgo"
AR="ar"
CC="clang"
CXX="clang++"
CGO_ENABLED="1"
GOMOD=""
CGO_CFLAGS="-g -O2"
CGO_CPPFLAGS=""
CGO_CXXFLAGS="-g -O2"
CGO_FFLAGS="-g -O2"
CGO_LDFLAGS="-g -O2"
PKG_CONFIG="pkg-config"
GOGCCFLAGS="-fPIC -m64 -pthread -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -fdebug-prefix-map=/var/folders/5g/59l0__050lg6p4hv1wv7mhw40000gn/T/go-build110012391=/tmp/go-build -gno-record-gcc-switches -fno-common"

My directory structure is as below:
pwd: /Users/ngadre/Desktop/Workspace/go/src/github.com
.
├── coredhcp
│   ├── LICENSE
│   ├── README.md
│   ├── cmds
│   │   ├── client
│   │   ├── coredhcp
│   │   └── coredhcp-generator
│   ├── config
│   │   ├── config.go
│   │   ├── config_test.go
│   │   └── errors.go
│   ├── go.mod
│   ├── go.sum
│   ├── handler
│   │   └── handler.go
│   ├── logger
│   │   └── logger.go
│   ├── plugins
│   │   ├── dns
│   │   ├── example
│   │   ├── file
│   │   ├── leasetime
│   │   ├── nbp
│   │   ├── netmask
│   │   ├── plugin.go
│   │   ├── range
│   │   ├── router
│   │   └── serverid
│   └── server
│       ├── handle.go
│       └── serve.go
├── go-immutable-radix
│   ├── CHANGELOG.md
│   ├── LICENSE
│   ├── README.md
│   ├── edges.go
│   ├── go.mod
│   ├── go.sum
│   ├── iradix.go
│   ├── iradix_test.go
│   ├── iter.go
│   ├── node.go
│   └── raw_iter.go

Both the projects "coredhcp" and "go-immutable-radix" I have cloned using git clone
I did some changes to the "go-immutable-radix" project and added logs, however, I am not able
to build my local changes into the "coredhcp" project which uses this "go-immutable-radix" project.
go build cmds/coredhcp/main.go

Any suggestions how I can compile local changes in "A" project into "X" project through go build.
Answer: If you have a locally cloned version of another go module, use the replace directive in the go.mod (the go.mod for the coredhcp package) to point the local copy:
replace github.com/.../go-immutable-radix => ../go-immutable-radix


Scene2d vs Sprites

Question: So I am currently designing a game where the main idea is that you choose your attack and then an animation plays out based on the attack that you picked (think pokemon). The game is turn-based as well.
My question is whether scene2d would be easier to use than implementing a custom solution for handling the animation part of the game. From what I've read (and I've found it difficult to find good information on scene2d), it sounds like scene2d would make designing the UI for the buttons/menu extremely easy, but I'm not sure how I can roll that into making the actors move. Is it as simple as handling the touch event on the button and calling the corresponding actor's action method based on the player's choice?
In what I have in mind, the actors never actually move (except during their animation and they don't move across the screen, they merely go through their animations in place). During the animation, there will also be particle effects (the attack) which, if using scene2d, would need to be their own actors. Would the synchronization of the actors and the attack be difficult to produce?
Answer: Actors do movee..
actor.addAction(Actions.moveTo(posX, posY, 5)));

by this your actor moves to posX, posY and 5 is the time duration ..
using scene2d would be a good idea in my opinion..
Comment: I know that actors move, but that is not what I am trying to accomplish. My actors are simply going through 4-6 frames of *action* (performing the attack animation). I am wondering if scene2d is appropriate to use here or if it would be easier a different way.
Answer: Scene2D would be better since you would have to manually implement the listener for actions such as Click when you use Sprite whereas Scene2D provides the functions to set Listeners.
Answer: you may already know this, but let me try to answer your question:
Scene2d has a very handy action system, which basically allows the following:

do any of the provided actions
fine tune them with the many provided interpolations
make new actions with Actions.run()
chain existing actions forming sequences

Like this:
import com.badlogic.gdx.scenes.scene2d.actions.Actions;
import com.badlogic.gdx.scenes.scene2d.Action;
Action a1 = Actions.sequence(Actions.fadeOut(0), Actions.fadeIn(3, Interpolation.bounce));
Action a2 = Actions.moveTo(100, 200, 3, Interpolation.pow2Out);
Runnable r = new Runnable() {
    @Override
    public void run() {
        setColor(1, 0, 0, 1);
        System.out.println("now I'm a red actor");
    }
};

And then combine then, for example like this:
addAction(Actions.sequence(Actions.parallel(a1, a2), Actions.run(r)));

This allows you to profit from scene2d's built-in sequencer saving you the half of the work, at least. So, answering your question, I think it is very possible indeed to easily implement fixed as well as reactive/randomized animations using this system. It also allows you to easily encapsulate simpler actions into complexer ones, and has the following advantages:

Very readable and maintainable code
Tradeoff CPU/Mem: much more memory-efficient than storing plain sequences or even videos
Reactivity: this way you can program your animations to be slightly different each time

On the other hand, this developing system can become very time consuming if you constantly want "uncovered" things, like the following:

Implement time-based actions yourself that aren't built-in (like camera travelling)
Make your own interpolations if the built-in ones don't fit your goals
Work with many little granular elements (for that sake I would use the ParticleEditor).

Which I don't think is your case. As a last remark, you should take a look at the spine animation engine. I don't use it myself but may be useful for what you have in mind.

Scene2d vs Sprites


Set value to input type checkbox with JQuery

Question: I am using Spring MVC to create a checkbox like this:
<form:checkbox id="idVerifiable" path="verifiable"/>

It generates me:
<input id="idVerifiable" type="checkbox" value="false" name="verifiable">

If I try:
$('#idVerifiable').val("true");

It sets the value but the checkbox is not checked, how to change this to make it work?
Answer: $('#idVerifiable').prop("checked", true);

Comment: @Jim Bolster glad I could help.
Answer: Try this,
$('#idVerifiable').attr("checked", true);

or
$('#idVerifiable').prop("checked", true);

Answer: You could do this:
$('input[name=verifiable]').attr('checked', true);


Circuit with GFCI/CAFGI breaker trips on a branch that turns off

Question: Scenario: GFCI/CAFGI circuit with a branch that is set up as: breaker then switch then light 1 then light 2. Light 1 has a socket on it already. Switch is in a box that contains switches for all the other branches on this circuit.
Situation: Breaker is on. Turn off the switch (open it). There is theoretically no power to light 1 or light 2. Squeeze the 12G wire that leads to light 2 with electrical pliers but without nicking anything.
Result: The breaker trips.
I looked at this AFCI Circuit Breaker trips after turn on any light on different circuit
Could it be a variation on that problem?
Comment: Which kind of breaker do you have? Some have a way of telling you the cause of the trip (ie ground, arc, or over-current fault). If yours do support diagnostics, try that, and tell us what was the cause of the trip.
Comment: GFCI/CAFGI Square D breaker. The kind with the purple button.
Keep in mind that it's very mysterious that there is no current in the cable we squeeze, but it manages to trip the breaker.
We squeezed the cable in preparation for stripping the wires down so we could attach the light socket.

Also, we did a reading with a multimetre - no current
Comment: Another point: after the wiring for this lighting branch leaves the box that has the switch, it goes through a box that is also used by a different circuit. There is absolutely no sharing of grounds or neutrals or anything like that going on. The wiring for the lighting branch is actually two lengths of cable, joined with wire nuts inside that second box.
Comment: Are you checking to make sure the box is de-energized to work in it? Do you only have to turn off one breaker, or more than one?  Google "Time Saver Diagnostics Square D" to get the 411 on getting the breaker to tell you the reason for the trip.  You need a stopwatch, or the ability to actually distinguish 2 seconds vs 5 seconds.
Answer: The only thing I can see that would cause this would be if the insulation on the neutral wire is degraded so that when squeezed, the neutral conductor contacts the (presumed bare) ground conductor.
Even though the hot is interrupted by the switch, the neutral and ground conductors are still connected to the rest of the circuit. The  momentary paralleling of the neutral and ground would be detected as a ground fault by the GFCI breaker.
You can verify this by disconnecting the neutral or ground to be cable and checking that this doesn't happen.
I'd recommend replacing the cable.
Comment: We did the test and it flipped immediately. What a great feature that is. And I think that jives with what DoxyLover says. So we will replace 1 the wire (she said, with a sinking heart) and see if that works. I'll report bback


How to understand the branch of a complex function is not defined at a point?

Question: I saw an exercise which asks to solve the integral $\int_{-1}^1 z^idz$, where $z^i = \exp(iLog(z))$ $(|z|>0, -\pi <Arg(z)<\pi)$. The solution says an antiderivative of this branch cannot be used since the branch is not even defined at $z=-1$. Then they replace the integrand by the branch $$z^i = \exp(i\log z)$$ where $|1+iz|>0, -\pi/2 <Arg(z)<3\pi/2)$

Question: what does it mean by the branch being not defined at $z=-1$? Does it mean that $Log(z)$ is not differentiable at $z=-1$? I know the branch cut of $Log(z)$ is the non-positive real axis.
Answer: Well, here they decided to use the branch which is the non negative real axis. And yes, if you choose this branch then you can't define logarithm on the negative real axis in a continuous way. In the points which are just above $-1$ (by above I mean the points near $-1$ which are in the top half of the complex plane) the argument is very close to $\pi$, at the points which are just below $-1$ the argument is very close to $-\pi$. So no chance to define $Log(-1)$ in a continuous way. And if a function is not continuous at a point then of course it can't be differentiable there.
Comment: Exactly the condition that I wrote-if we can't define it in a continuous way. If we choose the branch $-\pi<arg(z)<\pi$ then the domain of the branch is $\mathbb{C}\setminus (-\infty,0]$. If the branch is $0<arg(z)<2\pi$ then the domain is $\mathbb{C}\setminus [0,\infty)$. These are the two most common branches, though there are infinitely many.
Comment: Under which condition, do we say the branch is not defined at $z=-1$?


How to call completionHandler for performFetchWithCompletionHandler in Swift

Question: how can I call the completion Handler for the background fetch in Swift. I do the following:
func application(application: UIApplication,
    performFetchWithCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {

    // Do something

    completionHandler (UIBackgroundFetchResultNoData) // This does not work :(

    return

}

Can you please help me? Thanks,
Tobi
Answer: The enum case is UIBackgroundFetchResult.NoData, so the correct way is:
completionHandler (UIBackgroundFetchResult.NoData)

or even:
completionHandler (.NoData)

because the type can be inferred from the closure signature
Hint: when unsure about a function signature, or enum cases, etc., in Xcode write the type, in this case UIBackgroundFetchResult, and then cmd+click it to go to the definition, or option+click to popup its declaration. That usually helps a lot.
Comment: Oh man in the Documentation it looked like the cases were used without the point. Thank you!


Standard uses of USB if Ubuntu is installed

Question: I've learnt how to install ubuntu on USB drives. In the tutorials, they say that I have to partition my USB drive. I wonder if I can still use my USB for standard uses? (like storing data)
Note: I would like to install ubuntu on my USB, not live boot using it.
Comment: Short answer: No.
Comment: Yes, you can make the first partition Fat32 or NTFS which will allow sharing files between a Windows computer and the Full install USB drive. The USB drive can still be used for storing and transporting files.https://askubuntu.com/questions/1119700/how-to-fully-install-ubuntu-on-usb-flashdrive/1119713#1119713 and https://askubuntu.com/questions/873004/ubuntu-on-a-usb-stick-boot-in-both-bios-and-uefi-modes/1118412#1118412
Comment: C.S.Cameron, can you explain more about that please? I am totally a beginner.
Comment: Basically you will have partition for ubuntu, not taking whole usb space, and partition to store data - fat32 or ntfs - so it will be accessable in windows and ubuntu.
Comment: @user9989615: Please comment if any explanation is needed in the answer below. I you use Windows you may need to install **mkusb** to and run it from a live or persistent thumb drive made using UNetbootin or Rufus..
Comment: Thanks guys, I think I know what to do now. I am trying it soon.
Answer: Full Install to USB - BIOS/UEFI
If you plan on using your bootable USB on various computers it should boot on both BIOS and UEFI computers.
It is also good if there is a common partition on the drive that the various computers can access.
If Apple is involved the partition should be FAT32, if the drive is over 32GB the drive FS should be NTFS.
Mkusb makes a great base for a Full Install USB drive able to boot from both BIOS and UEFI:

Use mkusb to make a Live system on the Installer USB (2GB or larger).
Use mkusb to make a Persistent system on the Target USB using default settings with ~25GB persistence if available, (remaining NTFS partition is used as Windows accessible data partition).

As soon as mkusb finishes, open GParted and delete sdx4, the ISO9660 partition and expand sdx5 into the recovered space, (sdx being the device name of the Target drive).

Create a extra ext4 partition sdx6 for /home if a separate home directory is desired, (Optional).

Unplug or remove HDD before proceeding further, (optional but recommended, highly recommended in UEFI mode).
Boot Installer drive, select Try.
Insert Target drive
Start Install Ubuntu...
Select "Something else".
Select sdx5, (on the target drive), and click Change.

Select Use as: ext4, Format and Mount point: /.

Don't touch any other partitions (unless adding an optional /home partition to sdx4).

Select sdx5 as Device for boot loader installation.
Complete installation.
Cut or copy grub.cfg from sdx5/boot/grub and paste to sdx3/boot/grub, overwriting the existing grub.cfg file.
Boot the target drive and run sudo update-grub to add all drives to boot menu.
Do not install any propriety drivers, (ie Nvidia), on pre-18.04 installs.
Comment: Well, I still have a question. I saw people install the ubuntu .iso file in a USB and it will be able to boot. Then what is the use to install Ubuntu on the USB?
Comment: @user9989615: A Full install Boots faster than an ISO file, it is more Stable, it is Updateable and Upgradeable, has better Security and Security options, you can use Proprietary drivers with it, (Nvidia), It has Unlimited "Persistence", and Hibernation works. However a Full install does not work as a installation USB. See: https://askubuntu.com/questions/156026/difference-between-livecd-liveusb-full-install-and-persistence/396219#396219


can this antique douglas fir floor be saved?

Question: I bought a 100+ plus house and to my horror, under the carpet was not the strip hardwood floor we expected, but particleboard. Not OSB, not plywood - particleboard (which I just learned would need to be replaced anyways with plywood if new flooring going on top).
BUT! Under the particle board are very old wood planks! They're 5" t&g douglas fir (I think) and they look like they've never been sanded once. There's an old varnish or shellack finish (except for in the middle of the room where a rug must have been) so they where not installed as just subflooring.

They're awesome! But.. they're plenty soft, gaps as big as 1/4", plenty of damage and splinters, tons of nail holes, a large section by the front door was replaced with pine, etc. And here's the biggest problem maybe: there's no subfloor underneath them!
However I don't think they're worn badly at all and we're intent on restoring and using them, even if that means pulling them up and flipping them over to the unused side. It's only in one small room -- about 300 sq ft -- but it's the living room and the heart of the house. And we're on a major budget and new flooring is expensive, less sustainable than reclaimed, and not as cool :).
What do you recommend? Should I sand them with a drum sander or just a DA sander? Or would a DA sander catch splintered edges and rip out large sections? What finish do you recommend? Poly or a hard wax like rubio monocoat? What about wood filler? Any other tips??
Thanks! (BTW, I will NOT accept NO for an answer!)
[UPDATE: we sanded finished them: http://dannix.net/lib/abode/floor ]
Comment: From Google http://ths.gardenweb.com/discussions/2444999/anyone-using-a-fir-subfloor-as-a-primary-floor.
Comment: Are these planks at 45 deg to the walls in the house or parallel to some and perpendicular to others?
Comment: Where is this house and what are the climate and soil conditions?
Comment: @JimStewart no they're not at 45 degree angle, and they're above an unconditioned cellar. It's on NE Kansas in the Kansas River Valley "river bottom land" with excellent, very deep, well-drained, moderately permeable soils that formed in silty or loamy alluvium a.k.a. silt-loam a.k.a. awesome soil for gardening but causes high humidity in the cellar bellow the wood flooring in question :)
Answer: It is totally feasible to do this. Just a lot of hard work.
We redid a laundry room that had a worn painted outdoor porch floor (the house is from 1869 and has been organically growing for 150 years). Tongue in groove. Fir, we think. We pulled up the boards carefully, removed the nails, hand scraped the edges, (which had been coated with paint and would prevent close reassembly), put in a subfloor and then reassembled the porch floor over it. We then sanded it down (no drum sander -- too small an area and too hard to control). It is finished with a good satin poly, three coats. We left it a bit rustic.

You do need a subfloor for strength, to prevent flex and to minimize airflow from below.
You are likely to have a few damaged boards, so you may need to rearrange the pieces to compensate. This will leave you short several board feet, so you may need to use a border of new wood around the edges to fill in. Small holes can be left open or filled, depending on your taste.
Comment: @JamesOlson I actually like the broad end of a catspaw for lifting. It's a good size and a shallow leverage. I agree on the nail lifting approach. I usually use a carpenter's hammer - less curve for a slower pull and I put a shim under the head to reduce the chance of marring.
Comment: You probably need to cut through the ends with a multitool unless the ends of the boards are free after taking off a floor cap molding.
Comment: I would just add: if one uses wedges to pry the face-nailed boards up just ~3/8" then let down again, the nail head would protrude for use of a claw hammer; pry up each board, gradually, along each point held down by a nail to prevent cracking. Pry up the groove side of board first; the tongue will pivot within the groove.  Oh, start at wall furthest from room's exit, lol.
Comment: @JamesOlson Excellent technique advice. Also could use a small catspaw prybar to gently lift the boards.
Comment: thks, I though of including mention of catspaw but I like the pry radius of a claw hammer better.  Also, I don't like the flex of a catspaw as it stores kinetic energy and then *thwack* knuckles hit the floor.
Comment: So we will absolutely have to pull up the boards? I understand the advantage of putting a plywood subfloor under them but digging nails out easily dents the soft fir wood. I guess that's the reason for the advice givin to pry up the board first, lifting the nails enough to get a craw hammer under the nail. Thanks!
Comment: BTW the boards are very long, many of them are the length of the room! (24').
Comment: @bib, oh, you were referring to the catspaw to lift the boards. I was thinking you were referring to using it to pry up the nails.  I use wedges by tapping each one a little, then moving to the next wedge, etc. then returning to the first, tap it some more, move on, etc.  This ensures both sides of the T&G are as pristine as possible (so I can turn a bad one over).
Answer: Old post here but if anyone else is considering this. I recommend not even bothering to pull the floors. If you have a crawl space underneath, encapsulate it instead to prevent draft, make the house more efficient, and promote airflow from below (you want this as you allow a bit of heat to go into the encapsulated space.
Any gaps can be filled with filler wood or wood filler. Then you can just sand the boards as is, stain, and clear.
Comment: Any areas with flex can be fixed with sistered joists.
Answer: I had the same, sanded down in place, refinished with poly, insulated under floor, filled gaps with a complimentary color big stretch and looks beautiful.  Old growth Douglas fir, but concerned about hardness, but held of for two years great so far.
Comment: Welcome to [diy.se]! Would you please [edit] your answer to explain what "big stretch" means in "filled gaps with a complimentary color big stretch".


string with whitespace at struct - dont work

Question: pls can you explain why example1 is not working and example2 works? Or explain how can I put character with whitespace to string used in struct? I am beginner at programming C, in other problems I was able to find solution but in this case I do not really know :(
example1 (there not working whitespace string):
#include <stdio.h>

struct string {
    char word[20];
    char sentence[100];
} s;

int main() {

printf("Enter word:\t");
scanf("%s", s.word); //1st input without whitespace

printf("\nEnter more words with whitespace:\t");
scanf("%[^\n]s", s.sentence); //2nd input with whitespace - not working

printf("\nWord is: %s", s.word); // 1st input printed (OK)
printf("\nSentence is: %s \n", s.sentence); // 2nd input not printed (NOT! OK)

   return 0;
}

example2 (working whitespace string):
#include <stdio.h>

struct string {
    char word[20];
    char sentence[100];
} s;

int main() {

    printf("\nEnter more words with whitespace:\t");
    scanf("%[^\n]s", s.sentence); //1st input with whitespace

    printf("Enter word:\t");
    scanf("%s", s.word); //2nd input without whitespace

    printf("\nWord is: %s", s.word); // 2nd input printed (OK)
    printf("\nSentence is: %s \n", s.sentence); // 1st input printed (OK)

    return 0;
}

Between "example1" and "example2" are different order of input (see at code comment). I dont know how can I use whitespace to scanf input in struct. And sorry for my english.
Thank you in advance!
Comment: In `"%[^\n]s"`, `s` isn't necessary. `"%[^\n]"` is the correct format as `%[..]` expects a `char *` pointer. Remove the `s` and try again.
Comment: Not working, same problem as before, program not able to option me to do 2nd input. Answer of MichaelLee works and pages from paxdiablo is great.
Answer: For a start, the correct specifier for anything other than a newline is %[^\n] rather than %[^\n]s. Yours works but only as a coincidence of the values chosen :-)
Calling scanf with the %s format specifier will stop scanning when it reaches white space, that's how it works. From C11 188.8.131.52 /12, where it talks about the conversion specifiers and their meanings

s - Matches a sequence of non-white-space characters.

The reason why you're getting a blank sentence in the first code sample has to do with the way the word is scanned. In scanning the word, it stops at the first white space and leaves that in the input buffer. That first white space is the newline at the end of your word.
That means the sentence scan will grab everything up to the next newline which, because the newline is the first thing in the buffer, means it will get an empty string.
You can fix this by placing a getchar() after the word scan to consume the newline, before attempting to read the sentence.
However, if you really want robust user input in C, you'll be better off building something around fgets, something like the code found here.

The reason it works when you swap them around has to do with this snippet in that same standard (188.8.131.52 /8) which details what happens before the item is scanned:

Input white-space characters (as specified by the isspace function) are skipped, unless
  the specification includes a [, c, or n specifier.

So, even though the word scan in your second example also starts with a newline in the buffer, the %s specifier skips it before attempting to read a word. That's something the [ specifier does not do, as you've already seen.
Comment: Thank you for quickly respond! and link from which I will to learn. I found that my problem could be solved by input space between % and [ to this code `"% [^\n]s"` but i don't think is it OK. Once again thank you!
Comment: @Hancz, I strongly suggest you use the code linked to. It's battle-hardened over decades, preventing buffer overflow attacks and so on, something `scanf("%s")` won't do for you.
Comment: I make a note about that, because I thought that only `scanf()` is a "bullet proof" input (for begin programming).
Comment: @Hancz, `scanf` is safe, provided you control the input. Just remember that it stands for "scan formatted" and there's nothing _less_ formatted than input from pesky users :-)
Answer: In your example1, scanf("%s", s.word) would only scan the first word, but would not flush the rest of the line.
This should solve your issue:
#include <stdio.h>

struct string {
    char word[20];
    char sentence[100];
} s;

int main() {

    char c;

    printf("Enter word:\t");
    scanf("%s", s.word); //1st input without whitespace - if multiple words are entered, only the first word will be taken

    while ((c = getchar()) != '\n') {
        /* discard */ ;
    }

    printf("\nEnter more words with whitespace:\t");
    scanf("%[^\n]s", s.sentence); //2nd input with whitespace - this should work now

    printf("\nWord is: %s", s.word); // 1st input printed (OK, only first word printed)
    printf("\nSentence is: %s \n", s.sentence); // 2nd input printed (OK NOW!!!)

    return 0;
}

Comment: Also the `s` does not make sense here. `%[^\n]` already asks for all characters but a new-line.
Comment: Thank you, it working well. I did not think that solution for correctly functional 2nd input will be at 1st input :-)


Are there any python 3 modules that support OAuth pin-authentication?

Question: What it needs to do:

Take a pin generated server-side
Get an access token by posting the (pin + client_id + client_secret) to a new URL

The pin can be obtained externally using any browser but if the module supports doing this inline it would be even better.
Answer: Yes there is. One is called sanction and here's an example of how to pin-auth.
Go here for information on how to install sanction.


Implementing SitePoint's Infinite Scolling in rails by Ilya Bodrov-Krukowski

Question: I am implementing, http://www.sitepoint.com/infinite-scrolling-rails-basics/, into my own project.
It works when I type URL directly to browser after I have implemented it in my own project. However, it does not work if I link_to from a different page. It goes back to regular will_paginate, then I hit "reload" button on browser, it starts tp work again.
However, I don't want my users to hit "reload" button every time for making infinite scrolling to work. What might cause this and how can I fix it? Thanks a lot!
Answer: It is caused by turbolinks
However, it is not a fix by installing jquery-turbolinks.
After reading turbolinks documents, temporarily disable turbolink for that particular link with
Home (via Turbolinks)

  Home (without Turbolinks)


Authentication to host 'localhost' for user 'root' using method 'mysql_native_password' failed with message (using password: NO)

Question: Can you help me guys for my thesis and this is one of my problem in my system.
<code>MySqlConnection cn2 = new MySqlConnection(cn.ConnectionString);
cn2.Open();-->>> Authentication to host 'localhost' for user 'root' using method 'mysql_native_password' failed with message: Access denied for user 'root'@'localhost' (using password: NO)

listView1.Items.Clear();
string sql = "Select * from tblrecord where DateTime between '" + dateTimePicker1.Value + "' and '" + dateTimePicker2.Value + "'";
cm = new MySqlCommand(sql);
//cm = new MySqlCommand(sql, cn1);
dr = cm.ExecuteReader();
dr.Read();
if (dr.HasRows)
</code>
Comment: Go to your mysql server, and create a new user with a password defined by you. Use that user to login from Visual Studio. This is because using root account to login is generally not common, but if you insist, you will need to find out your default root password and use that.
Comment: The problem was in " cn2.Open(); "
Comment: May we see your connection string (I know its private, but I only ask since there is no password in it, according to the error). Or maybe your mysql server has not allowed root access without password yet.
Comment: what should i do to correct it ?
Answer: just add password in your connection string because you have not added it in your connction.


what is the brand of this sink faucet?

Question: enter image description hereOne of my sink faucets in my bathroom is leaking and I decide to fix it. I can uninstall the handle using allen wrench but then don't know how to find the O-ring or something. I need to know the brand but I couldn't find any logo on it. I need to know the brand no matter whether I will fix it or just go buy a new one (to be the same). Can someone help to identify the brand?
enter image description here
Comment: For help here you will want to remove the leaky handle and then take a nice clear photo close up to the faucet that has the handle removed. Someone will most likely then be able to tell you the process for opening the valve.
Comment: Getting brand information is going to be near impossible. Internationally there are many manufacturers that each make many models that they update every year or so.
Comment: @MichaelKaras: thanks. I was only able to update one picture and will upload more pictures.
Answer: just looking at the surface and general look and fit and finish, it looks like a made in china junk faucet.  these types of faucets are essentially disposable.  even if you can get it apart (which may not be the case), you will never get parts for it.
if you do want to try it, try removing the supply line and nut from the bottom (under the counter) and lift the handle assembly out.  there may be a set screw or something under the escutcheon.  i have seen enough of these to not offer much hope though.  get yourself a moen faucet as a replacement.  good pricing, lots of choice, and free parts for life.
Comment: if I go buy a new moen faucet, what standard size should I ask? I found that some double handles are closer to each other than mine. There must be different sizes and setups.
Comment: @kornbor - Your faucet spacing was determined by the installer when the holes were drilled in the cabinet top. You would want to look for a replacement that has separate faucet handles that interconnect with hoses/tubing that can accommodate a range of faucet spacing. Fixed spacing come into play either when the sink has ready made holes for the faucets and/or the faucets and spout are designed as an integrated unit.
Answer: The brand name of the faucet is often found facing the wall.
Put a hand mirror on the wall and illuminate it with a flashlight.

what is the brand of this sink faucet?


detect whether app is running on simulator or on device (as3)

Question: i've found some solutions for this but no one for as3:
I'm developping an app for ios with AS3, and i'd like to set a variable that detects whether the app is running in the adl simulator or on the real device.
Is that possible with as3? i've searched on adobe doc, this forum and google, and found nothing.
thanks.
Answer: Usually I create a Boolean for debug and set it true when developing and false when will release
Comment: thanks, i've already made this one, but i thought there would be a way to do it automatically.this makes me think my last publication went wrong because i forgot to change this variable. thank you for this.
Answer: As for ADL simulator you can simply check the Capabilities.cpuArchitecture == "ARM" statement. For ADL is false, whilst for iOS sim and iOS or Android device it is true.


Java cup: Shift/Reduce conflict

Question: I'm trying to write a parser using JFlex and Cup, but I have some issues dealing with recursive pointed notation like  function call with recursive properties access like :
var x = obj.property1.functionCall(p1, p2).property2;

Here is the related parser definition:
unary_exp ::= postfix_exp
              | ADD2 unary_exp
              | SUB2 unary_exp
              | unary_operator unary_exp;

unary_operator ::=  ADD
                    | SUB
                    | BIT_NOT
                    | NOT;

postfix_exp ::= primary_exp
                | postfix_exp LPAR_SQ right_value_exp RPAR_SQ
                | postfix_exp LPAR optional_postfix_exp_list RPAR
                | postfix_exp DOT postfix_exp
                | postfix_exp SUB2
                | postfix_exp ADD2;

primary_exp ::= BOOL
                | STRING
                | INTEGER
                | NUMBER
                | NULL;

I got following shift/reduce conflicts :
Warning : *** Shift/Reduce conflict found in state #190
  between postfix_exp ::= postfix_exp DOT postfix_exp (*)
  and     postfix_exp ::= postfix_exp (*) LPAR optional_postfix_exp_list RPAR
  under symbol LPAR
  Resolved in favor of shifting.

Warning : *** Shift/Reduce conflict found in state #190
  between postfix_exp ::= postfix_exp DOT postfix_exp (*)
  and     postfix_exp ::= postfix_exp (*) LPAR_SQ right_value_exp RPAR_SQ
  under symbol LPAR_SQ
  Resolved in favor of shifting.

Warning : *** Shift/Reduce conflict found in state #190
  between postfix_exp ::= postfix_exp DOT postfix_exp (*)
  and     postfix_exp ::= postfix_exp (*) DOT postfix_exp
  under symbol DOT
  Resolved in favor of shifting.

Warning : *** Shift/Reduce conflict found in state #190
  between postfix_exp ::= postfix_exp DOT postfix_exp (*)
  and     postfix_exp ::= postfix_exp (*) ADD2
  under symbol ADD2
  Resolved in favor of shifting.

Warning : *** Shift/Reduce conflict found in state #190
  between postfix_exp ::= postfix_exp DOT postfix_exp (*)
  and     postfix_exp ::= postfix_exp (*) SUB2
  under symbol SUB2
  Resolved in favor of shifting.

Error : *** More conflicts encountered than expected -- parser generation aborted

May someone explain to me how to deal with these conflicts or where to find a working example using java cup, yacc or bison?
Answer: Your grammar includes this production:
postfix_exp ::= postfix_exp DOT postfix_exp

Do you think that's accurate? Can the right operand of  . be an arbitrary postfix_exp? If so, what does a.3 mean? How about x.false? (A primary_exp is a postfix_exp, right? That's what the grammar says.)
Closer to home, what is the meaning of a.b++? Is there any sense in which b++ is an operand of .? Surely b is the name of a member of a, not an independent variable.
Grammars convey meaning even though they don't implement semantics. They specify the way different parts of an expression relate to each other. ("Parse" and "parts" sound similar because the verb "parse" comes from the noun "part", as in "to split into parts".) So you should strive to make your grammar correspond to the structure of the language.
Now, any time you see a production like:
foo ::= foo OPERATOR foo;

you know that the grammar is ambiguous. It's ambiguous because it generates both left- and right-associative parses for OPERATOR. IF OPERATOR were -, for example, it would be conflating (1 - 1) - 1 (assuming that foo could produce 1) with 1 - (1 - 1). And grammatical ambiguity always manifests as a parse table conflict.
Resolving the ambiguity is important because those two expressions have different values. Which is why we either have to use a hierarchy of expression types, or operator precedence declarations. (So we know how to solve the associativity problem.)
But in the case of the . operator, we really don't have a binary operator of unspecified associativity. We don't really have a binary operator at all, which is why the production here is called postfix_exp. The operator is a field selector, which we might think of as a collection of different postfix operators, one for each member name of the appropriate composite type.
So that's the simple answer here. As soon as  we say that the field selector has the form DOT IDENTIFIER, the ambiguity vanishes.
Comment: Alright, thank for this clear and concise explanation. I'm going to review that production rule.

Java cup: Shift/Reduce conflict


how ot use (in_array)

Question: I am using '  'to pass my array value  from one page to another. I have an array value that is doesn't have value always. How to put condition when it have value pass it but I don't have idea about (in array) in  .
this is my passing code
echo '$key['DocName'],'HosName'=>$key['HosName'],'DoctorNotes',['DoctorNotes'])),ENT_QUOTES | ENT_HTML401 | ENT_SUBSTITUTE | ENT_DISALLOWED,'UTF-8',true).'">More>>
';

this is get query
$DoctorNotes=$_GET ['DoctorNotes'];[enter image description here][1]

here is my result array
error msg
' Array to string conversion in.....'
Answer: in_array — Checks if a value exists in an array
<?php
$names = array("VYSAKH", "DODESTINO", "CHOORAKKATT", "VYSU");
if (in_array("DODESTINO", $names)) {
    echo "Got DODESTINO";
}
if (in_array("VYSU", $names)) {
    echo "Got VYSU";
}
?>

Answer: The in_array() function searches an array for a specific value.
Note: If the search parameter is a string and the type parameter is set to TRUE, the search is case-sensitive.

Syntax
in_array(search,array,type)

$people = array("Peter", "Joe", "Glenn", "Cleveland");

if (in_array("Glenn", $people))
{
    echo "Match found";
}
else
{
    echo "Match not found";
}

Reference

how ot use (in_array)


Can someone check the solution to this recurrence relation?

Question: Here's the recurrence relation: $a_n = 4a_{n−1} − 3a_{n−2} + 2^n + n + 3$ with $a_0 = 1$ and $a_1 = 4$
Here's the solution:Write:
$$
a_{n + 2} = 4 a_{n + 1} - 3 a_n + 2^n + n + 3 \quad a_0 = 1, a_1 = 4
$$
Define $A(z) = \sum_{n \ge 0} a_n z^n$. If you multiply the recurrence by $z^n$ and sum over $n \ge 0$ you get:
$$
\frac{A(z) - a_0 - a_1 z}{z^2}
  = 4 \frac{A(z) - a_0}{z} - 3 A(z)
        + \frac{1}{1 - 2 z} + \frac{z}{(1 - z)^2} + 3 \frac{1}{1 - z}
$$
This gives:
$$
\begin{align*}
A(z) &= \frac{1 - 4 z + 9 z^2 - 12 z^3 + 5 z^4}
             {1 - 8 z + 24 z^2 - 34 z^3 + 23 z^4 - 6 z^5} \\
     &= \frac{23}{8} \cdot \frac{1}{1 - 3 z}
          - \frac{1}{1 - 2 z}
          + \frac{3}{8} \cdot \frac{1}{1 - z}
          - \frac{3}{4} \cdot \frac{1}{(1 - z)^2}
          - \frac{1}{2} \cdot \frac{1}{(1 - z)^3}
\end{align*}
$$
Expanding the geometric series, and also:
$$
(1 - z)^{-k} = \sum_{n \ge 0} (-1)^n \binom{-k}{n} z^n
          = \sum_{n \ge 0} \binom{n + k - 1}{k - 1} z^n
$$
gives:
$$
a_n = \frac{23}{8} \cdot 3^n
         - 2^n
         + \frac{3}{8}
         - \frac{3}{4} \cdot \binom{n + 1}{1}
         - \frac{1}{2} \cdot \binom{n + 2}{2}
    = \frac{23}{8} \cdot 3^n - 2^n + \frac{3}{8}
         - \frac{1}{6} (n^3 + 6 n^2 + 5 n)
$$
The problem is that when I check this with Wolfram, it has the solution of $a_n = -4(2^n) - n^2 / 4 - 5n / 2 + 1/8 + (39/8)(3^n)$.  I just wanted to know if this was an error or what..thanks!
Comment: With integrations, you can check for correctness of a proposed answer by differentiating. With recurrences, you can do it by substituting.
Comment: How can I check when I only have two values though?  I can't check for $a_{n-2}$ ?
Comment: If $a_k$, for general $k$, is given by a certain formula, you can use that formula to find $a_{n-2}$, $a_{n-1}$, $a_n$.  **Another way:** Calculate what your formula predicts for $a_2$, $a_3$. Calculate what the recurrence gives. If there is a mismatch, you know there is a mistake. If the answers match, with a little luck the formula is correct.
Answer: You substituted $n+2$ instead of $n$ in your first step, but forgot to change the powers of $2$, etc. In other words, you should have
\begin{align}
a_{n + 2} = 4 a_{n + 1} - 3 a_n + 2^{n+2} + (n+2) + 3 \quad a_0 = 1, a_1 = 4
\end{align}
instead of
\begin{align}
a_{n + 2} = 4 a_{n + 1} - 3 a_n + 2^n + n + 3 \quad a_0 = 1, a_1 = 4
\end{align}
Comment: Damnit.  Is there any way you can show me how to correct the rest of it after that minor mistake?  Thanks Lord Soth for helping me out..
Comment: Well, you may need to recalculate your steps unfortunately.
You would have
\begin{align}
\frac{A(z) - a_0 - a_1 z}{z^2}
  = 4 \frac{A(z) - a_0}{z} - 3 A(z)
        + \frac{\color{red}{4}}{1 - 2 z} + \frac{z}{(1 - z)^2} + \color{red}{5} \frac{1}{1 - z},
\end{align}
Comment: The changes are in red. I guess you can take it from here using the same ideas.
Comment: UNfortunately it was after that initial step that I had trouble recalculating =(
Answer: But
    $a_{n+2}=4a_{n+1}−3a_n+2^{n+2}+(n+2)+3\,$!
Comment: You sure that's 3 factorial?  Lord Soth appears to think it's just 3...?
Comment: @jtm22: No, 3 and ! ending the sentence.
Comment: Haha thanks.  Any way you could help me correct the problem?
Answer: After the correction others have pointed out in your first line, you do the same z-transform/generating function stuff you did before, the only difference is now your two forcing terms are shifted by two.
\begin{align}
a_{n + 2} = 4 a_{n + 1} - 3 a_n + 2^{n+2} + (n+2) + 3 \quad a_0 = 1, a_1 = 4
\end{align}
You really only need to figure the generating functions for the following term
$$
\sum_{n=0}^{\infty} 2^{n+2} z^n = 2^2\sum_{n=0}^{\infty} 2^{n} z^n = \frac{4}{1-2z}
$$
What's left is $n+2+3=n+5$, so your last term turns into a $5$ in the denominator, while the second to last stays the same.  This gives you
$$
\frac{A(z) - a_0 - a_1 z}{z^2}
  = 4 \frac{A(z) - a_0}{z} - 3 A(z)
        + \frac{4}{1-2z} + \frac{z}{(1 - z)^2}+ \frac{5}{1 - z}
$$
At this point, you should be able to finish of the problem the same way as before: solve for $A(z)$, expand by partial fractions, then inverse transform.  It seems that you need help with this step?  I didn't do this by hand but used Mathematica quickly:
$$
A(z) = \frac{-12 z^4+24 z^3-14 z^2+4 z-1}{(z-1)^3 (2 z-1) (3 z-1)}
$$
$$
= -\frac{7}{4 (z-1)^2}+\frac{1}{2 (z-1)^3}+\frac{4}{2 z-1}-\frac{39}{8 (3 z-1)}-\frac{19}{8 (z-1)}
$$
This is in the same form as your second to last step, just with different coefficients.  Match them up in the function forms of $z$ and you have your final answer.
Comment: That was my problem..going from that the A(z) = step to the "expanding geometric series" step into the solution..
Comment: Yeah I'm just confused on how to get from that last step to the $a_n$ solution


getAsFile returning null in onPaste event when copying embedded image from outlook

Question: My client frequently receives emails in Outlook with screenshots embedded into the text.  I'm building them a work order tracker website, and they want to copy/paste from the email into the web page I'm building. (They are using Chrome Version 79.0.3945.117 (Official Build) (64-bit) and Microsoft Office 365 ProPlus Outlook Version 1902 (Build 11328.20492 Click-to-Run))
When they select the entire email's content the data in e.clipboardData.items doesn't include any references to the image.  It only includes the text (in plain, rte, and html formats) and the files collection has a length of 0.
When they select a single image in Outlook and copy/paste it into my form the data in e.clipboardData.items includes rte, html, and file types. The files collection still has a length of 0 though.  When I try to call getAsFile() on the item with the kind of file (and type of image/png) it returns null.
If the client right clicks the image and saves it, they can then upload it to my input type=file control, but I'm trying to save them some effort as they do this multiple times every day.
I've got a text box with an onpaste event:
<textarea name="maincontent_0$txtDetails" rows="2" cols="20" id="maincontent_0_txtDetails" class="orderFormDetails" onpaste="onPaste(event)"></textarea>

and a file input control:
<input type="file" name="maincontent_0$fuNewAttachment" id="maincontent_0_fuNewAttachment">

The onpaste event is defined as the following:
        function onPaste(e)
        {
            var items = e.clipboardData.items;

            const dT = new ClipboardEvent('').clipboardData || // Firefox < 62 workaround exploiting https://bugzilla.mozilla.org/show_bug.cgi?id=1422655
                       new DataTransfer();

            for (var i = 0; i < items.length; i++)
            {
                if (items[i].kind == "file")
                {
                    var blob = items[i].getAsFile();
                    if (blob != null)
                    {
                        dT.items.add(blob);
                    }
                }
            }
            if (dT.items.length > 0)
            {
                var uploadField = document.getElementById("maincontent_0_fuNewAttachment");
                uploadField.files = dT.files;
            }
        }

If I grab the html data instead of the file data I can get the location on the user's hard drive where the image is cached, but that's useless to me as I can't get the actual file's contents.
I've also tried using drag/drop to upload the image from Outlook and run into a similar problem (the e.dataTransfer.files collection is empty and the e.dataTransfer.items collection only has html with a local url to the image, not it's contents.)
Is there anything I can do to get at the contents of the image or is Outlook just not sending it?
Answer: I know this was asked a while ago, but I just wanted to give my two cents. (I am writing here as an 'answer' too because I don't have enough credits to add a 'comment'... so sorry about that!)
I had the exact problem that Brian Heward had. The answer that muditgoel3011 gave was 100% accurate. Essentially, when you copy multiple images onto your clipboard, it reads as a RTF instead. Thus, you have to isolate the item in your event.clipboardData that is type 'text/rtf'.
Then you can use the rtf.js (or another equivalent library that helps parse RTF) and convert all of the RTF data into buffers and append that to your HTML document (or another equivalent).
However, it only really worked on my Mac OS (and not on my Windows environment). It stems from the size of the rtf from the clipboard. Copy/pasting 2-3 images from Outlook would be less than 1MB on my Mac whereas it would be around ~60MB on Windows. A typical email would consist of around 30 images, and thus crashes my browser on Windows. On Mac, it works perfectly fine.
My example code is using Quill as an Editor:
for (let i = 0; i < items.length; i++) {
    if (items[i].type.indexOf('image') === 0) {
        image = items[i].getAsFile();
    }
    else if (items[i].type.indexOf('text/rtf') === 0) {
        var rtf = e.clipboardData.getData('text/rtf');
        var stringToBinaryArray = function(txt) {
            var buffer = new ArrayBuffer(txt.length);
            var bufferView = new Uint8Array(buffer);
            for (var i = 0; i < txt.length; i++) {
                bufferView[i] = txt.charCodeAt(i);
            }
            return buffer;
        }

        var doc = new RTFJS.Document(stringToBinaryArray(rtf), {});

        let self = this;
        doc.render()
            .then(function(htmlElements) {
                const div = document.createElement("div");
                div.append(...htmlElements);
                let delta = self.quill.clipboard.convert(div.innerHTML)
                self.quill.setContents(delta, 'silent');
            })
            .catch(error => console.error(error))
    }
}

Hope this helps someone. It definitely helped me. Thanks all!
Answer: When images etc are copied from outlook, they live in RTF format in the clipboard.  Majority of HTML editors such as Extjs editor, devxtreme HTML editor; even pasting such images to google mail; and even pasting in vsts do not support processing the Rich Text Format (RTF) , hence pasting images from outlook fails in all these cases.
(In general, copy and paste from Microsoft products to browser-based products doesn't work so well: Microsoft has all sorts of special characters in their content which you cannot see but which can mess with what you paste.
What you need is be able to transform the RTF content into HTML and paste. Algo is: Check if image file available in clipboarddata, if no; check if html content there, if yes; check whether that html content is refering to local file urls in img tags somewhere (ie, src="file:// exists in html content); if yes, check for rtf content, if exists; use a library like rtfjs and transform it to render to browser in paste handler.


How to compute $\int\limits_{\mathbb{R}^3}\det D^2 u(\mathbf{r}) d\mathbf{r}$?

Question: Let $u\in C^3(\mathbb{R}^3)$ and $u$ is zero outside some bounded domain. I need to find the value of
$$
\int\limits_{
\large\mathbb{R}^3}\det \mathrm D^2 u(\mathbf{r})
\, \mathrm d\mathbf{r}
$$
I suspect it equals zero. I can show this for some specific cases.
Here $\mathrm D u$ is a gradient of $u$, while $\mathrm D^2u$ is a Hessian.
Comment: @HandeBruijn $u\in C^3(\mathbb{R}^3)$ means that $u$ is three times continuously differentiable function defined on $\mathbb{R}^3$.
Comment: You mean this: $$\int\limits_{\large\mathbb{R}^3}\left[
\frac{\partial^2 u}{\partial x^2}\frac{\partial^2 u}{\partial y^2}\frac{\partial^2 u}{\partial z^2}
+2\frac{\partial^2 u}{\partial x\partial y}\frac{\partial^2 u}{\partial y\partial z}\frac{\partial^2 u}{\partial x\partial z}\\
-\frac{\partial^2 u}{\partial x^2}\left(\frac{\partial^2 u}{\partial y\partial z}\right)^2
-\frac{\partial^2 u}{\partial y^2}\left(\frac{\partial^2 u}{\partial x\partial z}\right)^2
-\frac{\partial^2 u}{\partial z^2}\left(\frac{\partial^2 u}{\partial x\partial y}\right)^2 \right] dx\,dy\,dz = 0 \; \mbox{ ?}$$
Comment: @HandeBruijn, exactly $\phantom{}$
Comment: What is the meaning of $u\in C^3(\mathbb{R}^3)$? Something with complex functions? And how is that different from $u\in \mathbb{R}(\mathbb{R}^3)$? (Sorry I'm so bad in set theoretic notation) I'm asking this because if I take $u = x^2+y^2+z^2$ and the bounded domain a unit cube, then your integral is simply $= 1$ and not zero.
Comment: OK, so I guess those continuity requirements make my "counter example" not work (apart from the fact that the outcome would have been $=8$, not $=1$)
Answer: Note that the Hessian matrix for $u: \mathbb{R}^3\to \mathbb{R}$ is the Jacobian of the gradient,
$$\text D^2u = \text D(\text Du) = \text J(\nabla u )$$
Let $\text{D}u = v = (v_x,v_y,v_z)$. Then, since $u$ and $v$ are continuous on $\mathbb{R}^3$ and vanish outside of some bounded domain $\Omega$, they must also vanish on the boundary. In particular, $v|_{\partial\Omega}\equiv 0$.
Recall that the Jacobian determinant is used to change coordinates in integration, since
$$\det \text Dv \ \mathrm{d}x\mathrm{d}y\mathrm{d}z = \mathrm{d}v_x\mathrm{d}v_y\mathrm{d}v_z$$
for any $v:\mathbb{R}^3\to\mathbb{R}^3$ (and in particular, $v=\text Du$), and so
$$\int_{\Omega}\det \text{D}^2u \ \mathrm{d}x\mathrm{d}y\mathrm{d}z = \int_{\Omega}\det \text D(\text{D}u) \ \mathrm{d}x\mathrm{d}y\mathrm{d}z = \int_{\Omega}\mathrm{d}v_x\mathrm{d}v_y\mathrm{d}v_z$$
By Gauss-Ostrogradsky Theorem,
$$\int_{\partial\Omega}F(r(s,t))\|\partial_s r\times \partial_t r\| \ \mathrm{d}s\mathrm{d}t = \int_{\partial \Omega}F \ \mathrm{d}S = \int_\Omega \text{tr}\text DF \ \mathrm{d}V$$
where $F: \mathbb{R}^3\to\mathbb{R}^3$ is any continuously differentiable function and $r: I_s \times I_t \to\mathbb{R}^3$ is a parameterization of $\partial \Omega$.
Let $F(v)=\frac{1}{3}v$ so that $\text DF = \frac{1}{3}\mathbf 1$ and so $\text{tr} \text DF = 1$. Then, for any $r$,
$$F(r(s,t)) = \frac{1}{3}v|_{\partial\Omega} \equiv 0$$
which gives us the result
$$\int_\Omega \det\text{D}^2u \ \mathrm{d}x\mathrm{d}y\mathrm{d}z = \int_{\Omega} \det \text D(\text{D}u) \ \mathrm{d}x\mathrm{d}y\mathrm{d}z = \int_\Omega \mathrm{d}v_x\mathrm{d}v_y\mathrm{d}v_z = \int_{\partial\Omega} 0\cdot\|\partial_s r\times \partial_t r\| \ \mathrm{d}s\mathrm{d}t = 0$$


Error: Component definition is missing display name

Question: i have following code using react-table hook. Vercel compilation shows the following error msg:
49:15  Error: Component definition is missing display name  react/display-name where the Line 49 indicated in the code below.
<code>const tableHooks = (hooks) => {
    hooks.visibleColumns.push((columns) => [
      ...columns,
      {
        accessor: "status",
        Header: "Status",
        Cell: ({ row }) => (  // Line 49
          <h6
            className={classes.editstatus}
            onClick={() => bookingDetailHandler(row.original.brewery_type)}
            value={row.original.brewery_type}
          >
            {row.original.brewery_type}
          </h6>
        ),
      },
    ]);
  };
  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    page,
    state: { pageIndex, pageSize },
    setPageSize,
    nextPage,
    previousPage,
    canNextPage,
    canPreviousPage,
    pageOptions,
    // state,
    gotoPage,
    pageCount,
    prepareRow,
    flatRows,
  } = useTable(
    {
      columns,
      data,
      // defaultColumn
    },
    tableHooks,
    // useFilters,
    useSortBy,
    usePagination
  );
</code>
Answer: Just switch arrow function to a named function
<code>{
    accessor: "status",
    Header: "Status",
    Cell: function statusItems({ row }) {
      return (
        <h6
            className={classes.editstatus}
            onClick={() => bookingDetailHandler(row.original.brewery_type)}
            value={row.original.brewery_type}
          >
            {row.original.brewery_type}
          </h6>
      );
    },
  }
</code>
Comment: Thanks Vitally for your time. After change it to named function, how do I declare the  statusItems in the ReactTable instance?
Comment: `statusItems` is custom function, you don't need to declare it in ReactTable instance
Comment: Thanks Vitaliy. your suggestion helps


meaning of data members in sched_rt_entity

Question: The following is the code for the entity class for RT policy in linux scheduling.
struct sched_rt_entity {
     struct list_head run_list;
     unsigned long timeout;
     unsigned int time_slice;

     struct sched_rt_entity *back;
     #ifdef CONFIG_RT_GROUP_SCHED
     struct sched_rt_entity  *parent;
     /* rq on which this entity is (to be) queued: */
     struct rt_rq            *rt_rq;
     /* rq "owned" by this entity/group: */
     struct rt_rq            *my_q;
     #endif
};

What is data member back required when the list is already implemented.
I also do not understand how the group scheduling policy is implemented, particularly why there is a need of my_rq and rt_rq and who will parent point to.
Also what is the meaning of timeout data member.
P.S.:
I have lots and lots of such question, Can anyone suggest a good read.
Answer: When using group scheduling, there is not a single queue, but a tree of groups and their queues. For example, when two users have a scheduling group each, the overall group/queue might allocate 50 % CPU to each user's group, while all the users' programs are in their group's queue and compete for that 50 %.
For a more detailed explanation of how the multiple queues work, see CFS group scheduling.
parent points to the entity one level up in the tree; rt_rq is the queue on which this entity runs, while my_q is the queue on which this entity's children run.
The back field is used as temporary storage in the dequeue_rt_stack() function to implement a stack, where we have a pointer to the lowest entity, but want to remove them beginning from the top-level one.
timeout is increased by the watchdog timer and used to check that the task does not hog the CPU for longer than RLIMIT_RTTIME.

There are no books about recent kernel changes.
Use the source, Luke.
Comment: I understand this but it would be great if you can offer some more insight on why such a structure is used as thee explanation has given rise to a few more questions. More specifically, why there is a need of the queue in which the children are running.
Comment: Also another question because you have brought up `dequeue_rt_stack`, I do not understand that what if the pointer is not to the lowest entity, when the temporary assignment using back is going to take place we assign `rt_se->back=back` which means we are assigning it `null` without talking care about if that was in the middle of any list, in other words  what if some other entities are pointing to it(as they were a part of same group) and now only this entity and their parents would remain together.


Page Content Refreshed via Web Socket or AJAX

Question: I am working on a project which is built on Springs MVC and Google App Engine with Objectify.
The major functionality of this app is: If someone posts something new to the Datastore then it should be auto published to the browsers to which it is connected without refreshing the page content. Basically it is a news like site. The data sent to browser is REST APIs based JSON Data.
For implementing this functionality I thought of using the following ways:

AJAX : I thought of using AJAX call in every 2-3 minutes to get updated. But this solution doesn't seems to be feasible as there are many datastore read operation due to many AJAX calls from many browsers.
Web Socket : This concept is pretty new to me. I am not aware of this thing. Some pusher.com uses this technology for establishing such connections.

Now I need your suggestions, using which of the two above or I am also open to other solutions.
Comment: WebSocket is definitely faster and more efficient than traditional Ajax, but if you use WebSocket, then you'll probably still need to code an Ajax backup for older browsers that don't support WebSocket.
Comment: sir, can you suggest me some examples using web-sockets. I need this app to be run on mobile browsers so may be I don't need to code the AJAX then.
Comment: Maybe you an use the channel API. https://developers.google.com/appengine/docs/java/channel/
Comment: If you're looking to use PHP for the back end, Google's [phpwebsocket](http://code.google.com/p/phpwebsocket/) is a good start. Note that the code is outdated though, and doesn't actually work. Nevertheless, all the component parts are there and it should get you thinking in the right direction. In addition to the above link, you'll also want to read and become familiar with the latest [WebSocket draft](http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17) in order to get the latest and most accurate information for how to do the handshake, mask/unmask data, etc., etc.
Answer: Google app engine does not support web sockets, however it supports something similiar called the channel api which works on older browsers as well. This may not be feasible depending on how many people you will have connected (channels cost 1c per 100). Channels also have some caveats: https://developers.google.com/appengine/docs/python/channel/overview#Caveats
As for using Ajax - if you cache the response in memcache and flush the key every 3 minutes then you won't be doing any data store reads unless a new instance is fired up or the key expires.


Is 2moons Expedition dead?

Question: I used to play an mmorpg back in 2006-2007 called 2moons Expedition. Wanting to relive the past today, I googled it, but can't find the website for this nor the game client. The last time people posted about 2moons was back in 2008.
Last I remember, the game was closed beta and there was going to be no reset/wipe when the real version was launched.
What happened to this game? Is my account gone forever?
Answer: Acclaim Games (the company behind 2Moons) went out of business in late 2010 and most of their games were also shut down, including 2Moons.
You could however try Dekaron, which is the Korean MMO that 2Moons was based on.
Comment: You beat me to it - this is what my research turned up.

Is 2moons Expedition dead?