text:
Q: Set up ido mode in emacs 21 I am using ido mode. and GNUM emacs 21.1.1 on AIX.
I add the ido.el in the .emacs.d. and add the following in the .emacs file.
(load-file "~/.emacs.d/site-lisp/ido/ido.el")
(require 'ido)
(ido-mode t)
(setq ido-enable-flex-matching t) ;; enable fuzzy matching

When start emacs, it complains. and there is no ido-mode.
How to fix this?
error: "Unknown req `min-colors' with options `(88)'"

To ensure normal operation, you should investigate the cause
of the error in your initialization file and remove it.  Start
Emacs with the `--debug-init' option to view a complete error
backtrace

contents of the backtrace
Debugger entered--Lisp error: (error "Unknown req `min-colors' with options `(88)'")
  signal(error ("Unknown req `min-colors' with options `(88)'"))
  error("Unknown req `%S' with options `%S'" min-colors (88))
  face-spec-set-match-display(((min-colors 88) (class color)) #<frame F1 0x201a3600\ >)
  face-spec-choose((((... ...) (:foreground "red1")) ((...) (:foreground "red")) (t (:underline t))) #<frame F1 0x201a3600\ >)
  face-spec-set(ido-subdir (((... ...) (:foreground "red1")) ((...) (:foreground "red")) (t (:underline t))) #<frame F1 0x201a3600\ >)
  custom-declare-face(ido-subdir (((... ...) (:foreground "red1")) ((...) (:foreground "red")) (t (:underline t))) "Face used by ido for highlighting subdirs in the alternatives." :group ido)
  (defface ido-subdir (quote (... ... ...)) "Face used by ido for highlighting subdirs in the alternatives." :group (quote ido))
  eval-buffer(#<buffer  *load*<2>> nil "~/.emacs.d/site-lisp/ido/ido.el" nil t)
  load-with-code-conversion("~/.emacs.d/site-lisp/ido/ido.el" "~/.emacs.d/site-lisp/ido/ido.el" nil nil)
  load("~/.emacs.d/site-lisp/ido/ido.el" nil nil t)
  load-file("~/.emacs.d/site-lisp/ido/ido.el")
  eval-buffer(#<buffer  *load*> nil "~/.emacs" nil t)
  load-with-code-conversion("~/.emacs" "~/.emacs" t t)
  load("~/.emacs" t t)
  #[nil "^H\205\227^@   Æ=\203^Q^@Ç^HÈQ\2025^@  É=\203'^@ÊÇËÌ#\203#^@Í\2025^@Î\2025^@   Ï=\2031^@Ð\2025^@Ç^HÑQ^ZÒ^SÓ\nÒ\211#\210^KÒ=\203F^@Ë^S^K\203\210^@Ô^K!Õ\232\203\210^@Ö^K!\211^\×P^]Ø^M!\203d$
  command-line()
  normal-top-level()

A: Emacs 21.1.1 is fairly ancient (21.1 was released almost exactly 10 years ago). Upgrade to a more recent version, and you should be fine (unless it no longer builds on AIX?) Lots of people are using the not-yet-final version 24, but 23.3 is the current stable release.
ido is also a standard part of Emacs, these days, so you should be able to get rid of your copy of that.
Admittedly you may well encounter other upgrade incompatibilities by taking this approach, but that issue will surely only get worse as time goes on...

A: I have the same problem.  We're upgrading to RHEL5, so I assume we'll have emacs 21 for a long time.  Luckily the EmacsWiki has a link to an older version.  It's over a decade old, but it's better than nothing.
It seems to work fine, but some of the constants have different names.  For example, I had set ido-default-file-method to selected-window, but the latter is named same-window in the older version of the code.


text:
Q: Get img url from uploads folder in cakephp I'm have images in webroot/uploads folder, Can I use this files in img tag? And what link in href i must use
 is not work =(

A: in php file:
<img src="<?php echo $this->webroot; ?>uploads/1.jpg"/>

OR
directly without php (if your site is hosted at the root of the domain)

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to set default date to today in google form? I need to set in a google form response the today date (Not hardcoded) when submited
I'm accesing the form, adding a date question, setting the title and the help text, but nothing more
function myFunction() {
    var myForm = FormApp.openById("MyFormID");
    var formDate = myForm.addDateItem();
    formDate.setTitle('Ciclo');
    formDate.setHelpText('Ciclo de registro');
    //This is doing nothing at all
    //var formDateResponse = formDate.createResponse(new Date());
 }

Im only getting the date question unfilled

A: A FormResponse has a getTimestamp() function built into it.
If you are using an onSubmit Trigger you can get it by:
function onSubmit(e){
  var response = e.response;
  var timestamp = response.getTimestamp(); //Date Object!
}

It's important to note that if you have an onSubmit Trigger in Google Sheets it does not provide the e.response FormResponse object, but instead a values array, namedValues array, or range object.


text:
Q: Trying to get the images to fit in box and Boxes to be responsive I am trying to get this code to work I am about 90% of the way there, but am having difficulty scaling and making flexbox responsive.
What I want to know is:
1) When I change the width to auto on line 20 (also 44, and 68) why does the image disappear? I want image to fit in box and the text overlay to be over image.
2) How do I get the image box to be responsive? When in Mobile I want them stacked and then to flex as they get to desktop so they are in row. So column to row. Why is that not working?
Any help to get images to fit in box and the text overlay to cover image and for it to flex and be responsive would be helpful. I have been stuck on this for quite a while and not sure why this is not working.
Code Pen link
HTML

Lorem Ipsum Title

Lorem Ipsum Text that doesnt matter

Lore Ipsum Title

Lorem Ipsum Text that doesnt matter

Lorem Ipsum Title

Lorem Ipsum Text that doesnt matter

CSS
.opener-wrapper {
  display: flex;
  flex-wrap: wrap;
}

.opener {
  width: 100%;
  height: 100%;
  min-width: 100%;
  min-height: 100%;
}

#opener1::before {
  background-image: url('https://source.unsplash.com/random');
  background-size: cover;
  background-position: center;
  content: "";
  display: block;
  position: absolute;
  width: 100%;
  height: 12em;
  z-index: -2;
  opacity: 0.7;
}

#opener1::after {
  background-color: #314F59;
  content: "";
  display: block;
  position: absolute;
  width: auto;
  height: 100%;
  z-index: -1;
  opacity: .35;
}

#opener2::before {
  background-image: url('https://source.unsplash.com/random');
  background-size: cover;
  background-position: center;
  content: "";
  display: block;
  position: absolute;
  width: 100%;
  height: 12em;
  z-index: -2;
  opacity: 0.7;
}

#opener2::after {
  background-color: #314F59;
  content: "";
  display: block;
  position: absolute;
  width: auto;
  height: 100%;
  z-index: -1;
  opacity: .35;
}

#opener3::before {
  background-image: url('https://source.unsplash.com/random');
  background-size: cover;
  background-position: center;
  content: "";
  display: block;
  position: absolute;
  width: 100%;
  height: 12em;
  z-index: -2;
  opacity: 0.7;
}

#opener3::after {
  background-color: #314F59;
  content: "";
  display: block;
  position: absolute;
  width: auto;
  height: 100%;
  z-index: -1;
  opacity: .35;
}

.flex-center {
  /* display: flex;
  flex-direction: column;
  justify-content: center;
  align-content: center;  */
}

.opener-msg {
  color: #fff;
  text-shadow: #343a40 2px 2px;
  min-width: 100%;
  min-height: 12em;
  position: relative;
  margin: 3% 0;
  text-transform: uppercase;
}

.opener-msg::before {
  content: "";
  display: block;
  position: absolute;
  margin-left: 0;
  min-width: 100%;
  min-height: 12em;
  z-index: -1;
  opacity: 0.4;
  background-color: #343a40;
}

.opener-title,
.opener-subtitle {
  width: 100%;
  display: block;
  text-align: center;
}

.opener-title {
  margin: 3% 0;
}

A:
1) When I change the width to auto on line 20 (also 44, and 68) why does the image disappear? I want image to fit in box and the text overlay to be over image.

This box is set to position: absolute. Absolutely positioned elements are sized relative to their parent container (or next relatively positioned parent). They require a width and height.
What if you set the background-image on #opener1, and set the color overlay on #opener1::after?

2) How do I get the image box to be responsive? When in Mobile I want them stacked and then to flex as they get to desktop so they are in row. So column to row. Why is that not working?

You need to set the flex-direction to row on the flex container. There is currently no flex-direction set on .opener-wrapper. This will allow the boxes to flow horizontally. Also, you have min-width set to 100%. This will ensure that your boxes take up 100% of the width -- which is not what you want. Remove this line, and add max-width: 33.33%;.
You may want to take a look at Chris Coyier's A Complete Guide to Flexbox if you haven't yet!

A: 1) width: auto; sets the width of the element to the browser default width. In this case, the browser initializes the :before pseudo-element with a width of 0px which can be seen in the computed styles in this imgur image
2) You will need @media rules to resize the elements depending on how the page is being viewed. Currently all of your openers have a width and min-width of 100%. This makes them use 100% of the space that they occupy. If you want elements to display on the same row, you have to divide that 100% by how many elements you want to display on each row. For the case of these three elements, I did the following.
.opener {
  width: 33%;
  height: 100%;
  min-width: 33%;
  min-height: 100%;
}

To follow this up, I added a @media section to the CSS to change the width of the elements to 100% when the display is smaller than 600px.
@media only screen and (max-width: 600px) {
    .opener {
        width: 100%;
        height: 100%;
        min-width: 100%;
        min-height: 100%;
    }

    #opener1::before {
        width: 100%;
        min-width: 100%;
    }

    #opener2::before {
        width: 100%;
        min-width: 100%;
    }

    #opener3::before {
        width: 100%;
        min-width: 100%;
    }

}

All together, your CSS should be similar to this:
.opener-wrapper {
  display: flex;
  flex-wrap: wrap;
}

.opener {
  width: 33%;
  height: 100%;
  min-width: 33%;
  min-height: 100%;
}

#opener1::before {
  background-image: url('https://source.unsplash.com/random');
  background-size: cover;
  background-position: center;
  content: "";
  display: block;
  position: absolute;
  width: 33%;
  height: 12em;
  z-index: -2;
  opacity: 0.7;
}

#opener1::after {
  background-color: #314F59;
  content: "";
  display: block;
  position: absolute;
  width: auto;
  height: 100%;
  z-index: -1;
  opacity: .35;
}

#opener2::before {
  background-image: url('https://source.unsplash.com/random');
  background-size: cover;
  background-position: center;
  content: "";
  display: block;
  position: absolute;
  width: 33%;
  height: 12em;
  z-index: -2;
  opacity: 0.7;
}

#opener2::after {
  background-color: #314F59;
  content: "";
  display: block;
  position: absolute;
  width: auto;
  height: 100%;
  z-index: -1;
  opacity: .35;
}

#opener3::before {
  background-image: url('https://source.unsplash.com/random');
  background-size: cover;
  background-position: center;
  content: "";
  display: block;
  position: absolute;
  width: 33%;
  height: 12em;
  z-index: -2;
  opacity: 0.7;
}

#opener3::after {
  background-color: #314F59;
  content: "";
  display: block;
  position: absolute;
  width: auto;
  height: 100%;
  z-index: -1;
  opacity: .35;
}

.flex-center {
  /* display: flex;
  flex-direction: column;
  justify-content: center;
  align-content: center;  */
}

.opener-msg {
  color: #fff;
  text-shadow: #343a40 2px 2px;
  min-width: 100%;
  min-height: 12em;
  position: relative;
  margin: 3% 0;
  text-transform: uppercase;
}

.opener-msg::before {
  content: "";
  display: block;
  position: absolute;
  margin-left: 0;
  min-width: 100%;
  min-height: 12em;
  z-index: -1;
  opacity: 0.4;
  background-color: #343a40;
}

.opener-title,
.opener-subtitle {
  width: 100%;
  display: block;
  text-align: center;
}

.opener-title {
  margin: 3% 0;
}

@media only screen and (max-width: 600px) {
    .opener {
        width: 100%;
        height: 100%;
        min-width: 100%;
        min-height: 100%;
    }

    #opener1::before {
        width: 100%;
        min-width: 100%;
    }

    #opener2::before {
        width: 100%;
        min-width: 100%;
    }

    #opener3::before {
        width: 100%;
        min-width: 100%;
    }

}


text:
Q: any can explain the function of stride in bitmapdata?         Bitmap bit1 = new Bitmap( bmpimg , width , height );
        Bitmap bit2 = new Bitmap( bmp , width , height );

        Bitmap bmpresult = new Bitmap( width , height );

        BitmapData data1 = bit1.LockBits( new Rectangle( 0 , 0 , bit1.Width , bit1.Height ) , ImageLockMode.ReadWrite , PixelFormat.Format24bppRgb );
        BitmapData data2 = bit2.LockBits( new Rectangle( 0 , 0 , bit2.Width , bit2.Height ) , ImageLockMode.ReadWrite , PixelFormat.Format24bppRgb );
        BitmapData data3 = bmpresult.LockBits( new Rectangle( 0 , 0 , bmpresult.Width , bmpresult.Height ) , ImageLockMode.ReadWrite , PixelFormat.Format24bppRgb );

unsafe
        {
            int remain1 = data1.Stride - data1.Width * 3;
            int remain2 = data2.Stride - data2.Width * 3;
            int remain3 = data3.Stride - data3.Width * 3;

            byte* ptr1 = ( byte* )data1.Scan0;
            byte* ptr2 = ( byte* )data2.Scan0;
            byte* ptr3 = ( byte* )data3.Scan0;

            for( int i = 0 ; i < height ; i ++ )
            {
                for( int j = 0 ; j < width * 3 ; j ++ )
                {
                    ptr3[ 0 ] = ( byte ) ( XOR_Operator( ptr1[ 0 ] , ptr2[ 0 ] ) );
                    ptr1 ++;
                    ptr2 ++;
                    ptr3 ++;
                }

                ptr1 += remain1;
                ptr2 += remain2;
                ptr3 += remain3;
            }

        }

        bit1.UnlockBits( data1 );
        bit2.UnlockBits( data2 );
        bmpresult.UnlockBits( data3 );

        return bmpresult;
    }

is it necessary to get remain for data objects

A: Stride is there due to hardware requirements that have unfortunately leaked through to the API layer.
It is important because Windows drivers sometimes require that scanlines (rows in the image) be memory aligned. That is why they are sometimes larger than they would strictly need to be.
See for example this MSDN article DIBs and Their Use.

Every scanline is DWORD-aligned. The scanline is buffered to alignment; the buffering is not necessarily 0.

Your handling seems to be sufficient.

A: Stride is the number of bytes your code must iterate past to reach the next vertical pixel.
This may be different from the image's width * pixel size if hardware requires a width of a certain multiple.

A: Scanlines are typically aligned on processor word boundaries.
http://javaboutique.internet.com/tutorials/rasters/index2.html has a nice diagram.
People implementing CPU-accessible bitmaps want to align their scanlines on processor word boundaries as the machine codes for accessing and manipulating processor words can be substantially faster than those for non-aligned addresses.

A: Yes, it's necessary.
The stride value is the offset from the start of one scan line to the start of the next scan line. If the scan lines are padded, the value is a few bytes more than what's needed for the pixels in the scan line.
If the bitmap is stored upside down in memory (i.e. the bottom scan line first), the stride value is negative. If you would read such a bitmap without using the stride value, you would get just garbage after the first scan line, or a memory access error.

A: The stride value is the number of bytes that the bitmap takes to represent one row of pixels. so you could move a memory pointer forward by the stride to move down a row


text:
Q: Is there any better way to render the fetched feed data on webpage with infinite scrolling? I am creating a webpage in ReactJS for post feed (with texts, images, videos) just like Reddit with infinite scrolling. I have created a single post component which will be provided with the required data. I am fetching the multiple posts from MySQL with axios. Also, I have implemented redux store in my project.
I have also added post voting. Currently, I am storing all the posts from db in redux store. If user upvotes or downvotes, that change will be in redux store as well as in database, and web-page is re-rendering the element at ease.
Is it feasible to use redux-store for this, as the data will be increased soon, maybe in millions and more ?
I previously used useState hook to store all the data. But with that I had issue of dynamic re-rendering, as I had to set state every time user votes.
If anyone has any efficient way, please help out.

A: Seems that this question goes far beyond just one topic. Let's break it down to the main pieces:

*

*Client state. You say that you are currently using redux to store posts and update the number of upvotes as it changes. The thing is that this state is not actually a state in your case(or at least most of it). This is a common misconception to treat whatever data that is coming from API a state. In most cases it's not a state, it's a cache. And you need a tool that makes work with cache easier. I would suggest trying something like react-query or swr. This way you will avoid a lot of boilerplate code and hand off server data cache management to a library.

*Infinite scrolling. There are a few things to consider here. First, you need to figure out how you are going to detect when to preload more posts. You can do it by using the IntersectionObserver. Or you can use some fance library from NPM that does it for you. Second, if you aim for millions of records, you need to think about virtualization. In a nutshell, it removes elements that are outside of the viewport from the DOM so browsers don't eat up all memory and die after some time of doomscrolling(that would be a nice feature tho). This article would be a good starting point: https://levelup.gitconnected.com/how-to-render-your-lists-faster-with-react-virtualization-5e327588c910.

*Data source. You say that you are storing all posts in database but don't mention any API layer. If you are shooting for millions and this is not a project for just practicing your skills, I would suggest having an API between the client app and database. Here are some good questions where you can find out why it is not the best idea to connect to database directly from client: one, two.


text:
Q: ckeditor 'paste from Word': retain font color if not black I'd like to get rid of most font styles as I paste in from Word, but have a way to retain font colours if they aren't the default (black). This way, if the text in my Word doc has a line of red text, I won't lose that.
Config options for the PasteFromWord plugin include a way to retain Word's font styles as they are pasted in (pasteFromWordRemoveFontStyles = false), but this opens the gates to whole lot of font cruft. All I want to let through is any non-default font color.
Retaining font sizes can be largely dealt with in Word by using H1-H6 styles there, but I don't see how I could have a style in Word for red text and have that paste over to CKEditor. Any help or ideas appreciated. Thanks.

A: Here's a little hack to preserve the color styles by modifying the Paste From Word plugin.
First, turn on the style filter in your ckeditor config:
config.pasteFromWordRemoveFontStyles = true;

Now, Under the "ckeditor/plugins/pastefromword" folder, open "default.js".
Find this code section (line 956 at the time of writing):
// Assume MS-Word mostly carry font related styles on <span>,
// adapting them to editor's convention.
if ( styleText ) {
    attrs.style = stylesFilter( [
        // Drop 'inline-height' style which make lines overlapping.
        [ 'line-height' ],
        [ ( /^font-family$/ ), null, !removeFontStyles ? styleMigrateFilter( config.font_style, 'family' ) : null ],
        [ ( /^font-size$/ ), null, !removeFontStyles ? styleMigrateFilter( config.fontSize_style, 'size' ) : null ],
        [ ( /^color$/ ), null, !removeFontStyles ? styleMigrateFilter( config.colorButton_foreStyle, 'color' ) : null ],
        [ ( /^background-color$/ ), null, !removeFontStyles ? styleMigrateFilter( config.colorButton_backStyle, 'color' ) : null ]
    ] )( styleText, element ) || '';
}

In the line that starts with /^color$/ change !removeFontStyles to removeFontStyles so the new line is now:
[ ( /^color$/ ), null, removeFontStyles ? styleMigrateFilter( config.colorButton_foreStyle, 'color' ) : null ],

Clear your browser cache before testing.


text:
Q: MacBook Pro stuck on loading screen trying to boot from new SSD So I recently bought a brand new SSD for my Macbook Pro Mid 2009 Unibody. I installed the new El Capitan operating system on the SSD by using a USB-SATA cable. After it finished installing, i replaced the old harddrive with the SSD and booted the mac. However when trying to boot it gets stuck on the apple logo with progress bar underneath. It just sits there at 100% (picture below) and has done so for about 5-6 hours now.
Anybody with some sort of solution or question feel free to write I am almost willing to do anything to get it to work.

A: Software causes
Possibly OS X might be booting expecting to have to work with the USB bus and getting confused by the fact it's now over SATA?
It in theory should handle that fine, but back in the day that did happen sometimes when making a clean install on a drive over USB and then moving it to SATA.
Never had the problem with Cloning an existing drive since then the OS was still set up like it was on the drive that you replaced, but clean installs sometimes would get set up in such at way that when it was no longer using USB to boot it would just hang.
So if that's it, running the install afresh should fix it up.
Just checking as well, is the SSD formatted as a GUID partition table, with a Mac OS X Extended (Journaled) filesystem?
Hardware Causes
If the above doesn't fit it, but the SSD works fine over the USB to SATA connector, then it might be a problem with the Hard Drive flex cable in your Mac, or possibly (though pretty unlikely, really) the SATA controller on the Logic Board.
Were you replacing the Hard Drive just because you felt like it was a upgrade, or were you having problems with it before. If you were previously having problems, the flex cable could very likely be your culprit.
Other than that, if you accidentally disturbed the Memory modules in your Mac, it is possible it might be hanging just because of that and removing and reinstalling them could get you up and running again. Best to se if you can start the computer from your removed hard drive or the Install CDs that came with the Mac first since if either of those work ok, then it is not the Memory, and you don't really want to handle those modules if you don't have to.
More Troubleshooting
Here is a bit more information you can update your post with that can help the folks here troubleshoot with you

*

*SSD model

*How you formatted the SSD

*Was the Hard Drive working fine before replacement

*Was the computer powered down normally (Apple Menu > Shut Down)
before the SSD was disconnected after you installed it

*Can you start the computer by holding the Command and R keys

A: Have you tried to reboot – often it helps in such situations?


text:
Q: Sylius demo broken cause of new channel As mentioned in the title: http://demo.sylius.org/ throws a 500 Error cause of a new channel which is disabled.
If you go to http://demo.sylius.org/admin/channels/ (I guess the guys working with it know how to login) you will see the "new" disabled channel. If you remove it, the http://demo.sylius.org/ will run again.
To make this a question: How to create a new Channel or is there a stable Sylius version?


text:
Q: If $f$ is a continuous periodic function with irrational period and if $\sum_n\frac{|f(n)|}{n}<\infty$, then $f$ is identically zero. Please show that if $f:\mathbb{R}\to\mathbb{R}$ is a continuous periodic function with irrational period and if $\sum_n\frac{|f(n)|}{n}<\infty$, then $f$ is identically zero.
(For example, using this we know $\sum_{n\ge1}\frac{|\sin n|}{n}$ diverges.)
The book mentions the "so-called equidistribution criterion"; I'm not sure if it's referring to this: http://en.wikipedia.org/wiki/Equidistribution_theorem )

A: Yes, the reference is correct.
Assume $f$ is nonzero and $p$ its period. Then there exist $\epsilon>0$ and  $0<a<b<p$ with $|f(x)|>\epsilon$ for all $x\in [a,b]$. For $m$ sufficiently big, the proportion of numbers $n\in \{m+1, m+2, \ldots, 2m\}$ such that $n\bmod p\in [a,b]$ is approximately $\frac{b-a}p$, hence
$$ \sum_{n=m+1}^{2m}\frac{|f(n)|}{n}\gtrsim\frac{b-a}pm\cdot \frac\epsilon{2m}=\frac{(b-a)\epsilon}{2p}$$
and hence the full series diverges. To make this precise, one must be more specific, what "approximately" means in the above.

A: Suppose that $f$ has period $\xi$ and that $\sum_n \frac{|f(n)|}{n} < +\infty$. By Kronecker's lemma, it follows that $\lim_{n \to \infty} \frac{1}{n} \sum_n |f(n)| = 0$. By the ergodic theorem (in this case equivalent to Weyl's equidistribution theorem), we also have that $\lim_{n \to \infty} \frac{1}{n} \sum_n |f(n)| = \frac{1}{\xi}\int_0^{\xi} |f(x)|dx$. Thus we conclude that $\int_0^{\xi} |f(x)|dx=0$, and thus $f=0$ almost everywhere. By continuity $f=0$ everywhere.

A: If there is a point $x_0$ such that $|f(x_0)|$ > 0 then there exists $
\epsilon $ such that if $|x-x_0|<\epsilon$ then $f(x) > f(x_0)/2$ by continuity.  Now look at all translates of the interval $[x_0-\epsilon,x_0+\epsilon]$ by the period $\alpha$ of the function.  Now the equidistribution theorem guarantees these intervals cover an integer value at least once every $\alpha / \epsilon = C$ translates.  Taking these we get a sequence of integers $n_0, n_1,...$ such that $n_k < Ck$ and $|f(n_i)|> |f(x_0)|/2$. Now combining these $|f(n_k)|/n_k > |f(x_0)|/(2Ck) = C'k^{-1}$.  So comparing the sum with the $C'$ times harmonic series, we see it must diverge.


text:
Q: uint32 vs uint64: What bases do I need for the 'int()' function to work properly If I have two hex-strings and want to convert one to an 32-bit unsigned integer and the other to a 64-bit unsigned integer, what bases would I provide the int() function?

A: Well, python usually decides how much memory to allocate itself. See the following example:
>>> type(int('0x7fffffff', 16))
<type 'int'>
>>> type(int('0x80000000', 16))
<type 'long'>

Based on the size of the number, Python allocates the right amount of memory.
BUT if you use the method long() instead of int(), always 8 bytes will be allocated, no matter what the number is:
>>> type(long('0x7fffffff', 16))
<type 'long'>
>>> type(long('0x80000000', 16))
<type 'long'>

*Tested for Python 2.7 (not tested with 3.x)

A: So I goofed up and int() does not determine the size or sign of your hex string.
By definition, hex is 16. So you would put in your string with the hex base of 16
int('A1S31231', 16)

The issue between 32 bit and 64 bit was simply the size of the string put in as an argument.
By virtue of their size,

2 hex characters = 1 byte

So if I had a 64 bit int, it would be 8 bytes or a 16 character hex string.
If I had a 32 bit int, it would be 4 bytes or 8 character hex string.
Based off Duncan's answer: In order to make your result unsigned. You would need to take your result and & them with their proper mask.
If you're looking to go from hex to an uint32 you would do the aforementioned int() conversion and then
result & 0xffffffff

If you wanted to go from hex to uint64 you would do the aforementioned int() conversion and then
result & 0xffffffffffffffff


text:
Q: Can't enable termination protection on a running ec2 instance I'm working with a few ec2 instances through the AWS console and I can't seem to enable Termination Protection.
When I right click on one of my instances and select "Change Termination Protection" and click "Yes, Enable", I get the error:
An error occurred while changing the termination protection setting of this instance.

This seems to happen on my Ubuntu 12.04 and Windows Server 2012 instances. I have used termination protection in the past so I'm not sure what has changed.
Thanks!

A: Aha! Figured it out.
Apparently you cannot enable Termination Protection with Spot Instances, at least using the current AWS console. I have no definitive proof on this but

*

*Enabling termination protection on my spot instances does not work but enabling termination protection on all my other instances does work.

*When you check "Request Spot Instances" in the current AWS Console on page three of the Launch Instance Wizard, the checkbox lower on the page labeled "Enable termination protection" disappears.
Something to muddy the waters however is this section from some AWS documentation which suggests that Termination Protection on Spot Instances is possible. Granted, it's an aside on a page in the MapReduce docs and the real Termination Protection page makes no similar mention, but it's there nonetheless.
Thanks everyone!


text:
Q: How to sort str in Python using NumPy a = np.array(10,2,3,1,20,30) #I got it from the Input.
b = np.sort(a)

it gives me a result [1,10,2,20,3,30] instead of [1,2,3,10,20,30]

A: Since you are getting input and adding it into an array the "numbers" will be str and not ints. You would need to first convert the input to take in int rather than str
Change input to be a int:
user_in = int(input()) # ex: '4'
print(type(user_in)) # <class 'int'>

Notice how I am using the int() around the input() casting the users input from a str to an int.
Now the input could be added to an array and you will get the expected results due to the values being integers and not strings.
Modify the existing items in the list to be int:
Another approach is to change the array that contains the numbers as strings to ints. You could map() over all items in the array to change them to int.
arr = list(map(int, arr))

This would go through your list and change every item to be of type int

A: import numpy as np
arr = np.array([10,2,3,1,20,30])
print(np.sort(arr))

This works fine. Firstly create a list before you try sorting it.

A: Accuracy when writing code, and your question counts.
Your sample array produces an error:
In [69]: a = np.array(10,2,3,1,20,30)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-69-d65567166292> in <module>
----> 1 a = np.array(10,2,3,1,20,30)

TypeError: array() takes from 1 to 2 positional arguments but 6 were given

Changing that to be a list of integers:
In [70]: a = np.array([10,2,3,1,20,30])
In [71]: a
Out[71]: array([10,  2,  3,  1, 20, 30])

Sort does what you want:
In [72]: np.sort(a)
Out[72]: array([ 1,  2,  3, 10, 20, 30])

But if the input was a string or list of strings:
In [73]: a = np.array('10,2,3,1,20,30'.split(','))
In [74]: a
Out[74]: array(['10', '2', '3', '1', '20', '30'], dtype='<U2')
In [75]: np.sort(a)
Out[75]: array(['1', '10', '2', '20', '3', '30'], dtype='<U2')

The sort is string lexical. And the use of quotes to show strings is clear.


text:
Q: What is Paging in memory management? I was just reading Operating System Principles by Silberschatz et al when I came across paging in memory management.I'm slightly confused about it.
It states that Physical Memory(I assume it's RAM) is divided into frames, and logical memory is divided into pages. CPU generates logical addresses containing page number and an offset. This page number is used to retrieve the frame number from a page table which gives the base address
so the physical address is calculated as base+offset.
My question is:

*is the page table maintained for every process?
I logically think that the answer would be yes as every process will need to map its own pages to frames. I may be wrong. Please clarify.
Also:

* paging and segmentation(where 'holes' are created in memory) are two totally different techniques that are not used in combination. Correct?

A:
is the page table maintained for every process?

If the system has to provide a secure virtual address space for each process, then yes.

paging and segmentation(where 'holes' are created in memory) are two totally different techniques that are not used in combination. Correct?

No, there is a virtual memory scheme called paged segmentation. (I recall this concept causing exasperation by my classmates when introduced by the prof.  If Silberschatz et al didn't mention this, then that textbook is incomplete.)  The original goal of paged virtual memory was to provide a large address space for executing a large program on a computer with limited RAM. In a simple paged virtual memory with multiprocessing, there would be no restriction on having two processes sharing one page.  But a segmented virtual memory is intended for multiprocessing, and would isolate each process to its own segments.
While it may seem redundant, the typical virtual memory scheme used in a secure OS uses both pages and segments, where the segments are the processes' binary images.  The typical HW will probably only support fixed-sized pages.  The segmentation is implemented in the OS.  The concept of segments facilitate management of multiple processes in memory.  The concept of pages facilitates a minimal memory footprint by each process.  A shared runtime library would be a special case of a write-protected, execute-only segment that was shareable among processes.
Be aware that "segment" in virtual memory schemes typically refer to a chunk of memory that is logically cohesive and has an arbitrary length.  This type of "segment" should not be confused with the Intel 8086/88 (aka x86) "segment" that starts on a 16-byte address boundary (i.e. a "paragraph") and is restricted to 64 KB in size.  X86 segments are a variation of memory banking rather than virtual memory.
Memory banking schemes are for systems that have a small address size (e.g. 16 bits) but larger physical memory space (e.g. up to 1 MB of adressable memory).  Virtual memory is (or was intended for) for the opposite situation: the address size is large (e.g at least 32 bits) and the installed memory is less than the address space (not always true nowadays).  Virtual memory is typically completely invisible to user programs, whereas the Intel 8086/88 programer must be aware of small/medium/large memory models and far versus near pointers.   BTW that lecture where I first learned of virtual memory and "paged segmentation" occurred before Intel designed the i8086.
As supporting text, Wikipedia also mentions that segmentation and paging can be combined (in hardware).

A: Segmentation yields Linear Addresses, Paging yields Physical Addresses
Regarding logical and physical addresses, from Bovet & Cesati (Understanding the Linux Kernel), I've got this:

As you can see, paging and segmentation are carried out by separate units of the hardware.  Although they may take place at the same time, the OS can disable the segmentation unit (so addresses are effectively treated not as logical but linear ones).
Generalities
You may already know this stuff, but I put it here anyway for completeness.
Pages occupy Frames: Swapping
As far as Silberschatz chapters 8,f is concerned, frames refer to the layout of the physical memory. The OS divides RAM into areas of equal and conveniently sized (e.g. 4K) frames.  Pages are frame-sized pieces of data, the basic unit of page replacement.
There may be more pages than available frames.  Some pages occupy frames, some pages are swapped out on disk.
If a page is swapped in from disk, it is aligned with a certain frame in memory (whichever the page replacement algorithm saw fit).
Operating Systems and the Hardware co-operate
As with many OS objectives, memory management always works in concert with the hardware: both the OS and hardware co-operate, to get the job done.  How they do it in a realistic scenario depends on

*

*the set of memory management primitives the hardware provides (paging, segmentation, and what the heck there exists), and

*which subset thereof the OS really uses on the particular architecture and situation (Linux@zArchitecture is different from Linux@Intel is different from Windows@Intel is different from Window@Intel@Boot-up)

For example, only a few architectures provide segmentation and the figure above applies to x86.  Linux, for portability reasons, does not very much exploit it.  If I remember it correctly from Tanenbaum, OS/2 was the only operating system to exploit Intel's segmentation to its full extent.
So far this Answer.
Depending on why you need to know this, the following approach might help you (it has helped me).
I suggest you first get familiar with the hardware and the individual primitives.  If Silberschatz is to vague on this point, try Tanenbaum (Modern Operating Systems) or Hennessy&Patterson (Computer Architechture, A Quantitative Approach).  If your curiosity is not satisfied by then, see how a particular OS uses it in various situations on a particular platform.

A: At first, your definitions are correct.
For your first question, in Simple Paging, it's yes. Operating system maintains page table for each process and that brings one of the problems of simple paging. It uses a lot of RAM to keep these page tables.
Process table count is not limited which means 100 process brings 100 different process table, 1000 process brings 1000 different process table and for your information I assume there's enough available RAM, otherwise process won't work.
Also, process table length is not limited which means one of page tables can have 100 pages, other one can have 1000, another one can have 10 pages. Depends on process.
That's the result.
The second one is, they can be combined well but depends on the era which book is written in, they might say it's not.


text:
Q: Inconsistent Line lengths and distance measurements I've imported OSM data, including specifically LineString railroad tracks for different subdivisions.
I want to distribute mile markers at fixed intervals, but am getting very different distance measurements with different tools and zooming scales. The original data is in 3857 as default  OSM and in my PostGIS db.
First I used the Marker line symbology for tick marks. It's consistent but any view with scale higher than 1:100000 and the distances and mark locations keep varying, even with feature clipping turned off. At lower scales the distances are wrong even if consistent. A line of length 82 is showing 102 miles by the marker distribution.
Then I created a virtual field simply with $length.. It's the same here, where only zoomed in closer than 1:100000 does the length stay consistent. The lengths do match what I measure with Google Earth, and whether in 3857 or UTM 32611, it's the same behavior and variance when zoomed out. This is the correct length but only closer than 1:100000 Is the geometry changing, or the projection at those scales??
The other feature I wanted was to "create points along geometry". This method doesn't vary spacing as it's not dynamic, but is also incorrect and showing 103 instead of 82 miles. I've tried a few other projections, but problem appears the same?
Why is the create points giving wrong distances, from the same line objects? Using the measure tool is consistent and represents the resulting spacing.
Any advice to get these distances to be correct? It's difficult to trust the measurements.
-UPDATE-
So I understand that Web Mercator is not a good projection for measuring distances, and am trying to get a better handle on projections in the workflow.
I used regional OSM data downloads, merged using Osmosis, then imported into PostGIS with osm2pgsql. I never addressed the projection at these steps, and data ended up with default PostGIS 3857. I then did some reprojections with QGIS to try to achieve correct measurements, including explicit reprojections in PostGIS or on the fly changes. At this stage none of these make any perceptible differences, which leads to...
Is correctness lost during first import to 3857, or is it reversible?
At what stage in the workflow do I need to ensure it's in the correct crs?
More succinctly, How can I correctly measure line distances from OSM data?


text:
Q: Cannot retrieve values from SOAP response When I print the response in createSOAPResponse, I do get the correct response body but I do not get actual values. I'll get a node element like this <xsd:element name="Incident_Number" type="xsd:string"/> but no associated value. I am new to this. Am I missing any steps?
I've included the entire source code of my class for clarity:
 public class RemedySOAPService {

    /**
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {

        // Establish SOAP Connection
        SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
        SOAPConnection soapConnection = soapConnectionFactory.createConnection();

        // Create SOAP Request
        String namespaceURI = "XXX";
        SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(), namespaceURI);

        // Create SOAP Response
        createSOAPResponse(soapResponse);

        // Close Connection
        soapConnection.close();

    }

    /**
     * @param soapResponse
     * @throws Exception
     */
    private static void createSOAPResponse(SOAPMessage soapResponse) throws Exception {
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        Source sourceContent = soapResponse.getSOAPPart().getContent();
        System.out.println("SOAP Response:");
        StreamResult result = new StreamResult(System.out);
        transformer.transform(sourceContent, result);
    }

    /**
     * @return soapMessage
     * @throws Exception
     */
    private static SOAPMessage createSOAPRequest() throws Exception {
        MessageFactory messageFactory = MessageFactory.newInstance();

        // Create SOAP Message
        SOAPMessage soapMessage = messageFactory.createMessage();

        /*<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="XXX">
           <soapenv:Header>
              <urn:AuthenticationInfo>
                 <urn:userName>XXX</urn:userName>
                 <urn:password>XXX</urn:password>

              </urn:AuthenticationInfo>
           </soapenv:Header>
           <soapenv:Body>
              <urn:HelpDesk_QueryList_Service>
                 <urn:Qualification>XXX</urn:Qualification>
              </urn:HelpDesk_QueryList_Service>
           </soapenv:Body>
        </soapenv:Envelope>*/

        // Create SOAP Part
        SOAPPart soapPart = soapMessage.getSOAPPart();

        // Set Constants
        String xmlns = "XXX";
        String username = "XXX";
        String password = "XXX";
        String qualification = "XXX";

        // Create SOAP Envelope
        SOAPEnvelope envelope = soapPart.getEnvelope();
        envelope.addNamespaceDeclaration("urn", xmlns);

        // Create SOAP Header
        SOAPHeader soapHeader = envelope.getHeader();

        // Create SOAP Element for AuthenticationInfo
        SOAPElement authInfoElem = soapHeader.addChildElement("AuthenticationInfo", "urn");

        // Create SOAP ChildElements for userName and password
        SOAPElement usernameChild = authInfoElem.addChildElement("userName", "urn");
        SOAPElement passwordChild = authInfoElem.addChildElement("password", "urn");

        // Assign values to SOAP ChildElements
        usernameChild.addTextNode(username);
        passwordChild.addTextNode(password);

        // Create SOAP Body
        SOAPBody soapBody = envelope.getBody();
        SOAPElement bodyElem = soapBody.addChildElement("HelpDesk_QueryList_Service", "urn");
        createElementAndSetText(bodyElem, "Qualification", qualification);

        // Create MimeHeaders
        String namespaceURI = "XXX";
        MimeHeaders headers = soapMessage.getMimeHeaders();
        headers.addHeader("SOAPAction", namespaceURI + "/XXX");

        // Save Request
        soapMessage.saveChanges();

        // Print the Request Message
        printSOAPRequest(soapMessage);

        return soapMessage;
    }

    /**
     * @param parent
     * @param element
     * @param text
     * @return
     * @throws SOAPException
     */
    private static SOAPElement createElementAndSetText(SOAPElement parent, String element, String text)
            throws SOAPException {
        SOAPElement child = parent.addChildElement(element, "urn");
        child.addTextNode(text);

        return child;
    }

    /**
     * @param soapMessage2
     * @throws SOAPException
     * @throws IOException
     */
    private static void printSOAPRequest(SOAPMessage soapMessage) throws SOAPException, IOException {
        System.out.print("SOAP Request:");
        System.out.println();
        soapMessage.writeTo(System.out);
        System.out.println();
        System.out.println();
    }

}

My goal is to collect a list of  returned from the SOAP response and use them in a second operation. But how can I extract the values from that element if they don't appear?
I have tested in SoapUI so I'm sure that the requests and responses are correct. I'm just having trouble building the client.


text:
Q: How to make object referencing to the same thing? public class Number {
    private int j;
    public Number(){
        j = 3;
    }

    public Number(int m){
        j = m;
    }

    public void SetNum(int n){
        j = n;
    }

    public int GetNum(){
        return j;
        }

    }

/// (different file, same directory)
    public class User {
        private Number jim;

        public User(){
                this.jim = new Number();
            }

            public static void main(String []args){
                User keith = new User();
                User justin = new User();
                ??????????????????????????
            }
     }

I want keith.jim = justin.jim and justin.jim = keith.jim. Such that if i do keith.jim.SetNum(34), both keith and justin's jim.j will be 34. How to do that? This idea will be implement in a bigger piece of code.
Also, user.java and Number.java must exist. The context cannot be changed,I can add new methods but I cannot alter the context in Number (E.G put j in user instead of Number). Each user must have a number object which every users is referencing to as well.

A: Others have suggested creating just one User object. An alternative would be to have two User objects, but with the same reference for the value of the jim field:
User keith = new User();
User justin = new User();
justin.jim = keith.jim;

This would be useful if you have other fields where keith and justin need to be different, but any change in the object that the value of the jim field refers to must be seen by both.
Both of these are valid options, depending on your requirements.
A few points, however:

*

*This means the original value of justin.jim because pointless; you could consider adding a User constructor taking a Number reference for the initial value of the field, allowing you to write:
User justin = new User(keith.jim);

*Shared mutable state like this can become tricky to reason about, particularly in the face of multiple threads

*As noted in comments, you should rename your Number class to be something that isn't in java.lang (or java.util etc, if possible).

*You should follow Java naming conventions for your methods, using camelCase instead of PascalCase - I'd call them getValue and setValue, personally.

A: Try this
   User keith = new User();
   User justin = keith;

A:    User keith = new User();
   User justin = keith;

Now both will refer to the same object, any change make in the keith will reflected to the justin because both are referring to same object.


text:
Q: What's the name of Perl distribution units? Package is a namespace. Module is a file with Perl code. cpan and cpanm are probably package managers. When I do cpanm XML::LibXML I install what exactly?

A: Distribution (or "dist" for short).
The name for a Perl distribution unit is distribution, so cpanm XML::LibXML installs the XML-LibXML distribution, because it includes the specified XML::LibXML module.
Example 1

Example 2

Note that linux distributions usually have a package manager such as apt or yum, and many Perl distributions are made available as packages for those package managers. Someone using those package managers might refer to Perl distributions as packages, but that's not standard Perl jargon.

A: When you download a package with a name like "UseFull::Munger"
You will at the very least get a file UseFull/Munger.pm installed in your perl library.
You could also get a set of modules used to implement the main module: "/UseFull/Munger/dyslexic.pm".
The module may be a wrapper around a C library (like LibXML) in which case you will get some binaries installed such as  "auto/XML/LibXML/LibXML.so".
If cpan needs to build a wrapper for a library you will get some "UseFull/Munger/SlickClib/SlikClib.xs" files which tell CPAN how to build the perl wrapper.
In addition, if the developer is nice, you may get lots of ".pod" document ion on how to use the module.

A: I call these Perl modules or CPAN modules. The individual .pm building blocks are Perl modules too, but you rarely use them directly.
When talking about the archive file that you upload to CPAN, you can use the word distribution. When talking about all the other files that are in there and that you can view on metacpan, taking a look at the dist(ribution) works well, too.


text:
Q: php, regex preg_match a specific word 0 or 1 time I want to match a string with the words of another string, keeping the order:
$string_original = "Number three is good, then two and one.";
$match_string = "three two one";
$result = magic_function($string_original,$match_string);

I want the result to be
$result = array(0 => 'three', 1 => 'two', 2 => 'one');

Because all the words in the match string are found in the original ordered.
An other example:
$string_original = "two is a magic number, one also and three";
$match_string = "three two one";
$result = magic_function($string_original,$match_string);
//RESULT WOULD BE
$result = array(0 => 'three');

//LAST EXAMPLE
$string_original = "three one, then two!";
$match_string = "three two one";
$result = magic_function($string_original,$match_string);
//RESULT WOULD BE
$result = array(0 => 'three', 1 => 'two');

My magic_function is something like
function magic_function($origin,$match){
$exploded = explode(' ',$match);
$pattern = '/';
foreach ($exploded as $word){
$pattern .= '';//I NEED SOMETHING TO PUT HERE, BUT MY REGEX IS PRETTY BAD AND I DON'T KNOW
}
$pattern .= '/';
preg_match($pattern,$origin,$matches);
return $matches;
}

Any help with the regex part? Thank you.

A: I would suggest using preg_split instead of preg_match. Also make sure to escape words you search for with preg_quote. I also suggest adding word boundary conditions (\b) to the regular expressions, so you only match complete words. Take that out if you want to match part of words:
function magic_function($string_original,$match_string) {
    foreach(explode(' ', $match_string) as $word) {
        $word = preg_quote($word);
        $split = preg_split("/\b$word\b/", $string_original, 2);
        if (count($split) < 2) break;
        $result[] = $word;
        $string_original = $split[1];
    }
    return $result;
}


text:
Q: Nifi - No Viable alternative @ Input '{' While trying to insert XML data in to Cassendra DB using apache Nifi, I am getting the below error. What's going wrong?

Error : "No Viable alternative at Input '{'

Below are my ReplaceText Processor entries:
Search Value : (?s:(^.*)$)
Replacement Value : $1
Character Set : UTF-8
Maximum Buffer Size :1 MB
Replacement Strategy :Regex Replace
Evaluation Mode :Entire text

A: PutCassandraQL expects the input to be a valid CQL statement. If you have JSON in the content (presumably you are following my suggestions from your other SO question), you need to create a CQL statement with JSON as the "payload", such as using ReplaceText with the following Replacement Value:
INSERT INTO myTable JSON '$1'

If the previous flow file contains a JSON object (and has no single quotes or they are escaped), this should create a valid CQL statement from it, for use in PutCassandraQL.


text:
Q: Another (perhaps tricky) integral. While solving my Math paper, I came across this integral, and I can't see any way to solve it. At least, any easy way. The integral is-
$$
\int{x^{2} \over 1 + x^{5}}\,\mathrm{d}x
$$
I'm not even sure it exists, by the looks of it. Any help ?.

A: We have
$$x^5+1 = (x+1)(x^4-x^3+x^2-x+1) = (x+1)(x^2+ax+1)(x^2-bx+1)$$
where $a-b=-1$ and $ab=1$.
Now use partial fractions and proceed.

A: I have the following rather lengthy approach: Initially, we note that the integral does not exist due to the pole at x=-1. However, $\int_0^\infty x^2/x^5 dx$ exists since $|x|^2/|x|^5 \le |x|^2$ for sufficiently large $|x| > 0$. I think, we can deal with this integral using the Residue theorem from function theory: f(z):= z^2/(1+z^5) is holomorphic on $\mathbb{C}$ except for the roots of $(1+z^5)$ which are given as
$$ a_k = e^{\pi i/5} e^{2\pi i k/5} \qquad k=0,...,4.$$
Consider the path
$$\gamma_R:= \alpha_R * \beta_R * \tilde\alpha_R$$
(first go $\alpha_R$ then $\beta_R$...) with
$$\alpha_R(t) = R t \qquad t \in [0,1]$$
$$\beta_R(t) = Re^{it} \qquad t \in [0, 2\pi/5]$$
$$\tilde\alpha_R(t) = (1-t)Re^{2\pi i/5} \qquad t\in [0,1]$$
for $R>1$. $\gamma_R$ goes a around a segment of B_R(0) which only encloses $a_0$. Therefore the Residue theorem yields
$$2\pi i Res_{a_0}f = \int_{\gamma_R}f(z)\, dz = \int_{\alpha_R}f + \int_{\beta_R}f + \int_{\tilde \alpha_R}f$$
Using Cauchys inequality from function theory the middle integral goes to 0 for $R\to \infty$. Now it can be shown that (found in most textbooks)
$$Res_{a_0}f = a_0^2/(5a_0^4) = 1/5 a_0^{-2} = 1/5 e^{-2/5 \pi i}.$$
and then
$$2/5 \pi i e^{-2/5 \pi i} = \int_0^R x^2/(1+x^5) dx - \int_0^R e^{2/5\pi i}\frac{(te^{2/5\pi i})^2}{1+(te^{2/5\pi i})^5} dt \\
= (1-e^{6/5\pi i})\int_0^R x^2/(1+x^5) dx \to (1-e^{6/5\pi i})\int_0^\infty x^2/(1+x^5) dx$$
for $R\to \infty$. Therefore
$$ \int_0^\infty x^2/(1+x^5) dx = \frac{2/5\pi i e^{-2/5\pi i}}{(1- e^{6/5\pi i})} = \frac{\pi/5}{1/(2i)(e^{2/5\pi i} - e^{8/5\pi i})} = \frac{\pi/5}{\sin(2/5 \pi)}$$
I have compared this to the result form wolfram alpha and it checks out. I hope I could help.
BS


text:
Q: Prove an equality between ideals in $\mathbb{C}[x, y]$. I have to prove that in $\mathbb{C}[x, y]$ we have the equality
$$ (x^3-x^2, x^2y-x^2, xy-y, y^2-y)=(x^2, y) \cap (x-1, y-1).$$
I have proven the inclusion $\subset$ proving that every generator of the LHS can be written as a linear combination both of elements of $(x^2, y)$ and of elements of $(x-1, y-1)$ (e.g.: $x^2y-x^2=x^2\cdot(y-1)$), but I am stuck with the reverse inclusion. Any suggestion?

A: Take an arbitrary element of the RHS and subtract linear combinations of the generators on the left hand side to simplify your element: the first and last generator on the LHS are enough to reduce your element to something of the form: $$ax^2+by+cxy+dx^2y,$$
as being an element of the RHS implies there is no constant or $\lambda x$ term.
Then the third generator gets rid of the $cxy$ term and the second gets rid of the $dx^2y$ term, leaving $$a'x^2+b'y.$$
Substituting in $x=1, y=1$ we get $0$ as we have an element of the RHS.
Thus $a'+b'=0$, so we are left with a scalar multiple of $x^2-y$.
But $$x^2-y=(x+1)(xy-y)-(x^2y-x^2)
$$
We conclude that any element of the RHS can be broken down to a linear combination of the 4 generators on the LHS.


text:
Q: How to implement Into trait to convert all input to usize not using `as usize`? I have a function that returns the compound duration based on an usize input:
pub fn format_dhms(seconds: usize) -> String

If the input is 6000000:
println!("{}", format_dhms(6000000));

It returns:
69d10h40m

This works when the input is a number, but when I use the output of another function with a fixed type, I need to use as usize. For example, if I use the output of Duration using methods as_secs() = u64 or as_nanos() = u128.
When someone passes u128::MAX, I would like to deal with it like as usize does by truncating the input to the max accepted value.
This is what I am trying: (https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=4a8bfa152febee9abb52d8244a5092c5)
#![allow(unused)]
use std::time::Instant;

fn format<T: Into<usize>>(number: T) {
    if number == 0 {
        //println!("{}", number)
    } else {
        //println!("{}> 0", number)
    }
}

fn main() {
    let now = Instant::now();
    format(now.elapsed().as_nanos()); // u128
    format(now.elapsed().as_secs()); // u64
}

But some of the errors I get are:
error[E0277]: the trait bound `usize: std::convert::From<i32>` is not satisfied
    the trait `std::convert::From<i32>` is not implemented for `usize`
...
error[E0369]: binary operation `==` cannot be applied to type `T`

If I remove the <T: Into<size>> it works, but I need to use as usize.
 format(now.elapsed().as_nanos() as usize);

Is there a way I could convert the input to prevent using the as usize or how to achieve same behavior when input is just a number with no defined type?

A: You can use std::mem::size_of to check if the input type fits in a usize and use bit-manipulations to truncate when it doesn't:
use std::convert::{ TryFrom, TryInto };
use std::fmt::Debug;
use std::ops::BitAnd;
use std::time::Instant;

fn format<T: TryInto<usize> + TryFrom<usize> + BitAnd<Output=T>> (number: T)
    where <T as TryFrom<usize>>::Error: Debug,
          <T as TryInto<usize>>::Error: Debug
{
    let number: usize = if std::mem::size_of::<T>() <= std::mem::size_of::<usize>() {
        number.try_into().unwrap()
    } else {
        (number & usize::MAX.try_into().unwrap()).try_into().unwrap()
    };
    if number == 0 {
        //println!("{}", number)
    } else {
        //println!("{}> 0", number)
    }
}

Playground
Note that so long as you only use unsigned types, the unwraps should never fail since the check on type sizes ensures that the conversions are always valid.

A: Using the TryFrom trait, you can "try" to convert to a different type. Should the input number be too big for usize, you will get an error.
fn foo<T: TryInto<usize>>(x: T) -> usize {
    x.try_into().unwrap() // Will panic if
                          // x cannot fit
                          // into a usize.
}

Additionally, this does not have the same semantic effect as as casts. Since those will truncate, while this will just not work.

The real best practice in this case would be to just use regular trait bounds for numbers, instead of using usize, since some values don't fit in there:
fn format<
    T: Sub<Output = T> +
       Mul<Output = T> +
       Div<Output = T> +
       Display +
       PartialEq +
       From<bool>        //etc. for all the operations you need.
    >(number: T) {
    if number == T::from(false) { // `false` turns into 0 for numbers.
        //println!("{}", number)
    } else {
        //println!("{}> 0", number)
    }
}

The std number traits however, are rather barebones, so I'd recommend you look at num_traits.


text:
Q: $\mathbb{Z}_m \oplus \mathbb{Z}_n$ isomorphic to $\mathbb{Z}_{mn}$ as $\mathbb{Z}_{mn}$ modules I would like to know if, when $\gcd(m,n)=1$, it is the case that $\mathbb{Z}_m \oplus \mathbb{Z}_n$ is isomorphic to $\mathbb{Z}_{mn}$  as $\mathbb{Z}_{mn}$ modules. I know they are isomorphic as groups but I couldn't show they were isomorphic as modules over the ring $\mathbb{Z}_{mn}$.

A: A $\mathbb{Z}_k$ module is just an abelian group of exponent $k$ (that is, an abelian group in which $kx=0$ for all $x$). In particular:
Theorem. Two abelian groups of exponent $k$ are isomorphic as $\mathbb{Z}_k$ modules if and only if they are isomorphic as groups.
Proof. Let $G$ and $H$ be two abelian groups (written additively) of exponent $k$. If they are isomorphic as $\mathbb{Z}_k$ modules, then there is a bijective $\mathbb{Z}_k$-module isomorphism $\phi\colon G\to H$; this module isomorphism is in particular an abelian group isomorphism, so $G$ and $H$ are isomorphic as abelian groups.
Conversely, suppose that $G$ and $H$ are isomorphic as abelian groups, and let $\psi\colon G\to H$ be an abelian group isomorphism. I claim that it is a $\mathbb{Z}_k$-module isomorphism. To establish this, it suffices to show that $\psi(ax) = a\psi x$ for all $a\in\mathbb{Z}_k$. Since $G$ and $H$ are of exponent $k$, "$ax$" is well defined since if $a\equiv a'\pmod{k}$, then $a=a'+km$ for some $m$, and then $ax = (a'+km)x = a'x + m(kx) = a'x+0 = a'x$. We proceed by induction on $a$: for $a=0$, $\psi(0x) = \psi(0) = 0 = 0\psi(x)$. Assuming the result holds for $a$, we have $\psi((a+1)x) = \psi(ax+x) = \psi(ax)+\psi(x)$ (since $\psi$ is an abelian group homomorphism), and $\psi(ax)+\psi(x) = a\psi(x)+\psi(x) = (a+1)\psi(x)$. Thus, $\psi$ is a $\mathbb{Z}_k$-module homomorphism as well. $\Box$

A: First, as abelian groups $\mathbb{Z}_m \times \mathbb{Z}_n$ and $\mathbb{Z}_{mn}$
are only isomorph if $(m,n) = 1$. Otherwise is
$$
\mathbb{Z}_m \times \mathbb{Z}_n \cong \mathbb{Z}_{[m,n]}.
$$
That said, what's the structure of $\mathbb{Z}_{mn}$-module on $\mathbb{Z}_m \times \mathbb{Z}_n$? Probably you refer to the following
$$
[h] ([x], [y]) = ([hx], [hy]) = h ([x], [y]).
$$
Where the multiplication on the left is that of the $\mathbb{Z}_{mn}$-module and that on the right is the multiplication of th $\mathbb{Z}$-module.
Now, given an isomorphism of $\mathbb{Z}$-modules $\Phi: \mathbb{Z}_m \times \mathbb{Z}_n \to \mathbb{Z}_{[m,n]}$ we have
$$
\Phi([h] ([x], [y])) = \Phi(h ([x], [y])) = h \Phi([x], [y]) = [h] \Phi([x], [y])
$$


text:
Q: как в React компонента react-router-dom генерировать link по id(to который href) и компонент куда id приходит с json а эта ссылка в map нужно что бы каждый раз когда по нему проходит, она добовляла ссылку(это она делает) только немогу сделать в какой компонент переходить
<Link className="btn btn-red bottonmore" to={id}    >  Посмотреть больше</Link>

A: Для начала вы должны добавить Route, который будет отрисовывать ваш компонент. Например:
import { Switch, Route } from 'react-router-dom';

const App = () => {
  return (
    <Switch>
      <Route path="/some_path/:id" component={MyComponent} />
    </Switch>
  );
}

Тогда ссылка будет такая:
<Link to={`/some_path/${id}`}>Click Me</Link>

По клику на ссылку или прямому переходу из строки браузера, будет отрисован компонент MyComponent. id можно будет получить в компоненте как:
const MyComponent = ({ match }) => {
  const { id } = match.params;

  return (/* ... */);
}


text:
Q: How to detect if a folder is too heavy, and if so delete part of it i need to control if a folder defined by a path is full of folders, if those folders are too much i need to delete, for example half of them, from the older one the newest one. Practically i need to make space for future folders.
void fCID(long pThreadId)
{
 ULARGE_INTEGER rFreeBytesAvailable, rTotalNumberOfBytes, rTotalNumberOfFreeBytes;
 if(sc.LB.TMCI && sc.LB.ISM == 1)
 {
   for(10000000000;10000000000 > sd;sd--) //wrong, i'm looking for it
   {
    if (::GetDiskFreeSpaceEx (NULL, &rFreeBytesAvailable, &rTotalNumberOfBytes,
      &rTotalNumberOfFreeBytes))
      {
       if (rFreeBytesAvailable.QuadPart > 10000000000)     //10gb
        {
         fAFOZA("C:\\S\\H1\\CA");   //function zip
        }
       else
       {
        sd=sd - 50% of (LA); //sd = space disposable
       }
      }
    }
  }
else
{
fDFOP(where.Trace_C_P);  //not interesting
fDFOP(where.Trace_C_CL_P); //not interesting
}
}

This code is only an idea
ULARGE_INTEGER rFreeBytesAvailable, rTotalNumberOfBytes,
rTotalNumberOfFreeBytes;
if(sc.LB.TMCI && sc.LB.ISM == 1)
{
if (::GetDiskFreeSpaceEx ("C:\\S\\H1\\CA\\LA", &rFreeBytesAvailable, &rTotalNumberOfBytes, &rTotalNumberOfFreeBytes))
{
  do
    {
      fDFOP("C:\\S\\H1\\CA\\LA"); //this function deletes what's inside the path
    }while(rFreeBytesAvailable.QuadPart == 10000000000)
    if (rFreeBytesAvailable.QuadPart > 10000000000)     //10gb
    {
      fAFOZA("C:\\S\\H1\\CA");//this one makes a zip
    }
 }
}

this is another possible implementation maybe

A: If you want to remove the oldest files in a directory structure to reclaim a certain amount of space, you could use the C++17 std::filesystem library class recursive_directory_iterator and the functions
last_write_time and
remove from the same library.
Example:
#include <cstdint>
#include <filesystem>
#include <set>
#include <string>
#include <system_error>
#include <tuple>

namespace fs = std::filesystem;

// a class containing the interesting information about each file
struct file {
    fs::path path;
    std::uintmax_t file_size;
    std::filesystem::file_time_type write_time;

    // An operator< to be able to sort files in this order:
    //  ascending write_time
    //  decending file_size (to remove the biggest of two files with the same write_time)
    //  ascending path
    bool operator<(const file& rhs) const {
        return
            std::tie(write_time, rhs.file_size, path) <
            std::tie(rhs.write_time, file_size, rhs.path);
    }
};

// A function to traverse a directory structure, collect file names, age and sizes
// and to remove the oldest until "bytes_to_remove" bytes have been removed
std::uintmax_t rm_old_files(const std::wstring& dir, std::uintmax_t bytes_to_remove) {
    std::uintmax_t bytes_removed = 0;
    std::set<file> files; // the set will sort file entries with the oldest first

    // collect all regular files in the directory structure starting at "dir"
    for (const fs::directory_entry& de : fs::recursive_directory_iterator(dir)) {
        if (de.is_regular_file()) {
            files.emplace(file{de, de.file_size(), fs::last_write_time(de)});
        }
    }

    // remove files until at least "bytes_to_remove" bytes have been removed
    std::error_code ec; // unread but used to prevent exceptions in fs::remove
    for (auto const& [path, file_size, write_time] : files) {
        std::wcout << L"removing " << path << L'\n';

        /* uncomment this part when you've made sure that it'll
           remove the correct files.
        if (fs::remove(path, ec)) {
            bytes_removed += file_size;
            if (bytes_removed >= bytes_to_remove) break;
        }
        */
    }

    return bytes_removed;
}

Example usage:
std::wstring dir = L"C:\\S\\H1\\CA\\LA";
ULARGE_INTEGER FreeBytesAvailableToCaller;
ULARGE_INTEGER TotalNumberOfBytes;
ULARGE_INTEGER TotalNumberOfFreeBytes;

if (GetDiskFreeSpaceExW(dir.c_str(), &FreeBytesAvailableToCaller,
                                     &TotalNumberOfBytes,
                                     &TotalNumberOfFreeBytes)) {
    // if less than half the total number of bytes are available,
    // execute rm_old_files to try to make at least half available.
    if (FreeBytesAvailableToCaller.QuadPart < TotalNumberOfBytes.QuadPart/2) {
        auto bytes_removed =
            rm_old_files(dir, TotalNumberOfBytes.QuadPart/2 -
                              FreeBytesAvailableToCaller.QuadPart);
        std::wcout << L"removed " << bytes_removed << L" bytes\n";
    }
}


text:
Q: Passing a callback and other parameters to jQuery ajax success? I wrote a function which I'm allowing a callback to be passed to. I then want to execute that with both the ajax repsonse, and another parameter.
My problem is the the callback is executed, and when I step through the code, it looks like the function is called with the proper parameters, however when actually stepping in to the callback function, the first parameter takes the value of whatever I assign to the second argument, and the second argument is undefined.
Here is my function:
namespace = {
fetch : function(sr, count, callback) {
    srCount = count ? count : '25'
    var sub;
    if (sr == 'frontpage'){
        sub = '';
    }else{
        sub = 'foo/' + sr + '/';
    };
    $.ajax({
        url: "http://www.example.com/"+sub+ ".json?count=" + count,
        dataType: "json",
        success: function(msg)
        {
            callback.call(msg, count)
        }
    })
};

Now, when I call it like this:
mynamespace.fetch($(this).attr('href'), 25, true, another namespace.createPost);

I would expect callback.call(msg, count) to resolve to callback.call(/*the ajax response*/, 25);
However, when I run it, I get msg == 25 and count == 'undefined'. I'm at a loss for why...

A: .call calls a function with explicit context given by the first argument, so callback.call(msg, count) calls the callback function with msg set as context (the this value inside the callback function for this call) and count as a first argument.
So you probably want callback( msg, count ) or callback.call( namespace, msg, count ); which means that this inside the callback will refer to namespace for that call.

A: $.ajax() function has a context parameter, which you can use for this purpose.
$.ajax({
  url: "http://www.example.com/"+sub+ ".json?count=" + count,
  context: "hello",
  dataType: "json",
  success: function(msg)
  {

    // here 'this' will be the 'hello' you specified for context while making the call.

    callback.call(msg, count)
  }
})


text:
Q: Sql server Backup & Restore From FileGroup I Use Sql Server 2019 And need to backUp & Restore the FileGroup.
Execution steps :
1.Create The Database With Two FilesGroup and [TestFileGroup] name.
2.Insert data in two tables, one in First FileGroup and the other in the second FileGroup .
3.First FullBackup [TestFileGroup].
4.Then re-enter the data for changes
5.BackUP FileGroup From [FG2] .
6.Restore First FullBackup With [TestFileGroup_New] name.
7.For Restore Partial Backup Need Tail Backup . and Tail Log Backup From [TestFileGroup_New].
8.Restore FILEGROUP Backup .
9.restore Database [TestFileGroup_New]  with RECOVERY
10. raise error !
Error Text :

Msg 4303, Level 16, State 1, Line 100
The roll forward start point is now at log sequence number (LSN) 37000000056800001. Additional roll forward past LSN 37000000058400001 is required to complete the restore sequence.
Msg 3013, Level 16, State 1, Line 100
RESTORE DATABASE is terminating abnormally.

Sql Server Query :
USE master
GO
DROP DATABASE IF EXISTS TestFileGroup
GO
DROP DATABASE IF EXISTS TestFileGroup_New
GO
--================================================================= Create DataBase
CREATE DATABASE TestFileGroup
ON PRIMARY
    ( NAME = N'PRIMARY',            FILENAME = N'D:\Temp\TestDB\TestFileGroup_PRIMARY.mdf'),
 FILEGROUP FG2
    ( NAME = N'secondary',          FILENAME = N'D:\Temp\TestDB\TestFileGroup_secondary.ndf')
 LOG ON
    ( NAME = N'TestFileGroup_log',  FILENAME = N'D:\Temp\TestDB\FGRestoreTEST_log.ldf')
GO
--================================================================= Insert Data(Level 1)
USE TestFileGroup
GO
CREATE TABLE T_primary
(
    ID INT PRIMARY KEY,
    Fname NVARCHAR(100),
    Lname NVARCHAR(100)
) ON [PRIMARY]
GO
CREATE TABLE T_fg2
(
    ID INT PRIMARY KEY,
    Fname NVARCHAR(100),
    Lname NVARCHAR(100)
) ON FG2
GO
--==================================================================
USE TestFileGroup
GO
INSERT INTO T_primary (ID,Fname,Lname) VALUES
    (1,N'Json',N'JJ'),
    (2,N'C#',N'CC'),
    (3,N'Python',N'PP'),
    (4,N'Test1',N'TT'),
    (5,N'C++',N'C')
GO
INSERT INTO T_fg2 (ID,Fname,Lname) VALUES
    (10,N'MMMM',N'M'),
    (20,N'SSSS',N'S'),
    (30,N'PPPPP',N'P')
GO
SELECT * FROM T_primary
SELECT * FROM T_fg2
GO
--================================================================== First Full Backup IN First year
BACKUP DATABASE TestFileGroup  TO  DISK = N'D:\Temp\TestDB\Backup\TestFileGroup_Full.bak'
    WITH FORMAT,COMPRESSION
GO
RESTORE FILELISTONLY FROM DISK = N'D:\Temp\TestDB\Backup\TestFileGroup_Full.bak'

--================================================================== Change Data
USE TestFileGroup
GO
INSERT T_primary
SELECT 6 ID,'Java'Fname,'jv' Lname

INSERT T_fg2
SELECT 40 ID,'HHHH'Fname,'H' Lname

SELECT * FROM T_primary
SELECT * FROM T_fg2
--================================================================== First FileGroup Backup
USE master
GO
BACKUP DATABASE TestFileGroup FILEGROUP = N'FG2' TO  DISK = N'D:\Temp\TestDB\Backup\TestFileGroup_FG2.bak'
    WITH FORMAT,COMPRESSION
GO
RESTORE LABELONLY FROM DISK=N'D:\Temp\TestDB\Backup\TestFileGroup_FG2.bak'
GO
RESTORE HEADERONLY FROM DISK=N'D:\Temp\TestDB\Backup\TestFileGroup_FG2.bak'
GO
RESTORE FILELISTONLY FROM DISK=N'D:\Temp\TestDB\Backup\TestFileGroup_FG2.bak'
GO

--================================================================== Restore Full Backup --->TestFileGroup_New
RESTORE DATABASE TestFileGroup_New FROM DISK=N'D:\Temp\TestDB\Backup\TestFileGroup_Full.bak' WITH
MOVE 'PRIMARY'              TO N'D:\Temp\TestDB\New\TestFileGroupNew_PRIMARY.mdf',
MOVE 'secondary'            TO N'D:\Temp\TestDB\New\TestFileGroupNew_secondary.ndf',
MOVE 'TestFileGroup_log'    TO N'D:\Temp\TestDB\New\TestFileGroupNew_log.ldf',
STATS=10 ,RECOVERY

--================================================================== For Restore Partial Backup Need Tail Backup
BACKUP LOG TestFileGroup_New
    to  DISK = N'D:\Temp\TestDB\Backup\TestFileGroup_New_Tail.trn' ---- Not Real
WITH NORECOVERY,FORMAT,COMPRESSION
GO
--================================================================== Restore FileGroup Backup
RESTORE DATABASE TestFileGroup_New FILEGROUP = N'FG2'
    FROM  DISK = N'D:\Temp\TestDB\BackUP\TestFileGroup_FG2.bak' WITH
NORECOVERY,REPLACE
GO
--==================================================================
RESTORE DATABASE TestFileGroup_New  WITH RECOVERY
/*
Msg 4303, Level 16, State 1, Line 100
The roll forward start point is now at log sequence number (LSN) 37000000056800001. Additional roll forward past LSN 37000000058400001 is required to complete the restore sequence.
Msg 3013, Level 16, State 1, Line 100
RESTORE DATABASE is terminating abnormally.
*/

A: You can't RECOVER until you restore the log file backup.  The whole database must be brought up to a consistent point-in-time by WITH RECOVERY.
After the File Group restore FG2 is ahead of FG1, and restoring the log backup will replay the missing transactions into FG1.
From the docs:

If the filegroup is read/write, an unbroken chain of log backups must
be applied to the last full or differential restore to bring the
filegroup forward to the current log file.

Piecemeal Restores - Applying Log Backups
So something like:
RESTORE log TestFileGroup_New from  DISK = N'D:\Temp\TestDB\Backup\TestFileGroup.trn' WITH RECOVERY

Also you can't restore full backup of TestFileGroup to TestFileGroup_new WITH RECOVERY, because if you do, you can never apply log backups from TestFileGroup.


text:
Q: How many regression bugs from refactoring is too many. Recent QA testing has found some regression bugs in our code. My team lead blames recent refactoring efforts for the regressions.
My team lead's stance is "refactor, but don't break too many things", but wouldn't tell me how many is "too many". My stance is it's QA's job to find bugs that we can't find, and refactoring usually introduces breaking changes. So sure, I can be careful, but I don't knowingly release code with bugs to QA. I do it because I don't see them.
If the refactoring was necessary, how many regression bugs should be considered too many?

A: You are right that refactoring code is important. It prevents code rot and improves code. It makes for cleaner code.
But good code is not only clean code, it's code that is correct, and thus by definition contains as few bugs as possible (ideally none). The first goal of your code is to produce its expected result. So if your refactoring is introducing bugs you might want to consider the net effect of those refactorings.
You should refactor code that is tested. If it's not, add tests and then refactor. This way you know you haven't broken anything. This will help mitigate the risks of a similar situation from happening in the future.
As for refactoring introducing bugs, refactoring should not alter the behavior of a program. I will quote from Wikipedia:

disciplined technique for restructuring an existing body of code, altering its internal structure without changing its external behavior

Sadly nowadays, refactoring has come to mean anything from this definition to total rewrites.
I would alter what your team lead said from:

refactor but don't break too many things

To:

refactor and don't break anything

As for finding bugs being the job of the QA, quality isn't someone else's problem. The goal should be that QA finds nothing. Realistically finding as little as possible.

A:
My stance is it's QA's job to find bugs that we can't find,

Finding bugs is a joint responsibility.
QA's job is to find bugs that you don't find.  There should not be such a thing as bugs that you can't find.  (And if there is, then maybe you should ask for access to the tools / tests that they are using so that you can find them for yourself.

refactoring usually introduces breaking changes.

That is not true.  Refactoring done properly doesn't break things.  And you could argue that fixing the things that break should be part of the refactoring.
The problems arise in reality when:

*

*the refactoring triggers latent bugs in other parts of the codebase that the tests you can run don't reveal, or

*you can't do the full refactor because someone else "owns" some parts of the code that is affected by the refactor.
You shouldn't cop the blame for latent bugs (unless they were yours in the first place).  But on the other hand, if your refactoring is intentionally changing APIs and or behaviours then you need to discuss this with all parties before you refactor, and have a plan for dealing with the effects.  On the third hand1, if the breaking change is unexpected or accidental ... then you should have thought it through in more detail.
And finally, if the regressions were your fault (or partly your fault), then "man up" and take the blame.  And aim to do better next time.

If he agrees that refactoring is necessary (which he does), then why does he have a problem when stuff breaks? Especially when it hasn't affected our schedule so far.

That is easy to answer if you put yourself into his shoes.  He thinks you did the wrong thing in the way you refactored the code.  This time it didn't impact on the schedule.  But next time, it could.  He is trying to prevent that eventuality.

1 - A Larry Niven allusion.


text:
Q: 2x3 custom button grid layout doesn't fit TableRow I am developing some sort of player with 2x3 grid of custom buttons... Buttons are made in customplayerbutton.xml and then they are used as "includes" in main.xml There is a problem with layout - my custom buttons do not fit the TableRow:
bad layout http://img841.imageshack.us/img841/6492/badlayout.png
What am I doing wrong?
customplayerbutton.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/linearLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@android:drawable/btn_default"
    android:clickable="true"
    android:focusable="true"
    android:longClickable="true"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="2.0"
        android:gravity="center"
        android:text="Track67890"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="2.0"
        android:gravity="center"
        android:text="99:99:999 / 99:99:999"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <ProgressBar
        android:id="@+id/progressBar1"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.1" />

</LinearLayout>

main.xml:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/TableLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:longClickable="true"
    android:stretchColumns="*" >

    <TableRow
            android:id="@+id/TableRow01"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1.0" >

            <include
                    android:id="@+id/include01"
                    android:layout_width="fill_parent"
                    android:layout_height="fill_parent"
                    android:layout_gravity="left"
                    layout="@layout/customplayerbutton" />

            <include
                    android:id="@+id/include1"
                    android:layout_width="fill_parent"
                    android:layout_height="fill_parent"
                    android:layout_gravity="right"
                    layout="@layout/customplayerbutton" />
    </TableRow>

    <TableRow
            android:id="@+id/tableRow1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1.0" >

            <include
                    android:id="@+id/include02"
                    android:layout_width="fill_parent"
                    android:layout_height="fill_parent"
                    layout="@layout/customplayerbutton" />

            <include
                    android:id="@+id/include04"
                    android:layout_width="fill_parent"
                    android:layout_height="fill_parent"
                    layout="@layout/customplayerbutton" />
    </TableRow>

    <TableRow
            android:id="@+id/TableRow02"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1.0" >

            <include
                    android:id="@+id/include03"
                    android:layout_width="fill_parent"
                    android:layout_height="fill_parent"
                    layout="@layout/customplayerbutton" />

            <include
                    android:id="@+id/include05"
                    android:layout_width="fill_parent"
                    android:layout_height="fill_parent"
                    layout="@layout/customplayerbutton" />
    </TableRow>

</TableLayout>

A: Finally, I solved this by replacing TableLayout to LinearLayout. Here is the xml worked to me:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1.0" >

            <include
                    android:id="@+id/include01"
                    android:layout_width="fill_parent"
                    android:layout_height="fill_parent"
                    android:layout_weight="1.0"
                    layout="@layout/customplayerbutton" />

            <include
                    android:id="@+id/include00"
                    android:layout_width="fill_parent"
                    android:layout_height="fill_parent"
                    android:layout_weight="1.0"
                    layout="@layout/customplayerbutton" />
    </LinearLayout>

    <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1.0" >

            <include
                    android:id="@+id/include02"
                    android:layout_width="fill_parent"
                    android:layout_height="fill_parent"
                    android:layout_weight="1.0"
                    layout="@layout/customplayerbutton" />

            <include
                    android:id="@+id/include04"
                    android:layout_width="fill_parent"
                    android:layout_height="fill_parent"
                    android:layout_weight="1.0"
                    layout="@layout/customplayerbutton" />
    </LinearLayout>

    <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1.0" >

            <include
                    android:id="@+id/include03"
                    android:layout_width="fill_parent"
                    android:layout_height="fill_parent"
                    android:layout_weight="1.0"
                    layout="@layout/customplayerbutton" />

            <include
                    android:id="@+id/include05"
                    android:layout_width="fill_parent"
                    android:layout_height="fill_parent"
                    android:layout_weight="1.0"
                    layout="@layout/customplayerbutton" />
    </LinearLayout>

</LinearLayout>

A: I tested the XML layouts you posted, i didn't got the output as you shown here, but i got differently. Then i removed 2 statements from main.xml file, now the output is good.
Try this.
In 1st <TableRow> 1st <include> remove the line android:layout_gravity="left"
and 2nd <include> remove the line android:layout_gravity="right"


text:
Q: splice inside a loop doesnt seem to be working I am looping to a json object, where  I have an array of objects.
I want to remove from my array, the objects with a null value on iban and with more than 12 digits on Account number.
If both this conditions are met, I want to remove the item.
I have 3 items on my list that should be removed because those meet this conditions, yet only 2 are removed.
my function goes like this
for (var i = 0; i < benefs.length; i++) {
                var befNumberIban = benefs[i].Iban;
                var befNumber = benefs[i].AccountNumber;
  if (befNumber != null) {

    if (isBefLenght && (befNumberIban == null || befNumberIban == "")) {

        benefs.splice(i, 1);

I cant understand why it only removes 2 our 3 objects that meet the condition...something about splice?

A: from splice the array will re-indexed, so for the last item i will be 1 and array length will be 1 too it will not go inside the loop and hence you are not getting the desire result inside for loop. You can use the filter to achieve this easily.

const benefs = [{
  Iban: null,
  AccountNumber: "",
}, {
  Iban: null,
  AccountNumber: "",
}, {
  Iban: null,
  AccountNumber: "",
}]

const isBefLenght = true;
var newArray = benefs.filter(a => {
  return isBefLenght && !(a.Iban === null || a.befNumberIban === "");
})

console.log(newArray);


text:
Q: heroku cli не работает установил heroku cli( 64 bit как и ос)
ввожу:
 heroku login и консоль пишет :"heroku" не является внутренней или внешней
командой, исполняемой программой или пакетным файлом. 32 бит тоже пробовал

A: Вообще path почему-то не обновился и пришлось добавить вручную.
Вероятно это баг программы, жду ответа поддержки.
Upd:: его пофиксили в новой версии,  подробностей не знаю

A: нашел много ответов по этой теме, что мол можно прописать путь c:/program files/heroku/bin в path и будет счастье.
Но у меня все оказалось сложнее. Я устанавливал на корпоративный комп, соответственно, чтобы прописать путь нужно было обратиться к системному администратору (пароль только у него).
Мы с ним прописали путь через путь>панель управления>система>доп. параметры системы>..., но при запуске cmd (а я не только заново запустил cmd, но и перезагрузил компьютер перед этим) heroku так и не определялся - cmd сообщала, что heroku не является внутренней и внешней и т.д.
В итоге помогло только открытие cmd с правами администратора и выполнение следующей команды:
$ setx /M path "%path%;c:/program files/heroku/bin"

И все отлично заработало. Также, если вы хотите добавить этот путь heroku только на текущую сессию работы в cmd, то нужно выполнить следующую программу:
$ set path = %path%;c:/program files/heroku/bin


text:
Q: How to undo dplyr mutate silently round the division operation I have the following data frame:

library(tidyverse)

dat <-  structure(list(sid = c("MK1", "MK2", "MK3"), nof_reads = c(19786677L,
29531664L, 1195340L), mapped_reads = c(19785168L, 29529532L,
1195250L)), .Names = c("sid", "nof_reads", "mapped_reads"), class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -3L))

dat
#> # A tibble: 3 x 3
#>   sid   nof_reads mapped_reads
#>   <chr>     <int>        <int>
#> 1 MK1    19786677     19785168
#> 2 MK2    29531664     29529532
#> 3 MK3     1195340      1195250

When I tried the following operation by dividing mapped_reads with nof_reads, I get this:
> dat %>% mutate(rate = mapped_reads/nof_reads)
# A tibble: 3 x 4
  sid   nof_reads mapped_reads  rate
  <chr>     <int>        <int> <dbl>
1 MK1    19786677     19785168 1.000
2 MK2    29531664     29529532 1.000
3 MK3     1195340      1195250 1.000

Notice the rate column the value is rounded into 1.000.
Where actually it is this for MK_1:
>  19785168/19786677
[1] 0.9999237

How can I resolve the issue, so that it output without rounding.

A: dat %>% mutate(rate = mapped_reads/nof_reads) %>% as.data.frame()

  sid nof_reads mapped_reads     rate
1 MK1  19786677     19785168 0.999924
2 MK2  29531664     29529532 0.999928
3 MK3   1195340      1195250 0.999925


text:
Q: drupal - node.js integration For a few days we'r trying to integrate drupal with node.js. but we couldn't connect with socket.io.js..
we're getting this error message from chrome console;
XMLHttpRequest cannot load http://mydomainname.com:8080/socket.io/1/?t=1340201859161. Origin http://mydomainname.com is not allowed by Access-Control-Allow-Origin.
and our backend settings are;
/**
* This configuration file was built using the 'Node.js server configuration builder'.
* For a more fully commented example see the file nodejs.config.js.example in the root of this module
*/
backendSettings = {
  "scheme":"http",
  "host":"mydomainname",
  "port":8080,
  "key":"/path/to/key/file",
  "cert":"/path/to/cert/file",
  "resource":"/sites/all/modules/nodejs/node_modules/socket.io/lib",
  "publishUrl":"publish",
  "serviceKey":"",
  "backend":{
  "port":80,
  "host":"urb5.com",
  "messagePath":"realtime"},
  "clientsCanWriteToChannels":false,
  "clientsCanWriteToClients":false,
  "extensions":["nodejs.server.extension.js"],
  "debug":true,
  "transports":["websocket",
  "flashsocket",
  "htmlfile",
  "xhr-polling",
  "jsonp-polling"],
  "jsMinification":true,
  "jsEtag":true,
  "logLevel":1};

and also, in source code we have a script socket.io script,
like
<script type="text/javascript" src="http://mydomainname.com:8080/sites/all/modules/nodejs/node_modules/socket.io/lib/socket.io.js"></script>

this scripts build number is 0.9.6, but if we follow this path in ftp, there is a socket.io.js but its build number is 0.9.5
any suggestions?,
thanks..

A: The problem here, is that you are trying to load up socket.io from the server, but your front-end files are located in another domain space / server.
There is security regulations that does not allows cross-domain ajax and resources requests if they are not enabled by server.
So on server side where socket.io.js is coming from, you should add in page header something like this:
Access-Control-Allow-Origin: http://hello-world.example
Access-Control-Max-Age: 3628800
Access-Control-Allow-Methods: PUT, DELETE

This will allow you to share resource content with specified domain. And browser will not throw Access-Control-Allow-Origin error anymore.
As well, why you are trying to include js file through port 8080? If this is port that you bind your socket.io listener, then this is wrong, and you need to get js file through usual port (in most cases without defining, or 80).


text:
Q: How to transform/migrate a mysql trigger to a Sql Server Trigger I did a trigger in mysql to shoot alerts always an input value was less than the set value. But now I need it is done in SQL SERVER.
I would be grateful if someone could help me transform mysql trigger to a SQL Server trigger.
Thanks to all at once.

My trigger is:
DELIMITER $$
create TRIGGER alert
AFTER INSERT ON records
FOR EACH ROW
begin
Set @comp=0;
Set @tempmax=0;
Set @tempmin=0;

select lim_inf_temp into @tempmin from sensores where idSensor=NEW.idSensor;

Set @maxidAlarme=0;
if (CAST(NEW.Temperatura AS UNSIGNED)<@tempmin) then
SELECT MAX(idAlarme) into @maxidAlarme FROM alarmes;
SET @maxidAlarme=@maxidAlarme+1;
INSERT INTO alarmes(idAlarme,descricao_alarme, idRegisto) VALUES (@maxidAlarme,"inserted below the normal temperature",New.idRegisto);
INSERT INTO sensores_tem_alarmes(idSensor,idAlarme,dataAlarme) VALUES (NEW.idSensor,@maxidAlarme,NOW());
set @comp=+1;
end if;

set @id_sensores_em_alerta=1;
SELECT MAX(id_sensores_em_alerta) into @id_sensores_em_alerta FROM sensores_em_alerta;
 INSERT INTO sensores_em_alerta(id_sensores_em_alerta, idSensor, idAlarme, data_registo, numerosensoresdisparados) VALUES (id_sensores_em_alerta,NEW.idSensor, @maxidAlarme, NOW(), @comp);
end $$;

DELIMITER  ;

I've tried to make the trigger in SQL Server, but as the script is different and I'm getting many difficulties to do the right way.
My attempt that was not going at all well:
CREATE TRIGGER Alert ON registos AFTER INSERT AS
BEGIN

DECLARE @comp decimal= 0
DECLARE @tempmax decimal= 0
DECLARE @tempmin decimal= 0

DECLARE @current_max_idAlarme int = (SELECT MAX(IdAlarme) FROM alarmes)

-- Insert into alarmes from the inserted rows if temperature less than tempmin
INSERT alarmes (IdAlarme, descricao_alarme, idRegisto)
SELECT
    ROW_NUMBER() OVER (ORDER BY i.idRegisto) + @current_max_idAlarme,
    'temp Error',
    i.idRegisto
FROM
    inserted AS i
WHERE
    i.Temperatura < @tempmin

END

But dont do anything.
Dont create data on table alarmes :S
Does anyone could help me please. I would be eternally grateful.
Many Greetings and thank you all.

A: First of all, MSSQL doesn't have the option FOR EACH ROW, so it treats multiple inserted rows at once as a set. You will therefore have to insert the values into a table variable.
Unfortunately I do not know much MySQL actually, but I believe this is a starting point?
CREATE TRIGGER ALERT
ON records
AFTER INSERT
AS
BEGIN
 DECLARE @comp INT;
 DECLARE @tempmax INT;
 DECLARE TABLE @tempmin (tempmin INT);

 INSERT INTO @tempmin
 SELECT s.lim_inf_temp FROM sensores s WHERE s.idSensor IN (inserted.idSensor);
--rest of the code

A: I'm going to post this code against my better judgement - redesign the tables is better than this hack.
This uses a ROW_number() to virtualise a surrogate identity key for the alarmes table. This is a 'bad plan' (tm).
Also the answer is partial - it doesn't do everything your question asked for -- I hope it gets your further along the road. Use it as a guide for how to interact with the virtual INSERTED table. Good luck
CREATE TRIGGER Alert ON records AFTER INSERT AS
BEGIN

DECLARE @comp INT = 0
DECLARE @tempmax INT = 0
DECLARE @tempmin INT = 0

-- get the max current id.
-- note that this is EXTREMELY unsafe as if two pieces of code are executing
-- at the same time then you *will* end up with key conflicts.
-- you could use SERIALIZABLE.... but better would be to redisn the schema
DECLARE @current_max_idAlarme = (SELECT MAX(IdAlarme) FROM alarmes)

-- Insert into alarmes from the inserted rows if temperature less than tempmin
INSERT alarmes (IdAlarme, descricao_alarme, idRegisto)
SELECT
    ROW_NUMBER() OVER (ORDER BY i.idRegisto) + @current_max_idAlarme,
    'temp Error',
    i.idRegisto
FROM
    inserted AS i
WHERE
    i.Temperatura < @tempmin

END


text:
Q: Error when register provider Zend in Netbeans 6.9 I install :

*

*netbeans 6.9 on 'C:\Program
Files\NetBeans 6.9'

*xampp 1.7.2 on D:\xampp

*i have upgrade zend through pear

I follow the screencast and when clicking the Register Provider button. But I get message like this:
on create config tab

Successfully written Zend Tool config.
It is located at: \Documents and Settings\Permana/.zf.ini

on enable.config.provider NetbeansCommandsProvider

                        User has no config file.
                          An Error Has Occurred
 Client has no persistent configuration.

Zend Framework Command Line Console Tool v1.10.7
Details for action "Enable" and provider "Config"
    zf enable config.manifest class-name
    zf enable config.provider class-name

And of course because of this error I cannot create zend project using netbeans. Did anyone know what is the problem?

A: Windows XP:
Make sure the environment variable ZF_HOME is set.

A: I found the soltution to this problem. Just delete the /home/username/.zf.ini and go to netbeans and register zendframework provider again. This will generate zf.ini file in your home directory with new path.

A: Yesterday I had the same problema. I wrote a post in my blog:
http://otroblogmas.com/error-zend-tool-netbeanscommandsprovider-php/
I found two solutions: either modify the file zf.ini in your profile, or copy the file NetBeansCommandsProvider.php in a path of include_path.

A: Ubuntu 10.10, NetBeans 6.9.1, Zend Framework 1.11
Reconfigurar
Edit PHP.ini
include_path = ".:/opt/lampp/etc/library" ; Files "/opt/lampp/etc/library/Zend"
gedit /etc/profile
export PATH=$PATH:/opt/lampp/bin # Includer zf.php and zf.sh
export PATH=$PATH:/opt/lampp/etc/library
Remove zf.ini and register NetBeans provider again (from Tools > Options > PHP > Zend).

A: The above answers are correct, however in my case there was no zf.ini file under my user directory (using Windows 7). In that case you need to run two commands:
zf --setup storage-directory
zf --setup config-file

That will create your zf.ini file and the storage directory under your user directory. Source: here