text:
Q: How to hide bookmarks from the new tab page in Chrome? I don't have the show bookmarks option turned on but whenever I open a new tab, it lists some of the bookmarks at the top of the new tab page by default. Is there a way to get rid of this?

A: This is now possible (January 2020) via a Registry edit, via Google Chrome's policy editor. This will cause a small note in "Settings" that your Google Chrome installation is now managed by an organization, but it's a small price to pay.
Make a System Restore point before continuing.

*

*Close Google Chrome.

*Press WIN+R and enter in regedit.

*Go to HKEY_LOCAL_MACHINE\SOFTWARE\Policies

*Create a new key under Policies key and set its name as Google

*Create another new key under Google key and set its name as Chrome

*Now select Chrome key and in right-side pane, right-click and select New -> DWORD (32-bit) Value option.

*Set its name as BookmarkBarEnabled and set its value as following:

*

*Set the value to 0 if you want to permanently remove and hide Bookmarks bar in Chrome including New Tab page.

*Set the value to 1 if you want to always enable and show Bookmarks bar in Chrome including New Tab page.
Confirmed working in Chrome 80.0.3987.87 on Windows 10 Pro x64 (18363) 1909. Source here.

A: The bookmarks listed at the top of a new tab are actually bookmarks that are in the Bookmarks bar folder. To remove them from showing up, go to the Chrome menu and select Bookmarks > Bookmark manager.
Move all items that you don't want showing up in a new tab into another bookmarks folder e.g Other bookmarks

A: This currently isn't supported by Google Chrome as answered on the Google Product Forums dated April 25, 2012. Fortunately though, you can use an extension that overrides the new tab page.
I, personally, would recommend the popular Speed Dial family of extensions. Specifically, Speed Dial 2 for Google Chrome. My current setup looks like this.

For those wanting to replicate my setup.

*

*Add a new page using the big + button. Fill in the details such as the URL
 and name.

*All the site-specific images are a deviation of the following URL.

http://sstatic.net/stackexchange/img/apple-touch-icon.png

Just replace the name stackexchange with the name of the particular site you want to
 use. Note, that for Meta sites you have to append meta to the main site name. For
 example, the icon for Super User Meta would be.

http://sstatic.net/superusermeta/img/apple-touch-icon.png

A: Use an extension to change the new tab. Such extensions can be found by searching for "new tab" in the Chrome Web Store. The one I use is The New Tab - Customize Your Start Page. I have my new tab configured to look like this.

A: I just use an extension called Clear New Tab and you can just press CTRL + SHIFT + B to hide the bookmark bar on the new tab page.

A: You may use the extension 'Homey'.
https://chrome.google.com/webstore/detail/homey-productive-and-cozy/lllnjdmfnfjifcfpppjmcnanpokikcpl
You install this extension from the Chrome web store and then go to Setting -> --> On startup, then select 'Open the New Tab page with Homey.
(This may have been automatically enabled.)

A: Just create another folder if you don't want to see any bookmarks dont save bookmarks in Bookmarks bar or Other bookmarks.
Simply create a new folder. Voila. job done.
It's that simple.

A: I found a solution for this:

*

*Click on Chrome options icon > Settings > Advanced Sync Settings.

*Change Sync Everything to Choose what to sync

*Uncheck Bookmarks, History or whatever you don't want to sync.

*Click on Chrome > Options > Settings > disconnect your Google account.

*Go to C:\Users\<USERNAME>\AppData\Local\Google\Chrome\User Data\Default and delete BookMarks and Bookmarks.bak file.

*Click on Chrome options icon > Settings > sign in to account

*Open a new tab and check if you are getting the bookmarks.


text:
Q: AWS EC2 Instances/volumes showing status in-use cannot start after stop of both volumes? I have 2 AWS EC2 Instances showing status 'in-use'.  I cannot start the instances after I had earlier stopped both instances.
I have a FREE tier account and don't have technical support available.
Fred Z.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Push Notifications Issue app Transfer i transferred my iOS app from my account to another account a month ago  using the new app transfer introduced by apple,  everything was ok ,and push notification was ok . but recently 2 days ago the push notification has stopped, and i didn't figure out why , do i have  to regenerate new certificates?

A: I faced a similar issue on transfer (in beta/TestFlight).
App is on Parse (yeah I know they are shutting down). When I created the new Dev account, push stopped working - everything in xcode, apple developer (profile,  signatures etc.) was valid - but it did not work!
The only thing I could think of was to reissue push certificates (both Dev and Prod) against each account and upload the .p12 files to Parse. Once done, everything started to work again.
Also, make sure you do not have the same bundle ID across the two accounts. In theory, that's the first thing xcode will/should complain about (mine did). Apple support guy highlighted that to me too.
I hope this helps.


text:
Q: Firewall Rule One way smb in two network Im trying to make an one way smb firewall rule in a MikroTik firewall rule
The thing is I have two network one on 192.168.1.0/24 and one 192.168.3.0/24
192.168.3.0 is the network that should be able to access the smb's on the 192.168.1.0/24 network
But network 192.168.1.0/24 should be able to connect to any smb on it's network.
And beacause there is a Data Server on 192.168.3.5 id like to have both network be able to access it.
Here is my two rule in fire wall

Now the first expected behaviour work ( 192.168.3.0/24 can access all smb's on 192.168.1.0/24 and 192.168.1.0/24 can't access 192.168.3.0/24 )
But Rule number 2 don't work ( I want to let 192.168.0.1/24 to access only 192.168.3.5 smb)
I Think it because the first rule drop the packet and the packet dont even get filter by the second rule.  So Here I am Is it possible to reproduce the beaviour that im expecting ??
Thanks for any help

A: I Finally realized why this was happening, And I though every one should know that the order of rules in the firewall is important!
See the next picture

ps:Rule #0 and #2 are identical
If I enable rule 0 and disable rule 2 it does'nt work. But if i have 0 disabled and 2 enabled it work!


text:
Q: Using Vulkan-hpp vk::enumerateInstanceVersion() causes segfault I encountered a weird issue. I can use vkEnumerateInstanceVersion from vulkan.h, but using vk::enumerateInstanceVersion() from vulkan.hpp causes an memory access violation (segfault).
I use this function to create the vk::Instance:
static vk::Instance createInstance()
{
    loadVulkanGlobalFunctions();

    uint32_t version;
    vkEnumerateInstanceVersion(&version); // works fine, returns version 1.2.131
    version = vk::enumerateInstanceVersion(); // error 0xC0000005 memory access violation

    std::cout << "Supported Vulkan Version is "
              << VK_VERSION_MAJOR(version) << '.'
              << VK_VERSION_MINOR(version) << '.'
              << VK_VERSION_PATCH(version) << '\n';

    // instance creation ...
}

I load global Vulkan functions using the default dynamic loader:
static void loadVulkanGlobalFunctions()
{
    vk::DynamicLoader loader;
    auto vkGetInstanceProcAddr = loader.getProcAddress<PFN_vkGetInstanceProcAddr>("vkGetInstanceProcAddr");
    VULKAN_HPP_DEFAULT_DISPATCHER.init(vkGetInstanceProcAddr);
}

I #define VULKAN_HPP_DISPATCH_LOADER_DYNAMIC 1 before #include <vulkan/vulkan.hpp> and I have VULKAN_HPP_DEFAULT_DISPATCH_LOADER_DYNAMIC_STORAGE exactly once in my code.

A: It turned out that the vk::DynamicLoader object created in loadVulkanGlobalFunctions must have its lifetime extended, as it unloads the dynamic library in its destructor. As it is a local variable that happens when loadVulkanGlobalFunctions exits and the stack unwinds.
I simply changed it to this:
static vk::DynamicLoader createVulkanLoader()
{
    vk::DynamicLoader loader;
    auto vkGetInstanceProcAddr = loader.getProcAddress<PFN_vkGetInstanceProcAddr>("vkGetInstanceProcAddr");
    VULKAN_HPP_DEFAULT_DISPATCHER.init(vkGetInstanceProcAddr);
    return loader;
}

And assigned the result to a variable, whose lifetime is longer than of the vkInstance.


text:
Q: Trying to make andyvr/picEdit plugin upload file via JQUERY post/ajax I'm using a lightweight image editor jQuery plugin called andyvr/picEdit
https://github.com/andyvr/picEdit
This is just a plugin that turns an input:file element into an HTML canvass, and allows the user to select/edit/crop/manipulate an image file on the client side. The actual uploading and processing is done via the usual FORM UPLOAD and PHP $_FILE processes.
What I wanted to do is grab the "edited" picture data from this plugin and send it via $.post() instead of through the Form submit action.
Do you guys know what element I should select to include in my post variables?
var postvars = {};
postvars.final_image = $("#what_element").val();

$.post("script-name.php", postvars ,function(data){.....

I tried to go through the JS file but I can't seem to figure it out.
PS
I hope I came across clear with this question. I was having a hard time structuring it.

A: Assuming you are using the same picedit as I used and are still looking for an answer:
The html file input:
<input type='file' name='thefile' id='thebox'>

The jquery to make the file input act like an image edit box:
$(function() {
    $('#thebox').picEdit();
});

The post command:
$.post( "handler.php", { story_edited : 1, id : 1 }, function( data ){ document.getElementById( 'photos' ).innerHTML = html =  data }, "html" );

Notes:
handler.php = the name of the file that you want to use to process the input!
<div id='photos' name='photos'>

is a standard div tag that I use to update onscreen info in another part of the page! So, document.getElementById( 'photos' ).innerHTML will load handlers.php in to the photos div tag!
Use:
foreach($_FILES as $file)

to process the images as normal file upload from a web page!
I have one other button that pulls it all together. After I finish editing the image, I click on an update button that calls the handler and uploads and saves the file as well as dynamic updating of a photoalbum section elsewhere on the page.
TODO:
If I could find a way to attach a callback function I would not need to use this separate button.


text:
Q: Define Piecewise Functions in Julia I have an application in which I need to define a piecewise function, IE, f(x) = g(x) for [x in some range], f(x)=h(x) for [x in some other range], ... etc.
Is there a nice way to do this in Julia? I'd rather not use if-else because it seems that I'd have to check every range for large values of x. The way that I was thinking was to construct an array of functions and an array of bounds/ranges, then when f(x) is called, do a binary search on the ranges to find the appropriate index and use the corresponding function (IE, h(x), g(x), etc.
It seems as though such a mathematically friendly language might have some functionality for this, but the documentation doesn't mention piecewise in this manner. Hopefully someone else has given this some thought, thanks!

A: with a Heaviside function you can do a interval function:
function heaviside(t)
   0.5 * (sign(t) + 1)
end

and
function interval(t, a, b)
   heaviside(t-a) - heaviside(t-b)
end

function piecewise(t)
   sinc(t) .* interval(t,-3,3) + cos(t) .* interval(t, 4,7)
end

and I think it could also implement a subtype Interval, it would be much more elegant

A: I tried to implement a piecewise function for Julia, and this is the result:
function piecewise(x::Symbol,c::Expr,f::Expr)
  n=length(f.args)
  @assert n==length(c.args)
  @assert c.head==:vect
  @assert f.head==:vect
  vf=Vector{Function}(n)
  for i in 1:n
    vf[i]=@eval $x->$(f.args[i])
  end
  return @eval ($x)->($(vf)[findfirst($c)])($x)
end
pf=piecewise(:x,:([x>0, x==0, x<0]),:([2*x,-1,-x]))
pf(1) # => 2
pf(-2) # => 2
pf(0) # => -1

A: Why not something like this?
function piecewise(x::Float64, breakpts::Vector{Float64}, f::Vector{Function})
       @assert(issorted(breakpts))
       @assert(length(breakpts) == length(f)+1)
       b = searchsortedfirst(breakpts, x)
       return f[b](x)
end

piecewise(X::Vector{Float64}, bpts, f) = [ piecewise(x,bpts,f) for x in X ]

Here you have a list of (sorted) breakpoints, and you can use the optimized searchsortedfirst to find the first breakpoint b greater than x. The edge case when no breakpoint is greater than x is also handled appropriately since length(breakpts)+1 is returned, so b is the correct index into the vector of functions f.


text:
Q: Can I award a bounty to the asker who asked it? I sometimes feel the need to reward the asker for posting a very useful and thoughtful question. Bounties are rewarded for answers, and not for questions. I can only upvote the question once, but if I'm ready to spare rep, is there any way I can reward the asker?

A: At present working of bounty, no there is not.
The bounty can be awarded only to answer.
To award the bounty to the OP, ask him to make an answer and then award it for the answer. Anyway I am not supporting this because, only to get bounty, if the OP answered his own question in which there is already an answer exists, if it is a plagiarism, it may subject to mod's actions.


text:
Q: Convert PDF to image with high resolution I'm trying to use the command line program convert to take a PDF into an image (JPEG or PNG). Here is one of the PDFs that I'm trying to convert.
I want the program to trim off the excess white-space and return a high enough quality image that the superscripts can be read with ease.
This is my current best attempt. As you can see, the trimming works fine, I just need to sharpen up the resolution quite a bit. This is the command I'm using:
convert -trim 24.pdf -resize 500% -quality 100 -sharpen 0x1.0 24-11.jpg

I've tried to make the following conscious decisions:

*

*resize it larger (has no effect on the resolution)

*make the quality as high as possible

*use the -sharpen (I've tried a range of values)

Any suggestions please on getting the resolution of the image in the final PNG/JPEG higher would be greatly appreciated!

A: Linux user here: I tried the convert command-line utility (for PDF to PNG) and I was not happy with the results.  I found this to be easier, with a better result:

*

*extract the pdf page(s) with pdftk

*

*e.g.: pdftk file.pdf cat 3 output page3.pdf

*open (import) that pdf with GIMP

*

*important: change the import Resolution from 100 to 300 or 600 pixel/in

*in GIMP export as PNG (change file extension to .png)

Edit:
Added picture, as requested in the Comments. Convert command used:
convert -density 300 -trim struct2vec.pdf -quality 100 struct2vec.png
GIMP : imported at 300 dpi (px/in); exported as PNG compression level 3.
I have not used GIMP on the command line (re: my comment, below).

A: It appears that the following works:
convert           \
   -verbose       \
   -density 150   \
   -trim          \
    test.pdf      \
   -quality 100   \
   -flatten       \
   -sharpen 0x1.0 \
    24-18.jpg

It results in the left image. Compare this to the result of my original command (the image on the right):

(To really see and appreciate the differences between the two, right-click on each and select "Open Image in New Tab...".)
Also keep the following facts in mind:

*

*The worse, blurry image on the right has a file size of 1.941.702 Bytes (1.85 MByte).
Its resolution is 3060x3960 pixels, using 16-bit RGB color space.

*The better, sharp image on the left has a file size of 337.879 Bytes (330 kByte).
Its resolution is 758x996 pixels, using 8-bit Gray color space.

So, no need to resize; add the -density flag. The density value 150 is weird -- trying a range of values results in a worse looking image in both directions!

A: I use pdftoppm on the command line to get the initial image, typically with a resolution of 300dpi, so pdftoppm -r 300, then use convert to do the trimming and PNG conversion.

A: I really haven't had good success with convert [update May 2020: actually: it pretty much never works for me], but I've had EXCELLENT success with pdftoppm. Here's a couple examples of producing high-quality images from a PDF:

*

*[Produces ~25 MB-sized files per pg] Output uncompressed .tif file format at 300 DPI into a folder called "images", with files being named pg-1.tif, pg-2.tif, pg-3.tif, etc:
 mkdir -p images && pdftoppm -tiff -r 300 mypdf.pdf images/pg

*[Produces ~1MB-sized files per pg] Output in .jpg format at 300 DPI:
 mkdir -p images && pdftoppm -jpeg -r 300 mypdf.pdf images/pg

*[Produces ~2MB-sized files per pg] Output in .jpg format at highest quality (least compression) and still at 300 DPI:
 mkdir -p images && pdftoppm -jpeg -jpegopt quality=100 -r 300 mypdf.pdf images/pg

For more explanations, options, and examples, see my full answer here:
https://askubuntu.com/questions/150100/extracting-embedded-images-from-a-pdf/1187844#1187844.
Related:

*

*[How to turn a PDF into a searchable PDF w/pdf2searchablepdf] https://askubuntu.com/questions/473843/how-to-turn-a-pdf-into-a-text-searchable-pdf/1187881#1187881

*Cross-linked:

*

*How to convert a PDF into JPG with command line in Linux?

*https://unix.stackexchange.com/questions/11835/pdf-to-jpg-without-quality-loss-gscan2pdf/585574#585574

A: For Windows (tested on W11):
magick.exe -verbose -density 150 "input.pdf" -quality 100 -sharpen 0x1.0 output.jpg

You need install:
ImageMagick https://imagemagick.org/index.php
ghostscript
https://www.ghostscript.com/releases/gsdnld.html
Additional info:

*

*Watch for using -flatten parameter since it can produce only first page as image

*Use -scene 1 parameter to start at index 1 with images names

*convert command mentioned in question has been deprecated in favor to magick

A: normally I extract the embedded image with 'pdfimages' at the native resolution, then use ImageMagick's convert to the needed format:
$ pdfimages -list fileName.pdf
$ pdfimages fileName.pdf fileName   # save in .ppm format
$ convert fileName-000.ppm fileName-000.png

this generate the best and smallest result file.
Note: For lossy JPG embedded images, you had to use -j:
$ pdfimages -j fileName.pdf fileName   # save in .jpg format

With recent "poppler-util" (0.50+, 2016) you can use -all that save lossy as jpg and lossless as png, so a simple:
$ pdfimages -all fileName.pdf fileName

extract always the best possible quality content from PDF.
On little provided Win platform you had to download a recent (0.68, 2018)  'poppler-util' binary from:
http://blog.alivate.com.au/poppler-windows/

A: One more suggestion is that you can use GIMP.
Just load the PDF file in GIMP->save as .xcf and then you can do whatever you want to the image.

A: I have used pdf2image. A simple python library that works like charm.
First install poppler on non linux machine. You can just download the zip. Unzip in Program Files and add bin to Machine Path.
After that you can use pdf2image in python class like this:
from pdf2image import convert_from_path, convert_from_bytes
images_from_path = convert_from_path(
   inputfile,
   output_folder=outputpath,
   grayscale=True, fmt='jpeg')

I am not good with python but was able to make exe of it.
Later you may use the exe with file input and output parameter. I have used it in C# and things are working fine.
Image quality is good. OCR works fine.
Edited:
Here is my another finding, You don't need to install Poppler for conversion.
Just make your converter.exe from Python and place it in binary bin folder of Poppler window.
I suppose it will work on azure aswell.

A: Personally I like this.
convert -density 300 -trim test.pdf -quality 100 test.jpg

It's a little over twice the file size, but it looks better to me.
-density 300 sets the dpi that the PDF is rendered at.
-trim removes any edge pixels that are the same color as the corner pixels.
-quality 100 sets the JPEG compression quality to the highest quality.
Things like -sharpen don't work well with text because they undo things your font rendering system did to make it more legible.
If you actually want it blown up use resize here and possibly a larger dpi value of something like targetDPI * scalingFactor  That will render the PDF at the resolution/size you intend.
Descriptions of the parameters on imagemagick.org are here

A: In ImageMagick, you can do "supersampling". You specify a large density and then resize down as much as desired for the final output size. For example with your image:
convert -density 600 test.pdf -background white -flatten -resize 25% test.png

Download the image to view at full resolution for comparison..
I do not recommend saving to JPG if you are expecting to do further processing.
If you want the output to be the same size as the input, then resize to the inverse of the ratio of your density to 72. For example, -density 288 and -resize 25%. 288=4*72 and 25%=1/4
The larger the density the better the resulting quality, but it will take longer to process.

A: I have found it both faster and more stable when batch-processing large PDFs into PNGs and JPGs to use the underlying gs (aka Ghostscript) command that convert uses.
You can see the command in the output of convert -verbose and there are a few more tweaks possible there (YMMV) that are difficult / impossible to access directly via convert.
However, it would be harder to do your trimming and sharpening using gs, so, as I said, YMMV!

A: It also gives you good results:
exec("convert -geometry 1600x1600 -density 200x200 -quality 100 test.pdf test_image.jpg");

A: PNG file you attached looks really blurred. In case if you need to use additional post-processing for each image you generated as PDF preview, you will decrease performance of your solution.
2JPEG can convert PDF file you attached to a nice sharpen JPG and crop empty margins in one call:
2jpeg.exe -src "C:\In\*.*" -dst "C:\Out" -oper Crop method:autocrop

A: Please take note before down voting, this solution is for Gimp using a graphical interface, and not for ImageMagick using a command line, but it worked perfectly fine for me as an alternative, and that is why I found it needful to share here.
Follow these simple steps to extract images in any format from PDF documents

*

*Download GIMP Image Manipulation Program

*Open the Program after installation

*Open the PDF document that you want to extract Images

*Select only the pages of the PDF document that you would want to extract images from.
N/B: If you need only the cover images, select only the first page.

*Click open after selecting the pages that you want to extract images from

*Click on File menu when GIMP when the pages open

*Select Export as in the File menu

*Select your preferred file type by extension (say png) below the dialog box that pops up.

*Click on Export to export your image to your desired location.

*You can then check your file explorer for the exported image.

That's all.
I hope this helps

A: I use icepdf an open source java pdf engine. Check the office demo.
package image2pdf;

import org.icepdf.core.exceptions.PDFException;
import org.icepdf.core.exceptions.PDFSecurityException;
import org.icepdf.core.pobjects.Document;
import org.icepdf.core.pobjects.Page;
import org.icepdf.core.util.GraphicsRenderingHints;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

public class pdf2image {

   public static void main(String[] args) {

      Document document = new Document();
      try {
         document.setFile("C:\\Users\\Dell\\Desktop\\test.pdf");
      } catch (PDFException ex) {
         System.out.println("Error parsing PDF document " + ex);
      } catch (PDFSecurityException ex) {
         System.out.println("Error encryption not supported " + ex);
      } catch (FileNotFoundException ex) {
         System.out.println("Error file not found " + ex);
      } catch (IOException ex) {
         System.out.println("Error IOException " + ex);
      }

      // save page captures to file.
      float scale = 1.0f;
      float rotation = 0f;

      // Paint each pages content to an image and
      // write the image to file
      for (int i = 0; i < document.getNumberOfPages(); i++) {
         try {
         BufferedImage image = (BufferedImage) document.getPageImage(
             i, GraphicsRenderingHints.PRINT, Page.BOUNDARY_CROPBOX, rotation, scale);

         RenderedImage rendImage = image;
         try {
            System.out.println(" capturing page " + i);
            File file = new File("C:\\Users\\Dell\\Desktop\\test_imageCapture1_" + i + ".png");
            ImageIO.write(rendImage, "png", file);
         } catch (IOException e) {
            e.printStackTrace();
         }
         image.flush();
         }catch(Exception e){
             e.printStackTrace();
         }
      }

      // clean up resources
      document.dispose();
   }
}

I've also tried imagemagick and pdftoppm, both pdftoppm and icepdf has a high resolution than imagemagick.

A: get Image from Pdf in iOS Swift Best solution
func imageFromPdf(pdfUrl : URL,atIndex index : Int, closure:@escaping((UIImage)->Void)){

    autoreleasepool {

        // Instantiate a `CGPDFDocument` from the PDF file's URL.
        guard let document = PDFDocument(url: pdfUrl) else { return }

        // Get the first page of the PDF document.
        guard let page = document.page(at: index) else { return }

        // Fetch the page rect for the page we want to render.
        let pageRect = page.bounds(for: .mediaBox)

        let renderer = UIGraphicsImageRenderer(size: pageRect.size)
        let img = renderer.image { ctx in
            // Set and fill the background color.
            UIColor.white.set()
            ctx.fill(CGRect(x: 0, y: 0, width: pageRect.width, height: pageRect.height))

            // Translate the context so that we only draw the `cropRect`.
            ctx.cgContext.translateBy(x: -pageRect.origin.x, y: pageRect.size.height - pageRect.origin.y)

            // Flip the context vertically because the Core Graphics coordinate system starts from the bottom.
            ctx.cgContext.scaleBy(x: 1.0, y: -1.0)

            // Draw the PDF page.
            page.draw(with: .mediaBox, to: ctx.cgContext)
        }
        closure(img)

    }

}

//Usage
    let pdfUrl = URL(fileURLWithPath: "PDF URL")
    self.imageFromPdf2(pdfUrl: pdfUrl, atIndex: 0) { imageIS in

    }

A: Many answers here concentrate on using magick (or its dependency GhostScript) as set by the OP question, with a few  suggesting Gimp as an alternative, without describing why some settings may work best for different cases.
Taking the OP "sample" the requirement is a crisp trimmed image as small as possible yet retaining good readability. and here the result is 96 dpi in 58 KB (a very small increase on the vector source 54 KB) yet retains a good image even zoomed in. compare that with 72 dpi (226 KB) in the accepted answer image above.

The key point is any image processor can be scripted to batch run from the command line using a profile as input, so here IrfanView (with or without GS) is set to auto crop the pdf page(s) and output at a default 96 dpi to PNG using only 4 BitPerPixel colour for 16 shades of greys.
The size could be further reduced by dropping resolution to 72 but 96 is an optimal setting for PNG screen display.

A: It's actually pretty easy to do with Preview on a mac.  All you have to do is open the file in Preview and save-as (or export) a png or jpeg but make sure that you use at least 300 dpi at the bottom of the window to get a high quality image.

A: this works for creating a single file from multiple PDF's and images files:
php exec('convert -density 300 -trim "/path/to/input_filename_1.png" "/path/to/input_filename_2.pdf" "/path/to/input_filename_3.png" -quality 100 "/path/to/output_filename_0.pdf"');

WHERE:
-density 300 = dpi
-trim = something about transparancy - makes edges look smooth, it seems
-quality 100 = quality vs compression (100 % quality)
-flatten ... for multi page, do not use "flatten"

A: Use this commandline:
convert -geometry 3600x3600 -density 300x300 -quality 100 TEAM\ 4.pdf team4.png

This should correctly convert the file as you've asked for.

A: The following python script will work on any Mac (Snow Leopard and upward). It can be used on the command line with successive PDF files as arguments, or you can put in into a Run Shell Script action in Automator, and make a Service (Quick Action in Mojave).
You can set the resolution of the output image in the script.
The script and a Quick Action can be downloaded from github.
#!/usr/bin/python
# coding: utf-8

import os, sys
import Quartz as Quartz
from LaunchServices import (kUTTypeJPEG, kUTTypeTIFF, kUTTypePNG, kCFAllocatorDefault)

resolution = 300.0 #dpi
scale = resolution/72.0

cs = Quartz.CGColorSpaceCreateWithName(Quartz.kCGColorSpaceSRGB)
whiteColor = Quartz.CGColorCreate(cs, (1, 1, 1, 1))
# Options: kCGImageAlphaNoneSkipLast (no trans), kCGImageAlphaPremultipliedLast
transparency = Quartz.kCGImageAlphaNoneSkipLast

#Save image to file
def writeImage (image, url, type, options):
    destination = Quartz.CGImageDestinationCreateWithURL(url, type, 1, None)
    Quartz.CGImageDestinationAddImage(destination, image, options)
    Quartz.CGImageDestinationFinalize(destination)
    return

def getFilename(filepath):
    i=0
    newName = filepath
    while os.path.exists(newName):
        i += 1
        newName = filepath + " %02d"%i
    return newName

if __name__ == '__main__':

    for filename in sys.argv[1:]:
        pdf = Quartz.CGPDFDocumentCreateWithProvider(Quartz.CGDataProviderCreateWithFilename(filename))
        numPages = Quartz.CGPDFDocumentGetNumberOfPages(pdf)
        shortName = os.path.splitext(filename)[0]
        prefix = os.path.splitext(os.path.basename(filename))[0]
        folderName = getFilename(shortName)
        try:
            os.mkdir(folderName)
        except:
            print "Can't create directory '%s'"%(folderName)
            sys.exit()

        # For each page, create a file
        for i in range (1, numPages+1):
            page = Quartz.CGPDFDocumentGetPage(pdf, i)
            if page:
        #Get mediabox
                mediaBox = Quartz.CGPDFPageGetBoxRect(page, Quartz.kCGPDFMediaBox)
                x = Quartz.CGRectGetWidth(mediaBox)
                y = Quartz.CGRectGetHeight(mediaBox)
                x *= scale
                y *= scale
                r = Quartz.CGRectMake(0,0,x, y)
        # Create a Bitmap Context, draw a white background and add the PDF
                writeContext = Quartz.CGBitmapContextCreate(None, int(x), int(y), 8, 0, cs, transparency)
                Quartz.CGContextSaveGState (writeContext)
                Quartz.CGContextScaleCTM(writeContext, scale,scale)
                Quartz.CGContextSetFillColorWithColor(writeContext, whiteColor)
                Quartz.CGContextFillRect(writeContext, r)
                Quartz.CGContextDrawPDFPage(writeContext, page)
                Quartz.CGContextRestoreGState(writeContext)
        # Convert to an "Image"
                image = Quartz.CGBitmapContextCreateImage(writeContext)
        # Create unique filename per page
                outFile = folderName +"/" + prefix + " %03d.png"%i
                url = Quartz.CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault, outFile, len(outFile), False)
        # kUTTypeJPEG, kUTTypeTIFF, kUTTypePNG
                type = kUTTypePNG
        # See the full range of image properties on Apple's developer pages.
                options = {
                    Quartz.kCGImagePropertyDPIHeight: resolution,
                    Quartz.kCGImagePropertyDPIWidth: resolution
                    }
                writeImage (image, url, type, options)
                del page

A: You can do it in LibreOffice Draw (which is usually preinstalled in Ubuntu):

*

*Open PDF file in LibreOffice Draw.

*Scroll to the page you need.

*Make sure text/image elements are placed correctly. If not, you can adjust/edit them on the page.

*Top menu: File > Export...

*Select the image format you need in the bottom-right menu. I recommend PNG.

*Name your file and click Save.

*Options window will appear, so you can adjust resolution and size.

*Click OK, and you are done.

A: convert -density 300 * airbnb.pdf

Looked perfect to me


text:
Q: How to get the temperature using hddtemp for a Samsung SSD/NVMe in Thinkpad T480 I try to read my SSD/NVMe temp in my T480. Therefore I want to use hddtemp as it runs as daemon in the background.
Debugging hddtemp I get the following:
sudo hddtemp /dev/nvme0n1 --debug

ERROR: /dev/nvme0n1: can't determine bus type (or this bus type is
unknown)

If one of the field value seems to match the temperature, be sure to
read the hddtemp man page before sending a report (section REPORT).
Thanks.

Using S.M.A.R.T I can read its temperature:
sudo smartctl -a /dev/nvme0n1

=== START OF INFORMATION SECTION ===
Model Number:                       SAMSUNG MZVLB1T0HALR-000L7
[...]

=== START OF SMART DATA SECTION ===
[...]
Temperature:                        40 Celsius
[...]

Any clue how to get hddtemp get running?

A: From:

*

*How do I check system health?
NVMe PCIe M.2 Gen 3.0 x 4 (or 2) SSD
If you have an SSD they're life span is measured in trillions of writes. Your SMART utility already measures SSD life but not for NVMe SSDs. For that you need nvme-cli. To install it use:
sudo apt install nvme-cli

Next gather information available from SSD:
$ sudo nvme smart-log /dev/nvme0
Smart Log for NVME device:nvme0 namespace-id:ffffffff
critical_warning                    : 0
temperature                         : 40 C
available_spare                     : 100%
available_spare_threshold           : 10%
percentage_used                     : 0%
data_units_read                     : 12,539,332
data_units_written                  : 10,623,582
host_read_commands                  : 281,194,884
host_write_commands                 : 96,528,713
controller_busy_time                : 672
power_cycles                        : 1,677
power_on_hours                      : 687
unsafe_shutdowns                    : 105
media_errors                        : 0
num_err_log_entries                 : 279
Warning Temperature Time            : 0
Critical Composite Temperature Time : 0
Temperature Sensor 1                : 40 C
Temperature Sensor 2                : 51 C
Temperature Sensor 3                : 0 C
Temperature Sensor 4                : 0 C
Temperature Sensor 5                : 0 C
Temperature Sensor 6                : 0 C
Temperature Sensor 7                : 0 C
Temperature Sensor 8                : 0 C

The most important field is Percentage used which shows as 0%. This isn't disk usage percent but life used percent. I've had this drive since October 2017 and now it's December 2018. As soon as Percentage used hits 1% I can multiply the number of months I've owned it by 100 to find out when it will die. At the current rate I can say the drive will live 100+ years. Of course it will be obsolete in ten years anyway.
Notice the temperature report.


text:
Q: How do I change this function which works in normal django to make it work with serializer? Hey guys I have this feedback create function which I use with my django..but Iam trying to implement the rest api and I am not sure about how to continue and change this function. I am able to list all the feedbacks without any problem but don't know how to implement the create function.
Help would be much appreciated.
This is my model.
class Action(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='actions', db_index=True,
                                                     on_delete=models.CASCADE)
    verb = models.CharField(max_length=255)
    target_ct = models.ForeignKey(ContentType, blank=True, null=True, related_name='target_obj',
                                                                on_delete=models.CASCADE)
    target_id = models.PositiveIntegerField(null=True, blank=True, db_index=True)
    target = GenericForeignKey('target_ct', 'target_id')
    created = models.DateTimeField(auto_now_add=True, db_index=True)

to create the feedback
def create_action(user, verb, target=None):
    now = timezone.now()
    last_minute = now - datetime.timedelta(seconds=30)
    similar_actions = Action.objects.filter(user_id=user.id, verb= verb, created__gte=last_minute)
    if target:
        target_ct = ContentType.objects.get_for_model(target)
        similar_actions = similar_actions.filter(target_ct=target_ct, target_id=target.id)
    if not similar_actions:
        action = Action(user=user, verb=verb, target=target)
        action.save()
        return True
    return False

serializer
class GenericActionRelatedField(serializers.RelatedField):
    def to_representation(self, value):
        if isinstance(value, Post):
            serializer = PostListSerializer(value)
            return serializer.data
        if isinstance(value, Comment):
            serializer = CommentSerializer(value)
            return serializer.data

class ActionFeedSerializer(serializers.Serializer): #TODO
    user = UserSerializer(read_only=True)
    verb = serializers.CharField()
    target = GenericActionRelatedField(read_only=True)
    created = serializers.DateTimeField()

    class Meta:
        model = Action
        fields = ['user', 'verb', 'target_ct', 'target_id', 'target', 'created']

Thanks a lot guys!

A: Override the to_representation(...) method of ActionFeedSerializer class,
class ActionFeedSerializer(serializers.Serializer):  # TODO
    user = UserSerializer(read_only=True)
    verb = serializers.CharField()
    target = GenericActionRelatedField(read_only=True)
    created = serializers.DateTimeField()

    class Meta:
        model = Action
        fields = ['user', 'verb', 'target_ct', 'target_id', 'target', 'created']

    def create(self, *arg, **kwargs):
        instance = super().create(*arg, **kwargs)
        create_action(instance.user, instance.verb, instance.target)
        return instance


text:
Q: laravel update registered user I have recently started working in Laravel, my first Framework. I have experience with PHP but I am a little lost now.
I used the default auth that comes with laravel. But I am trying to make a function to edit the users that have registered.
I dont quite see how the data gets to the database from the form.
My form: (didn't put all inputs)
@isset($user)
<form method="POST" action="{{ WHAT GOES HERE?? }}">
@csrf
{{--name--}}

    {{ __('Name') }}

        <input id="name" type="text" class="form-control{{ $errors->has('name') ? ' is-invalid' : '' }}" name="name" value="{{ $user->name }}" required autofocus>

{--last name--}}

    {{ __('Last Name') }}

        <input id="lastname" type="text"
               class="form-control{{ $errors->has('lastname') ? ' is-invalid' : '' }}" name="lastname" value="{{ $user->lastname }}" required autofocus>

        <button type="submit" class="btn btn-primary">
            {{ __('Edit user') }}
        </button>

I did not make a route yet, as I do not know how exactly. Or if this is even needed.
My controller:
public function edit_profile($userId, Request $request)
    {
        $this->isAllowed($userId, true);
        $userProfile = User::findOrFail((int)$userId);

        //TODO validation
        //TODO update user model + save to db

        $userProfile->update();

        return view('user/edit_profile', [
            /* $ */
            'user' => $userProfile,
        ]);
    }

As stated; I do know what needs to happen. I just don't know and understand how.
And last, my user.php
protected $fillable = [
'name',
'lastname',
'email',
'password',
'mobile_number',
'date_of_birth',
];

My next step would be to make a route, to get the data to the controller. But I don't see how this route would look.

A: You need to create a Route for your action.
Go to routes->web.php(laravel 5.3 or above) and add your route structure.
Route::http-verb('url name',"Controller name@Controller Method name");

This is the route you have to add in your web.php file
Route::post('edit-profile', 'ProfileController@edit_profile');

I am assuming that you have a controller with name as ProfileController and inside you have edit_profile method.
{{ url('/edit-profile') }}

add above code to action attribute.
If you are using laravel 5.2 or old version the routes configuration resides inside app/Http/routes.php.


text:
Q: Wicket: Panel nesting as component Is it possible (or what is the best way) to have own Panel with Component behaviours? Especially with HTML nesting...
I want something like that:
    public HeaderPanel(String id) { /* extends Wicket Panel */
        super(id);

        add(new Link(ID_HOME_LINK, null) {
            private static final long serialVersionUID = 1L;

            {
                add(new Image(ID_HOME_LOGO, new ContextRelativeResource("img/logo.png")));
            }

            @Override
            public void onClick(AjaxRequestTarget target) {
                setResponsePage(((BasicPage)getPage()).getLogoLinkPage());
            }
        });
    }

With HTML:
<!DOCTYPE html>
<html>
    <body>
        <wicket:panel>
             <a wicket:id="home-link">
                <img wicket:id="home-logo" src="img/logo.png" title="LearnMe" style="max-height: 65px;" />  <!-- HERE is problem - I would like to set children here -->
             </a>
        </wicket:panel>
    </body>
</html>

And this is the intent in Link (it is my "customized" panel that handles links):
public Link(String id, IModel<String> model, boolean ajax) { /* Extends Wicket Panel */
        super(id);
        this.ajax = ajax;
        this.model = model;

        setRenderBodyOnly(true);

         if (ajax) {
                add(link = new AjaxLink<String>(ID_LINK) {

                    @Override
                    public void onClick(AjaxRequestTarget target) {
                        Link.this.onClick(target);
                    }
                });
            } else {
                add(link = new org.apache.wicket.markup.html.link.Link<String>(ID_LINK) {

                    @Override
                    public void onClick() {
                        Link.this.onClick(null);
                    }
                });
            }
    }

With appropriate HTML:
<html>
    <body>
        <wicket:panel>
            <a wicket:id="link"></a> <!-- HERE is problem - I don't know, which ones and how many components go there  -->
        </wicket:panel>
    </body>
</html>

Now I get this Exception:
Last cause: Close tag not found for tag: <a wicket:id="home-link" id="home_link3">. For  Components only raw markup is allow in between the tags but not other Wicket Component. Component: [Link [Component id = home-link]]

Maybe I am wrong with Panel capacibility or doing unnecessary thing with Link component, but I am looking for idea of nesting/inheriting Panels in one template like it is usual with Components in Wicket (like HeaderPanel Link were Wicket Link, not my customized Panel "Link" - that works, but it is not "common" solution).

A: Your problem is in Link.html. There you have a <a wicket:id="link" for the Wicket's Link but you do not have HTML element for the image. The one defined in HeaderPanel.html is completely overridden by the markup provided by (your) Link.html.


text:
Q: At what point in a logistic regression does a predictor become significant in predicting outcome? Say we have a logistic regression with outcome  equal to a women's pregnancy resulting in a birth =1 and loss=0. The predictor variable is age ranging from 22-50, the Odds ratio point estimate is .819 with CI (.782 - .858). How can we figure out the age in which this result become significant? I.e if this is interpreted as a  1 unit increase in age with a decreases in the chances of live birth vs pregnancy loss of 18%. However, this result is very unlikely if say a women ages from 22 to 23, so at what point in age does this result produce a significant outcome?

A: Younger subjects are more fertile, and this is reflected in the in that point estimate of $\small \text{OR} = 0.819$ which corresponds to the odds ratio:
$$\begin{align}\text{OR} &=\frac{  \text{odds(live birth})_{\text{age a +1}}}{\text{odds(live birth})_{\text{age a}}}=\frac{\left(\frac{\Pr(\text{live})}{\Pr(\text{loss})}\right)_{\text{age a + 1}}}{\left(\frac{\Pr(\text{live})}{\Pr(\text{loss})}\right)_{\text{age a}}}\\[2 ex]
\text{OR} &= e^{\beta_{\text{age}}\times 1} = 0.819
\end{align}$$
As the age advances the odds ratio decreases, so that a difference in age of $\Delta_{\text{age}}$ will result in a change in the odds ratio of pregnancy of
$$0.819^{\Delta_{\text{age}}} = \left(e^{\beta_{\text{age}}}\right)^{\Delta_{\text{age}}}$$
In other words, we are exponentiating a value $<1$, and, hence, the relative odds keep on getting smaller and smaller. On the other hand, the odds of a live delivery would increase with time if the $\small \text{OR}>1.$


text:
Q: Center/align vertical list on active item This question is out of curiosity, to explore the limits of CSS and get a better understand of the layout possibilities. Consider the following example:

.container {
   display: inline-block;
   width: 6rem;
   vertical-align: -4rem;
}

.item {
  width: 6rem;
  height: 2rem;
  background-color: lightblue;
  line-height: 2rem;
}

.item.active {
  color: white;
  background-color: darkblue;
}

The selected element:

Pineapple

Apple

Tomato

Banana

Is it possible, with pure CSS, to always keep the active item aligned with the description text without hardcoding the number of items? In the example, you can see that the second item is active, and the description text is aligned to it.
My ideas:

*

*Is there some way to only make elements before the active element contribute to the height of the box? Then vertical-align: bottom should do what I want. However, I haven't found a way to do that while keeping the stacking of items intact.

*Floats don't always contribute to the height of a container, but inline-block ensures that all floats are contained. Perhaps there is a way to achieve this with floats and a few more levels of containers?

A: I realized you want the center align the left side text. You can do this using pseudo elements. Basically the pseudo element contains the text and it is positioned absolutely to the left(or right) of the list

.container {
   display: inline-block;
   flex-wrap: wrap;
   width: 6rem;
   margin-left: 10em;
}

.item {
  width: 6rem;
  height: 2rem;
  background-color: lightblue;
  line-height: 2rem;
  position: relative;
}

.item.active {
  color: white;
  background-color: darkblue;
}

.item.active::before {
  content: "The selected element: ";
  display: block;
  position: absolute;
  right: 105%;
  height: 100%;
  white-space: nowrap;
  color: black;
}

Pineapple

Apple

Tomato

Banana

Orange

Pineapple

Apple

Tomato

Banana

This is a way to move list items around which i thought it was what you wanted but after reading the questions again, I don't think this is it. However I left it here because I thought it might give you some ideas.
The container is set to display inline flex, all items are set to order of 1 while the active item is 0. The order makes the items realign based on it and since the active item has a higher order, it will appear first

.select-text {
  display: inline-block;
}
.container {
   display: inline-flex;
   flex-wrap: wrap;
   width: 6rem;
}

.item {
  width: 6rem;
  height: 2rem;
  background-color: lightblue;
  line-height: 2rem;
  order: 1;
}

.item.active {
  color: white;
  background-color: darkblue;
  order: 0;
}

The selected element:

Pineapple

Apple

Tomato

Banana

The selected element:

Pineapple

Apple

Tomato

Banana

Orange

A: Here is a simple idea where you can keep your code and rely on the default baseline alignment. The trick is to make all the elements floating but not the active and this one will define the baseline of its parent.
It's also scalable and will work with any text length. It can even work with mutltiple select at the same row:

.container {
  display: inline-block;
  width: 6rem;
}

.item {
  width: 100%;
  background-color: lightblue;
  line-height: 2rem;
  float: left;
}

.item.active {
  color: white;
  background-color: darkblue;
  float: none;
  clear: left;
}

div:not([class]) {
  margin:5px;
  outline:1px solid red;
}

The selected element:

Pineapple

Apple

Tomato

Banana

The selected :

Pineapple

Apple

Tomato

Banana

The selected element is the :

Pineapple

Apple

Tomato

Banana

The selected :

Pineapple

Apple

Tomato

Banana

The baseline of an 'inline-block' is the baseline of its last line box in the normal flow, unless it has either no in-flow line boxes or if its 'overflow' property has a computed value other than 'visible', in which case the baseline is the bottom margin edge ref

Make sure you don't add any oveflow property to your inline-block element:


text:
Q: Python - How can I avoid duplicates (list)? import random
d = [0,0,0,0,0,0,0,0,0,0,0,0,0]
for i in range(1, 13):
    d[i] = random.randint(0,10)
    print(d)

for i in range(10):
    perturbdp = random.randint(1,12)
    d[perturbdp] = random.randint(0,10)
    print(perturbdp)
    print(d)

Output:
[0, 3, 5, 1, 2, 2, 10, 0, 8, 0, 4, 8, 8]
8
[0, 3, 5, 1, 2, 2, 10, 0, 7, 0, 4, 8, 8]
10
[0, 3, 5, 1, 2, 2, 10, 0, 7, 0, 9, 8, 8]
9
[0, 3, 5, 1, 2, 2, 10, 0, 7, 2, 9, 8, 8]
10
[0, 3, 5, 1, 2, 2, 10, 0, 7, 2, 6, 8, 8]
12
[0, 3, 5, 1, 2, 2, 10, 0, 7, 2, 6, 8, 8]
12
[0, 3, 5, 1, 2, 2, 10, 0, 7, 2, 6, 8, 2]
8
[0, 3, 5, 1, 2, 2, 10, 0, 8, 2, 6, 8, 2]
6
[0, 3, 5, 1, 2, 2, 1, 0, 8, 2, 6, 8, 2]
7
[0, 3, 5, 1, 2, 2, 1, 6, 8, 2, 6, 8, 2]
10
[0, 3, 5, 1, 2, 2, 1, 6, 8, 2, 6, 8, 2]

I have created random lists as per the code.
When I iterate to generate further by picking some position, it picks and replaces the value with the same value. Please look last 3 lines from output section.
It has picked position 10 and it replaced with 6 again. How can we avoid this?

A: Repeat until it's different from the current value:
for i in range(10):
    perturbdp = random.randint(1,12)
    new_value = random.randint(0,10)
    while new_value == d[perturbdp]:
        new_value = random.randint(0,10)
    d[perturbdp] = new_value
    print(perturbdp)
    print(d)

If you don't want any repetition among your outputs, you will want to iterate over all possible combinations:
from itertools import combinations_with_replacement
import random

comb = combinations_with_replacement(range(11), 13) # all 13-elements combinations of int between 0 and 10
comb_r = [*comb]        # putting them in a list
random.shuffle(comb_r)  # shuffling the list

number_of_outputs = 10
for i in range(number_of_outputs):
    print(list(comb_r[i]))

A: You can use random.choice to pick the numbers from a list of potential values
for i in range(10):
    perturbdp = random.randint(1, 12)
    nums = list(range(0, d[perturbdp])) + list(range(d[perturbdp] + 1, 11))
    d[perturbdp] = random.choice(nums)
    print(perturbdp)
    print(d)

Output
5
[0, 6, 9, 7, 2, 1, 4, 5, 3, 3, 8, 4, 2]
1
[0, 1, 9, 7, 2, 1, 4, 5, 3, 3, 8, 4, 2]
5
[0, 1, 9, 7, 2, 6, 4, 5, 3, 3, 8, 4, 2]
3
[0, 1, 9, 3, 2, 6, 4, 5, 3, 3, 8, 4, 2]
6
[0, 1, 9, 3, 2, 6, 6, 5, 3, 3, 8, 4, 2]
3
[0, 1, 9, 1, 2, 6, 6, 5, 3, 3, 8, 4, 2]
7
[0, 1, 9, 1, 2, 6, 6, 4, 3, 3, 8, 4, 2]
7
[0, 1, 9, 1, 2, 6, 6, 1, 3, 3, 8, 4, 2]
10
[0, 1, 9, 1, 2, 6, 6, 1, 3, 3, 5, 4, 2]
8
[0, 1, 9, 1, 2, 6, 6, 1, 7, 3, 5, 4, 2]


text:
Q: Compute the homology group of $S^{1}\times D^{2}$ I'm having troubles computing the homology groups of $X=S^{1}\times D^{2}$ where $D^{2}$ is the $2$-disk. Actually I'm not sure what is the best idea here: if we want to apply cellular homology then we (should) have: as $0$-cells $e^{1}_{0}, e^{2}_{0}$, as $1$-cells: $e^{1}_{1}, e^{2}_{1}$ and just one $2$-cell $e_{2}$, but I'm not sure how to proceede now. On the other hand, I tried to find an excisive couple of $X$: $S^{1}$ can be taken as the union of two $1$-cells, say $a_{1}$ and $a_{2}$, in such a way that $A_{1}=a_{1}\times D^{2}$ and $A_{2}=a_{2}\times D^{2}$ is an excisive couple, and both are $A_{1}$ and $A_{2}$ are acyclic. My problem now is, what about the homology of $A_{1}\cap A_{2}$?

A: Thanks to @Pedro for the suggestion. The question is not actually hard but it took me off guard, so here is the idea:
since $D^{2}$ is convex, then it is contractible to a single point, so that we can write:
$$D^{2}\simeq\{x_{0}\}$$
Thus:
$$S^{1}\times D^{2}\simeq S^{1}\times\{x_{0}\}\simeq S^{1}$$
which turns into an isomorphism in homology, hence the work is done.


text:
Q: Is there an official process to remove a high-ranking Starfleet officer for misconduct? In DS9's Paradise Lost episode (season 04, episode 12), the plot is heavy with Starfleet intrigue: Sisko discovers that Admiral Leyton is plotting to take over control of Earth and put it under a military rule. His options seem limited to convincing the President of the United Federation of Planets of the plot, or convince captains working for Leyton to stop obeying orders.
The fact that these seem to be the only options seems suboptimal. Are there no other high-ranking Starfleet officers (fleet admirals, maybe?) in the chain of command between one of (presumably, many) admirals and the president of the Federation? Is there no official process (involving Internal Affairs, perhaps) to deal with claims of misconduct?


text:
Q: Whether the nested function hoisting affects the global variable (declared in the same function)? var b = 4;
function f() {
  b = 7;
  return b;
}

a = f();
console.log(a); //output: 7
console.log(b); //output: 7

In the codes above, b = 7 makes b automatically global, thus changing the value of var b to 7. But when a nested function b is added as below, I am confused about the output result:
var b = 4;
function f() {
  b = 7;
  return b;
  function b() {}
}

a = f();
console.log(a); //output: 7
console.log(b); //output: 4

In my opinion, since function b is hoisting in function f, a reference to function b is first created on the activation object, and when we get the interpreter gets to b = 7, we already see the property name b exists so the code b = 7 does nothing and proceeds, thus console.log(b) outputs 4. But how come console.log(a) still outputs 7? b = 7 should do nothing here, right?

A: For the first block of code this assertion isn't accurate:

In the codes above, b = 7 makes b automatically global, thus changing the value of var b to 7.

In the statement b = 7, b is bound to that outer var b declaration, so b = 7 assigns to that b variable in the closure.
In the second block of code, you have a misunderstanding of what hoisting does. Think of hoisting as simply moving a declaration to the top of its scope, so:
function f() {
  b = 7;
  return b;
  function b() {}
}

...behaves as though you did this:
function f() {
  let b = function () { }
  b = 7;
  return b;
}

On the line b = 7, you're assigning a new value 7 to the local variable b. Hence return b; returns 7.


text:
Q: Gas chamber problem Consider a rectangular isolated(non-conducting) chamber as shown below. The chamber is divided into three compartments. The wall separating A and B has negligible mass, no friction and is conducting, while the wall separating B and C has negligible mass and friction and is non-conducting.
Initially each compartment has the same amount of air at temperature $T$, volume $V$ and pressure $P$. Now compartment A is slowly heated through a heater such that the final volume of C becomes $\frac{4}{9}V$. Now my question is that once equilibrium is attained can I assume that each compartment would have the same pressure? According to the answer given in my book the final pressure in A and C are the same however in B has different pressure. Is this possible?
.


text:
Q: fullcalendar data is not getting displayed I am very new to javascript and json. I am trying to display the events stored in my database into a calender. But its not getting displayed.
This is my json-events.php
 <?php

include("connect.php");
    $year = date('Y');
    $month = date('m');

$command = "SELECT * FROM planner";

$result = mysql_query($command) or die (mysql_error());
$bookings = array();
while ($row = mysql_fetch_array($result)) {
echo "hi";

    $start = date("Y-m-d", strtotime($row['from_time']));
    $end = date("Y-m-d", strtotime($row['to_time']));

    $id =  $row['plan_id'];
    //$eventsArray['plan_id'] =  (int)trim($myid);
    //$eventsArray['title'] = $row['title'];
    $title = $row['purpose'];
    //$title = $row['title'];
    //echo $title;
    //$eventsArray['company'] = $title;
    //$eventsArray['from_time'] = $start;
    //$eventsArray['to_time'] = $start;
    $url = "edit_calendar.php?calendarid=".$row['plan_id'];
    // $eventsArray['end'] = $end;
    // $eventsArray['allDay'] = false;
   // $events[] = $eventsArray;

  $bookings = array(
    'id' => $id,
    'title' => $title,
    'start' => $start,
    'end' => $end,
    'url' => $url
    );

echo json_encode($bookings);}

?>

and here i am linking that in calendar.js
jsonEvents: function() {
            if($('#calendar_json').length) {
                $('#calendar_json').fullCalendar({
                    header: {
                        left: 'month,agendaWeek,agendaDay',
                        center: 'title',
                        right: 'prev,next'
                    },
                    buttonText: {
                        prev: '',
                        next: ''
                    },
                    editable: true,
                    firstDay: 1, // 0 - Sunday, 1 - Monday
                    events: "json-events.php",
                    eventDrop: function(event, delta) {
                        alert(event.title + ' was moved ' + delta + ' days\n' +
                            '(should probably update your database)');
                    }
                });
            }

and in my dashboard.php page

JSON events fetched from a script

But it just displays a calender not the data from database.
Can somebody plz suggest
When i echoed json-events, i get proper output
{"id":"3","title":"sdfsfsd dsdsbfb","start":"2015-01-05","end":"2015-01-14","url":"edit_calendar.php?calendarid=3"}

But in calender nothing is getting displayed


text:
Q: Preventing Bootstrap button from filling flexbox I added d-flex and flex-column classes to a Bootstrap card-body class in order to align a contained button to the bottom of the card, as suggested in this question's top answer. My problem is that doing so caused the button to widen to fill the card. How can I get the button to return to shrinking to fit the button's text, as it did before I added the flex classes?
...

    // THIS IS THE CARD WITH THE WIDENED BUTTON

Giving Back

Help others and feel useful

        Set a Goal

    // THIS CARD'S BUTTON SHRINKS TO FIT ITS TEXT

Spirituality

Connect to something larger than yourself

        Set a Goal

    ...

...

Here's what the buttons look like:

A: Just wrap your anchor in another div

    Set a Goal

<!DOCTYPE html>

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">

Giving Back

Help others and feel useful

              Set a Goal

OR
Just add align-items-center class on the flex div

<!DOCTYPE html>

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">

Giving Back

Help others and feel useful

              Set a Goal

A: To you button class, add mx-auto to center the button and mt-auto to push the button at the bottom of the card.
<!DOCTYPE html>

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">

Giving Back

Help others and feel useful

              Set a Goal


text:
Q: Mysql relating two tables with functions I have two tables one contains a list of teams, the other contains a list of schedules for these teams and score results.  I want to be able to update the teams table when I insert a row into the schedules table.  So for example if I have:
Teams table

Team1
Team2

.
Schedules table

team1, 3
team2, 1

what I want to be able to do is when the score fields are updated I need to update different fields in the teams table.  So when I update this schedule row,
It would insert 3 into one of the rows for team1, and 1 for the team2
Also I would like to be able to calculate the difference between the scores and also insert this into the teams table.
What would be the best way to implement this?
And I would need a function in order to do the comparison of the scores right?
Thanks,
So far I thought of doing something like this.
update table teams set teams.gamesplayed = teams.gameplayed +1  /*this would add one to the games played field because they just played.*/

then for the goals scored something like
update teams set teams.gf =
(

select t.goalsscored
from schedule t, teams s
where t.teamname = s.team1name AND )

)

A: you need add ON UPDATE and ON INSERT triggers to Teams table - thats all.
In trigger you can do anything you need. Of course you can create standalone function and call  it from triggers.


text:
Q: Extract numerical values using regex I have a filename in the following format:
xx_xx_xx_xx/Run02/isf2sync_output/xx_xx_xx_xx_xx_Run02_xxx3_20120301_144327/xx_xx_xx_xx_xx_Run02_xxx3_20120301_144395.x.x.x.log

I want to extract the date from it, in this case 20120301144327 and 20120301144395.
I have been using (\d+) to get the numerical value. How can i skip the first number values and get the desired one?

A: If I understand your need correctly, you can use something like (\d{8})_(\d{6}) to match exactly the number of digits you need, then you can compose the result using the two capturing groups.
For your example, it would match twice:
20120301_144327
and
20120301_144395
If you want to keep it simple, just get the whole thing in one capturing group, something like:
(\d{8}_\d{6})
And then replace the _ with something else (or nothing).

A: If you're sure the date will always be an 8 digit number, then something like :
my ($date) = ($fileName =~ m/_(\d{8})_/);

A: If I understand your needs, how about:
my $str = 'xx_xx_xx_xx/Run02/isf2sync_output/xx_xx_xx_xx_xx_Run02_xxx3_20120301_144327/xx_xx_xx_xx_xx_Run02_xxx3_20120301_144395.x.x.x.log';
my (undef, $second) = $str =~ /\d{8}_\d{6}/g;
say $second;

output:
20120301_144395

A: You can try my regex, although it only gets 20120301_144327, because it doesn't recognize 144395 as a valid time value for HHMMSS (and not even for seconds after midnight!).
my $re
    = qr/ (?: \D | ^ )
          ( \d{2} \d{2,}?            # Y3K? not a problem. Y10K? Not a problem
            (?: 0[1-9] | 1[012] )
            (?: 0[1-9] | [12]\d | 3[01] )
            _
            (?: [01]\d | 2[0-3] )
            (?: [0-5]\d ){2}
          )
          (?: \D | $ )
       /x;

You could even try my more elaborate (and sillier) regex:
      qr/ (?: \D | ^ )
          ( \d{2} (?: \d{2,} )?
            (?: (?: 0[946]   | 11 )    (?: 0[1-9]| [12]\d | 30 )
            |   (?: 0[13578] | 1[02] ) (?: 0[1-9]| [12]\d | 3[01] )
            |   02                     (?: 0[1-9]| [12]\d )
            )
            _
            (?: [01]\d | 2[0-3] )
            (?: [0-5]\d ){2}
          )
          (?: \D | $ )
       /x;


text:
Q: Drag-n-drop всего родителя при взаимодействии с дочерним элементом Как можно реализовать на чистом JS перетаскивание всего родительского контейнера при взаимодействии с дочерним элементом внутри этого родителя?
Само перетаскивание уже сделано и работает (на родителе стоит draggable=true и обработчики, на детях draggable=false)
Если поставить draggable=true на требуемый элемент, а на родителя draggable=false, то перетаскивание работает, но визуально перетаскивается только этот элемент.

    Parrent

      Draggable

        Draggable child

    Droppable

A: Как-то так

//Розовый
let draggable = document.querySelector(".draggable");

//Зеленый
let droppable = document.querySelector(".droppable");

//Обработчик события начала перетаскивания
draggable.ondragstart = (e) => {
  //определяем родителя
  let parrent = e.currentTarget.parentElement;
  //передаем ID родителя
  e.dataTransfer.setData('id', parrent.getAttribute("id"));
}

//Отмена дефолтных реакци на перетаскивание к дропу.
droppable.ondragover = (e) => {
  e.preventDefault();
}

//Событие на дроп айтема
droppable.ondrop = (e) => {
  //извлекаем ID родителя и находим его.
  let item = document.getElementById(e.dataTransfer.getData('id'));
  //применяем родителя к дропу
  e.currentTarget.append(item)
}
.wrapper {
  display: flex;
}

.parrent {
  width: 200px;
  height: 200px;
  border: 1px solid black;
  background: lightblue;
}

.draggable {
  background: pink;
  width: 100px;
  height: 100px;
}

.droppable {
  min-width: 300px;
  min-height: 300px;
  background: lightgreen;
}

    Parrent

      Draggable

    Droppable


text:
Q: Cannot dump Stack Overflow XML file into SQL Server 2008 Cannot dump Stack Overflow XML file into SQL Server 2008.
Could you please explain how I can do it step-by-step?

A: See if this helps. If not try to post what you have done so far and what errors you get.


text:
Q: How Flutter can decode a very large json array, Flutter just decode the only first 20 items? Hello I've an api that return a big list the min length of this list could be 100 or 120 element, and flutter decode only first 20 element is the list.
Now that it seems to you that I load a very large json array elements and don't care about the api fast the req only takes 300 mille sec as possible The Api Is : https://newsapi.org/. I use http package for loading data and thats my code.
Future getEverythingFunc({@required String query}) async {
    http.Response response =  await http.get(Uri.parse(ApiReq.everyThingForSearchingUrl(query:query)));
    if (response.statusCode >= 200 && response.statusCode <= 300) {
      print(response.body);
      return everythingModel = everythingModelFromJson(response.body);
    } else if (response.statusCode >= 400 && response.statusCode <= 500) {
      throw "Err while getting data ${response.statusCode}";
    } else {
      throw 'Unknown Err ${response.statusCode}';
    }
  }

Thanks for reading and hope you help me

A: I don't know how you are coding, but jsonDecode function is working fine. Have you read the doc from NewsAPI? when pageSize parameter is omitted the default is 20 results, and its maximum value for free subscription is 100. I've tested it, my code:
// @dart=2.13
import 'dart:async';
import 'dart:io';

import 'package:wnetworking/wnetworking.dart';

typedef JMap = Map<String, dynamic>;

class NewsAPI {
  static const _base = 'https://newsapi.org/v2';
  static const _apiKey = '111111111111111111111111111111';

  // 'pageSize' ranges from 0 to 100 for free subscription, more size is paid
  // source: https://newsapi.org/docs/endpoints/everything
  static FutureOr<void> fetchNews({required keyword, int pageSize=20}) async {
    final url = '$_base/everything?q=$keyword&pageSize=$pageSize&sortBy=publishedAt&apiKey=$_apiKey';
    List? news;

    stdout.write('Fetching news... ');
    await HttpReqService.getJson<JMap>(url)
      .then((response) {
        if (response != null) {
          news = response['articles'] as List;
        }
      })
      .whenComplete(() {
        print('done!');
        print('\nNews fetched: ${news!.length}');
      });
  }
}

void main(List<String> args) async {
  await NewsAPI.fetchNews(keyword: 'anime', pageSize: 100);
  print('Job done.');
}

Result:
Fetching news... done!

News fetched: 100
Job done.

Note

*

*wnetworking package is not ready to publish yet, it contains operations related to API, etc. You can replace HttpReqService.getJson with your typical http.get but keep in mind the return value and exceptions.


text:
Q: jqgrid can't display data from a variable I have here a javascript code. What I want is that I want to store the data result from this url:
'processjson.php?path=' + encodeURI('display/payTempEarn') + '&json=' + encodeURI(JSON.stringify(dataTempEarn)), to my variable 'tempIncDed', and display that data in my jqgrid.
My question here now is, why is that though when i alert the variable tempIncDed, it shows that it stores the correct data, but it does not display in my jqgrid?
Did I miss something in my code?
Below is my js code:
   var tempIncDed =  [];
    $(document).ready( function() {
      $("#tblIncDed").jqGrid({ data: tempIncDed,
        datatype: "local",
        colNames:['Code','Description', 'Taxable','Amount'],
            colModel:[
          {name:'ded_code',width: 85},
                {name:'ded_desc'},
                {name:'taxable',width: 95},
                {name:'amount', formatter:'currency', align:'right',width: 85}
        ],
        rowNum:20,
            viewrecords: true,
            rowList:[20,50,100],
        ppager: '#tblIncDedPager',
        viewrecords: true,
        caption: "Details"
      });

      $( "#btnEarn" ).click(function() {
        var empNo = $("#tblPayroll").jqGrid('getCell',($("#tblPayroll").jqGrid('getGridParam', 'selrow')),'emp_no');
        var dataTempEarn = {
            "SessionID": $.cookie("SessionID"),
            "dataType": "data",
            "per_id":$("#payPeriod").val(),
            "emp_no":empNo
        };
        $.ajax({
            type: 'GET',
            url:'processjson.php?path=' + encodeURI('display/payTempEarn') + '&json=' + encodeURI(JSON.stringify(dataTempEarn)),
            dataType: primeSettings.ajaxDataType,
            success: function(data) {
                if ('error' in data)
                {
                    showMessage('ERROR: ' + data["error"]["msg"]);
                }
                else{
                    var resLen = data.result.length;

                    tempIncDed = JSON.stringify(data.result);
          alert('this is the tempDed ' + tempIncDed);

                    $("#tblIncDed").jqGrid('setGridParam',{
                                      datatype: 'local',
                                      data:tempIncDed}
                                      ).trigger("reloadGrid");

                }
            }
        });
        $("#dialOtherIncDed").dialog( "open" );
        $("#dialOtherIncDed").attr("name","earnings");

      });
    })

This is the tempDed sample data: [{"ded_id":"10000000845","ded_code":"100","ded_desc":"MEAL ALL","taxable":"N","amount":"10"},{"ded_id":"10000000849","ded_code":"101","ded_desc":"TRANSPORTATION","taxable":"N","amount":"40"},{"ded_id":"10000000851","ded_code":"103","ded_desc":"LAUNDRY","taxable":"N","mOther_amnt":"50.00"}]
Some of my html code:

                Total amount:

                    Amount:
          <input class="numeric" type="text" id="amount" value = ""/>

                    Payroll Period:

                    Type:
                    Rate:

          Employee Name:

            <fieldset><legend>Payroll Details</legend>

EARNINGS

                        ....

...

...

Other earnings	<input class="numeric" style="width:60px" id="mOther_amnt" value = ""/>	<input type='button' value='...' id="btnEarn">

GROSS PAY

DEDUCTIONS

                            ....

                                    Other deductions
                                    <input class="numeric" style="width:60px;color:black" id="mOther_ded" value = "" disabled/>
                                    <input type='button' value='...' id="btnDed"/>

                                    Advances/Loans
                                    <input class="numeric" style="width:60px;color:black" id="mLoan_ded" value = "" disabled/>
                                    <input type='button' value='...' id="btnLoan">

NET PAY

            </fieldset>

            Suggest lowest NET PAY >>> <input type="text" id="lowNetPay" value = "" style="width:80px;color: black" value='0.00' disabled/>

                <button id="btnPayrollEdit">Edit</button>

The btnLoan, btnDed, and btnEarn will be using the same grid. I also used the variable tempIncDed to save the returned data from ajax..

A: I've finally solved my own problem. Lets say for example I have this data stored in var tempInc,
[{"ded_id":"10000000845","ded_code":"100","ded_desc":"MEAL ALL","taxable":"N","amount":"10"},{"ded_id":"10000000849","ded_code":"101","ded_desc":"TRANSPORTATION","taxable":"N","amount":"40"},{"ded_id":"10000000851","ded_code":"103","ded_desc":"LAUNDRY","taxable":"N","mOther_amnt":"50.00"}]

This data was an output from ajax request, when the button btnEarn is click.
Here's my javascript code of btnEarn.
  var tempInc = []; // global variable

  $( "#btnEarn" ).click(function() {
      $("#tblIncDed").clearGridData();
        var empNo = $("#tblPayroll").jqGrid('getCell',($("#tblPayroll").jqGrid('getGridParam', 'selrow')),'emp_no');
        var dataTempEarn = {
            "SessionID": $.cookie("SessionID"),
            "dataType": "data",
            "per_id":$("#payPeriod").val(),
            "emp_no":empNo
        };
        $.ajax({
            type: 'GET',
            url:'processjson.php?path=' + encodeURI('display/payTempEarn') + '&json=' + encodeURI(JSON.stringify(dataTempEarn)),
            dataType: primeSettings.ajaxDataType,
            success: function(data) {
              var tempIncDed = [];
                if ('error' in data)
                {
                    showMessage('ERROR: ' + data["error"]["msg"]);
                }
                else{
                    $.each(data.result, function(rowIndex, rowDataValue) {
                        var fldName = rowDataValue;
                        tempInc[rowIndex] = fldName;
                    });

                    var resLen = data.result.length;
                    $("#totalAmnt").text(data.result[resLen -1].mTot_amnt);

                    $("#disTemp").text((JSON.stringify(tempInc)));
                    $("#tblIncDed").jqGrid('setGridParam',{
            datatype: 'local',
            data:tempInc}
            ).trigger("reloadGrid");
                }
            }
        });
    $("#dialOtherIncDed").dialog( "open" );
        $("#dialOtherIncDed").attr("name","earnings");
    });

Everytime I click that button, it will send ajax request to the server. The data returned (particularlly the object since i have an array of objects) will be saved in global variable, tempInc. After that, I have this code:
$("#tblIncDed").jqGrid('setGridParam',{
    datatype: 'local',
    data:tempInc}
    ).trigger("reloadGrid");

that will display the tempInc in my jqgrid. Hope this will help someone out there.


text:
Q: Receive array inputs from a single line in c# Inputs are in the format: {10, 20, 30, 40, 50}
How should i split it into multiple elements using c#

A: First remove the brackets and spaces,
input = input.Replace("{", "");
input = input.Replace("}", "");
input = input.Replace(" ", "");

Leaving you with this:
10,20,30,40,50

Now you can split the string at the commas using this function:
https://msdn.microsoft.com/en-us/library/b873y76a(v=vs.110).aspx
Which would look like this:
IList<string> result = input.Split(',').ToList<string>();


text:
Q: How to get file path when I input a full filename in javascript? I hope to get the path of a filename, just like get the result /storage/emulated/0/Pictures/ when I input the string /storage/emulated/0/Pictures/Photo-2017-02-17-10-08-38_2271.JPG
How can I do in javascript? Thanks!

A: Try
var fullpath = "/storage/emulated/0/Pictures/Photo-2017-02-17-10-08-38_2271.JPG"
var pathWithoutFileName = fullpath.substr(0, fullpath.lastIndexOf('/') + 1);

A: var x = "/storage/emulated/0/Pictures/Photo-2017-02-17-10-08-38_2271.JPG"
var path = x.substr(0,x.lastIndexOf('/'));

A: var fullpath = "/storage/emulated/0/Pictures/Photo-2017-02-17-10-08-38_2271.JPG"
var path = fullpath.substr(0, fullpath.lastIndexOf('/') + 1);

The +1 is to include the last forward slash.


text:
Q: Make external drive connected to TimeCapsule appears as one drive with internal hard drive I have a TimeCapsule with an external drive connected. Right now I see in Finder two separate units.
I would like to make both hard drives (internal and external) appears as if they were a single disk.
Is it possible to do that?
Thanks!

A: No. You can add external hard drives for network access but Time Machine will only backup to one single drive and will not combo drives for storage space.


text:
Q: Hibernate configuration using annotation in JAR module not working in Spring MVC EAR project I have created ear project with one web module and one EJB module.
I'm using web module for Spring MVC view and controller. Model, service and repository are maintained in ejb module. (tried in JAR module as well).
I'm getting exception like, [springframework.web.servlet.DispatcherServlet] (ServerService Thread Pool -- 168) Context initialization failed: java.lang.IllegalStateException: Cannot load configuration class: com.sakthi.core.config.HibernateConfiguration Exception.
Could anyone please help me?
My HibernateConfiguration class is,
package com.sakthi.core.config;
import java.util.Properties;

import javax.sql.DataSource;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
public class HibernateConfiguration {

    @Bean
    public LocalSessionFactoryBean sessionFactory() {
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(dataSource());
        sessionFactory.setPackagesToScan(new String[] { "com.sakthi.core.model" });
        sessionFactory.setHibernateProperties(hibernateProperties());
        return sessionFactory;
     }

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/test");
        dataSource.setUsername("root");
        dataSource.setPassword("root");
        return dataSource;
    }

    private Properties hibernateProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
        properties.put("hibernate.show_sql", "root");
        properties.put("hibernate.format_sql", "root");
        return properties;
    }

    @Bean
    @Autowired
    public HibernateTransactionManager transactionManager(SessionFactory s) {
       HibernateTransactionManager txManager = new HibernateTransactionManager();
       txManager.setSessionFactory(s);
       return txManager;
    }

}

See the detailed Log below:
23:10:09,229 ERROR [org.springframework.web.servlet.DispatcherServlet] (ServerService Thread Pool -- 168) Context initialization failed: java.lang.IllegalStateException: Cannot load configuration class: com.sakthi.core.config.HibernateConfiguration
    at org.springframework.context.annotation.ConfigurationClassPostProcessor.enhanceConfigurationClasses(ConfigurationClassPostProcessor.java:384)
    at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanFactory(ConfigurationClassPostProcessor.java:263)
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:265)
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:126)
    at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:609)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
    at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:658)
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:530)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:484)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
    at javax.servlet.GenericServlet.init(GenericServlet.java:244)
    at io.undertow.servlet.core.LifecyleInterceptorInvocation.proceed(LifecyleInterceptorInvocation.java:117)
    at org.wildfly.extension.undertow.security.RunAsLifecycleInterceptor.init(RunAsLifecycleInterceptor.java:78)
    at io.undertow.servlet.core.LifecyleInterceptorInvocation.proceed(LifecyleInterceptorInvocation.java:103)
    at io.undertow.servlet.core.ManagedServlet$DefaultInstanceStrategy.start(ManagedServlet.java:231)
    at io.undertow.servlet.core.ManagedServlet.createServlet(ManagedServlet.java:132)
    at io.undertow.servlet.core.DeploymentManagerImpl.start(DeploymentManagerImpl.java:526)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentService.startContext(UndertowDeploymentService.java:101)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentService$1.run(UndertowDeploymentService.java:82)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
    at org.jboss.threads.JBossThread.run(JBossThread.java:320)
Caused by: java.lang.IllegalArgumentException: class com.sakthi.imsx.core.config.HibernateConfiguration$$EnhancerBySpringCGLIB$$13c7c533 is not an enhanced class
    at org.springframework.cglib.proxy.Enhancer.setCallbacksHelper(Enhancer.java:621)
    at org.springframework.cglib.proxy.Enhancer.registerStaticCallbacks(Enhancer.java:594)
    at org.springframework.context.annotation.ConfigurationClassEnhancer.createClass(ConfigurationClassEnhancer.java:131)
    at org.springframework.context.annotation.ConfigurationClassEnhancer.enhance(ConfigurationClassEnhancer.java:100)
    at org.springframework.context.annotation.ConfigurationClassPostProcessor.enhanceConfigurationClasses(ConfigurationClassPostProcessor.java:374)
    ... 24 more

23:10:09,229 ERROR [org.jboss.msc.service.fail] (ServerService Thread Pool -- 168) MSC000001: Failed to start service jboss.undertow.deployment.default-server.default-host./imsx-web: org.jboss.msc.service.StartException in service jboss.undertow.deployment.default-server.default-host./imsx-web: java.lang.IllegalStateException: Cannot load configuration class: com.sakthi.imsx.core.config.HibernateConfiguration
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentService$1.run(UndertowDeploymentService.java:85)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
    at org.jboss.threads.JBossThread.run(JBossThread.java:320)
Caused by: java.lang.IllegalStateException: Cannot load configuration class: com.sakthi.imsx.core.config.HibernateConfiguration
    at org.springframework.context.annotation.ConfigurationClassPostProcessor.enhanceConfigurationClasses(ConfigurationClassPostProcessor.java:384)
    at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanFactory(ConfigurationClassPostProcessor.java:263)
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:265)
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:126)
    at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:609)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
    at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:658)
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:530)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:484)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
    at javax.servlet.GenericServlet.init(GenericServlet.java:244)
    at io.undertow.servlet.core.LifecyleInterceptorInvocation.proceed(LifecyleInterceptorInvocation.java:117)
    at org.wildfly.extension.undertow.security.RunAsLifecycleInterceptor.init(RunAsLifecycleInterceptor.java:78)
    at io.undertow.servlet.core.LifecyleInterceptorInvocation.proceed(LifecyleInterceptorInvocation.java:103)
    at io.undertow.servlet.core.ManagedServlet$DefaultInstanceStrategy.start(ManagedServlet.java:231)
    at io.undertow.servlet.core.ManagedServlet.createServlet(ManagedServlet.java:132)
    at io.undertow.servlet.core.DeploymentManagerImpl.start(DeploymentManagerImpl.java:526)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentService.startContext(UndertowDeploymentService.java:101)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentService$1.run(UndertowDeploymentService.java:82)
    ... 6 more
Caused by: java.lang.IllegalArgumentException: class com.sakthi.imsx.core.config.HibernateConfiguration$$EnhancerBySpringCGLIB$$13c7c533 is not an enhanced class
    at org.springframework.cglib.proxy.Enhancer.setCallbacksHelper(Enhancer.java:621)
    at org.springframework.cglib.proxy.Enhancer.registerStaticCallbacks(Enhancer.java:594)
    at org.springframework.context.annotation.ConfigurationClassEnhancer.createClass(ConfigurationClassEnhancer.java:131)
    at org.springframework.context.annotation.ConfigurationClassEnhancer.enhance(ConfigurationClassEnhancer.java:100)
    at org.springframework.context.annotation.ConfigurationClassPostProcessor.enhanceConfigurationClasses(ConfigurationClassPostProcessor.java:374)
    ... 24 more

A: There's a mistake in your configuration above. Update this:
    private Properties hibernateProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
        properties.put("hibernate.show_sql", "root");
        properties.put("hibernate.format_sql", "root");
        return properties;
    }

to the following:
    private Properties hibernateProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
        properties.put("hibernate.show_sql", "true");
        properties.put("hibernate.format_sql", "true");
        return properties;
    }

The IllegalStateException Exception may be caused by the fact that "root" is being passed to a boolean property. So it needs to be 'true' or 'false'.


text:
Q: How to: Overlapping match Lets say we have this:
A2 A1 B.         #1

A1 B.            #2

A3 A1 A8 B.      #3

How would I go about if I want:

*

*To match: A2 A1 B. and A1 B.

*To match: A1 B.

*To match: A3 A1 A8 B. and A1 A8 B. and A8 B.
So far I've got this regex:
A\d\s(.*\.)

But it won't match subsets of code that's already been matched (I'm matching using re.finditer)/  My guess is that re.finditer is doing just as its supposed to, and I'm just trying to force it into doing stupid stuff.
Playground

A: You can use lookahead for this and capture values inside the lookahead:
regex = r"(?=((?:A\d+\s+)+B\.))"

RegEx Demo
RegEx Description:
(?=               # start lookahead
   (              # start capturing group #1
      (?:         # start non-capturing group
         A\d+\s+  # match A followed by 1 or more digit followed by 1 or more whitespace
      )           # end non-capturing group
      +B\.        # match B and literal DOT
   )              # end capture group #1
)                 # end lookahead

Code:
>>> regex = r"(?=((?:A\d+\s+)+B\.))"

>>> print re.findall(regex, 'A2 A1 B.')
['A2 A1 B.', 'A1 B.']

>>> print re.findall(regex, 'A1 B.')
['A1 B.']

>>> print re.findall(regex, 'A3 A1 A8 B.')
['A3 A1 A8 B.', 'A1 A8 B.', 'A8 B.']


text:
Q: spacing between buttons in scrollview in android in my application i am adding image buttons dynamically in linear-layout in scroll-view.but there is no spacing in between the image buttons.can any one help me in giving space between image buttons.
here is my code.
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.activity_main, null);

scrollview=(ScrollView)v.findViewById(R.id.scrollview);
LinearLayout ll =( LinearLayout)v.findViewById(R.id.scrollinear);

ImageButton img_travel = new ImageButton(this);

img_travel.setBackgroundResource(R.drawable.travel);

ImageButton img_work=new ImageButton(this);
img_work.setBackgroundResource(R.drawable.work);

ll.addView(img_work);
ll.addView(img_travel);

setContentView(v);

A: For instance:
 LinearLayout.LayoutParams layoutParams =    new LinearLayout.LayoutParams(
 LinearLayout.LayoutParams.FILL_PARENT,    LinearLayout.LayoutParams.WRAP_CONTENT);
 layoutParams.setMargins(20, 20, 20, 20);

  ll.addView(img_work, layoutParams);

A: TRy this...
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.activity_main, null);

scrollview=(ScrollView)v.findViewById(R.id.scrollview);
LinearLayout ll =( LinearLayout)v.findViewById(R.id.scrollinear);

ImageButton img_travel = new ImageButton(this);

img_travel.setBackgroundResource(R.drawable.travel);

ImageButton img_work=new ImageButton(this);
img_work.setBackgroundResource(R.drawable.work);

View dummyView= new View(this);
LinearLayout.LayoutParams viewParams = new    LinearLayout.LayoutParams(your width in dp, your height in dp);

dummyView.setLayoutParams(viewParams )

ll.addView(img_work);
ll.addView(dummyView);
ll.addView(img_travel);

setContentView(v);


text:
Q: jquery script works only on firefox After 2 weeks of hard work on my first, simple site/database I'm stuck. Friend of mine helped me on adding jquery, but now it works only in Mozilla, and he dont have idea why. I dont know java at all (and barely php). Can you take a look?
Chrome console point an error at
Uncaught SyntaxError: Unexpected token =

at line 49 which is
self.dataAdapter = function(id = 0, imie = '', nazwisko = '', kredyt = 0)

Do you have any idea what is the most compatible syntax?
The whole script:
$(document).ready(function()
{
    sui = new swiezakUI();
    sui.getData();
});

function swiezakUI()
{
    var self = this;
    self.scriptURL = "/data.php";

    self.send = function(key, stuff)
    {
        var post = {};
        post[key] = JSON.stringify(stuff);

        $.ajax({
            type: "POST",
            url: self.scriptURL,
            data: post,
            contentType: "application/x-www-form-urlencoded",
            dataType: "json",
            success: function(data)
            {
                self.getData();
                self.cleanForm();
            },
            failure: function(errMsg)
            {
                alert('fail');
            },
            error: function(errMsg)
            {
                alert("Blad \n" + errMsg.responseText);
            }
        });
    }

    self.id2Id = function(id)
    {
        for(var i = 0; i < self.myData.length; i++)
        {
            if(id == self.myData[i].id)
                return i;
        }
    }

    self.dataAdapter = function(id = 0, imie = '', nazwisko = '', kredyt = 0)
    {
        var data = new Object();
        data.id = id;
        data.imie = imie;
        data.nazwisko = nazwisko;
        data.kredyt = kredyt;
        return data;
    }

    self.dodajNowy = function()
    {
        return function()
        {
            var data = self.dataAdapter(null, $('#imie').val(), $('#nazwisko').val(), $('#kredyt').val().replace(/\D+/g,""));
            self.send('nowy',data);
        }
    }

    self.edytujWpis = function(id)
    {
        return function()
        {
            var data = self.dataAdapter(id, $('#imie').val(), $('#nazwisko').val(), $('#kredyt').val().replace(/\D+/g,""));
            self.send('edycja',data);
        }
    }

    self.kasujWpis = function(id)
    {
        return function()
        {
            var data = self.dataAdapter(id);
            self.send('kasuj',data);
        }
    }

    self.cleanForm = function()
    {
        $('#imie').val('');
        $('#nazwisko').val('');
        $('#kredyt').val('');
        $('#bZapisz').unbind();
        $('#bZapisz').click(self.dodajNowy());
    }

    self.editButtons = function()
    {
        $('.edit').click(function()
        {
            var did = $(this).attr('id').replace(/\D+/g,"");
            id = self.id2Id(did);
            $('#imie').val(self.myData[id].imie);
            $('#nazwisko').val(self.myData[id].nazwisko);
            $('#kredyt').val(self.myData[id].kredyt);
            $('#bZapisz').unbind();
            $('#bZapisz').click(self.edytujWpis(did));
        });
    }

    self.delButtons = function()
    {
        $('.delete').click(function()
        {
            var id = $(this).attr('id').replace(/\D+/g,"");
            console.log(id);
            self.kasujWpis(id)();
        });
    }

    $('#bZapisz').click(self.dodajNowy());

    $('#bCzysc').click(function(){
        self.cleanForm();
    });

    self.getData = function()
    {
        $('#lista').children('table').html("
id	imie	nazwisko	kredyt	"+
            "edycja	usun
");
        $.getJSON(self.scriptURL, function(data)
        {
            console.log(data);
            self.myData = data;

            for(var i = 0; i < data.length; i++)
            {
                $('#lista').children('table').append(
                    '
'+ data[i].id +'	'+
                    ''+ data[i].imie +'	'+
                    ''+ data[i].nazwisko +'	'+
                    ''+ data[i].kredyt +'	'+
                    '<button class="edit" id="e#'+data[i].id+'">e</button>	'+
                    '<button class="delete" id="d#'+data[i].id+'">d</button>
');
            }

            self.editButtons();
            self.delButtons();
        });
    }
}

A: Default parameters are currently part of the ES6 draft. This feature is not part of the most recent final ECMAScript standard (5.1), hence browser support is currently minimal. As of this writing, only Firefox (experimentally) implements default parameters.
There are many ways to simulate default parameters. An alternative to ES6's default parameters would be comparing arg === undefined to set the default value for it:
//if the kredyt argument has not been passed or is undefined
if (kredyt === undefined) {
   kredyt = 0;
}

When a function is called passing less arguments than its parameters count, the parameters without corresponding arguments are initialized to undefined.
This way, not passing a value for the argument as well as explicitly passing undefined as the argument value will use the default parameter value, the same behavior as ES6's default parameters.
So here's the complete example:
self.dataAdapter = function(id, imie, nazwisko, kredyt)
{
    //default parameters
    if (id === undefined) {
        id = 0;
    }
    if (imie === undefined) {
        imie = '';
    }
    if (nazwisko === undefined) {
        nazwisko = '';
    }
    if (kredyt === undefined) {
        kredyt = 0;
    }

    //function code
    var data = new Object();
    data.id = id;
    data.imie = imie;
    data.nazwisko = nazwisko;
    data.kredyt = kredyt;
    return data;
}

Another common approach is comparing arg == null, which has the same effect but also accepts passing null to use the default parameter value:
//if kredyt is null, undefined or not passed
if (kredyt == null) {
   kredyt = 0;
}

This works because == does type coercion, and null coerces to, and only to, undefined (ES5#11.9.3).

Yet another common approach is to use the || as the "default operator" (see related question):
kredyt = kredyt || 0; //in the beginning of the function
//...
data.kredyt = kredyt;

Or if the parameter is used only in a single place, it is possible to inline it as well:
data.kredyt = kredyt || 0;

The benefit is basically shorter code, but note that it will use the default parameter value not only when the argument is undefined, but also null, false, 0, empty string or NaN. Hence this is not a viable approach when one of these values is an acceptable parameter value different from its default parameter value.

Lastly, for use cases that need to differentiate a null/undefined value from a not passed argument (which is rare and not the case here), it's possible to check the arguments object's length property:
if (arguments.length < 4) {
    kredyt = 0;
}


text:
Q: Difference between LocalRedirectPermanent vs RedirectPermanent in ASP.NET Core Controller What is the difference between LocalRedirectPermanent vs RedirectPermanent in ASP.NET Core Controller? When to use which one?
I could not find some useful documentation regarding it.

A: RedirectPermanent produces a result that will redirect the browser/client to a given URL.
LocalRedirectPermanent produces the same result, but throws InvalidOperationException if the URL is not a local URL (source):

if (!urlHelper.IsLocalUrl(result.Url))
{
    throw new InvalidOperationException(Resources.UrlNotLocal);
}

A local URL is one that begins with something like "/" or "~/". LocalRedirectPermanent is useful for ensuring returnUrl parameters are local to your web application, for example.