text:
Q: Detect when embedded svg is loaded with Angular I've been struggling a long time with this, lots of older posts address the issue but in incomplete, indirect or obsolete ways. Its such a common issue, a common solution would be ideal. I cannot/should-not modify the SVG. The svg has an id and all the various groups have ids that I need to interact with.
The issue is that I can't assign a load event to the svg element itself because it isn't loaded yet when my controller runs; And if I assign the on load event to the parent embed tag, well, then I can't access the elements via getElementByID because they aren't loaded yet either.
View:

    <embed id="svgObject" width="100%" height="100%" ng-src="{{modelSVG}}" type="image/svg+xml"></embed>

Controller:
   .controller('HomeController',['BaseController','$scope','$location',function (BaseController,scope,location) {
            scope.modelSVG = location.protocol() + '://' + location.host() + '/svg/pic.svg';
            var svgObject = document.getElementById("svgObject");

            svgObject.addEventListener('load', function(){
                var svgDocument = svgObject.contentDocument;
                **Do lots of stuff to EACH and every shape loadeded (e.g. show/hide, set hover/click events, etc
            })
   }])

Another attempt to get at the actual svg document
var svgDocument = svgObject.contentDocument ? svgObject.contentDocument : svgObject.contentWindow.document;

I can't believe this is so difficult.

A: This is by far the prettiest and best solution I found that doesn't require much code. In essence, we GET the svg file and parse it as a document fragment so everything is added to the DOM (apparently and magically), then we assign the result back to the original div and can then access the svg directive by id.
View:

Controller:
.controller('HomeController',['BaseController','$scope','$location',function (BaseController,scope,location) {
            scope.modelSVG = location.protocol() + '://' + location.host() + '/svg/pic.svg';
            http({
               method : "GET",
               url : scope.svgPath
            }).then(function mySuccess(response) {
               var svgObject = document.getElementById('svgObject');
               svgObject.appendChild(parseSVG(response.data));

               var svgDocument = document.getElementById("svgDocument");//the id of the actual svg tag.
               //do anything to fully loaded svg
            }, function myError(response) {
                alert(response.statusText);
            });

The Magic Function:
function parseSVG(svg) {
    var div= document.createElementNS('http://www.w3.org/1999/xhtml', 'div');
    div.innerHTML= '<svg xmlns="http://www.w3.org/2000/svg">'+svg+'</svg>';
    var frag= document.createDocumentFragment();
    while (div.firstChild.firstChild)
        frag.appendChild(div.firstChild.firstChild);
    return frag;
}

Approach was discovered here: jquery's append not working with svg element?


text:
Q: how can I retrieve the current position of the vertices after they have been transformed? How can I retrieve the current position of the vertices after they have been transformed? I have the following code....
How can I get the position of the "modelVertices" after the transform has been applied?
I am really after the screen coordinates so I can tell if a vert has been clicked by the mouse.

glMatrixMode(GL_MODELVIEW);

// save model transform matrix
GLfloat currentModelMatrix[16];
glGetFloatv(GL_MODELVIEW_MATRIX, currentModelMatrix);

// clear the model transform matrix
glLoadIdentity();

// rotate the x and y axis of the model transform matrix
glRotatef(rotateX, 1.0f, 0.0f, 0.0f);
glRotatef(rotateY, 0.0f, 1.0f, 0.0f);

// reapply the previous transforms
glMultMatrixf(currentModelMatrix);

glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);

// since each vertes is defined in 3D instead of 2D parameter one has been
// upped from 2 to 3 to respect this change.
glVertexPointer(3, GL_FLOAT, 0, modelVertices);
glEnableClientState(GL_VERTEX_ARRAY);

A: GLU has the function gluProject() and gluUnProject():
http://www.opengl.org/sdk/docs/man/xhtml/gluProject.xml
If your platform doesn't have GLU you can always grab the code for MESA and see how it is implemented.

A: You could use the feedback buffer.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using concat with number values The problem is I want to present two numbers that are stored as strings nicely in a file I generate.
The following code works just fine, but the formatting is not really the one I would like it to be:
<xsl:call-template name="create-cell">

<xsl:with-param name="value" select="concat($value_one,' or ',$value_two)" />

So I thought that I'll add a format-number function and give the numbers the format I want them to have. In order to do so I cast the string to number, use the function and then cast back to string, like this:
<xsl:call-template name="create-cell">

<xsl:with-param name="value" select="concat(string(format-number(number($value_one), "###,###.00"),' or ',$value_two)" />

But the transformation ends without results (an error occurs). What exactly am I doing wrong when changing the type?
EDIT:
The error that occurs is:
Element type "xsl:with-param" must be followed by either attribute specifications, ">" or "/>"

I guess the solution is to escape the double quotas with &quot ...

A: This part :
<xsl:with-param name="value" select="concat(string(format-number(number($value_one), "###,###.00"),' or ',$value_two)" />

should be written as:
<xsl:with-param name="value" select="concat(format-number($value_one, '#,###.00'), ' or ', $value_two)"/>

Whether that's a good approach to solve the actual problem (of which we know practically nothing) is another question.

A:
But the transformation ends with result -

My guess is that $value_one is not a number. Perhaps it is formatted as 12,345.00? If the conversion to an xs:double fails, it will return NaN, which is a valid number, but not really. Using the format-number function, it should return NaN, regardless the picture string.
If your variable holds the empty sequence, format-number will return the empty sequence.
Since format-number already returns a string, using string() on the result will have no effect.
If the - in your question meant a literal minus-sign, then perhaps update your question with what your first snippet and second snippet return exactly, and what processor (exact version) you use.
Update (after you posted the error)
Your XSLT is not valid XML. All XSLT must be valid XML to begin with. Michael's answer shows where it goes wrong: an attribute value must be enclosed in quotes, and yours wasn't.


text:
Q: How do I change the number of columns in a matrix into n, so that every nth row is moved to the new column? So this probably a very newbie question, but let's say I have this matrix
mat <- matrix(rep(c(1,2),3),nrow=6)

     [,1]
[1,]    1
[2,]    2
[3,]    1
[4,]    2
[5,]    1
[6,]    2

If I change to the number of columns to 2, the order I get is
matrix(mat,ncol=2)
     [,1] [,2]
[1,]    1    2
[2,]    2    1
[3,]    1    2

But I want it to be
[1,]    1    2
[2,]    1    2
[3,]    1    2

I understand that n=col basically splits the matrix in half, and then moves the lower half to the new column. Is there a way to tell R to do in the specific way that I want?

A: If you use byrow = TRUE, R will assign the elements of the matrix along rows first, giving you what you want:
matrix(mat, ncol = 2, byrow = TRUE)

Output:
     [,1] [,2]
[1,]    1    2
[2,]    1    2
[3,]    1    2

A: We can use
cbind(mat[c(TRUE, FALSE),], mat[c(FALSE, TRUE),])
#     [,1] [,2]
#[1,]    1    2
#[2,]    1    2
#[3,]    1    2


text:
Q: Digital PLL behaviour when signals start off at the same frequency but out of phase I am studying Digital PLL's.  I'm puzzled by what happens when the two input signals (input + feedback) start at the same frequency but at different phases.  As far as I can see the error signal from the phase detector will cause the VCO to change to a different frequency ( either larger or smaller than the input frequency, depending on which of the two input signals is leading). Assuming that the initial phase difference is quite large, does the feedback frequency immediately change to a substantially different frequency and then slowly converge back to the input frequency as the difference in phase of the two signals gets smaller ?

A: There will be an error voltage due to the phase error and, if the control loop uses an integrator then the frequency of the VCO will slightly increase to catch up to the correct phase of the reference signal.
Once it reaches the correct phase the phase error will be zero but the integrator (working from the error signal) will drive the VCO past the perfect phase point and what happens next is totally down to what other error processing mechanisms you have in place for instance: -

*

*The overshoot of phase is small and gradually, after a few cycles of oscillating around the desired set-point, the error become pretty close to zero.

*The "system" continues to oscillate with the average error being zero

*The system becomes unstable

Without knowledge of the other components I cannot say what will happen but, the intention, I suspect would be to settle down to a zero error (indistinguishable from noise).


text:
Q: Asp.net, C#, Linq and Array usage, var result = (from p in productInQuery
      join o in orderInfoQuery on p.refNo equals o.refNo
      join x in productQuery on p.productNo equals x.no
      join t in productOutQuery on p.no equals t.productInNo into productIn
      from t in productIn.DefaultIfEmpty()
      //let dateOut = (from m in orderInfoQuery where m.refNo == t.refNo select m.delivered).FirstOrDefault()
      orderby o.processDate descending
      select new
      {
          modelNo = x.modelNo,
          mfgNo = p.mfgNo,
          serialNo = p.serialNo,
          poNo = p.poNo,
          lbs = p.lbs,
          width = p.width,
          height = p.height,
          depth = p.depth,
          qty = p.qty,
          dateIn = o.processDate,
          dateOut = (DateTime?)(from m in orderInfoQuery where m.refNo == t.refNo select m.processDate).FirstOrDefault()
      }).ToArray();

I want to add this result into iTextSharp table cell.
but I don't know how to do,
I tried,
int resultSize = result.Length;

/*
for (int j = 0; j < resultSize; j++)
{
    table.AddCell(result[j]);
}
*/

foreach (string[] test in result) //Error : Unable to cast object of type
{
    int testSize = test.Length;
    for (int j = 0; j < testSize; j++)
    {
        table.AddCell(test[j]);
    }
}

but I lost way :(
anybody knows, please advice me~
[EDIT]
int resultSize = result.Length; //192

test does have a fields...
[EDIT 2]
Actually the result be returned from Model.
PJ.WebUI.Models Reports Class
public class Reports
{
  public Array GetTransaction(){
    OrdersRepository ordersRepository = new OrdersRepository();
    var productInQuery = ordersRepository.ProductIn;
    var productOutQuery = ordersRepository.ProductOut;
    var productQuery = ordersRepository.Product;
    var orderInfoQuery = ordersRepository.OrderInfo;
    var result = (from p in productInQuery
      join o in orderInfoQuery on p.refNo equals o.refNo
      join x in productQuery on p.productNo equals x.no
      join t in productOutQuery on p.no equals t.productInNo into productIn
      from t in productIn.DefaultIfEmpty()
      //let dateOut = (from m in orderInfoQuery where m.refNo == t.refNo select m.delivered).FirstOrDefault()
      orderby o.processDate descending
      select new
      {
          modelNo = x.modelNo,
          mfgNo = p.mfgNo,
          serialNo = p.serialNo,
          poNo = p.poNo,
          lbs = p.lbs,
          width = p.width,
          height = p.height,
          depth = p.depth,
          qty = p.qty,
          dateIn = o.processDate,
          dateOut = (DateTime?)(from m in orderInfoQuery where m.refNo == t.refNo select m.processDate).FirstOrDefault()
      }).ToArray();
    return result;
  }
}

And in controller call the method to get the result.
Reports reposrts = new Reports();
var result = reposrts.GetTransaction();

..

foreach (var test in result)
{
     table.AddCell(test.modelNo);
}

Then
Error   1   'object' does not contain a definition for 'modelNo' and no extension method 'modelNo' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)

So,
I move the model method into controller method (put all together in same method) and run. then it works!.
but the result be used in the other controller too. so I want to keep the result in Model class to reuse.
I want to know why it does not work if the result query is not in same method.
could you help me a little more please?
Thank you very much!

A: 'result' will be an array of the anonymous type you selected to, not an array of string arrays, which is why you are getting an error in the foreach loop.
Your loop should probably look more like the following:
foreach (var test in result)
{
    table.AddCell(test.modelNo);
    table.AddCell(test.mfgNo);
    table.AddCell(test.serialNo);
    // etc
}

@Edit 2:
Because the result of GetTransaction() is 'Array', the calling method has no idea what the type is, it just sees it as an array of objects, and, because it is an anonymous type, you can't (reasonably) cast it back to the expected type.
I think your best bet in this case would be to make a new class which has the properties you want to return, e.g.:
public class Transaction
{
    public string ModelNo { get; set; }
    public string MfgNo { get; set; }
    public string SerialNo { get; set; }
   // etc. - but with the correct types for the properties
}

Then change the linq query to select into this type, instead of the anonymous type, e.g.:
...
orderby o.processDate descending
select new Transaction
{
    ModelNo = x.modelNo,
    MfgNo = p.mfgNo,
    SerialNo = p.serialNo,
    // etc.
...

And change the return type of GetTransaction() from Array to Transaction[].

A: It's not clear what you are trying to do but I believe you are casting each element of your result as a string incorrectly.
Try this:
foreach (var test in result)

You will probably need to tweak your inner code since test isn't an array, but that should get you past your current error.


text:
Q: how to map a Eigen::Matrix to std::vector? E.g., if I have an Eigen::MatrixXd of size 10 columns and 3 rows, how can I alias that to a std::vector of 10 elements of Eigen::Vector3d?
when I say alias I mean using the same memory block without copying.
I know that I can do the reversed mapping by something like:
std::vector<Vector3d> v(10);
...
Map<Matrix<double,3,Dynamic> >  m(v.data().data(), 3, 10);

but reversely, if I have an Eigen::Matrix, I tried to convert it to a vector of Eigen::vector but the following code line failed compilation
Eigen::Matrix2Xd points;
...
std::vector<Eigen::Vector2d> v_points(points.data()
    Eigen::aligned_allocator<Eigen::vector2d>(points_data()))

A: This is possible using a custom allocator as described there: Is it possible to initialize std::vector over already allocated memory?
To this end, you'll have to reinterpret it as a Vector3d*:
Vector3d* buf = reinterpret_cast<Vector3d*>(mat.data());

and then pass it to your custom allocator:
std::vector<Vector3d, PreAllocator<Vector3d>> my_vec(10, PreAllocator<Vector3d>(buf, 10));

Another option would be to wrap it within some views alike std::vector, e.g. gsl::span:
gsl::span<Vector3d> view(buf,mat.cols());

In both cases, the mat object must stay alive throughout the lifetime of the std::vector or span.
For completeness, you can also deeply copy it within a std::vector:
std::vector<Vector3d> v(10);
Matrix<double,3,Dynamic>::Map(v.data().data(),3,10) = mat;


text:
Q: Get Each Item Price By Given Total Price And Item Rate (%) If we purchase some items with the bulk price let say:

*

*Pencil 3 pcs

*Watches 2 pcs

*Drinking water 1 bottle

total price is $100 and we don't know the price for each item. How to get each price (per quantity) by adding rate (%) for every item.
Rate |  Item
30%  |  Pencil
50%  |  Watches
20%  |  Drinking water
Higher Rate % mean higher price/qty.
Example calculation (Just to show Watch is more expensive):

*

*Pencil: $12 * 3pcs = 36

*Watch: $30 * 2pcs = 60

*Drinking water: $4 * 1btl = 4

Total 36 + 60 + 4 = $100
Question: How to get item price ($12, $30, $4) based on % given?
Thank you in advance

A: Based on the rates provided, you would have spent $30 on pencils, $50 on watches and $20 on Drinking water bottle.  We then need to divide the amount paid for each type of item by the quantity of that item (i.e. $30/3 pencils = $10), so we wind up with final prices of $10 per pencil, $25 per watch and $20 per drinking water bottle.


text:
Q: Github API: Is it possible to list Pull Requests by label? I've been looking through the API docs, but I was unable to find a way to accomplish that. Thought I'd ask here in case anyone knows. thanks!

A: Use the Search Issues API endpoint:

*

*Use the repo keyword to filter by repo (e.g. repo:ionicabizau/scrape-it)

*Use the is:pr to filter the pull requests (note that pull requests are issues, but issues are not pull requests)

*Use the label keyword to filter by label: label:your-label
Example:

https://api.github.com/search/issues?q=is:pr%20label:enhancement%20repo:ionicabizau/scrape-it


text:
Q: Compile ffmpeg and x264 with --enable-shared I am trying to compile ffmpeg with shared-library support, because when I compiled it statically it ended up making huge libraries, like libavcodec.a with 75MB in size. Any programs that I compiled against libavcodec was at least 50MB in size. This only happens on my RaspberryPi though, if I do
ls -lsth $(which ffmpeg)
on my RPI3 I get
15M -rwxr-xr-x 1 pi pi 15M Jul 29 21:49 /home/pi/camiocam/cam/binaries/bin//ffmpeg
While if I do the same on my macbook I get this output
488 -r-xr-xr-x  1 john  admin   242K Jul 26 19:34 /usr/local/Cellar/ffmpeg/3.1.1/bin/ffmpeg
To get shared library support I did the following
# download and install libx264
cd ~/ffmpeg_build
git clone git://git.videolan.org/x264.git
cd x264
PATH="$HOME/bin:$PATH" ./configure --host=arm-unknown-linux-gnueabi  --prefix="$HOME/ffmpeg_build" --bindir="$HOME/bin" --enable-shared --disable-opencl
# PATH="$HOME/bin:$PATH" make -j 8
# PATH="$HOME/bin:$PATH" make install
# ldconfig

and ...
# to install ffmpeg

cd ~/ffmpeg_sources
wget http://ffmpeg.org/releases/ffmpeg-snapshot.tar.bz2
tar xjvf ffmpeg-snapshot.tar.bz2
cd ffmpeg
PATH="$HOME/bin:$PATH" PKG_CONFIG_PATH="$HOME/ffmpeg_build/lib/pkgconfig" ./configure --prefix="$HOME/ffmpeg_build" --arch=armel --target-os=linux --extra-cflags="-I$HOME/ffmpeg_build/include" --enable-pic  --extra-ldflags="-L$HOME/ffmpeg_build/lib" --bindir="$HOME/bin" --enable-gpl --enable-libx264 --enable-nonfree --enable-shared
PATH="$HOME/bin:$PATH" make -j 8

Which gives this output
License: nonfree and unredistributable
Creating config.mak, config.h, and doc/config.texi...
config.h is unchanged
libavutil/avconfig.h is unchanged
libavcodec/bsf_list.c is unchanged
libavformat/protocol_list.c is unchanged
CC      libavcodec/libx264.o
POD     doc/ffprobe.pod
POD     doc/ffmpeg-all.pod
POD     doc/ffserver-all.pod
POD     doc/ffmpeg.pod
POD     doc/ffprobe-all.pod
POD     doc/ffserver.pod
MAN     doc/ffprobe.1
MAN     doc/ffmpeg.1
MAN     doc/ffserver.1
MAN     doc/ffmpeg-all.1
MAN     doc/ffprobe-all.1
MAN     doc/ffserver-all.1
GEN     libavcodec/libavcodec.ver
LD      libavcodec/libavcodec.so.57
AR      libavcodec/libavcodec.a
LD      libavformat/libavformat.so.57
LD      libavfilter/libavfilter.so.6
LD      libavdevice/libavdevice.so.57
library.mak:102: recipe for target 'libavdevice/libavdevice.so.57' failed
make: *** [libavdevice/libavdevice.so.57] Killed
make: *** Deleting file 'libavdevice/libavdevice.so.57'

I've tried to add the --enable-pic flag to the ffmpeg configure command but that made no difference.


text:
Q: Validation errors on some fields of the form, clearing all the fields of the JSF form On a JSF page where there are about 5 input fields (some textboxes, dropdown, textarea, radio, etc) and a submit button.
On clicking the button, it validates all the input fields based on the value entered.
We are facing a problem with the page.
When any of the input fields have a validation error (say, you enter alphabets for the phone number textbox), then in addition to the erroneous field (phone textbox) getting cleared, some of the other fields (say, First Name field) that were filled with correct values and does not have any validation errors are also getting cleared.
The application is deployed on a WebSphere cluster environment, having 2 identical servers.
The strange part of the problem is that it does not happen all the time. It seems like, that when the application is served up from one of the servers, the problem happens, but when it is from the other server, it does not.
Also, noticed that this problem does not happen locally, that is when the application is run on local standalone WebSphere server from IBM RSA IDE.
Please see the screenshot of the problem
JSF 2.2 Mojarra
WebSphere ND version 8.5.5.9
IBM Rational® Software Architect for WebSphere Software : Version: 8.5
Can anyone please help me figure out how to solve this. Thank you

A: This issue is likely related to your cluster environment and serialization.  As a first step, check to see if using client side state saving with JSF resolves the problem:
<context-param>
    <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
    <param-value>client</param-value>
</context-param>

There is additional WebSphere-specific information relating to JSF and clustering here.  You'll want to make sure that javax.faces.SERIALIZE_SERVER_STATE is set to true, and that you don't have any serialization issues.


text:
Q: Can't get Typescript to understand the css prop (emotion) on Material-UI components I'm wanting to setup a Typescript project that is using Material-UI v4.11.4 to use emotion for styling in preparation for the MUI v5 release. The goal is to introduce emotion into the project so that developers can start using the new styling instead of continuing to write styles via the soon to be deprecated makeStyles function.
I have everything working except for the fact that I get a type error from Typescript on the css prop. I've been searching the documentation for an answer, but can't seem to find anything. Is there some additional types package I need to install in order for Typescript to understand the css prop exists on the MUI components?
import { Button } from "@material-ui/core";

const Btn = () => {
  return (
    // this successfully applies styles, but causes a TS error
    <Button css={{ backgroundColor: "red" }}>
      Click Me
    </Button>
  );
}

TS Error:
Property 'css' does not exist on type 'IntrinsicAttributes & { href: string; } & { children?: ReactNode; color?: Color | undefined; disabled?: boolean | undefined; disableElevation?: boolean | undefined; ... 6 more ...; variant?: "text" | ... 2 more ... | undefined; } & { ...; } & CommonProps<...> & Pick<...>'.

A: Well I feel stupid. I was thinking it was an issue with MUI not exporting types correctly, but it turns out I just needed to set the jsxImportSource in my tsconfig.json
"compilerOptions": {
  "jsxImportSource": "@emotion/react"
}


text:
Q: Why does runtime not scale with flops - Pointwise Multiplication vs 2D Convolutions Background
Based on the convolution theorem of Fourier Transforms convolutions in the spatial domain are equivalent to pointwise multiplications in the Fourier domain (and the other way around). I implemented a torch.nn.Conv2d that "operates" in the Fourier domain by performing pointwise multiplication instead of convolution (with a kernel that is transformed to the size of the intput) in PyTorch (as described e.g. here: https://arxiv.org/pdf/1312.5851.pdf)
Expectation & Results
I found that it did not perform well, similar to: Keras/Tensorflow - fourier pointwise multiplication implementation of conv2d running 4x slower than spatial convolution
After a number of benchmarks it appears that the pointwise multiplication is the major bottleneck of the operation. During the benchmarks I excluded the FFT process to isolate the operations of the layer (and used saved kernels in the appropriate size).
This is confusing because when considering the number of FLOPs required for a 2D convolution (stride=1) and element-wise multiplication:

*

*Conv2d FLOPs: Kernel_H * Kernel_W * C_in * C_out * H * W

*Pointwise FLOPs: C_in * C_out * H * W
E.g. given H = 32, W = 60, C_in = 64, C_out = 256:

*

*Conv2d FLOPs (k = 16): 16 * 16 * 32 * 60 * 64 * 256 = 8053 MFLOPs

*Pointwise (FLOPs): 64 * 256 * 32 * 60 = 31.46 MFLOPs
Considering that large difference in FLOPs I would expect the 2D convolution to take much longer to run (have read GPUs are optimized well for dot products)
I created a simple script to benchmark pointwise multiplication of torch.Tensor against torch.nn.Conv2d, since it appeared that the performance was equivalent or even slower for elementwise multiplication compared to 2D convolutions.
Below is an overview of 2 such benchmark result on a CPU and GPU (i9900k with torch.set_num_threads(1))
Results - CPU (i9900k)
(# Kernel Size = 16)

Benchmark Overview (device = cpu):
    Number of test iterations: 100
    Number of warm-up iterations: 5
    Pointwise: [1, 256, 32, 60] * [64, 256, 32, 60]
    Conv2d(in_ch=256, out_ch=64, kernel_size=16): Conv2d([1, 256, 32, 60)
    FLOP Estimation:
        Conv2d:      8053.06368 MFlops
        Pointwise:   31.45728 MFlops

Benchmark Results (device = cpu)
    Pointwise:   16.139 +/- 0.786 ms
    Conv2d:      12.947 +/- 0.784 ms

-------------------------
(# Kernel Size = 5)

Benchmark Overview (device = cpu):
    Number of test iterations: 100
    Number of warm-up iterations: 5
    Pointwise: [1, 256, 32, 60] * [64, 256, 32, 60]
    Conv2d(in_ch=256, out_ch=64, kernel_size=5): Conv2d([1, 256, 32, 60)
    FLOP Estimation:
        Conv2d:      786.432 MFlops
        Pointwise:   31.45728 MFlops

Benchmark Results (device = cpu)
    Pointwise:   36.085 +/- 3.668 ms
    Conv2d:      9.344 +/- 0.952 ms

Results - GPU (RTX Titan)
(# Kernel Size = 16)

Benchmark Overview (device = cuda:1):
    Number of test iterations: 1000
    Number of warm-up iterations: 5
    Pointwise: [1, 256, 32, 60] * [64, 256, 32, 60]
    Conv2d(in_ch=256, out_ch=64, kernel_size=16): Conv2d([1, 256, 32, 60)
    FLOP Estimation:
        Conv2d:      8053.06368 MFlops
        Pointwise:   31.45728 MFlops

Benchmark Results (device = cuda:1)
    Pointwise:   0.698 +/- 0.031 ms
    Conv2d:      2.916 +/- 0.161 ms

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

(# Kernel size = 3)

Benchmark Overview (device = cuda:1):
    Number of test iterations: 100
    Number of warm-up iterations: 5
    Pointwise: [1, 256, 32, 60] * [64, 256, 32, 60]
    Conv2d(in_ch=256, out_ch=64, kernel_size=3): Conv2d([1, 256, 32, 60)
    FLOP Estimation:
        Conv2d:      283.11552 MFlops
        Pointwise:   31.45728 MFlops
        FreqConv:    62.91456 MFlops

Benchmark Results (device = cuda:1)
    Pointwise:   0.681 +/- 0.011 ms
    Conv2d:      0.126 +/- 0.034 ms

The results do not appear to change significantly if I change the H or W or the channels. But for smaller kernels pointwise appears significantly slower.
Question
Can anyone suggest why the pointwise multiplication appears to be so slow when the FLOPs are at least 2 orders of magnitude larger, or where there may be an error in my thinking or code?
Benchmark Implementation
import torch
import numpy as np
from torch import nn
from time import time

torch.set_num_threads(1)

in_ch = 256
out_ch = 64
height = 32
width = 60
kernel_size = 16

warmup = 5
iters = 100

flops_pointwise = (out_ch * in_ch * height * width)
m_flops_conv = (flops_pointwise * kernel_size ** 2) / 1e6
m_flops_pw = (flops_pointwise) / 1e6

# Device to run benchmark on, e.g. 'cpu' or 'cuda:X'
device = 'cpu'

print(f'Benchmark Overview (device = {device}):')
print(f'\tNumber of test iterations: {iters}')
print(f'\tNumber of warm-up iterations: {warmup}')
print(f'\tPointwise: [1, {in_ch}, {height}, {width}] * [{out_ch}, {in_ch}, {height}, {width}]')
print(f'\tConv2d(in_ch={in_ch}, out_ch={out_ch}, kernel_size={kernel_size}): Conv2d([1, {in_ch}, {height}, {width})')

print('\tFLOP Estimation:')
print(f'\t\tConv2d:\t\t {m_flops_conv} MFlops')
print(f'\t\tPointwise:\t {m_flops_pw} MFlops')
print(f'\t\tFreqConv:\t {m_flops_freq_conv} MFlops')

print()

def benchmark(input_gen, operation, warmup=5, iters=1000):
    duration = []
    for i in range(iters + warmup):

        input = input_gen()

        start = time() # start timer
        with torch.no_grad():
            operation(input)

        # Sync if using cuda
        if device[:4] == 'cuda':
            torch.cuda.synchronize(device)
        end = time() # end timer

        if i < warmup:
            continue

        duration.append((end - start) * 1e3) # ms

    return np.array(duration)

def pointwise(input):
    x, y = input
    x * y

# Helper methods to generate new data
# for every iteration inside of the benchmark method

def _gen_pw_input(in_ch, out_ch, height, width):
    x = torch.rand(1, in_ch, height, width).to(device)
    k = torch.randn(out_ch, in_ch, height, width).to(device)
    return x, k

gen_pw_input = lambda : _gen_pw_input(in_ch, out_ch, height, width)

def _gen_conv_input(in_ch, out_ch, height, width):
    x = torch.rand(1, in_ch, height, width).to(device)
    return x

gen_conv_input = lambda : _gen_conv_input(in_ch, out_ch, height, width)

conv2d = nn.Conv2d(in_ch, out_ch, kernel_size=kernel_size).to(device)

pw_res = benchmark(gen_pw_input, pointwise, warmup=warmup, iters=iters)
conv_res = benchmark(gen_conv_input, conv2d, warmup=warmup, iters=iters)

print(f'Benchmark Results (device = {device})')
print('\tPointwise:\t {:.3f} +/- {:.3f} ms'.format(pw_res.mean(), pw_res.std()))
print('\tConv2d:\t\t {:.3f} +/- {:.3f} ms'.format(conv_res.mean(), conv_res.std()))

Eigen
I also implemented a basic benchmark test in Eigen (C++) to compare the elementwise multiplication and it was similar (slightly slower) to results observed in PyTorch; the backend BLAS used by PyTorch appears optimized.


text:
Q: Can't seem to replace current sprites with image I'm trying to replace the sprites with an image (in this case a race car), but the sprites aren't changing. They're remaining rectangles and aren't changing. The program doesn't give an errors so I don't know why it's not working. Is it the class thats not written right or the information I'm feeding to it? Any help would be greatly appreciated. The name of the image is racecar.png.
import pygame
import sys
import math
import random

pygame.init()
pygame.display.set_caption("__UNITY")
clock = pygame.time.Clock()

WIDTH = 1200
HEIGHT = 800
GRAVITY = 1

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)

IMAGE = pygame.image.load('racecar.png')
font = pygame.font.SysFont("comicsansms",30)
# beach = pygame.image.load("beach.jpeg")

screen = pygame.display.set_mode((WIDTH, HEIGHT))

class Sprite():
    def __init__(self, x, y, width, height):
        self.x = x
        self.y = y
        self.dx = 0
        self.dy = 0
        self.width = width
        self.height = height
        self.color = WHITE
        self.friction = 0.9

    def goto(self, x, y):
        self.x = x
        self.y = y

    def render(self):
        pygame.draw.rect(screen, self.color, pygame.Rect(int(self.x-self.width/2.0), int(self.y-self.height/2.0), self.width, self.height))

    def is_aabb_collision(self, other):
        x_collision = (math.fabs(self.x - other.x) * 2) < (self.width + other.width)
        y_collision = (math.fabs(self.y - other.y) * 2) < (self.height + other.height)
        return (x_collision and y_collision)

class Player(Sprite):
    def __init__(self, x, y, width, height,colour,image):
        Sprite.__init__(self, x, y, width, height)
        self.color=colour
        self.direction = pygame.math.Vector2(0,0)
        # super().__init__()
        self.rect = pygame.Rect(0, 0, width, height)
        self.image = pygame.Surface([width, height])
        self.image = pygame.image.load(image)

    def move(self):
        self.x += self.dx
        self.y += self.dy
        self.dy += GRAVITY

    def jump(self):
        self.dy -= 15

    def left(self):
        self.dx -= 6
        if self.dx < -12:
            self.dx = -12

    def right(self):
        self.dx += 6
        if self.dx > 12:
            self.dx = 12

player = Player(600, 0, 30, 40,RED,'racecar.png')
player2 = Player(600, 40, 20, 40,GREEN,'racecar.png')
blocks = []
blocks.append(Sprite(600, 200, 400, 20))
blocks.append(Sprite(600, 400, 600, 20))
blocks.append(Sprite(600, 600, 1000, 20))
blocks.append(Sprite(1000, 500, 100, 200))
blocks.append(Sprite(200, 500, 100, 200))

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

#controls
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                player.left()
            elif event.key == pygame.K_RIGHT:
                player.right()
            if event.key == pygame.K_UP:
                for block in blocks:
                    if player.is_aabb_collision(block):
                        player.jump()
                        break

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_a:
                player2.left()
            elif event.key == pygame.K_d:
                player2.right()
            elif event.key == pygame.K_w:
                for block in blocks:
                    if player2.is_aabb_collision(block):
                        player2.jump()
                        break

    player.move()
    player2.move()

    for block in blocks:
        if player.is_aabb_collision(block):

            if player.x < block.x - block.width/2.0 and player.dx > 0:
                player.dx = 0
                player.x = block.x - block.width/2.0 - player.width/2.0

            elif player.x > block.x + block.width/2.0 and player.dx < 0:
                player.dx = 0
                player.x = block.x + block.width/2.0 + player.width/2.0

            elif player.y < block.y:
                player.dy = 0
                player.y = block.y - block.height/2.0 - player.height/2.0 + 1
                player.dx *= block.friction

            elif player.y > block.y:
                player.dy = 0
                player.y = block.y + block.height/2.0 + player.height/2.0

        elif player.is_aabb_collision(player2):

            if player.x < player2.x - player2.width/2.0 and player.dx > 0:
              player.dx = 0
              player.x = player2.x - player2.width/2.0 - player.width/2.0

            elif player.x > player2.x + player2.width/2.0 and player.dx < 0:
                player.dx = 0
                player.x = player2.x + player2.width/2.0 + player.width/2.0

            elif player.y < player2.y:
                player.dy = 0
                player.y = player2.y - player2.height/2.0 - player.height/2.0 + 1
                player.dx *= player2.friction

            elif player.y > player2.y:
                player.dy = 0
                player.y = player2.y + player2.height/2.0 + player.height/2.0

        elif player2.is_aabb_collision(player):

            if player2.x < player.x - player.width/2.0 and player2.dx > 0:
              player2.dx = 0
              player2.x = player.x - player.width/2.0 - player2.width/2.0

            elif player2.x > player.x + player.width/2.0 and player2.dx < 0:
                player2.dx = 0
                player2.x = player.x + player.width/2.0 + player2.width/2.0

            elif player2.y < player.y:
                player2.dy = 0
                player2.y = player.y - player.height/2.0 - player2.height/2.0 + 1
                player2.dx *= player.friction

            elif player2.y > player.y:
                player2.dy = 0
                player2.y = player.y + player.height/2.0 + player2.height/2.0

        if player2.is_aabb_collision(block):

            if player2.x < block.x - block.width/2.0 and player2.dx > 0:
                player2.dx = 0
                player2.x = block.x - block.width/2.0 - player2.width/2.0

            elif player2.x > block.x + block.width/2.0 and player2.dx < 0:
                player2.dx = 0
                player2.x = block.x + block.width/2.0 + player2.width/2.0

            elif player2.y < block.y:
                player2.dy = 0
                player2.y = block.y - block.height/2.0 - player2.height/2.0 + 1
                player2.dx *= block.friction

            elif player2.y > block.y:
                player2.dy = 0
                player2.y = block.y + block.height/2.0 + player2.height/2.0

    if player.y > 800:
        player.goto(600, 0)
        player.dx = 0
        player.dy = 0
    if player2.y > 800:
        player2.goto(600, 0)
        player2.dx = 0
        player2.dy = 0

    screen.fill(BLACK)

    player.render()
    player2.render()
    for block in blocks:
        block.render()

    pygame.display.flip()

    clock.tick(30)


text:
Q: Translating JSON to XML using XSD to keep whitespace I am currently using ODI to import data that is in JSON format into an Oracle Database. I am currently using the Complex File topology, which requires me to identify the JSON file and the XSD used to translate it to XML before it maps the data into a table in the database.
I have a JSON file called sample.json:
{"DATA_DS": {"G_1": [
    {
        "FIELDA": "Test Data   ",
        "FIELDB": "12345",
        "FIELDC": "   ",
        "FIELDD": null,
        "FIELDE": "   Test Data"
    }
]}}

I have an XSD called sample.xsd:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://TargetNamespace.com/InboundService" xmlns:nxsd="http://xmlns.oracle.com/pcbpel/nxsd" targetNamespace="http://TargetNamespace.com/InboundService" elementFormDefault="qualified" nxsd:version="JSON" nxsd:encoding="UTF-8">
   <xsd:element name="Root-Element">
      <xsd:complexType>
         <xsd:sequence>
            <xsd:element name="DATA_DS">
               <xsd:complexType>
                  <xsd:sequence>
                     <xsd:element name="G_1" maxOccurs="unbounded">
                        <xsd:complexType>
                           <xsd:sequence>
                              <xsd:element name="FIELDA" type="xsd:string"/>
                              <xsd:element name="FIELDB" type="xsd:string"/>
                              <xsd:element name="FIELDC" type="xsd:string"/>
                              <xsd:element name="FIELDD" type="xsd:string"/>
                              <xsd:element name="FIELDE" type="xsd:string"/>
                           </xsd:sequence>
                        </xsd:complexType>
                     </xsd:element>
                  </xsd:sequence>
               </xsd:complexType>
            </xsd:element>
         </xsd:sequence>
      </xsd:complexType>
   </xsd:element>
</xsd:schema>

When trying to translate from JSON to XML, it says that it cannot normalize.
On further investigation, I noticed that the error occurs due to FIELDC having ONLY space.
I want to be able to keep everything that is inside the double quotes, including space.
I have tried changing the XSD twice, but to no avail.

*

*Created a simpleType and changed the type of every element inside to use the new simpleType:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://TargetNamespace.com/InboundService" xmlns:nxsd="http://xmlns.oracle.com/pcbpel/nxsd" targetNamespace="http://TargetNamespace.com/InboundService" elementFormDefault="qualified" nxsd:version="JSON" nxsd:encoding="UTF-8">
   <xsd:element name="Root-Element">
      <xsd:complexType>
         <xsd:sequence>
            <xsd:element name="DATA_DS">
               <xsd:complexType>
                  <xsd:sequence>
                     <xsd:element name="G_1" maxOccurs="unbounded">
                        <xsd:complexType>
                           <xsd:sequence>
                              <xsd:element name="FIELDA" type="stringspace"/>
                              <xsd:element name="FIELDB" type="stringspace"/>
                              <xsd:element name="FIELDC" type="stringspace"/>
                              <xsd:element name="FIELDD" type="stringspace"/>
                              <xsd:element name="FIELDE" type="stringspace"/>
                           </xsd:sequence>
                        </xsd:complexType>
                     </xsd:element>
                  </xsd:sequence>
               </xsd:complexType>
            </xsd:element>
         </xsd:sequence>
      </xsd:complexType>
   </xsd:element>
   <xsd:simpleType name="stringspace">
      <xsd:restriction base="xsd:string">
         <xsd:whiteSpace value="preserve" />
      </xsd:restriction>
   </xsd:simpleType>
</xsd:schema>

*Created a simpleType inside each element and identify to preserve whitespace:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://TargetNamespace.com/InboundService" xmlns:nxsd="http://xmlns.oracle.com/pcbpel/nxsd" targetNamespace="http://TargetNamespace.com/InboundService" elementFormDefault="qualified" nxsd:version="JSON" nxsd:encoding="UTF-8">
   <xsd:element name="Root-Element">
      <xsd:complexType>
         <xsd:sequence>
            <xsd:element name="DATA_DS">
               <xsd:complexType>
                  <xsd:sequence>
                     <xsd:element name="G_1" maxOccurs="unbounded">
                        <xsd:complexType>
                           <xsd:sequence>
                              <xsd:element name="FIELDA"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:whiteSpace value="preserve"/></xsd:restriction></xsd:simpleType></xsd:element>
                              <xsd:element name="FIELDB"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:whiteSpace value="preserve"/></xsd:restriction></xsd:simpleType></xsd:element>
                              <xsd:element name="FIELDC"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:whiteSpace value="preserve"/></xsd:restriction></xsd:simpleType></xsd:element>
                              <xsd:element name="FIELDD"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:whiteSpace value="preserve"/></xsd:restriction></xsd:simpleType></xsd:element>
                              <xsd:element name="FIELDE"><xsd:simpleType><xsd:restriction base="xsd:string"><xsd:whiteSpace value="preserve"/></xsd:restriction></xsd:simpleType></xsd:element>
                           </xsd:sequence>
                        </xsd:complexType>
                     </xsd:element>
                  </xsd:sequence>
               </xsd:complexType>
            </xsd:element>
         </xsd:sequence>
      </xsd:complexType>
   </xsd:element>
</xsd:schema>

I am kind of new to the whole JSON,XML,XSD space, so any kind of help will be greatly appreciated.
Thanks a lot in advance! :)

A: You say "it says that it cannot normalize" but you don't say what "it" is.
There are many ways of converting to JSON to XML, and you haven't said which one you are using. It sounds to me as if "it" is the particular conversion tool or library that you are using, and your problem is with this tool or library.
Also, rather than paraphrasing an error message, it's best to quote it exactly. There may be people here who recognize it and can tell you exactly what it means.


text:
Q: Informix 10 replication queues not moving I'm using Informix IDS 10.00.UC6 on Solaris 10, with two machines having the same database schema and all tables replicating in both directions using Enterprise Replication, so in theory both databases should have the same content.
However , a problem has arisen where one direction of replication (Host A to Host B) continues to work correctly, but the other direction (Host B to host A) does not work. The symptoms are:

*

*Changes made to a table on Host B do not propagate to Host A (as determined by changing a row on Host B and inspecting the table on Host A)

*cdr list serv shows Active and Connected (both directions), but on Host B there is a queue of millions of bytes.

*cdr list repl shows non-zero queues for several of the replicates.

*cdr stats recvq on Host A shows nothing received from Host B recently.

*cdr stats rqm shows data in the spool trg_send_stxn with flags SEND_Q, SPOOLED, PROGRESS_TABLE, NEED_ACK, SENDQ_MASK, SREP_TABLE.

*There are no errors or relevant messages in online.log or cdr_mon.log , or any other place I can think to look.

*Some of the tables are "out of sync" in that rows have conflicting data or are missing; this is for various reasons relating to past errors where one host was offline. However, even changes to tables with correct data on Host B are not propagated to Host A.

*

*I did a cdr cleanstart on Host B yesterday after this problem was occurring in both directions, which did at least make the A -> B direction start working (the opposite of what I expected), and the queue on Host B were 0 at that time.  After that cleanstart, some changes to tables (with correct data) would propagate to Host A, while some changes to other tables on B would not. But today, no tables are propagating from B to A.

*Before the cleanstart I had found by experimenting that sometimes deleting an individual replicate would reduce the size of the stuck queue but the queue remained stuck all the same;  and sometimes, deleting a replicate would make the queue move for a time before being stuck again.

*There is also a DR host that both A and B do one-way propagation to, and that is propagating correctly with no queue backup.

I'm at a loss now as to try and diagnose why the data in the replication queues is not moving. If there were sync errors (i.e. the replicated change could not be applied due to Host A data differing) I would expect log messages in online.log that the update was rejected, with information saved to $INFORMIXDIR/ats_dr and so on -- this has happened recently .  It seems as if there must be something in the queue being refused but not being cleared and not logged, blocking the queue. Host A has heavy live traffic and (thankfully) is correctly replicating to Host B, but not vice versa.
Any ideas of more things to try or ways to diagnose the problem would be most welcome.
Edit - may or may not be related to Retrieving or deleting a row with a blob in Informix 10 where it appears that the ER send spooler on Host B has corruption.

A: If there are any recent replication definition changes in your environment, I would look for the following for any clues. As Jonathan mentioned, IDS 10.0.xC6 is quite old and there were lots of addition to ER in the latest versions that makes it even more robust and resilient to failures

*

*Host B being Receive Only in the replicates

*ATS/RIS files

A: What does cdr error -a show (run on each server)?
(Just in case you don't have it ... a link to Version 10 ER manual:
http://publibfp.dhe.ibm.com/epubs/pdf/25122792.pdf)
Oh, and are ALL Servers "in time sync" (ntp)?
JJ

A: Regarding ATS/RIS files, can we assume all replicates do have these options on and this has already worked in the past?
What's in 'onstat -g rcv' (receive statistics) on A, and how does this output change over time?
What does 'onstat -g nif' say on B? Possibly a block in the transmission?
Can we assume both sides had been restarted at least once since the issue started so any internal thread confusion would have been resolved and ER re-initialized at least once on either side?
Is there possibly some huge transaction, from B underway to A, that's clogging replication, e.g. by filling up A's receive queue?  Any space problems in queue sbspaces (or queue header dbspaces)?
I guess a cleanstart on B will resolve the problem, but of course a re-sync of all replicated tables would have to occur (since you already did a cleanstart on A that's required anyway).
Andreas


text:
Q: How to implement a 32 bits counter based on 16 bits FTM counter? Problem: The micro controller i am using only supports returning 16 bits encoder values, but for my application, i need to 32 bits.
Question: Is there anyway to implement/have my own 32 bits counter to recount ticks based on returned 16 bits counter value?

A: most counters have a rollover mode our count to zero or count to all ones and reload.  for each rollover/reload have a variable count.
Say you want to count to 8000000 = 0x7A1200.  you could have the timer count to 256 and then count how many times that rolls over when you get to 0x7A12 rollovers you have counted to 8 million.
You have to do this such you dont miss any rollovers/reloads. for example you could count 0x7A12 per reload/rollover and then after 256 rollovers you have counted to 8 million.  giving your code a much longer time period in which to see that there had been a reload/rollover.


text:
Q: Getting list of column names and coeff in ols.param I'm using OLS with respect to two dataframes:
gab = ols(formula= 'only_volume ~ all_but_volume', data=data_p ).fit()

where,
only_volume = data_p.iloc[:,0] #Only first colum
all_but_volume = data_p.iloc[:, 1:data_p.shape[1]] #All but first column

When I try to extract something, say parameter or pvals, I get something like this:
In [3]: gab.params
Out[3]:
Intercept             2.687598e+06
all_but_volume[0]     5.500544e+01
all_but_volume[1]     2.696902e+02
all_but_volume[2]     3.389568e+04
all_but_volume[3]    -2.385838e+04
all_but_volume[4]     5.419860e+02
all_but_volume[5]     3.815161e+02
all_but_volume[6]    -2.281344e+04
all_but_volume[7]     1.794128e+04
...
all_but_volume[22]    1.374321e+00

Since gab.params provides with 23 values in LHS and all_but_volume has 23 columns, I was hoping if there was a way to get a list/zip of params with column names, instead of params with all_but_volume[i]
Like,
TMC     9.801195e+01
TAC     2.214464e+02
...

What I've tried:
removing all_but_volume and simply using data_p.iloc[:, 1:data_p.shape[1]]
Didn't work:
...
data_p.iloc[:, 1:data_p.shape[1]][21]    2.918531e+04
data_p.iloc[:, 1:data_p.shape[1]][22]    1.395342e+00

Edit:
Sample Data:
data_p.iloc[1:5,:]
Out[31]:
          Volume             A              B                  C\
1  569886.171878    759.089217     272.446022           4.163908
2  561695.886128    701.165406     330.301260           4.136530
3  627221.486089    377.746089     656.838394           4.130720
4  625181.750625    361.489041     670.575110           4.134467

                          D         E        F      G      H     I  \
1                  1.000842  12993.06  3371.28  236.90  4.92  6.13
2                  0.981514  13005.44  3378.69  236.94  4.92  6.13
3                  0.836920  13017.22  3384.47  236.98  4.93  6.13
4                  0.810541  13028.56  3388.85  237.01  4.94  6.13

                          J               K       L       M           N  \
1      ...                0               0       0        0          0
2      ...                0               0       0        0          0
3      ...                0               0       0        0          0
4      ...                0               0       0        0          0

           O             P     Q             R   S
1          0             0     0             1   9202.171648
2          0             0     0             0   4381.373520
3          0             0     0             0 -13982.443554
4          0             0     0             0 -22878.843149

only_volume is the first column 'volume'
all_but_volume is all columns except 'volume'

A: You can use DataFrame constructor or rename, because gab.params is Series:
Sample:
np.random.seed(2018)

import statsmodels.formula.api as sm
data_p = pd.DataFrame(np.random.rand(10, 5), columns=['Volume','A','B','C','D'])
print (data_p)
     Volume         A         B         C         D
0  0.882349  0.104328  0.907009  0.306399  0.446409
1  0.589985  0.837111  0.697801  0.802803  0.107215
2  0.757093  0.999671  0.725931  0.141448  0.356721
3  0.942704  0.610162  0.227577  0.668732  0.692905
4  0.416863  0.171810  0.976891  0.330224  0.629044
5  0.160611  0.089953  0.970822  0.816578  0.571366
6  0.345853  0.403744  0.137383  0.900934  0.933936
7  0.047377  0.671507  0.034832  0.252691  0.557125
8  0.525823  0.352968  0.092983  0.304509  0.862430
9  0.716937  0.964071  0.539702  0.950540  0.667982

only_volume = data_p.iloc[:,0] #Only first colum
all_but_volume = data_p.iloc[:, 1:data_p.shape[1]] #All but first column
gab = sm.ols(formula= 'only_volume ~ all_but_volume', data=data_p ).fit()
print (gab.params)
Intercept            0.077570
all_but_volume[0]    0.395072
all_but_volume[1]    0.313150
all_but_volume[2]   -0.100752
all_but_volume[3]    0.247532
dtype: float64

print (type(gab.params))
<class 'pandas.core.series.Series'>

df = pd.DataFrame({'cols':data_p.columns[1:], 'par': gab.params.values[1:]})
print (df)
  cols       par
0    A  0.395072
1    B  0.313150
2    C -0.100752
3    D  0.247532

If want return Series:
s = gab.params.rename(dict(zip(gab.params.index, data_p.columns)))
print (s)
Volume    0.077570
A         0.395072
B         0.313150
C        -0.100752
D         0.247532
dtype: float64

Series without first value:
s = gab.params.iloc[1:].rename(dict(zip(gab.params.index, data_p.columns)))
print (s)

A    0.395072
B    0.313150
C   -0.100752
D    0.247532
dtype: float64


text:
Q: sklearn Import error: cannot import name tfidfvectorizer ---------------------------------------------------------------------------
    ImportError                               Traceback (most recent call last)
    /usr/lib/python2.7/dist-packages/IPython/utils/py3compat.pyc in execfile(fname, *where)
    173             else:
    174                 filename = fname
--> 175             __builtin__.execfile(filename, *where)

     /home/sayghosh/doc.py in <module>()
     9
     10 from sklearn.datasets import load_mlcomp
---> 11 from sklearn.feature_extraction.text import TfidfVectorizer
     12 from sklearn.linear_model import SGDClassifier
     13 from sklearn.metrics import confusion_matrix

     ImportError: cannot import name TfidfVectorizer

I am getting this error when I am trying to run this code

A: Wrapping up the discussion in the comments to have Stack Overflow remove this question from the list of unanswered questions:
The solution is to install a more recent version of scikit-learn (0.13 or later). Apparently the original poster was using an old version of Debian or Ubuntu that shipped scikit-learn 0.10 as specified in the sklearn.__version__ package attribute.

A: For the later versions, you can find vectorizers and transformers like TfidVectorizer in sklearn.feature_extraction.text

A: First uninstall your current version of scikit-learn with the following syntax
$ pip uninstall scikit-learn

use the below syntax to install a new version of scikit-learn
$ pip install scikit-learn==0.13


text:
Q: 404 on github release download using java Why am I getting a 404 here, while downloading a private repo release artifact.
URL url = new URL("https://github.com/anandchakru/private_repo/releases/download/rel_v1/artif-3.0.jar?access_token=myaccesstoken");
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        System.out.println(connection.getResponseCode());  //404

and not here, while downloading a public repo release artifact?
URL url = new URL("https://github.com/anandchakru/fr/releases/download/1.0/fr.jar");
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        System.out.println(connection.getResponseCode());  //200

Note: I'm able to download https://github.com/anandchakru/private_repo/releases/download/rel_v1/artif-3.0.jar?access_token=myaccesstoken (in an incognito/provate_mode browser).

A: Ended doing the following:

*

*Add header Accept: application/json

*Hit https://api.github.com/repos/anandchakru/private_repo/releases/assets/<asset_id>?access_token=myaccesstoken to fetch the artifact.

Code:
URL url = new URL("https://api.github.com/repos/anandchakru/private_repo/releases/assets/<asset_id>?access_token=<token>");
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setRequestProperty("Accept", "application/octet-stream");
ReadableByteChannel uChannel = Channels.newChannel(connection.getInputStream());
FileOutputStream foStream = new FileOutputStream("C:/Users/username/artif-3.0.jar");
FileChannel fChannel = foStream.getChannel();
fChannel.transferFrom(uChannel, 0, Long.MAX_VALUE);
uChannel.close();
foStream.close();
fChannel.close();
System.out.println(connection.getResponseCode());

Don't forget to close the foStream & uChannel.


text:
Q: How to get Time between 2 String values which are in String form I Have Shop Working Hour JSON
{
  "MinPerAppointment": "30",
  "OpeningTime": "10:30",
  "BreakStartTime": "12:00",
  "BreakEndTime": "13:00",
  "ClosingTime": "19:30"
 }

I want to get All Data of time Interval of 30(MinPerAppointment) OpeningTime to ClosingTime by Neglecting BreakStartTime and BreakEndTime.
I want to get in Data in this Format
10:30
11:00
11:30
..Neglected Data Between BreakStartTime to BreakEndTime.. , which is 12 to 13:00
13:00
13:30
.....
.....
19:00

A: try this-
NSString *dateInString=@"11:15";// your OpeningTime

NSMutableArray *array=[[NSMutableArray alloc]init];

NSString *str_MinPerAppointment = @"30"; // your MinPerAppointment

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

[dateFormatter setDateFormat:@"HH:mm"];

NSDate *Breaktime = [dateFormatter dateFromString:@"14:00"] ; // your breakStartTime

NSDate *BreaktimeEnd = [dateFormatter dateFromString:@"15:00"] ; // your breakEndTime

NSDate *closeTime = [dateFormatter dateFromString:@"20:30"] ; // your closeTime

while ([[dateFormatter dateFromString:dateInString] compare:closeTime] == NSOrderedAscending) {

    NSDate *myDate = [dateFormatter dateFromString:dateInString] ;

    if([myDate compare:Breaktime] == NSOrderedDescending && [myDate compare:BreaktimeEnd] == NSOrderedAscending){

    }else{
        if ([myDate compare:Breaktime]==NSOrderedSame) {

        }else{
            [array addObject:dateInString];
        }
    }

    dateInString = [dateFormatter stringFromDate:[myDate dateByAddingTimeInterval:60*[str_MinPerAppointment integerValue]]];

}

NSLog(@"your data :%@",array);

OP:-
your data :(
"10:30",
"11:00",
"11:30",
"13:00",
"13:30",
"14:00",
"14:30",
"15:00",
"15:30",
"16:00",
"16:30",
"17:00",
"17:30",
"18:00",
"18:30",
"19:00"
)

A: As per my answer to your previous question, I would take the following approach.  You do not want to be comparing strings for time data:

*

*Convert all string hh:mm times into integer minutes.

*Iterate from the opening time to the closing time (minus appointment slot time) in steps of appointment slot time.

*If the time is between break start and end then ignore.

*Convert each value to an hh:mm string and add it to an array.
+ (int)minutesFromHhmm:(NSString *)hhmm
{
    int minutes = 0, hh, mm;
    if (sscanf([hhmm UTF8String], "%d:%d", &hh, &mm) == 2)
        minutes = (hh * 60) + mm;
    return minutes;
}

+ (NSString *)hhmmFromMinutes:(int)minutes
{
    int hh = minutes / 60;
    int mm = minutes - (hh * 60);
    hh %= 24;    // day roll-over
    return [NSString stringWithFormat:@"%02:%02d", hh, mm];
}

- (NSMutableArray *)yourMethod:(NSDictionary *)jsonData
{
    // 1.
    int minAppointmentTime = [self minutesFromHhmm:jsonData[@"MinPerAppointment"]];
    int openingTime = [self minutesFromHhmm:jsonData[@"OpeningTime"]];
    int breakStartTime = [self minutesFromHhmm:jsonData[@"BreakStartTime"]];
    int breakEndTime = [self minutesFromHhmm:jsonData[@"BreakEndTime"]];
    int closingTime = [self minutesFromHhmm:jsonData[@"ClosingTime"];

    NSMutableArray *appointmentSlots = [NSMutableArray new];

    // 2.
    for (int time = openingTime; time <= closingTime - minAppointmentTime; time += minAppointmentTime) {
        if (time >= breakStartTime && time <= breakEndTime)
            continue;      // 3.
        [appointmentSlots addObject:[self hhmmFromMinutes:time]];   // 4.
    }

    return appointmentSlots;
}

A:  NSDateFormatter * df = [[NSDateFormatter alloc] init];
    [df setDateFormat: @"yyyy-MM-dd"];

    NSDate * dt1 ;

    NSDate * dt2 ;

    dt1 = [df dateFromString: txt1.text];
    dt2 = [df dateFromString: txt2.text];

    NSComparisonResult result = [dt1 compare: dt2];

    switch (result) {
        case NSOrderedAscending:
            NSLog(@"%@ is greater than %@", dt2, dt1);
            break;
        case NSOrderedDescending:
            NSLog(@"%@ is less %@", dt2, dt1);
            break;
        case NSOrderedSame:
            NSLog(@"%@ is equal to %@", dt2, dt1);
            break;
        default:
            NSLog(@"erorr dates %@, %@", dt2, dt1);
            break;
    }


text:
Q: memcpy byte rate per second memcpy increases CPU usage to 100% for copying every 10000 elements from the buffer. is there any way to optimize memcpy so that it would reduce the CPU usage?

A: (The question has been completely rewritten since this answer).
Your code can be altered to run on Linux as follows:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

const size_t NUM_ELEMENTS = 2*1024 * 1024;
const size_t ITERATIONS = 10000;

int main(int argc, char *argv[])
{
    struct timespec start, stop;
    unsigned short * src = (unsigned short *) malloc(sizeof(unsigned short) * NUM_ELEMENTS);
    unsigned short * dest = (unsigned short *) malloc(sizeof(unsigned short) * NUM_ELEMENTS);

    for(int ctr = 0; ctr < NUM_ELEMENTS; ctr++)
    {
        src[ctr] = rand();
    }

    clock_gettime(CLOCK_MONOTONIC, &start);

    for(int iter = 0; iter < ITERATIONS; iter++){
        memcpy(dest, src, NUM_ELEMENTS * sizeof(unsigned short));
    }

    clock_gettime(CLOCK_MONOTONIC, &stop);

    double duration_d = (double)(stop.tv_sec - start.tv_sec) + (stop.tv_nsec - start.tv_nsec) / 1000000000.0;

    double bytes_sec = (ITERATIONS * (NUM_ELEMENTS/1024/1024) * sizeof(unsigned short)) / duration_d;

    printf("Duration: %.5lfs for %d iterations, %.3lfMB/sec\n", duration_d, ITERATIONS, bytes_sec);

    free(src);
    free(dest);

    return 0;
}

You may need to link with -lrt to get the clock_gettime() function.


text:
Q: My Electron app gets detected as a virus by Browsers, how can I fix? I made an Electron app with electron-forge, I ran npm run make (same as electron-forge make) and I get a perfect setup file with no problem. But when I send it to someone to download or I try to download it myself, I can't because Chrome says that It's a virus and Windows show a small warning screen that I can get past easily. How can I make the browser and Windows trust my app?

A: You have to sign your application, here are the documents
https://www.electronjs.org/es/docs/latest/tutorial/code-signing
and this extra for the Windows:
https://learn.microsoft.com/en-us/dotnet/framework/tools/signtool-exe


text:
Q: Android. WindowBackground center icon not centered like Activity icon I have this layer-list acting as my splashscreen's window background
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/white" />
    <item
        android:drawable="@drawable/ic_logo_splash"
        android:gravity="center" />
</layer-list>

And I set it to styles like so and add the theme to the Activity inside the manifest.
<style name="BackgroundedSplashTheme" parent="AppTheme">
        <item name="android:windowBackground">@drawable/bckgnd</item>
</style>

I also have an Activity which has a simple layout which contains, among 2 other things, the ic_logo_slash that I set in the above layer-list. It's contained inside a LinearLayout with
    <ImageView
        android:id="@+id/logo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:src="@drawable/ic_logo_splash"/>

so nothing special.
My PROBLEM is that you can first see the layer-list with the logo, after 1 second the splashscreen activity gets displayed (everything ok until now) but the issue is that the logo set as the windowBackground is lower than the logo in the splashscreen. It would seem that the Activity layout is a bit larger than ... what ?! the actual window ?! I'm very confused where the extra top padding comes for the window and why is the icon a bit lower than the one in the Activity. They're both centered, so they should be in the same position, no? The window and the activity layout have the same size ... no ? their centers should thus be the same center...
Left is the activity's layout, right is the layer-layout (so the window's background). When the activity's layout is eventually displayed, you can see the logo move up a bit, it looks really bad

Help ?!
EDIT
I played around with it and it seems to be a 24dp difference between the two. 'wonder where it comes from.

A: I've been trying to deal with this problem myself. And I think I have a solution.
The problem is that windowBackground in a theme has a larger area that it's working with (the window) compared to the area that your activity uses. The window also includes system bars and whatnot.
Your splash theme is centering its image in the window. Your activity is centering its image in the activity. These aren't necessarily the same.
I spent a long time trying to find a reliable solution, and the best I could find was a custom view that manually calculates the center of the window and draws the image there.
I think this is better than other solutions I've seen which seem to rely on having an Activity dedicated to being the splash screen so they can use background instead of windowBackground in the theme, or aren't reliable enough (they didn't work for me anyway).
First you need to put this in your res/values/attrs.xml:
    <declare-styleable name="WindowCenteredImageView">
        <!-- Sets a drawable as the content of this ImageView. -->
        <attr name="src" format="reference" />
    </declare-styleable>

Now replace your ImageView with this:
<your.package.name.WindowCenteredImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:src="@drawable/ic_logo_splash"/>

And here's the code for that new class:
package your.package.name

import android.app.Activity
import android.content.Context
import android.graphics.Canvas
import android.graphics.Point
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.view.View
import android.widget.ImageView
import your.package.name.R

/**
 * Simply draws the given drawable in the center of the current window with no scaling. This is not
 * very sophisticated, so cannot handle a lot of the features that a regular [ImageView] can. If
 * these features are required, you might want to try subclassing [ImageView].
 */
class WindowCenteredImageView(context: Context, attrs: AttributeSet): View(context, attrs) {

    // Obtain drawable from attributes.
    private val d: Drawable?
    init {
        context.theme.obtainStyledAttributes(
            attrs,
            R.styleable.WindowCenteredImageView,
            0, 0
        ).apply {
            try {
                d = getDrawable(R.styleable.WindowCenteredImageView_src)
            } finally {
                recycle()
            }
        }
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        if (d != null) {
            // We have a drawable, so try to draw it!
            if (d.intrinsicWidth >= 0 && d.intrinsicHeight >= 0) {
                // Our drawable doesn't fill the screen, so we should calculate its bounds. This is
                // where we take into account the current view's offset within the window...
                val viewTopLeftRelativeToWindow = onDrawCachedObjects.point1.apply {
                    val array = onDrawCachedObjects.array.apply { getLocationInWindow(this) }
                    set(array[0], array[1])
                }

                // And the window's dimensions...
                // (Casting here can't fail as views are always given activity context.)
                val window = (context as Activity).window.decorView
                val windowHeight = window.height
                val windowWidth = window.width

                // Do the calculations.
                // First, find out where we want the image to go in the window
                val imageTopLeftRelativeToWindow = onDrawCachedObjects.point2.apply {
                    set(
                        (windowWidth / 2) - (d.intrinsicWidth / 2),
                        (windowHeight / 2) - (d.intrinsicHeight / 2)
                    )
                }

                // Now we can calculate where the image should go in the view
                val imageTopLeftRelativeToView = onDrawCachedObjects.point3.apply {
                    set(
                        imageTopLeftRelativeToWindow.x - viewTopLeftRelativeToWindow.x,
                        imageTopLeftRelativeToWindow.y - viewTopLeftRelativeToWindow.y
                    )
                }

                // We have all the information needed to set the image bounds
                d.setBounds(
                    imageTopLeftRelativeToView.x,
                    imageTopLeftRelativeToView.y,
                    imageTopLeftRelativeToView.x + d.intrinsicWidth,
                    imageTopLeftRelativeToView.y + d.intrinsicHeight
                )
            }

            // Draw the drawable onto the canvas
            d.draw(canvas)
        }
    }

    /** Optimization: Objects to use in [onDraw] to avoid instantiations */
    private val onDrawCachedObjects = object {
        val array = IntArray(2)
        val point1 = Point()
        val point2 = Point()
        val point3 = Point()
    }
}


text:
Q: Is there a way to change my ASCII language in Windows 8? If I'm not mistaken, there are symbols in ASCII those differ depending on language.
For example, on my computer the default language for Windows 7 is Russian. So, I can save text files like "абацаба"using ANSI in notepad.
Also, this script shows russian characters from 128th in IDE not supporting unicode
#include<stdio.h>
#include<stdlib.h>
int main()
{
    for(int i=0;i<256;++i)
    {
        printf("%d - %c\n",i,char(i));
    }
    system("PAUSE");
    return 0;
}

My laptop has Windows 8 with English default language. When I send russian text files saved in ASCII to it, it doesn't show them correctly. (However, I can print and save russian characters in unicode).
Switching some of my applications to unicode seems very complicated, so can I change ascii, without reinstalling Win8?

A: Despite my Windows is single language edition, I managed to change locale in
Control panel -> all control panel items -> Language->advanced settings -> Apply language settings to the welcome screen, system accounts, and new user accounts->Administrative->Change system Locale


text:
Q: Migrate LinkedIn to API v2 I'm using LinkedIn API v1, and saw the announcement:

All developers need to migrate their apps to our newest APIs and OAuth
  2.0 by March 1, 2019.

I implemented the new Oauth2 Flow (it's basically the same, only changed the endpoint and the permission r_basicprofile to r_liteprofile) and it worked and returned the code that I use in the retrieve the access token.
After I get the access token, I make one call to return the user's firstName, lastName and id, and another to get the email (before it was only 1 request, but it's ok).
Here I saw that using the Authorization header it returned an error that said that I had not informed the access token, but if I put the access token in the paramenter oauth2_access_token I can make requests successfully.
In their docs (https://learn.microsoft.com/en-us/linkedin/consumer/integrations/self-serve/sign-in-with-linkedin?context=linkedin/consumer/context) they don't say where to put the access token, and in the Oauth2 flow docs (https://learn.microsoft.com/en-us/linkedin/shared/authentication/authorization-code-flow?context=linkedin/consumer/context) it uses the Authorization header with the v1 API. But, in any case, it worked using the parameter in the URL.
In v1 I'm doing:
After Oauth2 authorization:
URL: https://api.linkedin.com/v1/people/~?oauth2_access_token={{accessToken}}&format=json

After authorization using the Javascript SDK:
URL: https://api.linkedin.com/v1/people/~
Header: oauth_token={{accessToken}}

After authorization using the Mobile SDK (Android):
URL: https://api.linkedin.com/v1/people/~
Header: Authorization=Bearer {{accessToken}}
Header: x-li-src=msdk
Header: x-li-format=json

It's a bit chaotic, because each one is done in a different way, but I wasn't able to make the v1 API work in a general way for the 3 cases described above. It worked, nonetheless.
But now, how to get the user data using the v2 API?
For now I only achieved it with the Oauth2 Flow:
URL: https://api.linkedin.com/v2/me?projection=(...)&oauth2_access_token={{accessToken}}

(From what I saw other people posting, they where using the Authorization Header instead of the oauth2_access_token parameter, and I wanted to use the header, but was only able to make it work with the parameter. If anyone know how to make it work with the header instead I would be grateful).
In any case, my main question is:
How to make the migration from v1 to v2 and make it work in the same way it is now with v1? (using the token received from the frontend and also from the mobile app and retrieve the user information from that token in the back-end, like in the 3 cases I posted above using the v1 API, of which I was able to implement only the 1st, using the Oauth2 flow).

A: Unfortunately, it appears that the mobile and javascript SDKs have been deprecated. See here: https://engineering.linkedin.com/blog/2018/12/developer-program-updates

SDKs: Our JavaScript and Mobile Software Development Kits (SDKs) will stop working. Developers will need to migrate to using OAuth 2.0 directly from their apps.

To the best that I can tell, since the OAuth flow is available in the browser only, you'll now need to kick to web to do auth on mobile.


text:
Q: How can i make this linq query cleaner and more reusable? I have a linq query that returns the count of several ring sizes. However even though it is reusablable to an extent i want to see if i can improve it.
    private async Task<RingSizeLettersDto> CountOfLettersByRingFingerAsync(Func<RingSize, string> selector)
    {
        var ringSizes = await _ringSizeRepository.Get();

        RingSizeLettersDto ringSizeLetters = new RingSizeLettersDto();

        ringSizeLetters.G = ringSizes.Where(x => selector(x) == "G").Count();
        ringSizeLetters.H = ringSizes.Where(x => selector(x) == "H").Count();
        ringSizeLetters.I = ringSizes.Where(x => selector(x) == "I").Count();
        ringSizeLetters.J = ringSizes.Where(x => selector(x) == "J").Count();
        ringSizeLetters.K = ringSizes.Where(x => selector(x) == "K").Count();
        ringSizeLetters.L = ringSizes.Where(x => selector(x) == "L").Count();
        ringSizeLetters.M = ringSizes.Where(x => selector(x) == "M").Count();
        ringSizeLetters.N = ringSizes.Where(x => selector(x) == "N").Count();
        ringSizeLetters.O = ringSizes.Where(x => selector(x) == "O").Count();
        ringSizeLetters.P = ringSizes.Where(x => selector(x) == "P").Count();
        ringSizeLetters.Q = ringSizes.Where(x => selector(x) == "Q").Count();
        ringSizeLetters.R = ringSizes.Where(x => selector(x) == "R").Count();
        ringSizeLetters.S = ringSizes.Where(x => selector(x) == "S").Count();
        ringSizeLetters.T = ringSizes.Where(x => selector(x) == "T").Count();
        ringSizeLetters.U = ringSizes.Where(x => selector(x) == "U").Count();
        ringSizeLetters.V = ringSizes.Where(x => selector(x) == "V").Count();
        ringSizeLetters.W = ringSizes.Where(x => selector(x) == "W").Count();
        ringSizeLetters.X = ringSizes.Where(x => selector(x) == "X").Count();
        ringSizeLetters.Y = ringSizes.Where(x => selector(x) == "Y").Count();
        ringSizeLetters.Z = ringSizes.Where(x => selector(x) == "Z").Count();
        ringSizeLetters.Z1 = ringSizes.Where(x => selector(x) == "Z1").Count();
        ringSizeLetters.Z2 = ringSizes.Where(x => selector(x) == "Z2").Count();
        ringSizeLetters.Z3 = ringSizes.Where(x => selector(x) == "Z3").Count();
        ringSizeLetters.Z4 = ringSizes.Where(x => selector(x) == "Z4").Count();
        ringSizeLetters.Z5 = ringSizes.Where(x => selector(x) == "Z5").Count();
        ringSizeLetters.Z6 = ringSizes.Where(x => selector(x) == "Z6").Count();
        ringSizeLetters.NA = ringSizes.Where(x => selector(x) == "N/A").Count();

        return ringSizeLetters;

    }

A: I have two improvements in mind:

*

*You can use Count(x => selector(x) == "G"), which will reduce 1 method invocation per line.

*You can create a Dictionary<string, int> (probably char as key can be more accurate) which represents the count by character, then elsewhere in you application you can access it using the character you want to search for as a key:
var ringSizes = new[] { 1, 2, 2 };
var ringSizeLetters = ringSizes.GroupBy(x => Selector(x))
     .ToDictionary(x => x.Key, v => v.Count());

var ocurrences = ringSizeLetters["A"];

A: Depending on whether your specific use case allows for this, a cleaner solution would be to use a Dictionary. Judging from your code the best type would be IDictionary<string, int>. In this, the string key is the identifier (such as 'Z1') and the integer value is the result of .Count().
I've coughed up a possible code sample below;
public static IDictionary<string, int> GetRingSizeLettersAsDict(
    IEnumerable<string> sizeLetters,
    IEnumerable<object> ringSizes)
{
    IDictionary<string, int> ringSizeLetters = new();

    sizeLetters.Select(
        sl => ringSizeLetters.Add(
            sl,
            ringSizes.Where(rs => selector(rs).Equals(sl)).Count())
    );

    return ringSizeLetters;
}

This is just one of many solutions, but it should do the same as your code example, provided it fits your use case.

A: This is type of speudo-code but something like this should do the trick..
It is done via System.Reflection
                PropertyInfo[] properties = ringSizeLetters.GetProperties();
                foreach (PropertyInfo property in properties)
                {
                   var propertyName = property.Name;
                   var ringsizeValue = ringSizes.SingleOrDefault(x=> x.PROPERTYNAME == propertyName)

                   // if it finds ringsize Value
                  if(ringsizeValue != null)
                  {
                     property.SetValue(ringSizeLetters, ringsizeValue.Count());
                  }

                }

A: You can keep all your properties if you really want them:
class RingSizeDto{

  public int G { get; set;}
  public int H { get; set;}

... and avoid reflection by backing them with e.g. a dictionary instead:
class RingSizeDto{

  private Dictionary<string, int> _ringSizes = new();

  public int G { get => _ringSizes[nameof(G)]; set _ringSizes[nameof(G)] = value; }
  public int H { get => _ringSizes[nameof(H)]; set _ringSizes[nameof(H)] = value; }
  ...

This means the sizes can be set all in one go by providing the dictionary:
  public RingSizeDto(Dictionary <string, int> sizes){
    _ringSizes = sizes;
  }

And the dictionary can be generated by query e.g.
var sizes = someSizeList.GroupBy(s => s.SizeLetter).ToDictionary(g => g.Key, g => g.Count());

new RingSizeDto(sizes);

Note; if your list doesn't have every possible size, you'll want to avoid a crash on the dictionary access by using TryGetValue instead
public int G { get => _ringSizes.TryGetValue(nameof(G), out var x) ? x : 0; set _ringSizes[nameof(G)] = value; }


text:
Q: ASP.NET site slow during postback only in IE browser We have an ASP.NET web forms application hosted in Rackspace. We have a weird problem for the past three weeks, that the post back is responding very slow in Internet explorer sporadically. But, the issue doesn't occur in non IE browsers like Chrome, firefox. Also, when the HTTPS traffic is decrypted using Fiddler, the postback works fine in IE itself.
HTTPS postback from IE browser takes more than a minute to reach the server.
Any reason why the request takes so long to reach the server from IE browser?


text:
Q: Single table inheritance and relationship I'm trying to find a solution for a this problem:
We have a table (code_list) in the database which contains all enum -like data.
Let us say we have an Affiliate that can have an AffiliateType and a LanguageCode.
We put all this in the code_list table where id_code_list field tells us if we are talking about AffiliateType or Languagecode and we can have a String or Integer identifier that tells us about which AffiliateType we are talking.
Example of the data in table:
    | id_code_list | val_num | val_string | label  |
    | :----------: |:------: |:---------: | :-----:|
    | TYP_AFF      | 3       | 3          | Other  |
    | TYP_AFF      | 1       | 1          | Divers |
    | COD_LAN      | 1       | 1          | French |

I tried to map this that way:
Code List Parent
@Entity
@Table(name = "CODE_LIST")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "ID_CODE_LIST")
public abstract class CodeListString {

    @Id
    @Column(name = "VAL_STRING")
    protected String value;

    @Embedded
    protected Label label;
...

Affiliate Type:
@Entity
@DiscriminatorValue("TYP_AFF")
public class AffiliateType extends CodeListString{

    public static final AffiliateType SOCIAL_SECRETARIAT = new AffiliateType("1");
    public static final AffiliateType VARIOUS_SERVICES = new AffiliateType("2");
    public static final AffiliateType OTHERS = new AffiliateType("3");
    public static final AffiliateType SOPA = new AffiliateType("9");

    public AffiliateType() {}

    private AffiliateType(String value) {
        super(value);
    }
}

And my Affiliate entity:
@Entity
@Table(name = "AFF")
public class Affiliate {
    @ManyToOne
    @JoinColumn(name = "TYP_AFF")
    private AffiliateType type;

But I'm getting this error:

org.hibernate.MappingException: Foreign key (FK7re97tvvbbo2km961gy9b5jw6:aff [typ_aff])) must have same number of columns as the referenced primary key (code_list [val_string,id_code_list])

So, is there a way to make this work or do you have other solution for this problem ?
PS: I'm using Hibernate and the solution like
@ManyToOne(targetEntity = AffiliateType.class)
@JoinColumn(name = "TYP_AFF")
@Where(clause = "ID_CODE_LIST='TYP_AFF'")
private AffiliateType type;

Doesn't work...

A: I've removed a dependency to a custom library and this worked.
I could not reproduce this error on a clean project.
Anyway this solution is really slow !


text:
Q: CASE statement with search in MYSQL I have used CASE statement for action column.Is it possible to search with value view
How to add WHERE condition with LIKE operator for action column
SELECT al.id,
       al.article_file_id,
       U.firstname,
       U.lastname,
       al.action,
       al.accessed_time,
       a.file_size,
       al.is_backup,
       a.display_file_name,
       fb.display_file_name,
       CASE
           WHEN al.action ='v' THEN 'view'
           WHEN al.action = 'd' THEN 'download'
       END AS actions
FROM rfal al
LEFT JOIN `ru` U ON al.user_id = U.id
LEFT JOIN raf a ON a.id = al.article_file_id
LEFT JOIN rafb fb ON fb.list_id = al.article_file_id
WHERE (a.display_file_name LIKE "%s%")||(a.file_size LIKE "%s%")||(al.id LIKE "%s%")
ORDER BY id DESC
LIMIT 0,10;

My Problem is
In db , the value of action column is saved as v but i am displaying in the table as View . I have put a search filter for table and when i enter v ,it will give the result but typing view no results found is showing.
Input data is shown below


text:
Q: Add a subquery in leftjoin querydsl query i am trying to query the following data using querydsl. All works fine except the OneToMany properties like review.criteria.
I need to leftjoin the review.criteria where review.id equals to criterion.review.id, so i suppose  i need to use a subquery in leftjoin.
By default querydsl / jpa does not support this. Any idea how to do this?
Here is the code:
BlazeJPAQuery<Review> reviewJPAQuery = new BlazeJPAQuery<Tuple>(entityManager, cbf)
        .select(review).from(review)
        .leftJoin(review.configElement, configElement).fetchJoin()
        .leftJoin(configElement.node, node).fetchJoin()
        .leftJoin(node.project, project).fetchJoin()
        .leftJoin(review.milestone, milestone).fetchJoin()
        .leftJoin(review.criteria, criterion).fetchJoin()
        .where(globalReviewsFilter)
        .orderBy(orderSpecifiers);

As a note, i implemented also blaze persistence because it's supposed that it supports subqueries in joins, but the documentation confuses me. The joins are done more or less in from clause, that in my case doesn't help much.


text:
Q: Put text at top of div In my javascript code, I need to put text at absolute positions on the screen, according to the top and left.
So, I put the text in a div, and instead put the div at the absolute position on the screen; BUT, that doesn't put the text into the top-left corner of the div, which I want. How do I do this?
I tried additionally wrapping the text in a span, to try to use vertical-align with that, but that doesn't work either.

.a {
  position: absolute;
  display: block;
  background-color: red;
  font-size: 50px;
  color: gold;
  margin: 0px;
  padding: 0px;
  text-align: left;
  vertical-align: top;
}
.b {
  background-color: blue;
  vertical-align: top;
  text-align: left;
  margin: 0px;
  padding: 0px;
}

  Put Text At Top

Please note as the font size varies, I don't want to use some fixed negative margin as I read in another answer.

A: Use line-height: 100%;to make the line the same height as the font itself. Note: There can be still some space between the top of the uppercase characters and the top of the line, but that's due to the font design - in this case not all uppercase characters extend to the maximum height available.

.a {
  position: absolute;
  display: block;
  background-color: red;
  font-size: 50px;
  color: gold;
  margin: 0px;
  padding: 0px;
  text-align: left;
  vertical-align: top;
  line-height: 100%;
}
.b {
  background-color: blue;
  vertical-align: top;
  text-align: left;
  margin: 0px;
  padding: 0px;
  line-height: 100%;
}

  Put Text At Top Ö É $ Å Ñ


text:
Q: How can I get the argument spec on a decorated function? I need to determine the argspec (inspect.getargspec) of a function within a decorator:
def decor(func):
    @wraps(func)
    def _decor(*args, **kwargs):
        return func(*args, **kwargs)
    return _decor

@decor
def my_func(key=1, value=False):
    pass

I need to be able to inspect the wrapped "my_func" and return the key/value arguments and their defaults. It seems that inspect.getargspec doesn't get the proper function.
(FWIW I need this for some runtime inspection/validation and later documentation generation)

A: I've written a simple class that does what you want. This will achieve the same thing that functools.wraps does as well as preserve the function's signature (from getargspec's point of view). Read the docstring for this class on my gist for more information.
Note: this only works on decorating functions and not on class methods.
import types

class decorator(object):
    def __getattribute__(self, name):
        if name == '__class__':
            # calling type(decorator()) will return <type 'function'>
            # this is used to trick the inspect module >:)
            return types.FunctionType
        return super(decorator, self).__getattribute__(name)

    def __init__(self, fn):
        # let's pretend for just a second that this class
        # is actually a function. Explicity copying the attributes
        # allows for stacked decorators.
        self.__call__ = fn.__call__
        self.__closure__ = fn.__closure__
        self.__code__ = fn.__code__
        self.__doc__ = fn.__doc__
        self.__name__ = fn.__name__
        self.__defaults__ = fn.__defaults__
        self.func_defaults = fn.func_defaults
        self.func_closure = fn.func_closure
        self.func_code = fn.func_code
        self.func_dict = fn.func_dict
        self.func_doc = fn.func_doc
        self.func_globals = fn.func_globals
        self.func_name = fn.func_name
        # any attributes that need to be added should be added
        # *after* converting the class to a function
        self.args = None
        self.kwargs = None
        self.result = None
        self.function = fn

    def __call__(self, *args, **kwargs):
        self.args = args
        self.kwargs = kwargs

        self.before_call()
        self.result = self.function(*args, **kwargs)
        self.after_call()

        return self.result

    def before_call(self):
        pass

    def after_call(self):
        pass

Simply create a new decorator by subclassing
import time

class timeit(decorator):
    def before_call(self):
        self.start = time.time()
    def after_call(self):
        end = time.time()
        print "Function {0} took {1} seconds to complete.".format(
            self.__name__, end - self.start
        )

@timeit
def my_really_cool_function(a, b, c, d='asdf', q='werty'):
    time.sleep(5)

Use it like any normal decorated function
args = inspect.getargspec(my_really_cool_function)
print args

my_really_cool_function(1,2,3,4,5)

Output
ArgSpec(args=['a', 'b', 'c', 'd', 'q'], varargs=None,
        keywords=None, defaults=('asdf', 'werty'))
Function my_really_cool_function took 5.0 seconds to complete.

A: If you use Michele Simionato's decorator module to decorate your function,
its decorator.decorator will preserve the original function's signature.
import inspect
import decorator

@decorator.decorator
def decor(my_func,*args,**kw):
    result=my_func(*args,**kw)
    return result

@decor
def my_func(key=1, value=False):
    pass
decorated_argspec = inspect.getargspec(my_func)
print(decorated_argspec)
# ArgSpec(args=['key', 'value'], varargs=None, keywords=None, defaults=(1, False))


text:
Q: Radical Ideal in the Coordinate Ring is Intersection of Maximal Ideals I need to prove that a radical ideal in the coordinate ring $\mathbb{C}[V]$ (where V is an algebraic variety) is the intersection of all maximal ideals containing it.
The hint I was given was to consider the correspondence between ideals in a quotient ring $R/I$ and the ideals of $R$ containing $I$.
Any suggestions for where to begin? I don't even know where to start.

A: OK, so... I want to give a solution, but I also want to point out the geometry of this situation... the geometry is pretty important here. A radical ideal in $\mathbb{C}[V]$ corresponds to a (I think irreducible) subvariety of $V$. When we say maximal ideals containing $I$, what we really mean are maximal ideals corresponding to points in $\mathbb{C}^n$ (assuming our ambient dimension is $n$) which lie on this subvariety $V$. So the content of the statement, geometrically, is that a variety is made up of all the points contained in it as a set. (One ideal containing another corresponds to a reverse inclusion for their varieties. One maximal containing the radical $I$ corresponds to $V(I)$ containing the point corresponding to the maximal ideal.) So now we at least have some intuition for why the statement should be true if there's any justice in the world.
I was going to answer your algebraic content here, but apparently this question has already been answered with what I was meaning with Hilbert's Nullstellensatz basically: Intersection of all maximal ideals containing a given ideal
I will be marking your question as a duplicate.


text:
Q: Given a string, counting the number of permutations of the string with no repetitions(and forbidden characters) I have been hitting my head against an algorithmic problem for a couple of hours now.
The (fancy) statement of the problem is as follows:
Our garden contains a single row of flowers.You are given the current contents of the row in the String garden. Each character in garden represents one flower. Different characters represent different colors.Flowers of the same color all look the same. You may rearrange the flowers in your garden into any order you like. (Formally, you may swap any two flowers in your garden, and you can do so arbitrarily many times.)   You are also given a String forbid of the same length as garden.You want to rearrange garden into a new string G that will satisfy the following conditions :
No two adjacent flowers will have the same color.Formally, for each valid i,    G[i] and G[i + 1] must differ.
For each valid i, G[i] must not be equal to forbid[i].
Let X be the number of different strings G that satisfy all conditions given above.Compute and return the number(X modulo 1, 000, 000, 007).
Just to clarify with an example: X("aaabbb", "cccccc") = 2 ("ababab" and "bababa")
I have been trying by counting how many letters are in the string ( 'a'->3, 'b'->4, in the example) and then recursively counting the different possibilities (skipping if there is a repetition or a forbidden letter). Something on these lines:
using Map = std::map < char, size_t > ;
Map hist;
std::string forbid;

size_t countRecursive(std::string s, size_t len)
{
    if (len == 0)
        return 1;

    size_t curPos = s.size() ;
    size_t count(0);

    for (auto &p : hist) {
        auto key = p.first;

        if (hist[key] == 0) continue;
        if (forbid[curPos] == key) continue;
        if (curPos > 0 && s[curPos - 1] == key) continue;

        hist[key]--;
        count += countRecursive(s + key, len - 1);
        hist[key]++;
    }

    return count;
}

Where hist and forbid are previously initialized. However, this appears to be n! and since n can be <= 15, it really explodes in complexity.
I am not really looking for a complete solution. Only, if you had any kind of suggestion about the way I should approach the problem, I would be highly thankful!

A: I'd approach it as follows: your 'forbidden' string is as long as the 'garden'. This means that given an alphabet of N characters, each position G[i] can have at most N-1 possible characters (since one will be forbidden). This gives you an upper bound that's limited only by N. If that bound is less than the modulo it might lead to some interesting considerations, but let's move forward.
Now a very basic approach is counting the combinations: if the garden is K characters long, the first item G[0] will have N-1 possibilities; the second one G[1] will have N-2 possibilities if forbidden[1] is different than G[0], N-1 if forbidden[1] == G[0]. The third character G[2] will too have N-2 possibilities depending on forbidden[2] and G[1], and so on.
For clarity: N-2 comes from the fact that of the N-1 possibilities, another one must be removed that is the value of the character preceding it in the string, unless such character matches the forbidden character of the current position.
So if forbidden[i+1] is always different from G[i] you have N-1 * N-2 * N-2 * ... * N-2, K times. This is your lower bound.
Now between upper and lower bound there is a number of strings where e.g. forbidden[i+1] is equal to G[i] only for the second position; for the second and for the third; etc. So your number of strings is:
N-1 * N-2 * N-2 * N-2 ... K
N-1 * N-1 * N-2 * N-2 ... K
N-1 * N-1 * N-1 * N-2 ... K

and so on until you have a string where each character can have N-1 possibilities.
In other words,
N-1 * (N-2)^K-1
(N-1)^2 * (N-2)^K-2
(N-1)^3 * (N-2)^K-3

How many of those strings can you have? It depends how big is K, i.e. how large is your garden :)
That is, assuming I understood the problem correctly.


text:
Q: Cannot vertical align center an image and text on the same line React Bootstrap I am trying to align an image and text vertically on the same line in React Bootstrap:
<CardBody
    className="d-flex justify-content-between align-items-center"
    style={{borderTop: "1px solid #6c757d", paddingTop: "1rem"}}
>

{subtitle}

</CardBody>

However the output is like follows:

What am I doing wrong here?

A: It's the Bootstrap CSS attached to
 that you are using inside the first div that's doing this.
Visit the p element in devtools and notice the margin it has from Bootstrap:
p {
    margin-top: 0;
    margin-bottom: 1rem;
}

Override that and it should work.
Example sandbox

A: you can put them in an element and use flex like:

{subtitle}


text:
Q: Wait Functions and CloseHandle Dependency I settled down on using Wait Functions ( WaitForSingleObject,WaitForMultipleObject etc) for proper thread exit. In this case , the question is do i need to explicitly call CloseHandle ( Thread Handle ) to avoid memory leak or the wait function cleans up and closes the handle on its own? In case if CloseHandle needs to be explicitly called , will i be able to call "CreateThread ( same Thread Handle ) again? Will i be able to call GetExitCodeThread( ) again ?
NOTE : One StackOverFlow Question answers me the second part says i cannot call GetExitCode again , but it doesnt clarify whether missing to call out a CloseHandle after Wait function results in a Memory Leak or Not.

A: To avoid a memory leak you must call CloseHandle.  Using functions such as GetExitCodeThread or WaitForSingleObject after a HANDLE has been closed causes undefined behaviour.  It may work some of the time, but on other occasions it may crash or return a wrong answer.  As explained in Sabotaging yourself: Closing a handle and then using it

While it's true that WaitForSingleObject returns WAIT_FAILED when given an invalid parameter, handle recycling means that any invalid handle can suddenly become valid again (but refer to an unrelated object).

For that reason, it is usually best to do:
CloseHandle(handle);
handle = INVALID_HANDLE_VALUE;

This means that anything that tries to use the handle will fail with an appropriate error code.
Once you have cleaned up the handle properly, it is safe to then use it to create another thread.
handle = CreateThread(...);

It is now a handle that is assigned to your new thread and you can call GetExitCodeThread again until you do the final clean-up with CloseHandle.