text:
Q: making you-tube video player in Recycler view in android I have worked with Youtube Video player inside my activity. Now I have an requirement to place this youtube player in recyclerview adapter.
I have used fragment which uses youtube player class like this
    <FrameLayout
            android:id="@+id/youtube_holder"
            android:name="com.google.android.youtube.player.YouTubePlayerSu
                                pportFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

but it is making inflate exception.
I used this. but it is insufficient to understand. Please someone help me.
below is my LogCat result
>  Process: com.ensis.recyclerviewwithyoutubeplayer, PID: 12751
                                                                                android.view.InflateException: Binary XML file line #7: Binary XML file line #7: Error inflating class fragment
                                                                                at android.view.LayoutInflater.inflate(LayoutInflater.java:539)
                                                                                at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
                                                                                at com.ensis.recyclerviewwithyoutubeplayer.YoutubeVideoAdapter.onCreateViewHolder(YoutubeVideoAdapter.java:32)
                                                                                at com.ensis.recyclerviewwithyoutubeplayer.YoutubeVideoAdapter.onCreateViewHolder(YoutubeVideoAdapter.java:15)
                                                                                at android.support.v7.widget.RecyclerView$Adapter.createViewHolder(RecyclerView.java:6519)
                                                                                at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5706)
                                                                                at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5589)
                                                                                at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5585)
                                                                                at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2231)
                                                                                at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1558)
                                                                                at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1518)
                                                                                at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:610)
                                                                                at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3719)
                                                                                at android.support.v7.widget.RecyclerView.onMeasure(RecyclerView.java:3135)
                                                                                at android.view.View.measure(View.java:18911)
                                                                                at android.widget.RelativeLayout.measureChild(RelativeLayout.java:676)
                                                                                at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:479)
                                                                                at android.view.View.measure(View.java:18911)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5995)
                                                                                at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
                                                                                at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:139)
                                                                                at android.view.View.measure(View.java:18911)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5995)
                                                                                at android.support.v7.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:400)
                                                                                at android.view.View.measure(View.java:18911)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5995)
                                                                                at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
                                                                                at android.view.View.measure(View.java:18911)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5995)
                                                                                at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
                                                                                at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
                                                                                at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
                                                                                at android.view.View.measure(View.java:18911)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5995)
                                                                                at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
                                                                                at com.android.internal.policy.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2662)
                                                                                at android.view.View.measure(View.java:18911)
                                                                                at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2157)
                                                                                at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1261)
                                                                                at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1498)
                                                                                at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1140)
                                                                                at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6239)
                                                                                at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
                                                                                at android.view.Choreographer.doCallbacks(Choreographer.java:670)
                                                                                at android.view.Choreographer.doFrame(Choreographer.java:606)
                                                                                at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
                                                                                at android.os.Handler.handleCallback(Handler.java:739)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5551)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
                                                                                Caused b

A: You can add this line in your fragment tag in xml file
 android:name="com.google.android.youtube.player.YouTubePlayerSupportFragment"


text:
Q: Implement planar correction for skewed 3D profilometric data I have some data that represents small-scale surface topography. The data is planar but not flat because it's impractical to level this microscope to a tolerance of microns. It looks like this:

I'd like to postprocess that slope out, such that the major axis is colinear with the long side of the blue rectangle and the vertical axis can then be rescaled to show meaningful topographic variation instead of the (really large) planar slope.
One approach here might be to do an orthogonal transformation via (basically) principal component analysis, eg. find the three eigenvalue/eigenvector pairs, and then treat the eigenvectors corresponding to the largest two eigenvalues as the new X and Y axes. I'd be very interested to see how this (or some better way) might be done efficiently in Mathematica (this data is generally in the millions of rows).
An example of my data is here.
and this is the code I've written so far (which depends on version 9+ for Downsample[]):
    pathToDatafile = "path\\to\\file\\6000s.xyz";
    data = Import[pathToDatafile,"Table","HeaderLines"->15];
    data = DeleteCases[data,{__,_String,_String}]; (*remove the "no data" lines that the instrument creates*)
    data=Delete[data,-1]; (*throw away the instrument's pound sign at the end of the file*)
    data = Downsample[data,{100,1}];(*downsample by a lot because we have way too many datapoints*)
    ListPlot3D[data,
    Mesh->None,
    BoxRatios->Automatic,
    PlotStyle->LightBlue,
    Boxed->False,
Axes->{True,True,True},
AxesLabel->{"\[Mu]m","","\[Mu]m"},
PlotRange->{Automatic,Automatic,{0,250}},
ImageSize->Large
]

A: You can use LinearModelFit to create a linear-fit of the model, and use that to find an appropriate rotation.
model = LinearModelFit[
   data,
   {x, y},
   {x, y}];
(* We have: z = c + a x + b y *)
{c, a, b} = model["BestFitParameters"];

rt = Composition[
  RotationTransform[{
   {1, 0, a},
   {1, 0, 0}},
  {0, 0, c}],
 RotationTransform[{
   {0, 1, b},
   {0, 1, 0}},
  {0, 0, c}]];
 corrected = rt@data;
 ListPlot3D@corrected

(Note: As I don't have Mathematica v9 I downsampled by data = data[[;; ;;100, All]] which I assume is more-or-less the same in this case)
Edit: Answer used to be just corrected = data;
corrected[[All, 3]] -= model["Function"] @@@ corrected[[All, ;; 2]]; but as @bobthechemist points out that will squish together the plane.

A: This solution is giving some artifacts, I believe, due to the downsampling, but the problem can be solved by using RotationTransform similar to this
ListPlot3D[data]
ListPlot3D[RotationTransform[-2.2 Degree, {1, 0, 0}, data[[1]]]@data]

You can make an interactive leveler.  This requires a severely downsampled dataset in order to work smoothly (at least on my computer)
subdata = Downsample[data, {100, 1}];
Manipulate[Module[{d},
  d = RotationTransform[x Degree, {1, 0, 0}, subdata[[1]]]@subdata;
  d = RotationTransform[y Degree, {0, 1, 0}, d[[1]]]@d;
  ListPlot3D[d]
  ], {{x, 0}, -5, 5}, {{y, 0}, -5, 5}]

And then use those results on the full set of data
Module[{d},
 d = RotationTransform[-2.16 Degree, {1, 0, 0}, data[[1]]]@data;
 d = RotationTransform[0.12 Degree, {0, 1, 0}, d[[1]]]@d;
 ListPlot3D[d]
 ]

Which gets you a slightly tweaked version of the image I have above, so I won't repost it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: SBT using dependencyTree and evicted I ran sbt dependencyTree on sbt 1.5.5 and it prints the dependency tree and this
[error] (evicted) found version conflict(s) in library dependencies; some are suspected to be binary incompatible:
[error]
[error]         * org.typelevel:cats-core_2.12:2.6.1 (semver-spec) is selected over {2.6.0, 2.1.1, 1.1.0, 1.1.0, 2.4.2, 2.3.1, 2.4.2, 2.4.2, 2.4.2, 2.1.0, 1.1.0}
[error]             +- org.typelevel:cats-effect_2.12:2.5.0               (depends on 2.6.1)
[error]             +- org.typelevel:cats-free_2.12:1.1.0                 (depends on 1.1.0)
[error]             +- io.circe:circe-core_2.12:0.13.0                    (depends on 2.1.0)

So what I understand from this is that there are multiple versions of cats-core, coming from cats-effect, cats-free and circe.
But i can't find org.typelevel:cats-free nor circe-core in the dependecyTree which is printed. Shouldn't it be there ?
How do i know where are these dependencies coming from?
I want to track them so i can bump their version.
edit:
i also tried  whatDependsOn org.typelevel cats-free_2.12
but i just get the same evicted error
full tree: https://gist.github.com/adrian-salajan/97e0e5ae3fe5fb35b81a651c295f8a6e


text:
Q: What is the difference between key_id and key_name in App Engine Datastore? AFAIK, there is only one difference: key_id must be int and key_name must be string. Is there any other practice limitations using key_id vs key_name?

A: You are correct that the only difference is the type (1 != '1').  Note that it impacts the ordering of results if you sort by key (as you would expect) - integers are sorted before strings.

A: Key is a unique entity in all application like "ag5kZXZ-ZmVlbG1hcmtldHIRCxILU3RvY2tQcmljZXMYZgw"
Key name could be defined by you and apply only within the Entity Class
It could be like "john" or "mart"


text:
Q: Directions to the Algebra Zoo? Is there a good resources that lists known algebraic structures? I'm thinking of something like Scott Aaronson's Complexity Zoo or the OEIS, both of which have entries for various complexity classes/integer sequences, their properties, and relationships among them. You can cobble together something like this from the Wikipedia page on Algebraic Structures, but I was hoping there was something more comprehensive.
To clarify, I'm looking for something that has lots of specific examples of rings, groups, lattices, etc, not just a list of the various kinds.

A: It only applies to groups, but Groupprops ("The Group Properties Wiki") records numerous properties for a large selection of important groups.


text:
Q: File copy software that first checks for errors and than copies only undamaged files? I'm trying to copy files from a damaged HDD to a fine one (both connected via USB 3.0 under Windows 8.1) but I'm having a hard time since it's more than 1TB of data. I'm using robocopy with r:0 and w:0 but when a file with CRC error is found the copy process gets stuck for at least one minute for every damaged file, the dead time is not proportional to the file size and having more than 10k damaged files you can imagine how long it's taking.
I've tried other softwares but it's always the same, no matter if I say to skip a file with errors or set the wait time to 0 the copy process always waits a random amount of time before going to the next file so I was wondering... is there a software that can check for errors BEFORE trying to copy and than copies only the files without errors?
I also use Ubuntu so if there are linux utilities that work similar to robocopy or that answer my question please let me know!
Thanks everyone ;)

A: Roadkil's Unstoppable Copier
http://roadkil.net/listing.php/C1/Data%20Recovery !


text:
Q: Groovy, XmlParser, addNode, inserting a array of elements I have a loop below to create an array of variables on my XML. The issue is that for the first time it is running, it is including all my rows at the first occurrence in my output array.
Any comments are welcome.
Many thanks!
pqpwp*.appendNode('PostalAcc', values[0])
pqpwp*.appendNode('CloseAmt', values[1])
pqpwp*.appendNode('Rates',)
def rates = ltrData.PqPwp.Rates
def values = ["Under 0          0.10%   0.08%      0.10%","Under 1          0.10%   0.08%      0.10%","Under 2          0.10%   0.08%      0.10%","Under 3          0.10%   0.08%      0.10%"]

for (int i = 2; i<10; i++)
{
    if (values[i])
    {
        rates*.appendNode('Rate',)
        def rate = ltrData.PqPwp.Rates.Rate
        rate*.appendNode('Column1', values[i].substring(0,14))
        rate*.appendNode('Column2', values[i].substring(15,23))
        rate*.appendNode('Column3', values[i].substring(24,31))
        rate*.appendNode('Column4', values[i].substring(32,42))
    }
}

actual xml output
      <ltrData>
        <PqPwp>
          <PostalAcc>910060121</PostalAcc>
          <CloseAmt>514.17</CloseAmt>
          <Rates>
            <Rate>
              <Column1>Under �1      2</Column1>
              <Column2>   0.10%</Column2>
              <Column3>  0.08%</Column3>
              <Column4>     0.10%</Column4>
              <Column1>�1 plus       3</Column1>
              <Column2>   1.39%</Column2>
              <Column3>  1.11%</Column3>
              <Column4>     1.40%</Column4>
            </Rate>
            <Rate>
              <Column1>�1 plus       3</Column1>
              <Column2>   1.39%</Column2>
              <Column3>  1.11%</Column3>
              <Column4>     1.40%</Column4>
            </Rate>
          </Rates>

xml output desired
      <ltrData>
        <PqPwp>
          <PostalAcc>910060121</PostalAcc>
          <CloseAmt>514.17</CloseAmt>
          <Rates>
            <Rate>
              <Column1>Under �1      2</Column1>
              <Column2>   0.10%</Column2>
              <Column3>  0.08%</Column3>
              <Column4>     0.10%</Column4>
            </Rate>
            <Rate>
              <Column1>�1 plus       3</Column1>
              <Column2>   1.39%</Column2>
              <Column3>  1.11%</Column3>
              <Column4>     1.40%</Column4>
            </Rate>
          </Rates>

A: the fixed code is below, hope someone else needs it :)
        if (values[i] != "")
            {
            def rate =  rates*.appendNode('Rate')
            rate*.appendNode('Column1',values[i].substring(0,14))
            rate*.appendNode('Column2', values[i].substring(15,23))
            rate*.appendNode('Column3', values[i].substring(24,31))
            rate*.appendNode('Column4', values[i].substring(32,42))
            }
        }


text:
Q: tikz calendar shrank/compressed to single day I have a strange error and I have the feeling that the solution is quite obvious...
What I am trying to do is make a simple calendar with tikz. Here is my MWE:
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{calendar}

\begin{document}
\begin{tikzpicture}
    \calendar[dates=2018-10-01 to 2018-10-last];
    \calendar[dates=2018-11-01 to 2018-11-last];
    \calendar[dates=2018-12-01 to 2018-12-last];
    \calendar[dates=2019-01-01 to 2019-01-last];
    \calendar[dates=2019-02-01 to 2019-02-last];
\end{tikzpicture}

\begin{tikzpicture}
    \calendar[dates=2018-10-01 to 2019-02-last];
\end{tikzpicture}
\end{document}

I was trying to arrange the calendar such that I have 3 months per row, but actually I have some very basic problem here, as every day is printed on top of each other. The output looks as shown in the image. I compiled with PDFLaTeX and XeLaTeX (which I prefer) and both give the same results.
What am I missing?

A: You just forgot to add an option like week list. Having 3 months per row may be achieved with
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{calendar}

\begin{document}
\begin{tikzpicture}
\foreach \X [evaluate=\X as \Y using {int((\X-1)/12)+2018},
evaluate=\X as \PX using {mod(\X-10,3)},
evaluate=\X as \PY using {int((\X-10)/3)}] in {10,...,14}
{
    \calendar at (5*\PX,-5*\PY )[dates=\Y-\X-01 to \Y-\X-last,week list];
}
\end{tikzpicture}

\begin{tikzpicture}
    \calendar[dates=2018-10-01 to 2019-02-last,week list];
\end{tikzpicture}
\end{document}

Let me stress that I have no idea where the additional 1 comes from. Is is possible that TikZ gets confused when the calendar runs over two years where in the first year February has 29 days and in the next year it does not? Or am I doing something wrong?


text:
Q: How to provide default implementations in C++ 20 using concepts? I am experimenting the possibility of using concepts introduced in C++20 as static interfaces. So far, I am doing well except that I am unable to figure out a way to provide a "default implementation" for a concept.
For example, I have a concept named ByteBuffer, and it is stated like this:
template <typename T>
concept ByteBuffer = requires (T t) {
  { t.read_byte() } noexcept -> std::convertible_to<uint8_t>;
  { t.has_byte() } noexcept -> std::same_as<bool>;

  /* default implementation for `t.read_until(...)`? */
};

I should be able to, logically, provide a default implementation for t.read_until(...) (parameters omitted), and allow concrete implementations to override the default one. Is there a way? How can I do it?
If this is not possible, I think it is reasonable to add such an ability.
Currently, I have to resort to the CRTP to provide a facade class, and I think it more redundant than I could conceive.

A: Concepts are not base classes. In fact, concepts have no explicit or implicit relation to any of their template arguments.
Concepts do precisely one thing: verify whether a particular set of template parameters is appropriate to use when instantiating a particular template. That's all.
Concepts contain a sequence of expressions and terms that ought to be valid for the given template parameters. That's all that is needed to determine if a set of template parameters is valid for a particular use, so that's all concepts provide.
If you need some kind of default functionality, you will have to use alternate C++ mechanisms to do that. The simplest being a utility function that has its own constraint:
template<typename T>
concept ByteBufferReadUntil = ByteBuffer<T> &&
  requires(T bb) //Add parameters as appropriate
  {
    { t.read_until() } noexcept -> std::same_as<bool>;
  };

template<ByteBuffer T>
  requires ByteBufferReadUntil<T>
bool read_byte_buffer_until(T &bb)
{
  return t.read_until();
}

template<ByteBuffer T>
bool read_byte_buffer_until(T &bb)
{
  //default implementation for `t.read_until(...)`
}

So whenever you want to do read_until for an arbitrary ByteBuffer, you call read_byte_buffer_until.

A: Concepts are really just constraints on types, so it doesn't make sense to add a "default implementation" to a concept. Instead, what you can do is to provide a default implementation for read_until, and use that unless some ByteBuffer type provides its own implementation.
First you can write a separate concept that checks for read_until:
template <typename T>
concept Readable = requires (T t) {
 { t.read_until() } noexcept -> std::same_as<void>;  // takes no arguments, and returns void for demonstration
};

and then you can provide a default implementation for types that don't provide this function:
template <typename T>
void read_until_impl(T t) {
   std::cout << "default implementation";
}

template <Readable T>
void read_until_impl(T t) {
    t.read_until();  // call provided member function
}

and then some function that uses a ByteBuffer type could call the function like this:
template <ByteBuffer T>
void use(T t) {
    read_until_impl(t);
}

Here's a demo.

A: As already mentioned, C++20 Concepts really don't provide any mechanism to help with this problem at all. They're just predicates that constrain templates. Nothing more.
What I'll offer instead is a more concise alternative: use if constexpr:
template <ByteBuffer BB>
void read_until(BB& buffer) {
    if constexpr (requires { buffer.read_until(); }) {
        buffer.read_until();
    } else {
        while (buffer.has_byte()) {
            buffer.read_byte();
        }
    }
}

Or sometimes I like using function composition to make this clearer, using something like Boost.Hof:
auto read_until = first_of(
    [](ByteBuffer auto& bb) requires requires { bb.read_until(); } {
        // specialized impl
    },
    [](ByteBuffer auto& bb) {
        // default impl
    });

This can be overload too, since one is more constrained than the other, I just like using first_of since it just makes it that much clearer (and plus would work in C++17 with just a trailing-return-type-based constraint).

A: Concepts are not base classes. In fact, concepts have no explicit or implicit relation to any of their template arguments.
Concepts do precisely one thing: verify whether a particular set of template parameters is appropriate to use when instantiating a particular template. That's all.
Concepts contain a sequence of expressions and terms that ought to be valid for the given template parameters. That's all that is needed to determine if a set of template parameters is valid for a particular use, so that's all concepts provide.
If you need some kind of default functionality, you will have to use alternate C++ mechanisms to do that. The simplest being a utility function that has its own constraint:
template<typename T>
concept ByteBufferReadUntil = ByteBuffer<T> &&
  requires(T bb) //Add parameters as appropriate
  {
    { t.read_until() } noexcept -> std::same_as<bool>;
  };

template<ByteBuffer T>
  requires ByteBufferReadUntil<T>
bool read_byte_buffer_until(T &bb)
{
  return t.read_until();
}

template<ByteBuffer T>
bool read_byte_buffer_until(T &bb)
{
  //default implementation for `t.read_until(...)`
}

So whenever you want to do read_until for an arbitrary ByteBuffer, you call read_byte_buffer_until.


text:
Q: Is this correct? "I can't sing very much myself." I'm a student learning English as a second language.
I wanted to say that I can't sing very well, and I wanted to emphasize this sentence.
So.. Is it OK to say that "I can't sing very much myself"?

A: You can add "myself" in a redundant way to add emphasis.  There are other ways of adding emphasis.  "Myself" emphasises "me and not someone else"  But if you want emphasise "much" or "sing" you would need something different.
You should be careful not to change "well" to "much".  These have different meanings.  "I can't sing very well" means "I can only sing poorly".  But "I can't sing very much" means "I can only sing rarely"

I trained at the cathedral and I have very good voice.  But I am so busy with work that I can't sing very much, myself.

I was never taught to sing at school. Now I am a teacher, I sing in the school chapel every day, but I can't sing very well, myself.

In both cases the "myself" is rather distracting, and I would remove it.

A: The "myself" at the end would be used if someone else had said they can't sing first. Joe: "I really can't sing."  Jack: "Don't worry, I can't sing myself"
In your situation I'd put the "myself" closer to the start. "I hired a choir of ten singers. I myself can't sing at all."
"I can't sing very much" doesn't make sense. You could say "I can't sing very well". Or "I have problems with my voice. I can't sing for very long / for a long time".

A: to not be able to do something very much can have two meanings:

*

*I can't sing very much. = I am not a good singer
OR

*I can't sing very  much. = I cannot sing for too long at one time.

The myself is just for contrast with some other person in a discussion.
Another example of the same usage:

*

*I can't swim very much. [not a good swimmer]

*I can't swim very much. [for too long a time]

Emphasis: I, myself, cannot sing very well.
to sing well is the usual expression but as explained above, it can also be not x very much.


text:
Q: Bouncing ball not conforming to Conservation of Energy Rule I am currently busy on writing a small ball physics engine for my programming course in Win32 API and c++. I have finished the GDI backbuffer renderer and the whole GUI (couple of more things to adjust) but i am very near to completion. The only big obstacles that last are ball to ball collision (but i can fix this on my own) but the biggest problem of them all is the bouncing of the balls. What happens is that i throw a ball and it really falls, but once it bounces it will bounce higher than the point were i released it??? the funny thing is, it only happens if below a certain height. This part is the physics code:
(If you need any more code or explanation, please ask, but i would greatly appreciate it if you guys could have a look at my code.)
#void RunPhysics(OPTIONS &o, vector<BALL*> &b)
{
    UINT simspeed = o.iSimSpeed;
    DOUBLE  DT; //Delta T
    BOOL bounce; //for playing sound

    DT= 1/o.REFRESH;

    for(UINT i=0; i<b.size(); i++)
    {
        for(UINT k=0; k<simspeed; k++)
        {
            bounce=false;

            //handle the X bounce
            if( b.at(i)->rBall.left <= 0 && b.at(i)->dVelocityX < 0 ) //ball bounces against the left wall
            {
                b.at(i)->dVelocityX = b.at(i)->dVelocityX * -1 * b.at(i)->dBounceCof;
                bounce=true;
            }
            else if( b.at(i)->rBall.right >= SCREEN_WIDTH && b.at(i)->dVelocityX > 0) //ball bounces against the right wall
            {
                b.at(i)->dVelocityX = b.at(i)->dVelocityX * -1 * b.at(i)->dBounceCof;
                bounce=true;
            }
            //handle the Y bounce
            if( b.at(i)->rBall.bottom >= SCREEN_HEIGHT && b.at(i)->dVelocityY > 0 ) //ball bounces against the left wall
            {
                //damping of the ball
                if(b.at(i)->dVelocityY < 2+o.dGravity/o.REFRESH)
                {
                    b.at(i)->dVelocityY = 0;
                }

                //decrease the Velocity of the ball according to the bouncecof
                b.at(i)->dVelocityY = b.at(i)->dVelocityY * -1*b.at(i)->dBounceCof;
                b.at(i)->dVelocityX = b.at(i)->dVelocityX * b.at(i)->dBounceCof;

                bounce=true;
            }

            //gravity
            b.at(i)->dVelocityY += (o.dGravity)/o.REFRESH;
            b.at(i)->pOrigin.y += b.at(i)->dVelocityY + (1/2)*o.dGravity/o.REFRESH*DT*METER;
            //METER IS DEFINED GLOBALLY AS 100 which is the amount of pixels in a meter

            b.at(i)->pOrigin.x += b.at(i)->dVelocityX/o.REFRESH*METER;

            b.at(i)->UpdateRect();
        }
    }
    return;
}

A: You are using the Euler method of integration. It is possible that your time step (DT) is too large. Also there seems to be a mistake on the row that updates the Y coordinate:
  b.at(i)->pOrigin.y += b.at(i)->dVelocityY + (1/2)*o.dGravity/o.REFRESH*DT*METER;

You have already added the gravity to the velocity, so you don't need to add it to the position and you are not multiplying the velocity by DT. It should be like this:
  b.at(i)->pOrigin.y += b.at(i)->dVelocityY * DT;

Furthermore there appears to be some confusion regarding the units (the way METER is used).

A: Okay, a few things here.
You have differing code paths for bounce against left wall and against right wall, but the code is the same.  Combine those code paths, since the code is the same.
As to your basic problem: I suspect that your problem stems from the fact that you apply the gravity after you apply any damping forces / bounce forces.

A: When do you call RunPhysics? In a timer loop? This code is just an approximation and no exact calculation. In the short interval of delta t, the ball has already changed his position and velocity a litte bit which isn't considered in your algorithm and produces little mistakes. You'll have to compute the time until the ball hits the ground and predict the changes.
And the gravity is already included in the velocity, so don't add it twice here:
b.at(i)->pOrigin.y += b.at(i)->dVelocityY + (1/2)*o.dGravity/o.REFRESH*DT*METER;
By the way: Save b.at(i) in a temporary variable, so you don't have to recompute it in every line.
Ball* CurrentBall = b.at(i);

A: ANSWER!!ANSWER!!ANSWER!! but i forgot my other account so i can't flag it :-(
Thanks for all the great replies, it really helped me alot! The answers that you gave were indeed correct, a couple of my formulas were wrong and some code optimisation could be done, but none was really a solution to the problem. So i just sat down with a piece of paper and started calculation every value i got from my program by hand, took me like two hours :O But i did find the solution to my problem:
The problem is that as i update my velocity (whith corrected code) i get a decimal value, no problem at all. Later i increase the position in Y by adding the velocity times the Delta T, which is a verry small value. The result is a verry small value that needs to be added. The problem is now that if you draw a Elipse() in Win32 the point is a LONG and so all the decimal values are lost. That means that only after a verry long period, when the values velocity starts to come out of the decimal values something happens, and that alongside with that, the higher you drop the ball the better the results (one of my symptons) The solution to this problem was really simple, ad an extra DOUBLE value to my Ball class which contained the true position (including decimals) of my ball. During the RenderFrame() you just take the floor or ceiling value of the double to draw the elipse but for all the calculations you use the Double value. Once again thanks alot for all your replies, STACKOVERFLOW PEOPLE ROCK!!!

A: If your dBounceCof is > 1 then, yes your ball will bounce higher.
We do not have all the values to be able to reply to your question.

A: I don't think your equation for position is right:
 b.at(i)->dVelocityY += (o.dGravity)/o.REFRESH;

This is v=v0+gt - that seems fine, although I'd write dGravity*DT instead of dGravity/REFRESH_FREQ.
 b.at(i)->pOrigin.y += b.at(i)->dVelocityY + (1/2)*o.dGravity/o.REFRESH*DT*METER;

But this seems off: It is eqivalent to  p = p0+v + 1/2gt^2.

*

*You ought to multiply velocity * time to get the units right

*You are scaling the gravity term by pixels/meter, but not the velocity term.  So that ought to be multiplied by METER also

*You have already accounted for the effect of gravity when you updated velocity, so you don't need to add the gravity term again.

A: Thanks for the quick replies!!! Sorry, i should have been more clear, the RunPhysics is beiing run after a PeekMessage. I have also added a frame limiter which makes sure that no more calculations are done per second than the refresh rate of the monitor. My dleta t is therefore 1 second devided by the refresh rate. Maybe my DT is actually too small to calculate, although it's a double value??? My cof of restitution is adjustable but starts at 0.9

A: You need to recompute your position on bounce, to make sure you bounce from the correct place on the wall.
I.e. resolve the exact point in time when the bounce occured, and calculate new velocity/position based on that direction change (partially into a "frame" of calculation) to make sure your ball does not move "beyond" the walls, more and more on each bounce.
W.r.t. time step, you might want to check out my answer here.

A: In a rigid body simulation, you need to run the integration up to the instant of collision, then adjust the velocities to avoid penetration at the collision, and then resume the integration.  It's sort of an instantaneous kludge to cover the fact that rigid bodies are an approximation.  (A real ball deforms during a collision.  That's hard to model, and it's unnecessary for most purposes.)
You're combining these two steps (integrating the forces and resolving the collisions).  For a simple simulation like you've shown, it's probably enough to skip the gravity bit on any iteration where you've handled a vertical bounce.
In a more advanced simulation, you'd split any interval (dt) that contains a collision at the actual instance of collision.  Integrate up to the collision, then resolve the collision (by adjusting the velocity), and then integrate for the rest of the interval.  But this looks like overkill for your situation.


text:
Q: ValidateAntiForgeryToken breaks page I have an ASP .Net Core 1.1 MVC web app. When I add the [ValidateAntiForgeryToken] decoration to my Edit/Delete/Create controllers, the pages don't load (
HTTP 400 error). Any ideas why? I read somewhere that I have to add a corresponding @HtmlHelper.AntiForgeryToken to my Views, or something like that? But not sure where to put it... However, I've also read that it's not necessary to do this anymoer in ASP .Net Core...
Here is an example of my Edit view for a "Users" controller:
@model InspectionsData.Models.User

@{
    ViewData["Title"] = "Edit";
}

Edit

<form asp-action="Edit">

User

                <input asp-for="UserId" class="form-control" />

                <input asp-for="FirstName" class="form-control" />

                <input asp-for="LastName" class="form-control" />

</form>

    Back to List

Thank you

A: You need to change your form declaration to something like the following.
<form asp-controller="User"
    asp-action="Edit" method="post" asp-antiforgery="true">

Like you mention, the asp-antiforgery="true" may be optional, but I like to always add that to make sure that I show my intentions. This works for me every time.
Hope this helps.

A: Yes, you are correct. You don't have to manually put AntiForgeryToken anymore in ASP.NET Core.

The Form tag helper generates a hidden Request Verification Token to
  prevent cross-site request forgery (when used with the
  [ValidateAntiForgeryToken] attribute in the HTTP Post action method)

Taken from ASP.NET Core docs
Having that said, are you sure your actions correspond to POST request?
Also specifying the Controller is also a good idea.
<form asp-controller="Users" asp-action="Edit">

P.S: Adding the code for your action methods would help solve the issue faster.


text:
Q: Prove that $|p_1 - q_1| \leq p_2 - q_2$ relation is transitive for all points in $\mathbb{R}^2$ Given two points $p,q \in \mathbb{R}^2$, we say $p \preccurlyeq q$ if $|p_1 - q_1| \leq p_2 - q_2$.
How do I show that this relation is transitive?
By definition I have to show that if xRy and yRz then xRz $\forall x,y,z \in \mathbb{R}^2$.

A: Suppose $p \preccurlyeq q$ and $q \preccurlyeq r$, we want to show that $p \preccurlyeq r$. Using the triangle inequality, we have:
$|p_1 - r_1| = |p_1 - q_1 + q_1 - r_1| \leq |p_1 - q_1| + |q_1 - r_1| \leq p_2 - q_2 + q_2 - r_2 = p_2 - r_2$
Therefore, one has $p \preccurlyeq r$.


text:
Q: Authorization in WebApi I am building an admin page (MVC 5) using an AdminColntroller:
[Authorize(Roles = "Admin")]
public class AdminController : ApplicationBaseController
{
    public ActionResult Index()
    {
        return View();
    }
}

I want to implement it as a single page application so I will be making client-side ajax calls to an admin web api which I also want to secure access to:
[RoutePrefix("api/admin")]
[Authorize(Roles = "admin")]
public class AdminApiController : ApiController
{
    [Route("echo")]
    public HttpResponseMessage GetEcho()
    {
        return Request.CreateResponse(HttpStatusCode.OK, new {Result = "Hello World"});
    }
}

This is the ajax call I'm making form the admin view:
<script>
    jQuery.ajax("https://example.com/api/admin/echo").done(function(data) {
        console.log(data);
    }).fail(function(a,b,c) {
        console.log(a);
    });
</script>

This throws an error (fail() method): "Authorization has been denied for this request." I don't understand why - my user has a role Admin (that's why I am able to even get to the admin page), and if I remove [Authorize] from GetEcho() method and then set a breakpoint inside it, I see the correct User object. Any ideas what I am doing wrong?

A: The issue that you are having is that against the MVC controller, you have this:
[Authorize(Roles = "Admin")]

Whilst against the API controller, you have this:
[Authorize(Roles = "admin")]

The role check is case sensitive.  If you change the API controller to use Admin instead of admin, it should solve the issue.

A: You always have to carry by your authentication data or the user token (based on the authentication way you use) with your API request.
In plain jQuery it could look like
$.ajax({
   beforeSend: function (xhr) {
     xhr.setRequestHeader("ownToken", authToken);


text:
Q: Computer freezes for 2+ seconds, mouse still moves I have this problem on my workstation. The computer would effectively freeze for 2-5 seconds for no apparent reason, then continue as normal. While frozen the mouse would still be movable, but only on one of screens in my multi-screen setup. What can be the likely cause.
System:

*

*CPU: i7-920

*Memory: 12G of Patriot DDR3, 6 modules

*OS: SLED 11, Suse Linux Enterprise Desktop, using Gnome

*Main board: Asus P6T

*Video: two Nvidia 9500GT connected to three displays

I am using memory at recommended settings of 8-8-8-1333. It has an XMP profile. Th CPU is a bit overclocked to 3.3 GHz, but my cooling more than allows for it. I ran the computer with all overclocks off and lower memory speed but the issue was still there.
Any ideas? Where should I start looking?

A: Any chance your workstation is mounting /home over nfs?  That can cause the exact symptoms you describe if your network connectivity gets interrupted or the nfs server goes down briefly.


text:
Q: Allocate scatter plot into specific bins I have a scatter plot that gets sorted into 4 Bins. These are separated by two arcs and a line in the middle (see figure below).
There's a slight problem with the two arcs. If the X-Coordiante is greater than the ang2 it doesn't get attributed to the correct Bin. (Please see figure below)
import math
import matplotlib.pyplot as plt
import matplotlib as mpl

X = [24,15,71,72,6,13,77,52,52,62,46,43,31,35,41]
Y = [94,61,76,83,69,86,78,57,45,94,82,74,56,70,94]

fig, ax = plt.subplots()
ax.set_xlim(-100,100)
ax.set_ylim(-40,140)
ax.grid(False)

plt.scatter(X,Y)

#middle line
BIN_23_X = 0
#two arcs
ang1 = -60, 60
ang2 = 60, 60
angle = math.degrees(math.acos(2/9.15))
E_xy = 0,60

Halfway = mpl.lines.Line2D((BIN_23_X,BIN_23_X), (0,125), color = 'white', lw = 1.5, alpha = 0.8, zorder = 1)
arc1 = mpl.patches.Arc(ang1, 70, 110, angle = 0, theta2 = angle, theta1 = 360-angle, color = 'white', lw = 2)
arc2 = mpl.patches.Arc(ang2, 70, 110, angle = 0, theta2 = 180+angle, theta1 = 180-angle, color = 'white', lw = 2)
Oval = mpl.patches.Ellipse(E_xy, 160, 130, lw = 3, edgecolor = 'black', color = 'white', alpha = 0.2)

ax.add_line(Halfway)
ax.add_patch(arc1)
ax.add_patch(arc2)
ax.add_patch(Oval)

#Sorting the coordinates into bins
def get_nearest_arc_vert(x, y, arc_vertices):
err = (arc_vertices[:,0] - x)**2 + (arc_vertices[:,1] - y)**2
nearest = (arc_vertices[err == min(err)])[0]
return nearest

arc1v = ax.transData.inverted().transform(arc1.get_verts())
arc2v = ax.transData.inverted().transform(arc2.get_verts())

def classify_pointset(vx, vy):
    bins = {(k+1):[] for k in range(4)}
    for (x,y) in zip(vx, vy):
        nx1, ny1 = get_nearest_arc_vert(x, y, arc1v)
        nx2, ny2 = get_nearest_arc_vert(x, y, arc2v)

        if x < nx1:
            bins[1].append((x,y))
        elif x > nx2:
            bins[4].append((x,y))
        else:
            if x < BIN_23_X:
                bins[2].append((x,y))
            else:
               bins[3].append((x,y))
    return bins

#Bins Output
bins_red  = classify_pointset(X,Y)

all_points = [None] * 5
for bin_key in [1,2,3,4]:
    all_points[bin_key] = bins_red[bin_key]

Output:
[[], [], [(24, 94), (15, 61), (71, 76), (72, 83), (6, 69), (13, 86), (77, 78), (62, 94)], [(52, 57), (52, 45), (46, 82), (43, 74), (31, 56), (35, 70), (41, 94)]]

This isn't quite right. Looking at the figure output below, 4 coordinates are in Bin 3 and 11 are in Bin 4. But 8 are attributed to Bin 3 and 7 are attributed to Bin 4.
I think the problem is the blue coordinates. Specifically, when the X-Coordinate is greater than ang2, which is 60. If I alter these to be less than 60 they will be corrected into Bin 3.
I'm not sure if I should extend the arcs to be greater than 60 or if the code can be improved?
Please note this is just for Bin 4 and ang2. The issue will occur for Bin 1 and ang1. That is, if the X-Cooridnate is less than 60 it won't get attributed to Bin 1
Intended Output:
[[], [], [(24, 94), (15, 61), (6, 69), (13, 86)], [(71, 76), (72, 83), (52, 57), (52, 45), (46, 82), (43, 74), (31, 56), (35, 70), (41, 94), (77, 78), (62, 94)]]

Note: The intended output is preferred. The example uses one row of input data. However, my dataset is much larger. If we use numerous rows the output should be row by row. e.g
#Numerous rows
X = np.random.randint(50, size=(100, 10))
Y = np.random.randint(80, size=(100, 10))

Out:
Row 0 = [(x,y)],[(x,y)],[(x,y)],[(x,y)]
Row 1 = [(x,y)],[(x,y)],[(x,y)],[(x,y)]
Row 2 = [(x,y)],[(x,y)],[(x,y)],[(x,y)]
etc

A: Patches have a test for containing points or not: contains_point and even for arrays of points:contains_points
Just to play with I have a code snippet for you, which you can add between the part where you're adding your patches and the #Sorting the coordinates into bins codeblock.
It adds two additional (transparent) ellipses for calculating if the arcs would contain points if they were fully closed ellipses. Then your bin calculation is just a boolean combination of tests if a point belongs to the big oval, the left or right ellipsis or has positive or negative x-coordinate.
ov1 = mpl.patches.Ellipse(ang1, 70, 110, alpha=0)
ov2 = mpl.patches.Ellipse(ang2, 70, 110, alpha=0)
ax.add_patch(ov1)
ax.add_patch(ov2)

for px, py in zip(X, Y):
    in_oval = Oval.contains_point(ax.transData.transform(([px, py])), 0)
    in_left = ov1.contains_point(ax.transData.transform(([px, py])), 0)
    in_right = ov2.contains_point(ax.transData.transform(([px, py])), 0)
    on_left = px < 0
    on_right = px > 0
    if in_oval:
        if in_left:
            n_bin = 1
        elif in_right:
            n_bin = 4
        elif on_left:
            n_bin = 2
        elif on_right:
            n_bin = 3
        else:
            n_bin = -1
    else:
        n_bin = -1
    print('({:>2}/{:>2}) is {}'.format(px, py, 'in Bin ' +str(n_bin) if n_bin>0 else 'outside'))

The output is:
(24/94) is in Bin 3
(15/61) is in Bin 3
(71/76) is in Bin 4
(72/83) is in Bin 4
( 6/69) is in Bin 3
(13/86) is in Bin 3
(77/78) is outside
(52/57) is in Bin 4
(52/45) is in Bin 4
(62/94) is in Bin 4
(46/82) is in Bin 4
(43/74) is in Bin 4
(31/56) is in Bin 4
(35/70) is in Bin 4
(41/94) is in Bin 4

Note you still should decide how to define bins when points have x-coord=0 - at the moment they're equal to outside, as on_left and on_rightboth do not feel responsible for them...
PS: Thanks to @ImportanceOfBeingErnest for the hint to the necessary transformation: https://stackoverflow.com/a/49112347/8300135
Note: for all the following EDITS you'll need to import numpy as np
EDIT:
Function for counting the bin distribution per X, Y array input:
def bin_counts(X, Y):
    bc = dict()
    E = Oval.contains_points(ax.transData.transform(np.array([X, Y]).T), 0)
    E_l = ov1.contains_points(ax.transData.transform(np.array([X, Y]).T), 0)
    E_r = ov2.contains_points(ax.transData.transform(np.array([X, Y]).T), 0)
    L = np.array(X) < 0
    R = np.array(X) > 0
    bc[1] = np.sum(E & E_l)
    bc[2] = np.sum(E & L & ~E_l)
    bc[3] = np.sum(E & R & ~E_r)
    bc[4] = np.sum(E & E_r)
    return bc

Will lead to this result:
bin_counts(X, Y)
Out: {1: 0, 2: 0, 3: 4, 4: 10}

EDIT2:
many rows in two 2D-arrays for X and Y:
np.random.seed(42)
X = np.random.randint(-80, 80, size=(100, 10))
Y = np.random.randint(0, 120, size=(100, 10))

looping over all the rows:
for xr, yr in zip(X, Y):
    print(bin_counts(xr, yr))

result:
{1: 1, 2: 2, 3: 6, 4: 0}
{1: 1, 2: 0, 3: 4, 4: 2}
{1: 5, 2: 2, 3: 1, 4: 1}
...
{1: 3, 2: 2, 3: 2, 4: 0}
{1: 2, 2: 4, 3: 1, 4: 1}
{1: 1, 2: 1, 3: 6, 4: 2}

EDIT3:
for returning not the number of points in each bin, but an array with four arrays containing the x,y-coordinates of the points in each bin, use the following:
X = [24,15,71,72,6,13,77,52,52,62,46,43,31,35,41]
Y = [94,61,76,83,69,86,78,57,45,94,82,74,56,70,94]

def bin_points(X, Y):
    X = np.array(X)
    Y = np.array(Y)
    E = Oval.contains_points(ax.transData.transform(np.array([X, Y]).T), 0)
    E_l = ov1.contains_points(ax.transData.transform(np.array([X, Y]).T), 0)
    E_r = ov2.contains_points(ax.transData.transform(np.array([X, Y]).T), 0)
    L = X < 0
    R = X > 0
    bp1 = np.array([X[E & E_l], Y[E & E_l]]).T
    bp2 = np.array([X[E & L & ~E_l], Y[E & L & ~E_l]]).T
    bp3 = np.array([X[E & R & ~E_r], Y[E & R & ~E_r]]).T
    bp4 = np.array([X[E & E_r], Y[E & E_r]]).T
    return [bp1, bp2, bp3, bp4]

print(bin_points(X, Y))
[array([], shape=(0, 2), dtype=int32), array([], shape=(0, 2), dtype=int32), array([[24, 94],
       [15, 61],
       [ 6, 69],
       [13, 86]]), array([[71, 76],
       [72, 83],
       [52, 57],
       [52, 45],
       [62, 94],
       [46, 82],
       [43, 74],
       [31, 56],
       [35, 70],
       [41, 94]])]

...and again, for applying this to the big 2D-arrays, just iterate over them:
np.random.seed(42)
X = np.random.randint(-100, 100, size=(100, 10))
Y = np.random.randint(-40, 140, size=(100, 10))

bincol = ['r', 'g', 'b', 'y', 'k']

for xr, yr in zip(X, Y):
    for i, binned_points in enumerate(bin_points(xr, yr)):
        ax.scatter(*binned_points.T, c=bincol[i], marker='o' if i<4 else 'x')

A: This is a version where I sort it into ellipses. As the OP is using simple geometric shapes one can test this with a simple formula, i.e. not "asking" the patch. I generalized it for n arcs with the small disadvantage that bin numbering is not from left to right, but this can be taken care of elsewhere.
Output is of type
[ [ [x,y], [x,y],...], ... ]

i.e. a list of x,y for each bins. Numbering here is from -3 to 3 though, with 0 being outside.
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np

def in_ellipse( xy, x0y0ab):
    x, y = xy
    x0, y0 = x0y0ab[0]
    a = x0y0ab[1]/2.  ## as the list of ellipses takes width and not semi axis
    b = x0y0ab[2]/2.
    return ( x - x0 )**2 / a**2+ ( y - y0 )**2 / b**2 < 1

def sort_into_bins( xy, mainE, eList ):
    binCntr = 0
    xyA = (np.abs(xy[0]),xy[1]) ## all positive
    if in_ellipse( xyA, mainE ):
        binCntr +=1
        for ell in eList:
            if in_ellipse( xyA, ell ):
                break
            binCntr +=1
    binCntr=np.copysign( binCntr, xy[0] )
    return int( binCntr )

X = 200 * np.random.random(150) - 100
Y = 140 * np.random.random(150) - 70 + 60

fig, ax = plt.subplots()
ax.set_xlim(-100,100)
ax.set_ylim(-40,140)
ax.grid(False)

BIN_23_X = 0
mainEllipse = [ np.array([0, 60]), 160, 130 ]
allEllipses = [ [ np.array([60,60]), 70., 110. ], [ np.array([60,60]), 100, 160 ]  ]

Halfway = mpl.lines.Line2D((BIN_23_X,BIN_23_X), (0,125), color = '#808080', lw = 1.5, alpha = 0.8, zorder = 1)
Oval = mpl.patches.Ellipse( mainEllipse[0], mainEllipse[1], mainEllipse[2], lw = 3, edgecolor = '#808080', facecolor = '#808080', alpha = 0.2)
ax.add_patch(Oval)
ax.add_line(Halfway)

for ell in allEllipses:
    arc =  mpl.patches.Arc( ell[0] , ell[1], ell[2], angle = 0,  color = '#808080', lw = 2, linestyle=':')
    ax.add_patch( arc )
    arc =  mpl.patches.Arc( ell[0] * np.array([ -1, 1 ]), ell[1], ell[2], angle = 0,  color = '#808080', lw = 2, linestyle=':')
    ax.add_patch( arc )

binDict = dict()
for x,y in zip(X,Y):
    binDict[( x,y)]=sort_into_bins( (x,y), mainEllipse, allEllipses )

rowEval=[]
for s in range(-3,4):
    rowEval+=[[]]
for key, val in binDict.iteritems():
    rowEval[ val + 3 ]+=[key]

for s in range(-3,4):
    plt.scatter( *zip( *rowEval[ s + 3 ] ) )

plt.show()

showing

Note that I used the fact of symmetry with respect to x=0. If the ellipses are shifted with respect to x the code has to be modified a little.
Also note that the order in which the ellipses are provided matters!


text:
Q: Not able to install OCRPaddle for WIndows I'm trying to install the PaddleOCR package following the Quick Start Guide. When I run this command to install PaddleOCR Whl Package:

pip install "paddleocr>=2.0.1" # Recommend to use version 2.0.1+

I'm getting this error when building the Poligon3 wheel:

  Building wheel for Polygon3 (setup.py) ... error
  error: subprocess-exited-with-error

  × python setup.py bdist_wheel did not run successfully.
  │ exit code: 1
  ╰─> [14 lines of output]
      Using NumPy extension!
      running bdist_wheel
      running build
      running build_py
      creating build
      creating build\lib.win-amd64-cpython-37
      creating build\lib.win-amd64-cpython-37\Polygon
      copying Polygon\IO.py -> build\lib.win-amd64-cpython-37\Polygon
      copying Polygon\Shapes.py -> build\lib.win-amd64-cpython-37\Polygon
      copying Polygon\Utils.py -> build\lib.win-amd64-cpython-37\Polygon
      copying Polygon\__init__.py -> build\lib.win-amd64-cpython-37\Polygon
      running build_ext
      building 'Polygon.cPolygon' extension
      error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
  ERROR: Failed building wheel for Polygon3
  Running setup.py clean for Polygon3
Failed to build Polygon3
Installing collected packages: Polygon3, lmdb, zipp, typing-extensions, tifffile, shapely, scipy, rapidfuzz, PyWavelets, python-dateutil, pyparsing, pycryptodome, opencv-python, opencv-contrib-python, networkx, MarkupSafe, lxml, itsdangerous, imageio, future, fonttools, et-xmlfile, dill, cython, cycler, cssselect, colorama, cachetools, Babel, attrdict, Werkzeug, tqdm, pandas, packaging, openpyxl, multiprocess, kiwisolver, Jinja2, importlib-metadata, bce-python-sdk, scikit-image, matplotlib, cssutils, click, premailer, imgaug, flask, Flask-Babel, visualdl, paddleocr
  Running setup.py install for Polygon3 ... error
  error: subprocess-exited-with-error

  × Running setup.py install for Polygon3 did not run successfully.
  │ exit code: 1
  ╰─> [16 lines of output]
      Using NumPy extension!
      running install
      C:\Users\jd\miniconda3\envs\ocrpaddle\lib\site-packages\setuptools\command\install.py:37: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools.
        setuptools.SetuptoolsDeprecationWarning,
      running build
      running build_py
      creating build
      creating build\lib.win-amd64-cpython-37
      creating build\lib.win-amd64-cpython-37\Polygon
      copying Polygon\IO.py -> build\lib.win-amd64-cpython-37\Polygon
      copying Polygon\Shapes.py -> build\lib.win-amd64-cpython-37\Polygon
      copying Polygon\Utils.py -> build\lib.win-amd64-cpython-37\Polygon
      copying Polygon\__init__.py -> build\lib.win-amd64-cpython-37\Polygon
      running build_ext
      building 'Polygon.cPolygon' extension
      error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: legacy-install-failure

× Encountered error while trying to install package.
╰─> Polygon3

note: This is an issue with the package mentioned above, not pip.

Has anyone encountered this problem? I'm using a conda environment with Python 3.7.

A: It is clearly mentioned that you need to install "Microsoft Visual C++ 14.0 or above"
Please install it and you are good to go.


text:
Q: In Graph to tree: name of operation where edges removed and vertex/edge additions?
The graph has tree paths IN-1-OUT, IN-2-OUT and IN-3&4-OUT between IN and OUT in the left. I want to make each path to a branch like the right.

What is the name of this operation or the name of this procedure to make a graph into a tree?

A: Not tree unless changes such as changing the OUT vertices or removing paths
This picture below does not represent a tree because

"a tree is an undirected graph in which any two vertices are connected by exactly one path."

where you have many paths between IN vertex and OUT vertex. You could call different OUT vertices with OUT1, OUT2 and OUT3 -- similarly for paths IN-3-OUT and IN-4-OUT so each parallelization increases the number of OUT vertices by one.

Operations to make the graph to tree
The name of the operations contain insertion of vertices and removal/insertion of edges as written in the picture. Other way to see this is to consider graph theory in terms of linear algebra. So

*

*the path matrix $P_{in}$ where $in$ is the root is {{1, out}, {2,out}, {3,out}, {4,out}} while the reduced path matrx $P_{in}^{-1}$ is {{1}, {2}, {3}, {4}} with the last out-edge removed.

*Path matrix $P_n$ representation for graph $G$ where $n$ is a root vertex. The $j$th column is a path such that the entry is 1 if the edge in the path and 0 otherwise. (Page 17 of Graphs And Matrices by Babat 2nd ed)

*Textbook on Graph Theory using Linear Algebra


text:
Q: Makefile explanation. Understanding someone else's Makefile I am relatively new to programming on Linux.
I understand that Makefiles are used to ease the compiling process when compiling several files.
Rather than writing "g++ main.cpp x.cpp y.cpp -o executable" everytime you need to compile and run your program, you can throw it into a Makefile and run make in that directory.
I am trying to get a RPi and Arduino to communicate with each other using the nRF24L01 radios using tmrh20's library here. I have been successful using tmrh20's Makefile to build the the executable needed (on the RPi). I would like to, however, use tmrh20's library to build my own executables.
I have watched several tutorial videos on Makefiles but still cannot seem to piece together what is happening in tmrh20's.
The Makefile (1) in question is here.  I believe it is somehow referencing a second Makefile (2) (for filenames?) here. (Why is this necessary?)
If it helps anyone understand (it took me a while) I had to build using SPIDEV (the instructions here) the Makefile (3) in the RF24 directory which produced several object files which I think are relevant to Makefile (1)&(2).
How do I find out what files I need to make my own Makefile, from tmrh20's Makefile (if that makes sense?) He seems to use variables in his Makefile that are not defined? Or are perhaps defined elsewhere?
Apologies for my poor explanation.

A: The canonical sequence is not just make and make install. There is an initial ./configure step (such a file is here) that sets up everything and generates several files used in the make steps.
You only need to run this configure script successfully only once, unless you want to change build parameters. I say "successfully" because the first execution will usually complain that you are missing libraries or header files. But ince ./configure runs without errors, make and make install should run without errors.
PS: I didn't try to compile it, but since the project has a rather comprehensive configure it is likely complete and you shouldn't need to tweak makefiles if your follow the usual procedure.

A: The reason for splitting the Makefiles in the way you've mentioned and linked to here is to separate the definition of the variables from the implementation. This way you could have multiple base Makefiles that define their PROGRAM variable differently, but all do the same thing based on the value of that variable.
In my own personal opinion, I see some value here - but there very many ways to skin this proverbial cat.
Having learned GNU Make the hard way, I can only recommend you do the same. There's a slight steep curve at the beginning, but once you get the main concepts down following other peoples Makefiles gets pretty easy.
Good luck: https://www.gnu.org/software/make/manual/html_node/index.html


text:
Q: mysql - Limit a query with left join I have 2 tables like this:
Table person
id | name
---------
1  | john
2  | mike
3  | carl
4  | keny
5  | anna

Table vehicle
owner | vechicle
----------------
1     | RTA457
3     | GSW684
3     | GKI321
3     | SNE798
5     | YTT662

So, I want to make a query joining both tables, something like this:
SELECT * FROM person LEFT JOIN vehicle ON person.id=vehicle.owner

Getting these results
id | name | owner | vechicle
----------------------------
1  | john | 1     | RTA457
2  | mike | NULL  | NULL
3  | carl | 3     | GSW684
3  | carl | 3     | GKI321
3  | carl | 3     | SNE798
4  | keny | NULL  | NULL
5  | anna | 5     | YTT662

Finally, I want to limit it to 3 persons, showing all their vehicles, like this:
id | name | owner | vechicle
----------------------------
1  | john | 1     | RTA457
2  | mike | NULL  | NULL
3  | carl | 3     | GSW684
3  | carl | 3     | GKI321
3  | carl | 3     | SNE798

There is any way to do it?

A: May help with a subquery
SELECT
    *
FROM
    (SELECT * FROM person LIMIT 3) t
LEFT JOIN vehicle ON t.id = vehicle.owner

A: Didn't try it, but something like this:
SELECT * FROM person
LEFT JOIN vehicle ON person.id = vehicle.owner
WHERE person.id IN (SELECT ID FROM PERSON LIMIT 3);

A: You could simply have your query as such:
SELECT * FROM person LEFT JOIN vehicle ON person.id=vehicle.owner LIMIT 10;

This SO could be handy as well. Hope this helps!


text:
Q: Looking for a way to read and write a text file I am making a program and I have absolutely no clue how to read and write a text file. I would like it so that I only need one text file that has all kinds of data, so I need to be able to read specific lines of the file.

A: You can use StreamReader and StreamWriter classes:
StreamReader sr = new StreamReader("C:\\Sample.txt");

var data = sr.ReadLine();

StreamWriter sw = new StreamWriter("C:\\Test.txt");

sw.WriteLine("Hello World!!");

Taken from: http://support.microsoft.com/kb/816149.
EDIT: To clarify, always close the streams. sr.Close() sw.Close(). Or wrap them within a using statement just as James did on his answer.

A: using (System.IO.StreamReader sr = new System.IO.StreamReader("YourFile.txt"))
{
  String line = sr.ReadLine();
  Console.WriteLine(line);
}

A: you can also use the File class.
string h1 = File.ReadAllText("D:\\TempFiles\\h1.txt");
string h1 = File.WriteAllText("D:\\TempFiles\\h1.txt");


text:
Q: Issue with join in Teradata I have a very strange problem when I do the following join on two different tables in Teradata. It does not return any results, indicating that there is no common value between table_A and table_B.
SELECT
*
FROM
table_A a JOIN table_B b ON a.id = b.id;

<>
0 rows returned

However when I run the following two queries, I do get results indicating that the id column in both the tables has at least one row with 'John'.
SELECT
id
FROM table_A
WHERE
id = 'John';

<>
 1 row returned

SELECT
id
FROM table_B
WHERE
id = 'John';

<>
1 row returned

The data type for all the columns in table_A and table_B is null

A: Can you try using  the below approach :
ON trim(UPPER(table_A.id)) = trim(UPPER(table_B.id))


text:
Q: Msg 4104 using INNER JOINS - SQL SERVER 2012 I have these tables:
I am trying to get the article_id, article_name, article_title, article_description and article_date from articles and username from users by using a connecting table, user_articles.
I have tried this code:
SELECT E.article_id, E.article_title, E.article_description, E.article_date, u.username
FROM articles AS E, users as u
INNER JOIN user_articles as A ON A.article_id = E.article_id
INNER JOIN users as u2 ON u2.user_id = A.user_id
WHERE E.article_status = 1

And I am getting this error message:
Msg 4104, Level 16, State 1, Line 3
The multi-part identifier "E.article_id" could not be bound.

I am using SQL Server 2012 Express.

A: You can not select from one table and apply a join on the other. Try this query:
SELECT E.article_id, E.article_title, E.article_description, E.article_date, u.username
FROM articles AS E
    INNER JOIN user_articles as A ON A.article_id = E.article_id
    INNER JOIN users as u ON u.user_id = A.user_id
WHERE E.article_status = 1

A: The problem is that you are mixing JOIN types, you have both comma separated implicit JOINs and then explicit JOINs.  Your code should be:
SELECT E.article_id,
  E.article_title,
  E.article_description,
  E.article_date,
  u.username
FROM articles AS E
INNER JOIN user_articles as A
  ON A.article_id = E.article_id
INNER JOIN users as u
  ON A.user_id = u.user_id
WHERE E.article_status = 1;

A: im thinking why do u even need such a table as : users_articles ?
wouldnt it be more efficient to add a column named (article_author) to the articles table which is populated with the id of the user ??  then u can inner join on that value.just saying


text:
Q: Как сгруппировать элементы ListView? wpf Вопрос простой. Мне нужно сгруппировать мой ListView (в котором GridView) где-то так:
Проблема в том, что я перелопатил кучу статей и везде используется куча кода в Code-Behind (даже коллекцию часто задают в конструкторе). Мне нужно нормальное MVVM решение.

A: Проблема решена. Что нужно было сделать, так это добавить в ресурсы CollectionViewSource и в него добавить GroupDescription. В моем случае это:
<Window.Resources>
    <CollectionViewSource x:Key="envVariables" Source="{Binding Variables}">
        <CollectionViewSource.GroupDescriptions>
            <PropertyGroupDescription PropertyName="Hive"/>
        </CollectionViewSource.GroupDescriptions>
    </CollectionViewSource>
</Window.Resources>

А в ListView установить ItemsSource следующим образом:
<ListView ItemsSource="{Binding Source={StaticResource envVariables}}">

и добавить GroupStyle:
<ListView.GroupStyle>
    <GroupStyle>
        <GroupStyle.HeaderTemplate>
            <DataTemplate>
                <TextBlock FontWeight="Bold" FontSize="14" Text="{Binding Name}"/>
            </DataTemplate>
        </GroupStyle.HeaderTemplate>
    </GroupStyle>
</ListView.GroupStyle>


text: Q: Linux kernel: how to load module last I wrote a kernel simple module, and I can select my module with make menuconfig. The module compiles and executes without a problem. Is there a method to force the kernel to load my module last - after all other modules? Are kernel modules loaded randomly or predictably? If they are loaded predictably, how can I specify that my module loads last? If I compile the module into the kernel, can this action somehow cause my module to load last of all modules?


text:
Q: Reproducing Google image viewer with jQuery I'm trying to simulate Google image preview in my project. I think I'm almost there but there are couple of things I struggle to implement.
So the image viewer should do the following:

*

*Clicking a thumbnail will open up a preview panel right
underneath and close other preview panel that was from other row.
Closing other panel and opening current panel need slide transition.

*Clicking the same thumbnail will close the preview panel.

*Clicking "X" will also close the preview panel.

*Opening another thumbnail that is from the same row won't do any open/close action and will just swap contents.
My accomplishment so far is:

*

*is working partially - because it will only slideDown() for the
first preview panel and won't open/close with slide transition
anymore. And I'm not sure how other panel gets closed - I don't have any implementation for this yet.

*I can't make this work with all other conditions together. I've tried to use id of the triggered thumbnail and assign that id to the preview panel, then if they are match, close the preview panel but it will open/close at the same time which isn't the click toggle I'm after.

*works ok.

*works ok although I'm not 100% sure about my approach with oldIndex.

This is the JS Fiddle for you to play with containing the following script.
$.videoWatch = function(element) {
  this.$element = $(element);
  this.init();
};
var oldIndex = -1;

$.videoWatch.prototype = {

  init: function() {

    this.$openLinks = this.$element.find(".open");
    this.$closeLinks = this.$element.find(".close");
    this.open();
    this.close();
  },

  _getContent: function(element) {
    var $parent = element.parent(),
      title = $parent.data('title');

    return {
      title: title
    }
  },

  open: function() {
    var self = this;

    self.$openLinks.on("click", function(e) {
      e.preventDefault();

      var $a = $(this),
        content = self._getContent($a),
        $li = $a.parents("li"),
        $title = $(".title");

      $title.text(content.title);

      $li.append($(".preview"));

      var $preview = $li.find(".preview");

      if (!($li.index() == oldIndex)) {
        $preview.slideDown('fast');
        oldIndex = $li.index();
      }
    });
  },
  close: function() {
    this.$closeLinks.on("click", function(e) {
      e.preventDefault();
      $(this).parent().slideUp('fast');
            oldIndex = -1;
    });
  }
};

$(function() {
  var watch = new $.videoWatch("ul");
});

A: nice demo, but I'm not sure what your questions are. as you've said you're expectations are unclear for how to accomplish #1 and #2
please see
https://jsfiddle.net/mouseoctopus/7ryfLu68/
for working demo
to accomplish #1, rehide the first preview before display
 if (!($li.index() == oldIndex)) {
     $preview.hide(); // add this line
     $preview.slideDown('fast');

to accomplish #2, unsure how to do without hax, had to store figure id and hide when the same one was clicked and then reshow when id is different
  else{
    var figureId = $a.parent()[0].id;
    if  ( oldFigureId == figureId ){
      $preview.slideUp('fast');
      oldFigureId = -1;
    }else{
      $preview.slideDown('fast');
      oldFigureId = figureId;
    }

  }

I'm not sure about the hax either with the oldIndex, oldFigureId, etc. its not clean.

A: 1 - Your appending and sliding code :
if (!($li.index() == oldIndex)) {
    $(".preview").slideUp('fast', function(){
        $li.append($(".preview"));

      var $preview = $li.find(".preview");
      $preview.slideDown('fast');
      oldIndex = $li.index();
    });
} else {
    $li.append($(".preview"));
}

2 - You can store current thumb id and check if it's open before doing anything and if it is, close it
if (curID == $(this).parent().attr("id")) {
    $(".preview").slideUp('fast');
    oldIndex = -1;
    curID = "";
    return false;
} else {
    curID = $(this).parent().attr("id");
}

UPDATED FIDDLE


text:
Q: How to understand the proof of disjoint closed set with distance $d > 0$ I am not student in Mathematics.
The following proof comes from the book: Real Analysis, by Elias and Rami (p.18):

The folloing is my problem:

*

*It seems the yellow part implies the result (but it does not prove anything). What is the difference between the yellow part and the conclusion $d(K,F)\geq\delta>0$? (Hope to know the logic of this proof)

*If no the condition "$K$ is compact", just "$K$ is closed", then there may not exist $\delta_x>0$ such that $d(x,F)>3\delta_x$. Correct?


text:
Q: Upgrade matrix synapse postgresql database from 9.6 to 11 I have a VM on my server where I host a Matrix synapse homeserver.
Now I need to update postgresql, because version 9.6 is EOL.
The database in /var/lib/postgresql/9.6/main already has 56 GByte.
I dumped the database in sql files with this script:
#!/bin/bash
DB=synapse
U=irc-bridge
# directory to dump files without trailing slash:
DIR=/home/synapse/postgres-backup
mkdir -p $DIR
TABLES="$(psql -q -d $DB -U $U -t -c "SELECT table_name FROM information_schema.tables WHERE table_type='BASE TABLE' ORDER BY table_name")"
w=$(echo $TABLES|wc -w)
echo $w tables
i=0
for table in $TABLES; do
  i=$((i + 1))
  echo "$i/$w: backup $table ..."
  pg_dump -U $U -t $table $DB | gzip > $DIR/$table.sql.gz;
done;

I get about 9 GByte of zipped Files.
What would be the easyest path to upgrade the Postgres cluster up from 9.6?

A: The best way is to dump the whole database and import it in the new cluster:
sudo -u postgres pg_dumpall --cluster 9.6/main > dump.sql
sudo -u postgres psql -d postgres --cluster 13/main -f dump.sql

see https://decatec.de/linux/postgresql-upgrade-auf-neue-version-durchfuehren

A: I had to do the upgrade as well, as Synapse, starting from version 1.72.0, dropped support for Postgresql older than version 11.
Context: Our installation is done with docker-compose, in /opt/synapse, with the postgres container defined like this:
db:
  image: docker.io/postgres:10-alpine
  shm_size: 1gb
  restart: unless-stopped
  environment:
    - POSTGRES_USER=synapse
    - POSTGRES_PASSWORD=my_postgres_password
    - POSTGRES_INITDB_ARGS=--encoding=UTF-8 --lc-collate=C --lc-ctype=C
  volumes:
    - ./schemas:/var/lib/postgresql/data

This means that the postgres data files are in /opt/synapse/schemas.
I used https://github.com/tianon/docker-postgres-upgrade to do the postgres data upgrade.
I ran into one problem: not having the role (user) postgres in my old (version 11) installation. I resolved that by specifying to the pg_upgrade script to use the role synapse, and manually bootstraping the new (version 15) database, because both old and new installation must have the same user available.
Step by step, it goes like this:

*

*Backup the data: cp -a schemas schemas-v11-backup

*Create folder structure the way docker-postgres-upgrade expects it to have:

mkdir -p upgradepg/10/data
mkdir -p upgradepg/15/data

*Copy the old postgres data into the "OLD" directory:
cp -a schemas/* upgradepg/10/data/

*Clean the schemas postgres data folder, so that we can initialize it with postgres version 15 data files: rm -rf schemas/*

*Change the postgres version in docker-compose.yml to 15 ( -> whole line is image: docker.io/postgres:15-alpine), and start the service with docker-compose up db. This will bootstrap the database container with user synapse and database synapse.

*pg_upgrade will be, however, migrating the old data ( = the old database), and it would fail if there already was a database called synapse. We have to delete the database:

docker-compose exec db psql -U synapse
\c postgres
drop database synapse;
exit

*Stop the running postgres 15 container (ctrl+c if it is bound to a terminal, otherwise docker-compose stop db)

*Copy the newly bootstrapped postgres 15 data directory into upgradepg/15/data: cp schemas/* upgradepg/15/data/

*run the migration tool: docker run --rm -v /opt/synapse/upgradepg:/var/lib/postgresql tianon/postgres-upgrade:10-to-15 -U synapse (the -U synapse makes pg_upgrade use user synapse). The output in terminal should end with following:

Upgrade Complete
----------------
Optimizer statistics are not transferred by pg_upgrade.
Once you start the new server, consider running:
    /usr/lib/postgresql/15/bin/vacuumdb -U synapse --all --analyze-in-stages

*Copy the migrated data back to your synapse db container data directory: cp -a upgradepg/15/data/* schemas/

*For some reason, the password for the synapse user was not set, leading to synapse not being able to connect to the database. To make sure the password authentication will work, start the db container, and set the synapse user's password:

docker-compose up db

(in another terminal, in /opt/synapse):

docker-compose exec db psql -U synapse
alter role synapse with password 'your_synapse_pw_from_docker-compose.yml';
exit

That's it. For cleanup, remove the upgradepg and (after your synapse is running properly:), schemas-v11-backup.


text:
Q: How to apply a WP child theme to a different site? -- I copied files and it didn't work I have the twentyeleven theme on this site: http://richardclunan.com/ -- with some changes -- so I have a twentyeleven-child theme.
They're smallish changes -- things like the font and the font size.
I would like to make the same changes to this site: http://richardclunan.net/
…I logged into my hosting account and copied twentyeleven-child from the richardclunan.com theme folder to the richardclunan.net theme folder…
…but the changes didn't appear on richardclunan.net
-- Is there something else I need to do to make this happen?
-- Or is it not possible to make the relevant changes in this way -- copying across the folder and files -- should I be doing this a different way?
(I'm not a techie, and might not understand phraseology unless the 'what' and the 'where' is spelled out :)

A: You must change the theme in your  http://richardclunan.net/ wordpress admin.
Inside your site admin, go to Aparence->Themes and select your theme.


text:
Q: Generic protocol buffers de-serializer in Apache Flink using Java Scenario: Apache Flink, Kafka, Protocol buffers data consumer.
The data source is Kafka topics (multiple topics: topic#1, topic#3, topic#3) in protocol buffers format.
The consumer is Apache Flink consumer. Each topic has a unique protobuf definitions.
List<String> topicList = Arrays.asList("topic#1,topic#2,topic#3".split(","));
inputStream = env.addSource(new FlinkKafkaConsumer[ProtobufDeserializationSchema](topicList, new ProtobufDeserializationSchema(), properties));

I am trying to develop a generic data ingestion job in Apache Flink to ingest the data from Kafka into the database.
How to implement a generic protobuf deserializer for Apache Flink? I am looking for implementation to link the Kafka topic to protobuf definition for deserialization.
The initial approach was to bring byte arrays into Flink datastream and then based on the Kafka topic name determine the protobuf definition to deserialize the messages in the map function. How can I do it in a generic fashion?

A: flink-statefun includes a generic protobuf (de)serializer that might be useful.
https://github.com/apache/flink-statefun/blob/release-3.0/statefun-flink/statefun-flink-common/src/main/java/org/apache/flink/statefun/flink/common/protobuf/ProtobufSerializer.java


text:
Q: How to I avoid storing a local copy of predecessor versions with subversion? I use subversion for all my code even on the local machine. Since the repository is always available on my machine, there is really no need for .svn subdirectories which store a copy of the predecessor.  Is there a way I can avoid this and let the subversion always talk to the repository for the predecessor whenever there is a need?  I understand it may be a performance hit, but it is ok. I am running out of disk space some times.
There are several working copies using this repository and, by policy, all those working copies use the same predecessor revision. We need to conserve some disk space on this machine by avoiding (if possible) .svn directories of this huge code base in each working-copy.

A: An indirect answer...  We used to have the same problem with svn, but then we switched to git.  IIRC, we saved several times on disk space and increased speed by about 10X.
Since git is a distributed SCM, it is perfect for storing local-only copies of files and folders.  In fact, our entire administrative file share is versioned in git for historical integrity and research purposes.
Consider the switch, you won't look back...

A: I don't know any way to avoid .svn directories. As far as I know, even when you use ra-local (local repository access) they are created.
If you are using a local server anyway why wouldn't you consider using one of the distributed revision control systems instead of Subversion (Git, Mercurial, Bazaar). They all are very conscious about space and are very good at compressing the repository down to the minimum size.

A: I think you'll have to wait for svn 1.7, and even then I'm not sure if it will fully satisfy your requirements, but there are working copy improvements based on a new design. Also see this issue.
Maybe someone on the development team will answer this question, if not, you're probably better off asking the Subversion mailing list.

A: You cannot get rid of the .svn directories because they are what make your working copy a working copy.  Without them, you don't have an SVN working copy anymore.


text:
Q: How can I print just specific elements of a Java 2D array? Below is the code I'm messing with, pretty basic. I was looking for a way to print only specific elements of the array. For example, if I wanted to print only the element at index 1 of array[i], as well as the element at index 1 of array[j] when its value is 1. See below for the output I'm looking for.
Expected output :
1 3 5
  4
7 8 9

Code:
public class multiDimensional {

    public static void main(String args[]){

        int arr[][] = {{1,3,5}, {2,4,6}, {7,8,9}};

        for(int i=0; i < 3; i++){
            for(int j=0; j < 3; j++){
                System.out.print(arr[i][j]+" ");
                //System.out.println();
            }

            System.out.println();
        }

    }

}

Actual output :
1 3 5
2 4 6
7 8 9

A: You can produce your expected output by using an if statement to decide when to write a value:
public static void main(String args[]){

    int arr[][] = {{1,3,5}, {2,4,6}, {7,8,9}};

    for(int i=0; i < 3; i++){
        for(int j=0; j < 3; j++){

            if (i == 0             // in the first row
                || i == 2      // in the last row
                || j == 1) {   // in the middle column of the middle row

                System.out.print(arr[i][j]+" ");

            } else {

                System.out.print("  ");    // this is here to keep the spacing right

            }
            //System.out.println();
        }

        System.out.println();
    }

}

Note: There are many other ways of coding this, however the approach I am showing is merely to demonstrate how the if statement works.


text:
Q: Get text using jquery with text-transform I have an html element and i toggle its class and show capital/small letters with  text-transform.
Is it possible to get the text its text-transform?

$('#toggle').click(function(){
  $('#char').toggleClass('upper');
});

$('#getdata').click(function(){
  var text = $('#char').text();
  alert(text);  /// here i need to get the actual word with capital/lower i selected
});
.upper{
 text-transform:uppercase;
}

a

<button id="toggle">Toggle case</button>
<button id="getdata">gat data</button>

A: you can check for the class and use toUpperCase:-

$('#toggle').click(function(){
  $('#char').toggleClass('upper');
});

$('#getdata').click(function(){
  var $char = $('#char');
  var text = $char.hasClass('upper') ? $char.text().toUpperCase() : $char.text();
  alert(text);  /// here i need to get the actual word with capital/lower i selected
});
.upper{
 text-transform:uppercase;
}

a

<button id="toggle">Toggle case</button>
<button id="getdata">gat data</button>

A: There is currently no way to get the rendered text with JavaScript.
When you are using English, toUpperCase and toLowerCase works well for the CSS value uppercase and lowercase.
But when you need it for non-English, or when you use capitalize,  full-width etc., you have to reproduce the CSS logic (mostly unicode logic) with JS.
Below is a few rules that Firefox is doing. Chrome also knows some of them.

*

*In German (de), the ß becomes SS in uppercase.

*In Dutch (nl), the ij digraph becomes IJ, even with text-transform: capitalize, which only put the first letter of a word in uppercase.

*In Greek (el), vowels lose their accent when the whole word is in uppercase (ά/Α), except for the disjunctive eta (ή/Ή). Also, diphthongs with an accent on the first vowel lose the accent and gain a diaeresis on the second vowel (άι/ΑΪ).

*And so on...

It's also fun when you need to apply other CSS values:

*

*capitalize - What constitutes a "word"? How do browsers split iPhone-6s+? Behold, Unicode consortium to the rescue!

*full-width - The MDN example looks easy, but it does not show them all, for example [] to [], and maybe someday they will convert ... to … instead of ...

*full-size-kana - How's your Japanese? No worry, this CSS4 proposals is dropped - in preference of a (future) fully customisable character mapping rules!  Hope your CSS parser skill is up to par.

So, count yourself lucky if you use only English. You have my consolation if you, like me, work with multilingual systems.  Timezone is nothing at all.

A: Maybe like this?
// Store css to javascript values in this object
var textTypes = {
  "uppercase": "toUpperCase",
  "lowercase": "toLowerCase"
}

// get the element
var div = document.getElementsByTagName('div')[0];

// get the computed style type
var type = window.getComputedStyle(div)['text-transform'];

// print the transformed text
console.log(div.innerHTML[textTypes[type]]());

Working Fiddle


text:
Q: Is it possible to get the index you're sorting over in Underscore.js? I'm using the JS library Underscore and in particular using the _.each and _.sortby library calls.  I'm wondering if there's any possible way to get the index of the value within the iterator delegate
_.sortBy([1, 4, 2, 66, 444, 9], function(num){
    /*It'd be great to have access to the index in here */
    return Math.sin(num);
});

A: You can get the index of the current iteration by adding another parameter to your iterator function, e.g.
_.each(['foo', 'bar', 'baz'], function (val, i) {
    console.log(i + ": " + val); // 0: foo, 1: bar, 2: baz
});

A: I think it's worth mentioning how the Underscore's _.each() works internally. The _.each(list, iteratee) checks if the passed list is an array object, or an object.
In the case that the list is an array, iteratee arguments will be a list element and index as in the following example:
var a = ['I', 'like', 'pancakes', 'a', 'lot', '.'];
_.each( a, function(v, k) { console.log( k + " " + v); });

0 I
1 like
2 pancakes
3 a
4 lot
5 .

On the other hand, if the list argument is an object the iteratee will take a list element and a key:
var o = {name: 'mike', lastname: 'doe', age: 21};
_.each( o, function(v, k) { console.log( k + " " + v); });

name mike
lastname doe
age 21

For reference this is the _.each() code from Underscore.js 1.8.3
_.each = _.forEach = function(obj, iteratee, context) {
   iteratee = optimizeCb(iteratee, context);
   var i, length;
   if (isArrayLike(obj)) {
      for (i = 0, length = obj.length; i < length; i++) {
         iteratee(obj[i], i, obj);
      }
   } else {
      var keys = _.keys(obj);
      for (i = 0, length = keys.length; i < length; i++) {
         iteratee(obj[keys[i]], keys[i], obj);
      }
   }
   return obj;
};

A: If you'd rather transform your array, then the iterator parameter of underscore's map function is also passed the index as a second argument. So:
_.map([1, 4, 2, 66, 444, 9], function(value, index){ return index + ':' + value; });

... returns:
["0:1", "1:4", "2:2", "3:66", "4:444", "5:9"]

A: Index is actually available like;
_.sortBy([1, 4, 2, 66, 444, 9], function(num, index){  });

A: The iterator of _.each is called with 3 parameters (element, index, list). So yes, for _.each you cab get the index.
You can do the same in sortBy

A: More generally, under most circumstances, underscore functions that take a list and argument as the first two arguments,  provide access to the list index as the next to last argument to the iterator.  This is an important distinction when it comes to the two underscore functions, _.reduce and _.reduceRight, that take 'memo' as their third argument -- in the case of these two the index will not be the second argument, but the third:
var destination = (function() {
    var fields = ['_333st', 'offroad', 'fbi'];
    return _.reduce(waybillInfo.destination.split(','), function(destination, segment, index) {
        destination[fields[index]] = segment;
        return destination;
    }, {});
})();

console.log(destination);
/*
_333st: "NYARFTW  TX"
fbi: "FTWUP"
offroad: "UP"

The following is better of course but not demonstrate my point:
var destination = _.object(['_333st', 'offroad', 'fbi'], waybillInfo.destination.split(','));
*/

So if you wanted you could get the index using underscore itself: _.last(_.initial(arguments)).  A possible exception (I haven't tried) is _.map, as it can take an object instead of a list: "If list is a JavaScript object, iterator's arguments will be (value, key, list)." -- see: http://underscorejs.org/#map

A: When available, I believe that most lodash array functions will show the iteration. But sorting isn't really an iteration in the same way: when you're on the number 66, you aren't processing the fourth item in the array until it's finished. A custom sort function will loop through an array a number of times, nudging adjacent numbers forward or backward, until the everything is in its proper place.


text:
Q: Is there a java analog to supervisord I am writing a distributed system in which jobs (processes) will be run on multiple nodes (LINUX machines).
I want to be able to launch job on these machines, terminate a job (kill), monitor what is running on each machine.
I am looking for a framework (preferably in Java) which I can use to implement this solution.
I have looked at using the underlying components that frameworks like Hadoop or Akka use but have not come up with anything satisfactory.
A few additional constraints on what I'm looking for:

*

*It should have reasonable proliferation into production grade projects

*It should allow me to launch UNIX processes written in arbitrary languages

*It should be open source

*It should be lightweight -- An answerer has suggested I look at agent based frameworks -- though these satisfy the requirements I've posted -- I've found them to be very heavy weight. I'm looking for something that really fulfills the stated requirements and does not require me to adopt a more comprehensive methodology.

Thanks.

A: It's called multi-agent system and there are several frameworks available that you can use:

*

*JADE

*Janus

*Ascape

*Cougar

*JIAC

*Boris

*Swarm


text:
Q: What property is needed for combo boxes? Basically I have created an app that reads and writes values in text boxes to an XML file. Instead of using all text boxes I want to add in some combo boxes but I am not sure what property is needed for it.
 String ^strMake  = this->txtMake->Text;
             String ^strModel = this->txtModel->Text;
             String ^strName = this->txtName->Text;
             String ^strParentPart = this->txtParentPart->Text;
             String ^strPartID = this->txtPartId->Text;
             String ^strPartType = this->comboBox1->???????????????

(The question marks is what I need to fill in)

A: I'm not a C++ programmer, but can you try SelectedText property?

A: your question is not clear, there are some properties you might be interested in: Text, SelectedText, SelectedItem, SelectedValue


text:
Q: sending value of NSString to ViewController PopOver Im looking to access the value of an NSString from the parent ViewController inside the PopOver View Controller.  Below is the code i have that generates the popover when selecting a row from a tableView.  I need to be able to access the varToPass value in the editPersonViewController.
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    UIView *anchorr = tableView;
    UIViewController *viewControllerForPopover =
    [self.storyboard instantiateViewControllerWithIdentifier:@"editPersonViewController"];

    popover = [[UIPopoverController alloc]
               initWithContentViewController:viewControllerForPopover];
    [popover presentPopoverFromRect:anchorr.frame
                             inView:anchorr.superview
           permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];

    Person *person = [arrayOfPersons objectAtIndex:indexPath.row];

    // I Need to Send/Access This Value In editPersonViewController
    NSString *varToPass = person.personID;

}

A: Add a public property in your editPersonViewController.h file called personID like so
@property (nonatomic, strong) NSString *personID;

Then, just reorder your instantiation of the editViewController to look like this:
UIView *anchorr = tableView;
Person *person = [arrayOfPersons objectAtIndex:indexPath.row];
EditPersonViewController *viewControllerForPopover =
(EditPersonViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"editPersonViewController"];

viewControllerForPopover.personID= person.personID;

popover = [[UIPopoverController alloc]
           initWithContentViewController:viewControllerForPopover];
[popover presentPopoverFromRect:anchorr.frame
                         inView:anchorr.superview
       permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];


text:
Q: How to save Azure Pipeline definition (Json) to another git repo I wonder if there is a way to save all my pipeline definitions in another git repository outside Azure.
I can see that every change in the pipeline is being versioned, and it gives me the option to compare and revert. However, where is it being saved? Can I set up a git repo outside of Azure to control it?
Diego

A: The very idea behind YAML pipelines is the ability of versioning the pipeline definition in a git repo.
I would suggest for you to try to switch to YAML pipelines, that's what they were created for. If you're using classic pipelines, most of actions / steps can be transformed into YAML easily.

A: Since Azure DevOps is a cloud offering service. Your data is cloud-hosted.
For Azure Pipeline definition (Json), you could manually download it from Azure DevOps UI and store it locally.
You could not use Git Repo to control the pipeline definition.

A: It's stored in the SQL database that stores most stuff in Azure DevOps. It's not in a user serviceable location. You can use the REST API to read build definition revisions. And you can store the output whereever you want. You can use the Update API to update the build definition.
The "new style" YAML pipelines are stored in human readable text in your Git Repository. You can version and manage the repository from there with ease.


text:
Q: Trying to implement Albers projection in Python, what is going wrong? I have a platform where I can't import Proj4. I only need to convert points to Albers projection, so it seemed simple, but my conversion has some errors:
Projection definition: +proj=aea +lat_1=52 +lat_2=64 +lat_0=0 +lon_0=105 +x_0=18500000 +y_0=0 +ellps=krass +units=m +towgs84=28,-130,-95,0,0,0,0 +no_defs'
Here's the code implemented from the formulae on Wikipedia:

from math import sin, radians, cos

def albers_proj(lon0, fi0, fi1, fi2, R=6367444.5, x0=0):
    lon0, fi0, fi1, fi2 = [radians(i) for i in (lon0, fi0, fi1, fi2)]

    n = (sin(fi1) + sin(fi2)) / 2
    C = cos(fi1) ** 2 + 2 * n * sin(fi1)
    ro0 = R / n * (C - 2 * n * sin(fi0)) ** .5
    def transformer(lon, lat):
        lon, lat = radians(lon), radians(lat)
        ro = R / n * (C - 2 * n * sin(lat)) ** .5
        theta = n * (lon - lon0)

        return ro * sin(theta) + x0, ro0 - ro * cos(theta)

    return transformer

albers_siberia = albers_proj(105, 0, 52, 64, R=6367444.5, x0=18500000)
print(albers_siberia(83, 55))

Output:
(17127237.118954152, 5777762.666018201)

I found the best R to minimise the error, but still something is not right:
    wgs84: 83.0 55.0

r = 6356302.97445488

     qgis: 17121825.913615   5767652.8720776
my script: 17129639.13010738 5767652.944553478
    error:     7813.21649238       0.072475878

What am I doing wrong?

A: The formulae you have used are for the spherical case. However, your proj4 string indicates that you are using an ellipsoid (+ellps=krass). In order to get the proper results on the ellipsoid, you will have to implement the ellipsoidal formulae.
These formulae can be found in this working manual from USGS at page 101. The parameters for different ellispoids (semi-major, semi-minor axis, flattening) can be found in this Wikipedia article.


text:
Q: Rails regex for specific pattern I need to grab the first occurrence of this pattern [some-file-name ci] OR [some-file-name-ci.yml ci]
So far I'm able to create this pattern
CONFIG_FILE_PATTERN = /\[(\w*[ _-]ci|\w*[ _-]*\.yml ci|.\w*[ _-]*\.yml ci|.\w*[-_]\w*[ _-]*\.yml ci|\w*[-_]\w*[ _-]*\.yml ci|\w*[-_]\w*[ _-]*\w ci|.\w*[-_]\w*[ _-]*\w ci)\]/i.freeze

This works fine for all cases except when there are multiple hyphens (-) in the file name.
Examples:
[hello-ci.yml ci] # works fine for this
[hello.yml ci] # works fine for this
[hello ci] # works fine for this
[hello-world-ci.yml ci] # does not work for this as the file name now have multiple hyphens

Any help will be appreciated.

A: You may use
/\[([^\]\[]*[ _-]ci)\]/i

See the Rubular demo
Details

*

*\[ - a [ char

*([^\]\[]*[ _-]ci) - Group 1:

*

*[^\]\[]* - 0+ chars other than [ and ]

*[ _-] - a space, _ or -

*ci - a ci substring

*\] - a ] char.

A Ruby test at IDEONE to extract the first occurrence:
s = '[hello-ci.yml ci] works fine for this [second-DONT-EXTRACT-hello-ci.yml ci]'
puts s[/\[([^\]\[]*[ _-]ci)\]/i, 1] # => hello-ci.yml ci