Programs & Examples On #Sqldatetime

Converting java date to Sql timestamp

java.util.Date utilDate = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
System.out.println("utilDate:" + utilDate);
System.out.println("sqlDate:" + sqlDate);

This gives me the following output:

 utilDate:Fri Apr 04 12:07:37 MSK 2014
 sqlDate:2014-04-04

.NET DateTime to SqlDateTime Conversion

var sqlCommand = new SqlCommand("SELECT * FROM mytable WHERE start_time >= @StartTime");
sqlCommand.Parameters.Add("@StartTime", SqlDbType.DateTime);
sqlCommand.Parameters("@StartTime").Value = MyDateObj;

Python: print a generator expression?

Unlike a list or a dictionary, a generator can be infinite. Doing this wouldn't work:

def gen():
    x = 0
    while True:
        yield x
        x += 1
g1 = gen()
list(g1)   # never ends

Also, reading a generator changes it, so there's not a perfect way to view it. To see a sample of the generator's output, you could do

g1 = gen()
[g1.next() for i in range(10)]

how to compare two string dates in javascript?

Parse the dates and compare them as you would numbers:

function isLater(str1, str2)
{
    return new Date(str1) > new Date(str2);
}

If you need to support other date format consider a library such as date.js.

bash: npm: command not found?

in redhat base OS (tested in centos 7)

yum install nodejs npm -y

in debian base OS

apt-get install -y npm    

How do I load an org.w3c.dom.Document from XML in a string?

Just had a similar problem, except i needed a NodeList and not a Document, here's what I came up with. It's mostly the same solution as before, augmented to get the root element down as a NodeList and using erickson's suggestion of using an InputSource instead for character encoding issues.

private String DOC_ROOT="root";
String xml=getXmlString();
Document xmlDoc=loadXMLFrom(xml);
Element template=xmlDoc.getDocumentElement();
NodeList nodes=xmlDoc.getElementsByTagName(DOC_ROOT);

public static Document loadXMLFrom(String xml) throws Exception {
        InputSource is= new InputSource(new StringReader(xml));
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        DocumentBuilder builder = null;
        builder = factory.newDocumentBuilder();
        Document doc = builder.parse(is);
        return doc;
    }

How to access the local Django webserver from outside world

I'm going to add this here:

  1. sudo python manage.py runserver 80

  2. Go to your phone or computer and enter your computers internal IP (e.g 192.168.0.12) into the browser.

At this point you should be connected to the Django server.

This should also work without sudo:

python manage.py runserver 0.0.0.0:8000

How to create range in Swift?

I want to do this:

print("Hello"[1...3])
// out: Error

But unfortunately, I can't write a subscript of my own because the loathed one takes up the name space.

We can do this however:

print("Hello"[range: 1...3])
// out: ell 

Just add this to your project:

extension String {
    subscript(range: ClosedRange<Int>) -> String {
        get {
            let start = String.Index(utf16Offset: range.lowerBound, in: self)
            let end = String.Index(utf16Offset: range.upperBound, in: self)
            return String(self[start...end])
        }
    }
}

Android Design Support Library expandable Floating Action Button(FAB) menu

When I tried to create something simillar to inbox floating action button i thought about creating own custom component.

It would be simple frame layout with fixed height (to contain expanded menu) containing FAB button and 3 more placed under the FAB. when you click on FAB you just simply animate other buttons to translate up from under the FAB.

There are some libraries which do that (for example https://github.com/futuresimple/android-floating-action-button), but it's always more fun if you create it by yourself :)

How can I declare a two dimensional string array?

you can also write the code below.

Array lbl_array = Array.CreateInstance(typeof(string), i, j);

where 'i' is the number of rows and 'j' is the number of columns. using the 'typeof(..)' method you can choose the type of your array i.e. int, string, double

C# "No suitable method found to override." -- but there is one

Make sure that you have the child class explicitly inherit the parent class:

public class Ext : Base { // stuff }

Node.js Error: Cannot find module express

create one folder in your harddisk e.g sample1 and go to command prompt type :cd and gives the path of sample1 folder and then install all modules...

npm install express

npm install jade

npm install socket.io

and then whatever you are creating application save in sample1 folder

try it...

how to stop Javascript forEach?

Below code will break the foreach loop once the condition is met, below is the sample example

    var array = [1,2,3,4,5];
    var newArray = array.slice(0,array.length);
    array.forEach(function(item,index){
        //your breaking condition goes here example checking for value 2
        if(item == 2){
            array.length = array.indexOf(item);
        }

    })
    array = newArray;

In what cases do I use malloc and/or new?

To answer your question, you should know the difference between malloc and new. The difference is simple:

malloc allocates memory, while new allocates memory AND calls the constructor of the object you're allocating memory for.

So, unless you're restricted to C, you should never use malloc, especially when dealing with C++ objects. That would be a recipe for breaking your program.

Also the difference between free and delete is quite the same. The difference is that delete will call the destructor of your object in addition to freeing memory.

Filtering a data frame by values in a column

The subset command is not necessary. Just use data frame indexing

studentdata[studentdata$Drink == 'water',]

Read the warning from ?subset

This is a convenience function intended for use interactively. For programming it is better to use the standard subsetting functions like ‘[’, and in particular the non-standard evaluation of argument ‘subset’ can have unanticipated consequences.

pip install gives error: Unable to find vcvarsall.bat

First, you should look for the file vcvarsall.bat in your system.

If it does not exist, I recommend you to install Microsoft Visual C++ Compiler for Python 2.7. This will create the vcvarsall.bat in "C:\Program Files (x86)\Common Files\Microsoft\Visual C++ for Python\9.0" if you install it for all users.

The problem now is in the function find_vcvarsall(version) in the C:/Python27/Lib/distutils/msvc9compiler.py module, which is looking for the vcvarsall.bat file.

Following the function calls you will see it is looking for an entry in the registry containing the path to the vcvarsall.bat file. It will never find it because this function is looking in other directories different from where the above-mentioned installation placed it, and in my case, the registry didn't exist.

The easiest way to solve this problem is to manually return the path of the vcvarsall.bat file. To do so, modify the function find_vcvarsall(version) in the msvc9compiler.py file with the absolute path to the vcvarsall.bat file like this:

def find_vcvarsall(version):
    return r"C:\Program Files (x86)\Common Files\Microsoft\Visual C++ for Python\9.0\vcvarsall.bat"

This solution worked for me.

If you already have the vcvarsall.bat file you should check if you have the key productdir in the registry:

(HKEY_USERS, HKEY_CURRENT_USERS, HKEY_LOCAL_MACHINE or HKEY_CLASSES_ROOT)\Software\Wow6432Node\Microsoft\VisualStudio\version\Setup\VC

Where version = msvc9compiler.get_build_version()

If you don't have the key just do:

def find_vcvarsall(version):
        return <path>\vcvarsall.bat

To understand the exact behavior check msvc9compiler.py module starting in the find_vcvarsall(version) function.

Java 8: merge lists with stream API

Already answered above, but here's another approach you could take. I can't find the original post I adapted this from, but here's the code for the sake of your question. As noted above, the flatMap() function is what you'd be looking to utilize with Java 8. You can throw it in a utility class and just call "RandomUtils.combine(list1, list2, ...);" and you'd get a single List with all values. Just be careful with the wildcard - you could change this if you want a less generic method. You can also modify it for Sets - you just have to take care when using flatMap() on Sets to avoid data loss from equals/hashCode methods due to the nature of the Set interface.

Edit - If you use a generic method like this for the Set interface, and you happen to use Lombok, make sure you understand how Lombok handles equals/hashCode generation.

  /**
    * Combines multiple lists into a single list containing all elements of
    * every list.
    * 
    * @param <T> - The type of the lists.
    * @param lists - The group of List implementations to combine
    * @return a single List<?> containing all elements of the passed in lists.
    */
   public static <T> List<?> combine(final List<?>... lists) {
      return Stream.of(lists).flatMap(List::stream).collect(Collectors.toList());
   }

Plot 3D data in R

I use the lattice package for almost everything I plot in R and it has a corresponing plot to persp called wireframe. Let data be the way Sven defined it.

wireframe(z ~ x * y, data=data)

wireframe plot

Or how about this (modification of fig 6.3 in Deepanyan Sarkar's book):

p <- wireframe(z ~ x * y, data=data)
npanel <- c(4, 2)
rotx <- c(-50, -80)
rotz <- seq(30, 300, length = npanel[1]+1)
update(p[rep(1, prod(npanel))], layout = npanel,
    panel = function(..., screen) {
        panel.wireframe(..., screen = list(z = rotz[current.column()],
                                           x = rotx[current.row()]))
    })

Multiple wireframe plots using panel and update

Update: Plotting surfaces with OpenGL

Since this post continues to draw attention I want to add the OpenGL way to make 3-d plots too (as suggested by @tucson below). First we need to reformat the dataset from xyz-tripplets to axis vectors x and y and a matrix z.

x <- 1:5/10
y <- 1:5
z <- x %o% y
z <- z + .2*z*runif(25) - .1*z

library(rgl)
persp3d(x, y, z, col="skyblue")

rgl::persp3d

This image can be freely rotated and scaled using the mouse, or modified with additional commands, and when you are happy with it you save it using rgl.snapshot.

rgl.snapshot("myplot.png")

What is a classpath and how do I set it?

The classpath in this context is exactly what it is in the general context: anywhere the VM knows it can find classes to be loaded, and resources as well (such as output.vm in your case).

I'd understand Velocity expects to find a file named output.vm anywhere in "no package". This can be a JAR, regular folder, ... The root of any of the locations in the application's classpath.

android pick images from gallery

If you are only looking for images and multiple selection.

Look @ once https://stackoverflow.com/a/15029515/1136023

It's helpful for future.I personally feel great by using MultipleImagePick.

JavaScript: How to find out if the user browser is Chrome?

User could change user agent . Try testing for webkit prefixed property in style object of body element

if ("webkitAppearance" in document.body.style) {
  // do stuff
}

Understanding the map function

map doesn't relate to a Cartesian product at all, although I imagine someone well versed in functional programming could come up with some impossible to understand way of generating a one using map.

map in Python 3 is equivalent to this:

def map(func, iterable):
    for i in iterable:
        yield func(i)

and the only difference in Python 2 is that it will build up a full list of results to return all at once instead of yielding.

Although Python convention usually prefers list comprehensions (or generator expressions) to achieve the same result as a call to map, particularly if you're using a lambda expression as the first argument:

[func(i) for i in iterable]

As an example of what you asked for in the comments on the question - "turn a string into an array", by 'array' you probably want either a tuple or a list (both of them behave a little like arrays from other languages) -

 >>> a = "hello, world"
 >>> list(a)
['h', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd']
>>> tuple(a)
('h', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd')

A use of map here would be if you start with a list of strings instead of a single string - map can listify all of them individually:

>>> a = ["foo", "bar", "baz"]
>>> list(map(list, a))
[['f', 'o', 'o'], ['b', 'a', 'r'], ['b', 'a', 'z']]

Note that map(list, a) is equivalent in Python 2, but in Python 3 you need the list call if you want to do anything other than feed it into a for loop (or a processing function such as sum that only needs an iterable, and not a sequence). But also note again that a list comprehension is usually preferred:

>>> [list(b) for b in a]
[['f', 'o', 'o'], ['b', 'a', 'r'], ['b', 'a', 'z']]

Date object to Calendar [Java]

Calendar.setTime()

It's often useful to look at the signature and description of API methods, not just their name :) - Even in the Java standard API, names can sometimes be misleading.

JavaScript function in href vs. onclick

Personally, I find putting javascript calls in the HREF tag annoying. I usually don't really pay attention to whether or not something is a javascript link or not, and often times want to open things in a new window. When I try doing this with one of these types of links, I get a blank page with nothing on it and javascript in my location bar. However, this is sidestepped a bit by using an onlick.

Moving Git repository content to another repository preserving history

If you're looking to preserve the existing branches and commit history, here's one way that worked for me.

git clone --mirror https://github.com/account/repo.git cloned-repo
cd cloned-repo
git push --mirror {URL of new (empty) repo}

# at this point only remote cloned-repo is correct, local has auto-generated repo structure with folders such as "branches" or "refs"
cd ..
rm -rf cloned-repo
git clone {URL of new (empty) repo}
# only now will you see the expected user-generated contents in local cloned-repo folder

# note: all non-master branches are avaialable, but git branch will not show them until you git checkout each of them
# to automatically checkout all remote branches use this loop:
for b in `git branch -r | grep -v -- '->'`; do git branch --track ${b##origin/} $b; done

Now, suppose you want to keep the source and destination repos in sync for a period of time. For example, there's still activity within the current remote repo that you want to bring over to the new/replacement repo.

git clone -o old https://github.com/account/repo.git my-repo
cd my-repo
git remote add new {URL of new repo}

To pull down the latest updates (assuming you have no local changes):

git checkout {branch(es) of interest}
git pull old
git push --all new

NB: I have yet to use submodules, so I don't know what additional steps might be required if you have them.

What is __main__.py?

__main__.py is used for python programs in zip files. The __main__.py file will be executed when the zip file in run. For example, if the zip file was as such:

test.zip
     __main__.py

and the contents of __main__.py was

import sys
print "hello %s" % sys.argv[1]

Then if we were to run python test.zip world we would get hello world out.

So the __main__.py file run when python is called on a zip file.

How to increase application heap size in Eclipse?

In the run configuration you want to customize (just click on it) open the tab Arguments and add -Xmx2048min the VM arguments section. You might want to set the -Xms as well (small heap size).

Why is "using namespace std;" considered bad practice?

This is a bad practice, often known as global namespace pollution. Problems may occur when more than one namespace has the same function name with signature, then it will be ambiguous for the compiler to decide which one to call and this all can be avoided when you are specifying the namespace with your function call like std::cout . Hope this helps. :)

Repeat a task with a time delay?

In my case, I had to execute a process if one of these conditions were true: if a previous process was completed or if 5 seconds had already passed. So, I did the following and worked pretty well:

private Runnable mStatusChecker;
private Handler mHandler;

class {
method() {
  mStatusChecker = new Runnable() {
            int times = 0;
            @Override
            public void run() {
                if (times < 5) {
                    if (process1.isRead()) {
                        executeProcess2();
                    } else {
                        times++;
                        mHandler.postDelayed(mStatusChecker, 1000);
                    }
                } else {
                    executeProcess2();
                }
            }
        };

        mHandler = new Handler();
        startRepeatingTask();
}

    void startRepeatingTask() {
       mStatusChecker.run();
    }

    void stopRepeatingTask() {
        mHandler.removeCallbacks(mStatusChecker);
    }


}

If process1 is read, it executes process2. If not, it increments the variable times, and make the Handler be executed after one second. It maintains a loop until process1 is read or times is 5. When times is 5, it means that 5 seconds passed and in each second, the if clause of process1.isRead() is executed.

Automatically set appsettings.json for dev and release environments in asp.net core?

Just an update for .NET core 2.0 users, you can specify application configuration after the call to CreateDefaultBuilder:

public class Program
{
   public static void Main(string[] args)
   {
      BuildWebHost(args).Run();
   }

   public static IWebHost BuildWebHost(string[] args) =>
      WebHost.CreateDefaultBuilder(args)
             .ConfigureAppConfiguration(ConfigConfiguration)
             .UseStartup<Startup>()
             .Build();

   static void ConfigConfiguration(WebHostBuilderContext ctx, IConfigurationBuilder config)
   {
            config.SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("config.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"config.{ctx.HostingEnvironment.EnvironmentName}.json", optional: true, reloadOnChange: true);

   }
 }

What exactly is OAuth (Open Authorization)?

OAuth is all about delegating Authorization (choosing someone who can do Authorization for you). Note that Authentication and Authorization are different things. OAuth is Authorization (Access control), and if you want to implement Authentication (ID verification) also, OpenID protocol can be used on top of OAuth.

All big companies like Facebook, Google, Github,... use this kind of authentication/authorization nowadays. For example, I just signed in on this website using my Google account, this means Stackoverflow doesn't know my password, it receives the allowance from Google where my password (hashed obviously) is saved. This gives a lot of benefits, one of them is; In the near future you won't have to make several accounts on every website. One website (which you trust most) can be used to login to all other websites. So you'll only have to remember one password.

Can I get "&&" or "-and" to work in PowerShell?

It depends on the context, but here's an example of "-and" in action:

get-childitem | where-object { $_.Name.StartsWith("f") -and $_.Length -gt 10kb }

So that's getting all the files bigger than 10kb in a directory whose filename starts with "f".

How to run an android app in background?

As apps run in the background anyway. I’m assuming what your really asking is how do you make apps do stuff in the background. The solution below will make your app do stuff in the background after opening the app and after the system has rebooted.

Below, I’ve added a link to a fully working example (in the form of an Android Studio Project)

This subject seems to be out of the scope of the Android docs, and there doesn’t seem to be any one comprehensive doc on this. The information is spread across a few docs.

The following docs tell you indirectly how to do this: https://developer.android.com/reference/android/app/Service.html

https://developer.android.com/reference/android/content/BroadcastReceiver.html

https://developer.android.com/guide/components/bound-services.html

In the interests of getting your usage requirements correct, the important part of this above doc to read carefully is: #Binder, #Messenger and the components link below:

https://developer.android.com/guide/components/aidl.html

Here is the link to a fully working example (in Android Studio format): http://developersfound.com/BackgroundServiceDemo.zip

This project will start an Activity which binds to a service; implementing the AIDL.

This project is also useful to re-factor for the purpose of IPC across different apps.

This project is also developed to start automatically when Android restarts (provided the app has been run at least one after installation and app is not installed on SD card)

When this app/project runs after reboot, it dynamically uses a transparent view to make it look like no app has started but the service of the associated app starts cleanly.

This code is written in such a way that it’s very easy to tweak to simulate a scheduled service.

This project is developed in accordance to the above docs and is subsequently a clean solution.

There is however a part of this project which is not clean being: I have not found a way to start a service on reboot without using an Activity. If any of you guys reading this post have a clean way to do this please post a comment.

How to create bitmap from byte array?

You'll need to get those bytes into a MemoryStream:

Bitmap bmp;
using (var ms = new MemoryStream(imageData))
{
    bmp = new Bitmap(ms);
}

That uses the Bitmap(Stream stream) constructor overload.

UPDATE: keep in mind that according to the documentation, and the source code I've been reading through, an ArgumentException will be thrown on these conditions:

stream does not contain image data or is null.
-or-
stream contains a PNG image file with a single dimension greater than 65,535 pixels.

Load an image from a url into a PictureBox

Here's the solution I use. I can't remember why I couldn't just use the PictureBox.Load methods. I'm pretty sure it's because I wanted to properly scale & center the downloaded image into the PictureBox control. If I recall, all the scaling options on PictureBox either stretch the image, or will resize the PictureBox to fit the image. I wanted a properly scaled and centered image in the size I set for PictureBox.

Now, I just need to make a async version...

Here's my methods:

   #region Image Utilities

    /// <summary>
    /// Loads an image from a URL into a Bitmap object.
    /// Currently as written if there is an error during downloading of the image, no exception is thrown.
    /// </summary>
    /// <param name="url"></param>
    /// <returns></returns>
    public static Bitmap LoadPicture(string url)
    {
        System.Net.HttpWebRequest wreq;
        System.Net.HttpWebResponse wresp;
        Stream mystream;
        Bitmap bmp;

        bmp = null;
        mystream = null;
        wresp = null;
        try
        {
            wreq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);
            wreq.AllowWriteStreamBuffering = true;

            wresp = (System.Net.HttpWebResponse)wreq.GetResponse();

            if ((mystream = wresp.GetResponseStream()) != null)
                bmp = new Bitmap(mystream);
        }
        catch
        {
            // Do nothing... 
        }
        finally
        {
            if (mystream != null)
                mystream.Close();

            if (wresp != null)
                wresp.Close();
        }

        return (bmp);
    }

    /// <summary>
    /// Takes in an image, scales it maintaining the proper aspect ratio of the image such it fits in the PictureBox's canvas size and loads the image into picture box.
    /// Has an optional param to center the image in the picture box if it's smaller then canvas size.
    /// </summary>
    /// <param name="image">The Image you want to load, see LoadPicture</param>
    /// <param name="canvas">The canvas you want the picture to load into</param>
    /// <param name="centerImage"></param>
    /// <returns></returns>

    public static Image ResizeImage(Image image, PictureBox canvas, bool centerImage ) 
    {
        if (image == null || canvas == null)
        {
            return null;
        }

        int canvasWidth = canvas.Size.Width;
        int canvasHeight = canvas.Size.Height;
        int originalWidth = image.Size.Width;
        int originalHeight = image.Size.Height;

        System.Drawing.Image thumbnail =
            new Bitmap(canvasWidth, canvasHeight); // changed parm names
        System.Drawing.Graphics graphic =
                     System.Drawing.Graphics.FromImage(thumbnail);

        graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
        graphic.SmoothingMode = SmoothingMode.HighQuality;
        graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
        graphic.CompositingQuality = CompositingQuality.HighQuality;

        /* ------------------ new code --------------- */

        // Figure out the ratio
        double ratioX = (double)canvasWidth / (double)originalWidth;
        double ratioY = (double)canvasHeight / (double)originalHeight;
        double ratio = ratioX < ratioY ? ratioX : ratioY; // use whichever multiplier is smaller

        // now we can get the new height and width
        int newHeight = Convert.ToInt32(originalHeight * ratio);
        int newWidth = Convert.ToInt32(originalWidth * ratio);

        // Now calculate the X,Y position of the upper-left corner 
        // (one of these will always be zero)
        int posX = Convert.ToInt32((canvasWidth - (image.Width * ratio)) / 2);
        int posY = Convert.ToInt32((canvasHeight - (image.Height * ratio)) / 2);

        if (!centerImage)
        {
            posX = 0;
            posY = 0;
        }
        graphic.Clear(Color.White); // white padding
        graphic.DrawImage(image, posX, posY, newWidth, newHeight);

        /* ------------- end new code ---------------- */

        System.Drawing.Imaging.ImageCodecInfo[] info =
                         ImageCodecInfo.GetImageEncoders();
        EncoderParameters encoderParameters;
        encoderParameters = new EncoderParameters(1);
        encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality,
                         100L);

        Stream s = new System.IO.MemoryStream();
        thumbnail.Save(s, info[1],
                          encoderParameters);

        return Image.FromStream(s);
    }

    #endregion

Here's the required includes. (Some might be needed by other code, but including all to be safe)

using System.Windows.Forms;
using System.Drawing.Drawing2D;
using System.IO;
using System.Drawing.Imaging;
using System.Text.RegularExpressions;
using System.Drawing;

How I generally use it:

 ImageUtil.ResizeImage(ImageUtil.LoadPicture( "http://someurl/img.jpg", pictureBox1, true);

Angular2 @Input to a property with get/set

@Paul Cavacas, I had the same issue and I solved by setting the Input() decorator above the getter.

  @Input('allowDays')
  get in(): any {
    return this._allowDays;
  }

  //@Input('allowDays')
  // not working
  set in(val) {
    console.log('allowDays = '+val);
    this._allowDays = val;
  }

See this plunker: https://plnkr.co/edit/6miSutgTe9sfEMCb8N4p?p=preview

How to read request body in an asp.net core webapi controller?

To those who simply want to get the content (request body) from the request:

Use the [FromBody] attribute in your controller method parameter.

[Route("api/mytest")]
[ApiController]
public class MyTestController : Controller
{
    [HttpPost]
    [Route("content")]
    public async Task<string> ReceiveContent([FromBody] string content)
    {
        // Do work with content
    }
}

As doc says: this attribute specifies that a parameter or property should be bound using the request body.

What are the proper permissions for an upload folder with PHP/Apache?

I will add that if you are using SELinux that you need to make sure the type context is tmp_t You can accomplish this by using the chcon utility

chcon -t tmp_t uploads

Javascript : Send JSON Object with Ajax?

If you`re not using jQuery then please make sure:

var json_upload = "json_name=" + JSON.stringify({name:"John Rambo", time:"2pm"});
var xmlhttp = new XMLHttpRequest();   // new HttpRequest instance 
xmlhttp.open("POST", "/file.php");
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send(json_upload);

And for the php receiving end:

 $_POST['json_name'] 

Catching access violation exceptions?

Not the exception handling mechanism, But you can use the signal() mechanism that is provided by the C.

> man signal

     11    SIGSEGV      create core image    segmentation violation

Writing to a NULL pointer is probably going to cause a SIGSEGV signal

How to upload images into MySQL database using PHP code

This is the perfect code for uploading and displaying image through MySQL database.

<html>
<body>
<form method="post" enctype="multipart/form-data">
<input type="file" name="image"/>
<input type="submit" name="submit" value="Upload"/>
</form>
<?php
    if(isset($_POST['submit']))
    {
     if(getimagesize($_FILES['image']['tmp_name'])==FALSE)
     {
        echo " error ";
     }
     else
     {
        $image = $_FILES['image']['tmp_name'];
        $image = addslashes(file_get_contents($image));
        saveimage($image);
     }
    }
    function saveimage($image)
    {
        $dbcon=mysqli_connect('localhost','root','','dbname');
        $qry="insert into tablename (name) values ('$image')";
        $result=mysqli_query($dbcon,$qry);
        if($result)
        {
            echo " <br/>Image uploaded.";
            header('location:urlofpage.php');
        }
        else
        {
            echo " error ";
        }
    }
?>
</body>
</html>

"X-UA-Compatible" content="IE=9; IE=8; IE=7; IE=EDGE"

If you support IE, for versions of Internet Explorer 8 and above, this:

<meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=7" />

Forces the browser to render as that particular version's standards. It is not supported for IE7 and below.

If you separate with semi-colon, it sets compatibility levels for different versions. For example:

<meta http-equiv="X-UA-Compatible" content="IE=7; IE=9" />

Renders IE7 and IE8 as IE7, but IE9 as IE9. It allows for different levels of backwards compatibility. In real life, though, you should only chose one of the options:

<meta http-equiv="X-UA-Compatible" content="IE=8" />

This allows for much easier testing and maintenance. Although generally the more useful version of this is using Emulate:

<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" />

For this:

<meta http-equiv="X-UA-Compatible" content="IE=Edge" />

It forces the browser the render at whatever the most recent version's standards are.

For more information, there is plenty to read about on MSDN,

Convert bytes to int?

Assuming you're on at least 3.2, there's a built in for this:

int.from_bytes( bytes, byteorder, *, signed=False )

...

The argument bytes must either be a bytes-like object or an iterable producing bytes.

The byteorder argument determines the byte order used to represent the integer. If byteorder is "big", the most significant byte is at the beginning of the byte array. If byteorder is "little", the most significant byte is at the end of the byte array. To request the native byte order of the host system, use sys.byteorder as the byte order value.

The signed argument indicates whether two’s complement is used to represent the integer.


## Examples:
int.from_bytes(b'\x00\x01', "big")                         # 1
int.from_bytes(b'\x00\x01', "little")                      # 256

int.from_bytes(b'\x00\x10', byteorder='little')            # 4096
int.from_bytes(b'\xfc\x00', byteorder='big', signed=True)  #-1024

Compare two columns using pandas

Wrap each individual condition in parentheses, and then use the & operator to combine the conditions:

df.loc[(df['one'] >= df['two']) & (df['one'] <= df['three']), 'que'] = df['one']

You can fill the non-matching rows by just using ~ (the "not" operator) to invert the match:

df.loc[~ ((df['one'] >= df['two']) & (df['one'] <= df['three'])), 'que'] = ''

You need to use & and ~ rather than and and not because the & and ~ operators work element-by-element.

The final result:

df
Out[8]: 
  one  two three que
0  10  1.2   4.2  10
1  15   70  0.03    
2   8    5     0  

ubuntu "No space left on device" but there is tons of space

It's possible that you've run out of memory or some space elsewhere and it prompted the system to mount an overflow filesystem, and for whatever reason, it's not going away.

Try unmounting the overflow partition:

umount /tmp

or

umount overflow

Force browser to refresh css, javascript, etc

Make sure this isn't happening from your DNS. For example Cloudflare has it where you can turn on development mode where it forces a purge on your stylesheets and images as Cloudflare offers accelerated cache. This will disable it and force it to update everytime someone visits your site.

What does "to stub" mean in programming?

Stub is a piece of code which converts the parameters during RPC (Remote procedure call).The parameters of RPC have to be converted because both client and server use different address space. Stub performs this conversion so that server perceive the RPC as a local function call.

How to change text color and console color in code::blocks?

You can also use rlutil:

  • cross platform,
  • header only (rlutil.h),
  • works for C and C++,
  • implements setColor(), cls(), getch(), gotoxy(), etc.
  • License: WTFPL

Your code would become something like this:

#include <stdio.h>

#include "rlutil.h"

int main(int argc, char* argv[])
{
    setColor(BLUE);
    printf("\n \n \t This is dummy program for text color ");
    getch();

    return 0;
}

Have a look at example.c and test.cpp for C and C++ examples.

sudo echo "something" >> /etc/privilegedFile doesn't work

sudo sh -c "echo 127.0.0.1 localhost >> /etc/hosts"

How can I implement custom Action Bar with custom buttons in Android?

enter image description here

This is pretty much as close as you'll get if you want to use the ActionBar APIs. I'm not sure you can place a colorstrip above the ActionBar without doing some weird Window hacking, it's not worth the trouble. As far as changing the MenuItems goes, you can make those tighter via a style. It would be something like this, but I haven't tested it.

<style name="MyTheme" parent="android:Theme.Holo.Light">
    <item name="actionButtonStyle">@style/MyActionButtonStyle</item>
</style>

<style name="MyActionButtonStyle" parent="Widget.ActionButton">
    <item name="android:minWidth">28dip</item>
</style>

Here's how to inflate and add the custom layout to your ActionBar.

    // Inflate your custom layout
    final ViewGroup actionBarLayout = (ViewGroup) getLayoutInflater().inflate(
            R.layout.action_bar,
            null);

    // Set up your ActionBar
    final ActionBar actionBar = getActionBar();
    actionBar.setDisplayShowHomeEnabled(false);
    actionBar.setDisplayShowTitleEnabled(false);
    actionBar.setDisplayShowCustomEnabled(true);
    actionBar.setCustomView(actionBarLayout);

    // You customization
    final int actionBarColor = getResources().getColor(R.color.action_bar);
    actionBar.setBackgroundDrawable(new ColorDrawable(actionBarColor));

    final Button actionBarTitle = (Button) findViewById(R.id.action_bar_title);
    actionBarTitle.setText("Index(2)");

    final Button actionBarSent = (Button) findViewById(R.id.action_bar_sent);
    actionBarSent.setText("Sent");

    final Button actionBarStaff = (Button) findViewById(R.id.action_bar_staff);
    actionBarStaff.setText("Staff");

    final Button actionBarLocations = (Button) findViewById(R.id.action_bar_locations);
    actionBarLocations.setText("HIPPA Locations");

Here's the custom layout:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:enabled="false"
    android:orientation="horizontal"
    android:paddingEnd="8dip" >

    <Button
        android:id="@+id/action_bar_title"
        style="@style/ActionBarButtonWhite" />

    <Button
        android:id="@+id/action_bar_sent"
        style="@style/ActionBarButtonOffWhite" />

    <Button
        android:id="@+id/action_bar_staff"
        style="@style/ActionBarButtonOffWhite" />

    <Button
        android:id="@+id/action_bar_locations"
        style="@style/ActionBarButtonOffWhite" />

</LinearLayout>

Here's the color strip layout: To use it, just use merge in whatever layout you inflate in setContentView.

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="@dimen/colorstrip"
    android:background="@android:color/holo_blue_dark" />

Here are the Button styles:

<style name="ActionBarButton">
    <item name="android:layout_width">wrap_content</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:background">@null</item>
    <item name="android:ellipsize">end</item>
    <item name="android:singleLine">true</item>
    <item name="android:textSize">@dimen/text_size_small</item>
</style>

<style name="ActionBarButtonWhite" parent="@style/ActionBarButton">
    <item name="android:textColor">@color/white</item>
</style>

<style name="ActionBarButtonOffWhite" parent="@style/ActionBarButton">
    <item name="android:textColor">@color/off_white</item>
</style>

Here are the colors and dimensions I used:

<color name="action_bar">#ff0d0d0d</color>
<color name="white">#ffffffff</color>
<color name="off_white">#99ffffff</color>

<!-- Text sizes -->
<dimen name="text_size_small">14.0sp</dimen>
<dimen name="text_size_medium">16.0sp</dimen>

<!-- ActionBar color strip -->
<dimen name="colorstrip">5dp</dimen>

If you want to customize it more than this, you may consider not using the ActionBar at all, but I wouldn't recommend that. You may also consider reading through the Android Design Guidelines to get a better idea on how to design your ActionBar.

If you choose to forgo the ActionBar and use your own layout instead, you should be sure to add action-able Toasts when users long press your "MenuItems". This can be easily achieved using this Gist.

How to remove leading and trailing whitespace in a MySQL field?

A general answer that I composed from your answers and from other links and it worked for me and I wrote it in a comment is:

 UPDATE FOO set FIELD2 = TRIM(Replace(Replace(Replace(FIELD2,'\t',''),'\n',''),'\r',''));

etc.

Because trim() doesn't remove all the white spaces so it's better to replace all the white spaces u want and than trim it.

Hope I could help you with sharing my answer :)

Warning as error - How to get rid of these

To treat all compiler warnings as compilation errors

  1. With a project selected in Solution Explorer, on the Project menu, click Properties.
  2. Click the Compile tab. (or Build Tab may be there)
  3. Select the Treat all warnings as errors check box. (or select the build setting and change the “treat warnings as errors” settings to true.)

and if you want to get rid of it

To disable all compiler warnings

  1. With a project selected in Solution Explorer, on the Project menu click Properties.
  2. Click the Compile tab. (or Build Tab may be there)
  3. Select the Disable all warnings check box. (or select the build setting and change the “treat warnings as errors” settings to false.)

java SSL and cert keystore

First of all, there're two kinds of keystores.

Individual and General

The application will use the one indicated in the startup or the default of the system.

It will be a different folder if JRE or JDK is running, or if you check the personal or the "global" one.

They are encrypted too

In short, the path will be like:

$JAVA_HOME/lib/security/cacerts for the "general one", who has all the CA for the Authorities and is quite important.

Default value for field in Django model

You can also use a callable in the default field, such as:

b = models.CharField(max_length=7, default=foo)

And then define the callable:

def foo():
    return 'bar'

How to get response status code from jQuery.ajax?

When your XHR request returns a Redirect response (HTTP Status 301, 302, 303, 307), the XMLHttpRequest automatically follows the redirected URL and returns the status code of that URL.

You can get the non-redirecting status codes (200, 400, 500 etc) via the status property of the xhr object.

So you cannot get the redirected location from the response header of a 301, 302, 303 or 307 request.

You might have to change your server logic to respond in a way that you can handle the redirect, rather than letting the browser do it. An example implementation.

"SSL certificate verify failed" using pip to install packages

If adding pypi.python.org as a trusted host does not work, you try adding files.pythonhosted.org. For example

python -m pip install --upgrade --trusted-host files.pythonhosted.org <package-name>

EC2 instance types's exact network performance?

Almost everything in EC2 is multi-tenant. What the network performance indicates is what priority you will have compared with other instances sharing the same infrastructure.

If you need a guaranteed level of bandwidth, then EC2 will likely not work well for you.

How to declare a Fixed length Array in TypeScript

The Tuple approach :

This solution provides a strict FixedLengthArray (ak.a. SealedArray) type signature based in Tuples.

Syntax example :

// Array containing 3 strings
let foo : FixedLengthArray<[string, string, string]> 

This is the safest approach, considering it prevents accessing indexes out of the boundaries.

Implementation :

type ArrayLengthMutationKeys = 'splice' | 'push' | 'pop' | 'shift' | 'unshift' | number
type ArrayItems<T extends Array<any>> = T extends Array<infer TItems> ? TItems : never
type FixedLengthArray<T extends any[]> =
  Pick<T, Exclude<keyof T, ArrayLengthMutationKeys>>
  & { [Symbol.iterator]: () => IterableIterator< ArrayItems<T> > }

Tests :

var myFixedLengthArray: FixedLengthArray< [string, string, string]>

// Array declaration tests
myFixedLengthArray = [ 'a', 'b', 'c' ]  // ? OK
myFixedLengthArray = [ 'a', 'b', 123 ]  // ? TYPE ERROR
myFixedLengthArray = [ 'a' ]            // ? LENGTH ERROR
myFixedLengthArray = [ 'a', 'b' ]       // ? LENGTH ERROR

// Index assignment tests 
myFixedLengthArray[1] = 'foo'           // ? OK
myFixedLengthArray[1000] = 'foo'        // ? INVALID INDEX ERROR

// Methods that mutate array length
myFixedLengthArray.push('foo')          // ? MISSING METHOD ERROR
myFixedLengthArray.pop()                // ? MISSING METHOD ERROR

// Direct length manipulation
myFixedLengthArray.length = 123         // ? READ-ONLY ERROR

// Destructuring
var [ a ] = myFixedLengthArray          // ? OK
var [ a, b ] = myFixedLengthArray       // ? OK
var [ a, b, c ] = myFixedLengthArray    // ? OK
var [ a, b, c, d ] = myFixedLengthArray // ? INVALID INDEX ERROR

(*) This solution requires the noImplicitAny typescript configuration directive to be enabled in order to work (commonly recommended practice)


The Array(ish) approach :

This solution behaves as an augmentation of the Array type, accepting an additional second parameter(Array length). Is not as strict and safe as the Tuple based solution.

Syntax example :

let foo: FixedLengthArray<string, 3> 

Keep in mind that this approach will not prevent you from accessing an index out of the declared boundaries and set a value on it.

Implementation :

type ArrayLengthMutationKeys = 'splice' | 'push' | 'pop' | 'shift' |  'unshift'
type FixedLengthArray<T, L extends number, TObj = [T, ...Array<T>]> =
  Pick<TObj, Exclude<keyof TObj, ArrayLengthMutationKeys>>
  & {
    readonly length: L 
    [ I : number ] : T
    [Symbol.iterator]: () => IterableIterator<T>   
  }

Tests :

var myFixedLengthArray: FixedLengthArray<string,3>

// Array declaration tests
myFixedLengthArray = [ 'a', 'b', 'c' ]  // ? OK
myFixedLengthArray = [ 'a', 'b', 123 ]  // ? TYPE ERROR
myFixedLengthArray = [ 'a' ]            // ? LENGTH ERROR
myFixedLengthArray = [ 'a', 'b' ]       // ? LENGTH ERROR

// Index assignment tests 
myFixedLengthArray[1] = 'foo'           // ? OK
myFixedLengthArray[1000] = 'foo'        // ? SHOULD FAIL

// Methods that mutate array length
myFixedLengthArray.push('foo')          // ? MISSING METHOD ERROR
myFixedLengthArray.pop()                // ? MISSING METHOD ERROR

// Direct length manipulation
myFixedLengthArray.length = 123         // ? READ-ONLY ERROR

// Destructuring
var [ a ] = myFixedLengthArray          // ? OK
var [ a, b ] = myFixedLengthArray       // ? OK
var [ a, b, c ] = myFixedLengthArray    // ? OK
var [ a, b, c, d ] = myFixedLengthArray // ? SHOULD FAIL

django MultiValueDictKeyError error, how do I deal with it

Another thing to remember is that request.POST['keyword'] refers to the element identified by the specified html name attribute keyword.

So, if your form is:

<form action="/login/" method="POST">
  <input type="text" name="keyword" placeholder="Search query">
  <input type="number" name="results" placeholder="Number of results">
</form>

then, request.POST['keyword'] and request.POST['results'] will contain the value of the input elements keyword and results, respectively.

inverting image in Python with OpenCV

You can use "tilde" operator to do it:

import cv2
image = cv2.imread("img.png")
image = ~image
cv2.imwrite("img_inv.png",image)

This is because the "tilde" operator (also known as unary operator) works doing a complement dependent on the type of object

for example for integers, its formula is:

x + (~x) = -1

but in this case, opencv use an "uint8 numpy array object" for its images so its range is from 0 to 255

so if we apply this operator to an "uint8 numpy array object" like this:

import numpy as np
x1 = np.array([25,255,10], np.uint8) #for example
x2 = ~x1
print (x2)

we will have as a result:

[230 0 245]

because its formula is:

x2 = 255 - x1

and that is exactly what we want to do to solve the problem.

How to scroll to an element inside a div?

You need to get the top offset of the element you'd like to scroll into view, relative to its parent (the scrolling div container):

var myElement = document.getElementById('element_within_div');
var topPos = myElement.offsetTop;

The variable topPos is now set to the distance between the top of the scrolling div and the element you wish to have visible (in pixels).

Now we tell the div to scroll to that position using scrollTop:

document.getElementById('scrolling_div').scrollTop = topPos;

If you're using the prototype JS framework, you'd do the same thing like this:

var posArray = $('element_within_div').positionedOffset();
$('scrolling_div').scrollTop = posArray[1];

Again, this will scroll the div so that the element you wish to see is exactly at the top (or if that's not possible, scrolled as far down as it can so it's visible).

key_load_public: invalid format

It seems that ssh cannot read your public key. But that doesn't matter.

You upload your public key to github, but you authenticate using your private key. See e.g. the FILES section in ssh(1).

Groovy built-in REST/HTTP client?

The simplest one got to be:

def html = "http://google.com".toURL().text

New og:image size for Facebook share?

According to facebooks best practices it is like this (2016)

Image Sizes

Use images that are at least 1200 x 630 pixels for the best display on high resolution devices. At the minimum, you should use images that are 600 x 315 pixels to display link page posts with larger images. Images can be up to 8MB in size. enter image description here

Small Images

If your image is smaller than 600 x 315 px, it will still display in the link page post, but the size will be much smaller. enter image description here

We've also redesigned link page posts so that the aspect ratio for images is the same across desktop and mobile News Feed. Try to keep your images as close to 1.91:1 aspect ratio as possible to display the full image in News Feed without any cropping.

Minimum Image Size

The minimum image size is 200 x 200 pixels. If you try to use an image smaller than this you will see an error in the Sharing Debugger.

Game Apps Images

There are two different image sizes to use for game apps:

Open Graph Stories Images appear in a square format. Image ratios for these apps should be 600 x 600 px. Non-open Graph Stories Images appear in a rectangular format. You should use a 1.91:1 image ratio, such as 600 x 314 px.

What's the point of the X-Requested-With header?

A good reason is for security - this can prevent CSRF attacks because this header cannot be added to the AJAX request cross domain without the consent of the server via CORS.

Only the following headers are allowed cross domain:

  • Accept
  • Accept-Language
  • Content-Language
  • Last-Event-ID
  • Content-Type

any others cause a "pre-flight" request to be issued in CORS supported browsers.

Without CORS it is not possible to add X-Requested-With to a cross domain XHR request.

If the server is checking that this header is present, it knows that the request didn't initiate from an attacker's domain attempting to make a request on behalf of the user with JavaScript. This also checks that the request wasn't POSTed from a regular HTML form, of which it is harder to verify it is not cross domain without the use of tokens. (However, checking the Origin header could be an option in supported browsers, although you will leave old browsers vulnerable.)

New Flash bypass discovered

You may wish to combine this with a token, because Flash running on Safari on OSX can set this header if there's a redirect step. It appears it also worked on Chrome, but is now remediated. More details here including different versions affected.

OWASP Recommend combining this with an Origin and Referer check:

This defense technique is specifically discussed in section 4.3 of Robust Defenses for Cross-Site Request Forgery. However, bypasses of this defense using Flash were documented as early as 2008 and again as recently as 2015 by Mathias Karlsson to exploit a CSRF flaw in Vimeo. But, we believe that the Flash attack can't spoof the Origin or Referer headers so by checking both of them we believe this combination of checks should prevent Flash bypass CSRF attacks. (NOTE: If anyone can confirm or refute this belief, please let us know so we can update this article)

However, for the reasons already discussed checking Origin can be tricky.

Update

Written a more in depth blog post on CORS, CSRF and X-Requested-With here.

Is it possible to use raw SQL within a Spring Repository

The @Query annotation allows to execute native queries by setting the nativeQuery flag to true.

Quote from Spring Data JPA reference docs.

Also, see this section on how to do it with a named native query.

How to make CREATE OR REPLACE VIEW work in SQL Server?

IF NOT EXISTS(select * FROM sys.views where name = 'data_VVVV ')
    BEGIN
        CREATE VIEW data_VVVV AS 
        SELECT VCV.xxxx, VCV.yyyy AS yyyy, VCV.zzzz AS zzzz FROM TABLE_A VCV
    END
ELSE
    BEGIN
        ALTER VIEW data_VVVV AS 
        SELECT VCV.xxxx, VCV.yyyy AS yyyy, VCV.zzzz AS zzzz FROM TABLE_A VCV
    END

Finding element in XDocument?

You can do it this way:

xml.Descendants().SingleOrDefault(p => p.Name.LocalName == "Name of the node to find")

where xml is a XDocument.

Be aware that the property Name returns an object that has a LocalName and a Namespace. That's why you have to use Name.LocalName if you want to compare by name.

Adding a dictionary to another

You can loop through all the Animals using foreach and put it into NewAnimals.

How to display hexadecimal numbers in C?

i use it like this:

printf("my number is 0x%02X\n",number);
// output: my number is 0x4A

Just change number "2" to any number of chars You want to print ;)

Determining the last row in a single column

I realise this is quite an old thread but it's one of the first results when searching for this problem.

There's a simple solution to this which afaik has always been available... This is also the "recommended" way of doing the same task in VBA.

var lastCell = mySheet.getRange(mySheet.getLastRow(),1).getNextDataCell(
  SpreadsheetApp.Direction.UP
);

This will return the last full cell in the column you specify in getRange(row,column), remember to add 1 to this if you want to use the first empty row.

Performance of FOR vs FOREACH in PHP

I'm not sure this is so surprising. Most people who code in PHP are not well versed in what PHP is actually doing at the bare metal. I'll state a few things, which will be true most of the time:

  1. If you're not modifying the variable, by-value is faster in PHP. This is because it's reference counted anyway and by-value gives it less to do. It knows the second you modify that ZVAL (PHP's internal data structure for most types), it will have to break it off in a straightforward way (copy it and forget about the other ZVAL). But you never modify it, so it doesn't matter. References make that more complicated with more bookkeeping it has to do to know what to do when you modify the variable. So if you're read-only, paradoxically it's better not the point that out with the &. I know, it's counter intuitive, but it's also true.

  2. Foreach isn't slow. And for simple iteration, the condition it's testing against — "am I at the end of this array" — is done using native code, not PHP opcodes. Even if it's APC cached opcodes, it's still slower than a bunch of native operations done at the bare metal.

  3. Using a for loop "for ($i=0; $i < count($x); $i++) is slow because of the count(), and the lack of PHP's ability (or really any interpreted language) to evaluate at parse time whether anything modifies the array. This prevents it from evaluating the count once.

  4. But even once you fix it with "$c=count($x); for ($i=0; $i<$c; $i++) the $i<$c is a bunch of Zend opcodes at best, as is the $i++. In the course of 100000 iterations, this can matter. Foreach knows at the native level what to do. No PHP opcodes needed to test the "am I at the end of this array" condition.

  5. What about the old school "while(list(" stuff? Well, using each(), current(), etc. are all going to involve at least 1 function call, which isn't slow, but not free. Yes, those are PHP opcodes again! So while + list + each has its costs as well.

For these reasons foreach is understandably the best option for simple iteration.

And don't forget, it's also the easiest to read, so it's win-win.

Importing Maven project into Eclipse

I want to import existing maven project into eclipse. I found 2 ways to do it, one is through running from command line mvn eclipse:eclipse and another is to install maven eclipse plugin from eclipse. What is the difference between the both and which one is preferable?

The maven-eclipse-plugin is a Maven plugin and has always been there (one of the first plugin available with Maven 1, one of the first plugin migrated to Maven 2). It has been during a long time the only decent way to integrateimport an existing maven project with Eclipse. Actually, it doesn't provide real integration, it just generates the .project and .classpath files (it has also WTP support) from a Maven project. I've used this plugin during years and was very happy with it (and very unsatisfied at this time by Eclipse plugins for Maven like m2eclipse).

The m2eclipse plugin is one of the Eclipse plugins for Maven. It's actually the first and most mature of the projects aimed at integrating Maven within the Eclipse IDE (this has not always been the case, it was not really usable ~2 years ago, see the feedback in Mevenide vs. M2Eclipse, Q for Eclipse/IAM). But, even if I do not use things like creating a Maven project from Eclipse or the POM editor or other fancy wizards, I have to say that this plugin is now totally usable, provides very smooth integration, has nice features... In other words, I finally switched to it :) I'd now recommend it to any user (advanced or beginners).

If I install maven eclipse plugin through the eclipse menu Help -> Install New Software, do I still need to modify my pom.xml to include the maven eclipse plugin in the plugins section?

This question is a bit confusing but the answer is no. With the m2eclipse plugin installed, just right-click the package explorer and Import... > Maven projects to import an existing maven project into Eclipse.

How to check for a valid Base64 encoded string

Why not just catch the exception, and return False?

This avoids additional overhead in the common case.

Can I get all methods of a class?

To know about all methods use this statement in console:

javap -cp jar-file.jar packagename.classname

or

javap class-file.class packagename.classname

or for example:

javap java.lang.StringBuffer

Run a JAR file from the command line and specify classpath

Alternatively, use the manifest to specify the class-path and main-class if you like, so then you don't need to use -cp or specify the main class. In your case it would contain lines like this:

Main-Class: com.test.App
Class-Path: lib/one.jar lib/two.jar

Unfortunately you need to spell out each jar in the manifest (not a biggie as you only do once, and you can use a script to build the file or use a build tool like ANT or Maven or Gradle). And the reference has to be a relative or absolute directory to where you run the java -jar MyJar.jar.

Then execute it with

java -jar MyJar.jar

Best way to reset an Oracle sequence to the next value in an existing column?

You can temporarily increase the cache size and do one dummy select and then reset the cache size back to 1. So for example

ALTER SEQUENCE mysequence INCREMENT BY 100;

select mysequence.nextval from dual;

ALTER SEQUENCE mysequence INCREMENT BY 1;

How to get evaluated attributes inside a custom directive

For an attribute value that needs to be interpolated in a directive that is not using an isolated scope, e.g.,

<input my-directive value="{{1+1}}">

use Attributes' method $observe:

myApp.directive('myDirective', function () {
  return function (scope, element, attr) {
    attr.$observe('value', function(actual_value) {
      element.val("value = "+ actual_value);
    })
 }
});

From the directive page,

observing interpolated attributes: Use $observe to observe the value changes of attributes that contain interpolation (e.g. src="{{bar}}"). Not only is this very efficient but it's also the only way to easily get the actual value because during the linking phase the interpolation hasn't been evaluated yet and so the value is at this time set to undefined.

If the attribute value is just a constant, e.g.,

<input my-directive value="123">

you can use $eval if the value is a number or boolean, and you want the correct type:

return function (scope, element, attr) {
   var number = scope.$eval(attr.value);
   console.log(number, number + 1);
});

If the attribute value is a string constant, or you want the value to be string type in your directive, you can access it directly:

return function (scope, element, attr) {
   var str = attr.value;
   console.log(str, str + " more");
});

In your case, however, since you want to support interpolated values and constants, use $observe.

How can I get the first two digits of a number?

Comparing the O(n) time solution with the "constant time" O(1) solution provided in other answers goes to show that if the O(n) algorithm is fast enough, n may have to get very large before it is slower than a slow O(1).

The strings version is approx. 60% faster than the "maths" version for numbers of 20 or fewer digits. They become closer only when then number of digits approaches 200 digits

# the "maths" version
import math

def first_n_digits1(num, n):
    return num // 10 ** (int(math.log(num, 10)) - n + 1)

%timeit first_n_digits1(34523452452, 2)
1.21 µs ± 75 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%timeit first_n_digits1(34523452452, 8)
1.24 µs ± 47.5 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

# 22 digits
%timeit first_n_digits1(3423234239472523452452, 2)
1.33 µs ± 59.4 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%timeit first_n_digits1(3423234239472523452452, 15)
1.23 µs ± 61.2 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

# 196 digits
%timeit first_n_digits1(3423234239472523409283475908723908723409872390871243908172340987123409871234012089172340987734507612340981344509873123401234670350981234098123140987314509812734091823509871345109871234098172340987125988123452452, 39)
1.86 µs ± 21.8 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

# The "string" verions
def first_n_digits2(num, n):
    return int(str(num)[:n])

%timeit first_n_digits2(34523452452, 2)
744 ns ± 28.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%timeit first_n_digits2(34523452452, 8)
768 ns ± 42.7 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

# 22 digits
%timeit first_n_digits2(3423234239472523452452, 2)
767 ns ± 33.6 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%timeit first_n_digits2(3423234239472523452452, 15)
830 ns ± 55.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

# 196 digits
%timeit first_n_digits2(3423234239472523409283475908723908723409872390871243908098712340987123401208917234098773450761234098134450987312340123467035098123409812314098734091823509871345109871234098172340987125988123452452, 39)
1.87 µs ± 140 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

Wait for a void async method

You don't really need to do anything manually, await keyword pauses the function execution until blah() returns.

private async void SomeFunction()
{
     var x = await LoadBlahBlah(); <- Function is not paused
     //rest of the code get's executed even if LoadBlahBlah() is still executing
}

private async Task<T> LoadBlahBlah()
{
     await DoStuff();  <- function is paused
     await DoMoreStuff();
}

T is type of object blah() returns

You can't really await a void function so LoadBlahBlah() cannot be void

MySQL query finding values in a comma separated string

If the set of colors is more or less fixed, the most efficient and also most readable way would be to use string constants in your app and then use MySQL's SET type with FIND_IN_SET('red',colors) in your queries. When using the SET type with FIND_IN_SET, MySQL uses one integer to store all values and uses binary "and" operation to check for presence of values which is way more efficient than scanning a comma-separated string.

In SET('red','blue','green'), 'red' would be stored internally as 1, 'blue' would be stored internally as 2 and 'green' would be stored internally as 4. The value 'red,blue' would be stored as 3 (1|2) and 'red,green' as 5 (1|4).

List only stopped Docker containers

Only stopped containers can be listed using:

docker ps --filter "status=exited"

or

docker ps -f "status=exited"

How to delete a file from SD card?

Also you have to give permission if you are using >1.6 SDK

uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"

in AndroidManifest.xml file

position fixed header in html

The position :fixed is differ from the other layout. Once you fixed the position for your header, keep in mind that you have to set the margin-top for the content div.

How to add empty spaces into MD markdown readme on GitHub?

After different tries, I end up to a solution since most markdown interpreter support Math environment. The following adds one white space :

$~$

And here ten:

$~~~~~~~~~~~$

How to represent a fix number of repeats in regular expression?

In Java create the pattern with Pattern p = Pattern.compile("^\\w{14}$"); for further information see the javadoc

round() doesn't seem to be rounding properly

printf the sucker.

print '%.1f' % 5.59  # returns 5.6

How do I verify that a string only contains letters, numbers, underscores and dashes?

As an alternative to using regex you could do it in Sets:

from sets import Set

allowed_chars = Set('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-')

if Set(my_little_sting).issubset(allowed_chars):
    # your action
    print True

How do I get an apk file from an Android device?

I got a does not exist error

Here is how I make it works

adb shell pm list packages -f | findstr zalo
package:/data/app/com.zing.zalo-1/base.apk=com.zing.zalo

adb shell
mido:/ $ cp /data/app/com.zing.zalo-1/base.apk /sdcard/zalo.apk
mido:/ $ exit


adb pull /sdcard/zalo.apk Desktop

/sdcard/zalo.apk: 1 file pulled. 7.7 MB/s (41895394 bytes in 5.200s)

import error: 'No module named' *does* exist

I met the same problem, and I try the pdb.set_trace() before the error line.

My problem is the package name duplicate with the module name, like:

test
+-- __init__.py
+-- a
¦   +-- __init__.py
¦   +-- test.py
+-- b
    +-- __init__.py

and at file a/__init__.py, using from test.b import xxx will cause ImportError: No module named b.

A method to reverse effect of java String.split()?

There has been an open feature request since at least 2009. The long and short of it is that it will part of the functionality of JDK 8's java.util.StringJoiner class. http://download.java.net/lambda/b81/docs/api/java/util/StringJoiner.html

Here is the Oracle issue if you are interested. http://bugs.sun.com/view_bug.do?bug_id=5015163

Here is an example of the new JDK 8 StringJoiner on an array of String

String[] a = new String[]{"first","second","third"};
StringJoiner sj = new StringJoiner(",");
for(String s:a) sj.add(s);
System.out.println(sj); //first,second,third

A utility method in String makes this even simpler:

String s = String.join(",", stringArray);

How can I get useful error messages in PHP?

You can also run the file in the Terminal (command line) like so: php -f filename.php.

This runs your code and gives you the same output in case of any errors that you'd see in the error.log. It mentions the error and the line number.

Check if a input box is empty

Quite simple:

<input ng-model="somefield">
<span ng-show="!somefield.length">Please enter something!</span>
<span ng-show="somefield.length">Good boy!</span>

You could also use ng-hide="somefield.length" instead of ng-show="!somefield.length" if that reads more naturally for you.


A better alternative might be to really take advantage of the form abilities of Angular:

<form name="myform">
  <input name="myfield" ng-model="somefield" ng-minlength="5" required>
  <span ng-show="myform.myfield.$error.required">Please enter something!</span>
  <span ng-show="!myform.myfield.$error.required">Good boy!</span>
</form> 

Updated Plnkr here.

How to find the length of an array in shell?

Assuming bash:

~> declare -a foo
~> foo[0]="foo"
~> foo[1]="bar"
~> foo[2]="baz"
~> echo ${#foo[*]}
3

So, ${#ARRAY[*]} expands to the length of the array ARRAY.

What is the preferred Bash shebang?

#!/bin/sh

as most scripts do not need specific bash feature and should be written for sh.

Also, this makes scripts work on the BSDs, which do not have bash per default.

Django: TemplateSyntaxError: Could not parse the remainder

Template Syntax Error: is due to many reasons one of them is {{ post.date_posted|date: "F d, Y" }} is the space between colon(:) and quote (") if u remove the space then it work like this ..... {{ post.date_posted|date:"F d, Y" }}

Switch case in C# - a constant value is expected

Now you can use nameof:

public static void Output<T>(IEnumerable<T> dataSource) where T : class
{
    string dataSourceName = typeof(T).Name;
    switch (dataSourceName)
    {
        case nameof(CustomerDetails):
            var t = 123;
            break;
        default:
            Console.WriteLine("Test");
    }
}

nameof(CustomerDetails) is basically identical to the string literal "CustomerDetails", but with a compile-time check that it refers to some symbol (to prevent a typo).

nameof appeared in C# 6.0, so after this question was asked.

Converting JSONarray to ArrayList

if you want to extract data form JSON string array, here is my working code. change parameter as your data.


PoJo class

public class AllAppModel {
    private String appName;
    private String packageName;
    private int uid;
    private boolean isSelected;
    private boolean isSystemApp;
    private boolean isFav;
}

Extract your data using below line of code

try {
    JSONArray jsonArr = new JSONArray("Your json string array");
    List<AllAppModel> lstExtrextData = new ArrayList<>();
    for (int i = 0; i < jsonArr.length(); i++) {
        JSONObject jsonObj = jsonArr.getJSONObject(i);
        AllAppModel data = new AllAppModel();
        data.setAppName(jsonObj.getString("appName"));
        data.setPackageName(jsonObj.getString("packageName"));
        data.setUid(jsonObj.getInt("uid"));
        data.setSelected(jsonObj.getBoolean("isSelected"));
        data.setSystemApp(jsonObj.getBoolean("isSystemApp"));
        data.setFav(jsonObj.getBoolean("isFav"));
        lstExtrextData.add(data);
    }
} catch (JSONException e) {
    e.printStackTrace();
}

it will return you List of PoJo class object.

How can I make an EXE file from a Python program?

py2exe:

py2exe is a Python Distutils extension which converts Python scripts into executable Windows programs, able to run without requiring a Python installation.

Android; Check if file exists without creating a new one

The methods in the Path class are syntactic, meaning that they operate on the Path instance. But eventually you must access the file system to verify that a particular Path exists

 File file = new File("FileName");
 if(file.exists()){
 System.out.println("file is already there");
 }else{
 System.out.println("Not find file ");
 }

How do I add slashes to a string in Javascript?

replace works for the first quote, so you need a tiny regular expression:

str = str.replace(/'/g, "\\'");

My docker container has no internet

I also encountered such an issue while trying to set up a project using Docker-Compose on Ubuntu.

The Docker had no access to internet at all, when I tried to ping any IP address or nslookup some URL - it failed all the time.

I tried all the possible solutions with DNS resolution described above to no avail.

I spent the whole day trying to find out what the heck is going on, and finally found out that the cause of all the trouble was the antivirus, in particular it's firewall which for some reason blocked Docker from getting the IP address and port.

When I disabled it - everything worked fine.

So, if you have an antivirus installed and nothing helps fix the issue - the problem could be the firewall of the antivirus.

'Missing recommended icon file - The bundle does not contain an app icon for iPhone / iPod Touch of exactly '120x120' pixels, in .png format'

For any Xamarin.iOS or Xamarin.Forms developers, additionally you will want to check the .csproj file (for the iOS project) and ensure that it contains references to the PNG's and not just the Asset Catalog i.e.

<ItemGroup>
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Contents.json" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon-40.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon-40%402x.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon-40%403x.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon-60%402x.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon-60%403x.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon-72.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon-72%402x.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon-76.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon-76%402x.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon-83.5%402x.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon-Small-50.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon-Small-50%402x.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon-Small.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon-Small%402x.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon-Small%403x.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon%402x.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\NotificationIcon%402x.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\NotificationIcon%403x.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\NotificationIcon~ipad.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\NotificationIcon~ipad%402x.png" />
</ItemGroup>

Can a java lambda have more than 1 parameter?

To make the use of lambda : There are three type of operation:
1. Accept parameter --> Consumer
2. Test parameter return boolean --> Predicate
3. Manipulate parameter and return value --> Function

Java Functional interface upto two parameter:
Single parameter interface
Consumer
Predicate
Function

Two parameter interface
BiConsumer
BiPredicate
BiFunction

For more than two, you have to create functional interface as follow(Consumer type):

@FunctionalInterface
public interface FiveParameterConsumer<T, U, V, W, X> {
    public void accept(T t, U u, V v, W w, X x);
}

Removing empty lines in Notepad++

Well I'm not sure about the regex or your situation..

How about CTRL+A, Select the TextFX menu -> TextFX Edit -> Delete Blank Lines and viola all blank line gone.

A side note - if the line is blank i.e. does not contain spaces, this will work

Set Memory Limit in htaccess

In your .htaccess you can add:

PHP 5.x

<IfModule mod_php5.c>
    php_value memory_limit 64M
</IfModule>

PHP 7.x

<IfModule mod_php7.c>
    php_value memory_limit 64M
</IfModule>

If page breaks again, then you are using PHP as mod_php in apache, but error is due to something else.

If page does not break, then you are using PHP as CGI module and therefore cannot use php values - in the link I've provided might be solution but I'm not sure you will be able to apply it.

Read more on http://support.tigertech.net/php-value

How do I change the font-size of an <option> element within <select>?

.service-small option {
    font-size: 14px;
    padding: 5px;
    background: #5c5c5c;
}

I think it because you used .styled-select in start of the class code.

How can I represent 'Authorization: Bearer <token>' in a Swagger Spec (swagger.json)

My Hackie way to solve this was by modifying the swagger.go file in the echo-swagger package in my case:

At the bottom of the file update the window.onload function to include a requestInterceptor which correctly formats the token.

window.onload = function() {
  // Build a system
  const ui = SwaggerUIBundle({
  url: "{{.URL}}",
  dom_id: '#swagger-ui',
  validatorUrl: null,
  presets: [
    SwaggerUIBundle.presets.apis,
    SwaggerUIStandalonePreset
  ],
  plugins: [
    SwaggerUIBundle.plugins.DownloadUrl
  ,
  layout: "StandaloneLayout",
  requestInterceptor: (req) => {
    req.headers.Authorization = "Bearer " + req.headers.Authorization
  return req
  }
})

window.ui = ui

}

sql query with multiple where statements

This..

(
        (meta_key = 'lat' AND meta_value >= '60.23457047672217')
    OR
        (meta_key = 'lat' AND meta_value <= '60.23457047672217')
)

is the same as

(
        (meta_key = 'lat')
)

Adding it all together (the same applies to the long filter) you have this impossible WHERE clause which will give no rows because meta_key cannot be 2 values in one row

WHERE
    (meta_key = 'lat' AND meta_key = 'long' )

You need to review your operators to make sure you get the correct logic

jQuery textbox change event

The change event only fires after the input loses focus (and was changed).

RelativeLayout center vertical

This is working for me.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rell_main_bg"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#096d74" > 

<ImageView 
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true"
    android:src="@drawable/img_logo_large"
    android:contentDescription="@null" />

</RelativeLayout>

How can I read Chrome Cache files?

I had some luck with this open-source Python project, seemingly inactive: https://github.com/JRBANCEL/Chromagnon

I ran:

python2 Chromagnon/chromagnonCache.py path/to/Chrome/Cache -o browsable_cache/

And I got a locally-browsable extract of all my open tabs cache.

How do I view the SQL generated by the Entity Framework?

I am doing integration test, and needed this to debug the generated SQL statement in Entity Framework Core 2.1, so I use DebugLoggerProvider or ConsoleLoggerProvider like so:

[Fact]
public async Task MyAwesomeTest
    {
        //setup log to debug sql queries
        var loggerFactory = new LoggerFactory();
        loggerFactory.AddProvider(new DebugLoggerProvider());
        loggerFactory.AddProvider(new ConsoleLoggerProvider(new ConsoleLoggerSettings()));

        var builder = new DbContextOptionsBuilder<DbContext>();
        builder
            .UseSqlServer("my connection string") //"Server=.;Initial Catalog=TestDb;Integrated Security=True"
            .UseLoggerFactory(loggerFactory);

        var dbContext = new DbContext(builder.Options);

        ........

Here is a sample output from Visual Studio console:

Sample SQL statement output

Java 8 Stream and operation on arrays

You can turn an array into a stream by using Arrays.stream():

int[] ns = new int[] {1,2,3,4,5};
Arrays.stream(ns);

Once you've got your stream, you can use any of the methods described in the documentation, like sum() or whatever. You can map or filter like in Python by calling the relevant stream methods with a Lambda function:

Arrays.stream(ns).map(n -> n * 2);
Arrays.stream(ns).filter(n -> n % 4 == 0);

Once you're done modifying your stream, you then call toArray() to convert it back into an array to use elsewhere:

int[] ns = new int[] {1,2,3,4,5};
int[] ms = Arrays.stream(ns).map(n -> n * 2).filter(n -> n % 4 == 0).toArray();

mysql datatype for telephone number and address

Well, personally I do not use numeric datatype to store phone numbers or related info.

How do you store a number say 001234567? It'll end up as 1234567, losing the leading zeros.

Of course you can always left-pad it up, but that's provided you know exactly how many digits the number should be.

This doesn't answer your entire post,
Just my 2 cents

Struct like objects in Java

A very-very old question, but let me make another short contribution. Java 8 introduced lambda expressions and method references. Lambda expressions can be simple method references and not declare a "true" body. But you cannot "convert" a field into a method reference. Thus

stream.mapToInt(SomeData1::x)

isn't legal, but

stream.mapToInt(SomeData2::getX)

is.

HTML5 Video Autoplay not working correctly

Mobile browsers generally ignore this attribute to prevent consuming data until user explicitly starts the download.

UPDATE: newer version of mobile browser on Android and iOS do support autoplay function. But it only works if the video is muted or has no audio channel:

Some additional info: https://webkit.org/blog/6784/new-video-policies-for-ios/

Open a URL without using a browser from a batch file

You can try put in a shortcut to the site and tell the .bat file to open that.

start Google.HTML
exit

How to remove all files from directory without removing directory in Node.js

Building on @Waterscroll's response, if you want to use async and await in node 8+:

const fs = require('fs');
const util = require('util');
const readdir = util.promisify(fs.readdir);
const unlink = util.promisify(fs.unlink);
const directory = 'test';

async function toRun() {
  try {
    const files = await readdir(directory);
    const unlinkPromises = files.map(filename => unlink(`${directory}/${filename}`));
    return Promise.all(unlinkPromises);
  } catch(err) {
    console.log(err);
  }
}

toRun();

create table in postgreSQL

Replace bigint(20) not null auto_increment by bigserial not null and datetime by timestamp

How do I apply a diff patch on Windows?

I know you said you would prefer a GUI, but the commandline tools will do the work nicely. See GnuWin for a port of unix tools to Windows. You'd need the patch command, obviously ;-)

You might run into a problem with the line termination, though. The GnuWin port will assume that the patchfile has DOS style line termination (CR/LF). Try to open the patchfile in a reasonably smart editor and it will convert it for you.

How to perform case-insensitive sorting in JavaScript?

ES6 version:

["Foo", "bar"].sort((a, b) => a.localeCompare(b, 'en', { sensitivity: 'base' }))

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare

Installing specific package versions with pip

This below command worked for me

Python version - 2.7

package - python-jenkins

command - $ pip install 'python-jenkins>=1.1.1'

How to force HTTPS using a web.config file

To augment LazyOne's answer, here is an annotated version of the answer.

<rewrite>
  <rules>
     <clear />
     <rule name="Redirect all requests to https" stopProcessing="true">
       <match url="(.*)" />
         <conditions logicalGrouping="MatchAll">
           <add input="{HTTPS}" pattern="off" ignoreCase="true" />
         </conditions>
         <action 
            type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" 
            redirectType="Permanent" appendQueryString="false" />
     </rule>
  </rules>
</rewrite>

Clear all the other rules that might already been defined on this server. Create a new rule, that we will name "Redirect all requests to https". After processing this rule, do not process any more rules! Match all incoming URLs. Then check whether all of these other conditions are true: HTTPS is turned OFF. Well, that's only one condition (but make sure it's true). If it is, send a 301 Permanent redirect back to the client at http://www.foobar.com/whatever?else=the#url-contains. Don't add the query string at the end of that, because it would duplicate the query string!

This is what the properties, attributes, and some of the values mean.

  • clear removes all server rules that we might otherwise inherit.
  • rule defines a rule.
    • name an arbitrary (though unique) name for the rule.
    • stopProcessing whether to forward the request immediately to the IIS request pipeline or first to process additional rules.
  • match when to run this rule.
    • url a pattern against which to evaluate the URL
  • conditions additional conditions about when to run this rule; conditions are processed only if there is first a match.
    • logicalGrouping whether all the conditions must be true (MatchAll) or any of the conditions must be true (MatchAny); similar to AND vs OR.
  • add adds a condition that must be met.
    • input the input that a condition is evaluating; input can be server variables.
    • pattern the standard against which to evaluate the input.
    • ignoreCase whether capitalization matters or not.
  • action what to do if the match and its conditions are all true.
    • type can generally be redirect (client-side) or rewrite (server-side).
    • url what to produce as a result of this rule; in this case, concatenate https:// with two server variables.
    • redirectType what HTTP redirect to use; this one is a 301 Permanent.
    • appendQueryString whether to add the query string at the end of the resultant url or not; in this case, we are setting it to false, because the {REQUEST_URI} already includes it.

The server variables are

  • {HTTPS} which is either OFF or ON.
  • {HTTP_HOST} is www.mysite.com, and
  • {REQUEST_URI} includes the rest of the URI, e.g. /home?key=value
    • the browser handles the #fragment (see comment from LazyOne).

See also: https://www.iis.net/learn/extensions/url-rewrite-module/url-rewrite-module-configuration-reference

Cannot open Windows.h in Microsoft Visual Studio

If you already haven't done it, try adding "SDK Path\Include" to:

Project ? Preferences ? C/C++ ? General ? Additional Include Directories

And add "SDK Path\Lib" to:

Project ? Preferences ? Linker ? General ? Additional Library Directories

Also, try to change "Windows.h" to <windows.h>

If won't help, check the physical existence of the file, it should be in "\VC\PlatformSDK\Include" folder in your Visual Studio install directory.

How to find Oracle Service Name

With SQL Developer you should also find it without writing any query. Right click on your Connection/Propriety.

You should see the name on the left under something like "connection details" and should look like "Connectionname@servicename", or on the right, under the connection's details.

Fix columns in horizontal scrolling

Demo: http://www.jqueryscript.net/demo/jQuery-Plugin-For-Fixed-Table-Header-Footer-Columns-TableHeadFixer/

HTML

<h2>TableHeadFixer Fix Left Column</h2>

<div id="parent">
    <table id="fixTable" class="table">
        <thead>
            <tr>
                <th>Ano</th>
                <th>Jan</th>
                <th>Fev</th>
                <th>Mar</th>
                <th>Abr</th>
                <th>Maio</th>
                <th>Total</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>2012</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>550.00</td>
            </tr>
            <tr>
                <td>2012</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>550.00</td>
            </tr>
            <tr>
                <td>2012</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>550.00</td>
            </tr>
            <tr>
                <td>2012</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>550.00</td>
            </tr>
            <tr>
                <td>2012</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>550.00</td>
            </tr>
        </tbody>
    </table>
</div>

JS

    $(document).ready(function() {
        $("#fixTable").tableHeadFixer({"head" : false, "right" : 1}); 
    });

CSS

    #parent {
        height: 300px;
    }

    #fixTable {
        width: 1800px !important;
    }

https://jsfiddle.net/5gfuqqc4/

Returning Arrays in Java

If you want to use the numbers method, you need an int array to store the returned value.

public static void main(String[] args){
    int[] someNumbers = numbers();
    //do whatever you want with them...
    System.out.println(Arrays.toString(someNumbers));
}

PHP Composer update "cannot allocate memory" error (using Laravel 4)

Please disable js bundling and increase memory. That should fix it. I fixed mine by disabling js bundling.

Thanks

Converting String Array to an Integer Array

Stream.of().mapToInt().toArray() seems to be the best options.

int[] arr = Stream.of(new String[]{"1", "2", "3"})
                  .mapToInt(Integer::parseInt).toArray();
System.out.println(Arrays.toString(arr));

How can I do an OrderBy with a dynamic string parameter?

Absolutely. You can use the LINQ Dynamic Query Library, found on Scott Guthrie's blog. There's also an updated version available on CodePlex.

It lets you create OrderBy clauses, Where clauses, and just about everything else by passing in string parameters. It works great for creating generic code for sorting/filtering grids, etc.

var result = data
    .Where(/* ... */)
    .Select(/* ... */)
    .OrderBy("Foo asc");

var query = DbContext.Data
    .Where(/* ... */)
    .Select(/* ... */)
    .OrderBy("Foo ascending");

How to make an Android device vibrate? with different frequency?

Kotlin update for more type safety

Use it as a top level function in some common class of your project such as Utils.kt

// Vibrates the device for 100 milliseconds.
fun vibrateDevice(context: Context) {
    val vibrator = getSystemService(context, Vibrator::class.java)
    vibrator?.let {
        if (Build.VERSION.SDK_INT >= 26) {
            it.vibrate(VibrationEffect.createOneShot(100, VibrationEffect.DEFAULT_AMPLITUDE))
        } else {
            @Suppress("DEPRECATION")
            it.vibrate(100)
        }
    }
}

And then call it anywhere in your code as following:

vibrateDevice(requireContext())

Explanation

Using Vibrator::class.java is more type safe than using String constants.

We check the vibrator for nullability using let { }, because if the vibration is not available for the device, the vibrator will be null.

It's ok to supress deprecation in else clause, because the warning is from newer SDK.

We don't need to ask for permission at runtime for using vibration. But we need to declare it in AndroidManifest.xml as following:

<uses-permission android:name="android.permission.VIBRATE"/>

X-UA-Compatible is set to IE=edge, but it still doesn't stop Compatibility Mode

Even if you have unchecked the "Display intranet sites in Compatibility View" option, and have the X-UA-Compatible in your response headers, there is another reason why your browser might default to "Compatibility View" anyways - your Group Policy. Look at your console for the following message:

HTML1203: xxx.xxx has been configured to run in Compatibility View through Group Policy.

Where xxx.xxx is the domain for your site (i.e. test.com). If you see this then the group policy for your domain is set so that any site ending in test.com will automatically render in Compatibility mode regardless of doctype, headers, etc.

For more information, please see the following link (explains the html codes): http://msdn.microsoft.com/en-us/library/ie/hh180764(v=vs.85).aspx

Switching between GCC and Clang/LLVM using CMake

System wide C change on Ubuntu:

sudo update-alternatives --config cc

System wide C++ change on Ubuntu:

sudo update-alternatives --config c++

For each of the above, press Selection number (1) and Enter to select Clang:

  Selection    Path            Priority   Status
------------------------------------------------------------
* 0            /usr/bin/gcc     20        auto mode
  1            /usr/bin/clang   10        manual mode
  2            /usr/bin/gcc     20        manual mode
Press enter to keep the current choice[*], or type selection number:

Create HTML table using Javascript

This beautiful code here creates a table with each td having array values. Not my code, but it helped me!

var rows = 6, cols = 7;

for(var i = 0; i < rows; i++) {
  $('table').append('<tr></tr>');
  for(var j = 0; j < cols; j++) {
    $('table').find('tr').eq(i).append('<td></td>');
    $('table').find('tr').eq(i).find('td').eq(j).attr('data-row', i).attr('data-col', j);
  }
}

How to make a GUI for bash scripts?

Please, take a look at my library: http://sites.google.com/site/easybashgui

It is intended to handle, with the same commands set, indifferently all four big tools "kdialog", "Xdialog", "cdialog" and "zenity", depending if X is running or not, if D.E. is KDE or Gnome or other. There are 15 different functions ( among them there are two called "progress" and "adjust" )...

Bye :-)

How to find the duration of difference between two dates in java?

As Michael Borgwardt writes in his answer here:

int diffInDays = (int)( (newerDate.getTime() - olderDate.getTime()) 
                 / (1000 * 60 * 60 * 24) )

Note that this works with UTC dates, so the difference may be a day off if you look at local dates. And getting it to work correctly with local dates requires a completely different approach due to daylight savings time.

What does "<>" mean in Oracle

It means not equal to

Should I use != or <> for not equal in TSQL?

Have a look at the link. It has detailed explanation of what to use for what.

How to fix error "ERROR: Command errored out with exit status 1: python." when trying to install django-heroku using pip

You need to add the package containing the executable pg_config.

A prior answer should have details you need: pg_config executable not found

VBA Subscript out of range - error 9

Subscript out of Range error occurs when you try to reference an Index for a collection that is invalid.

Most likely, the index in Windows does not actually include .xls. The index for the window should be the same as the name of the workbook displayed in the title bar of Excel.

As a guess, I would try using this:

Windows("Data Sheet - " & ComboBox_Month.Value & " " & TextBox_Year.Value).Activate

Can "git pull --all" update all my local branches?

There are a lot of answers here but none that use git-fetch to update the local ref directly, which is a lot simpler than checking out branches, and safer than git-update-ref.

Here we use git-fetch to update non-current branches and git pull --ff-only for the current branch. It:

  • Doesn't require checking out branches
  • Updates branches only if they can be fast-forwarded
  • Will report when it can't fast-forward

and here it is:

#!/bin/bash
currentbranchref="$(git symbolic-ref HEAD 2>&-)"
git branch -r | grep -v ' -> ' | while read remotebranch
do
    # Split <remote>/<branch> into remote and branchref parts
    remote="${remotebranch%%/*}"
    branchref="refs/heads/${remotebranch#*/}"

    if [ "$branchref" == "$currentbranchref" ]
    then
        echo "Updating current branch $branchref from $remote..."
        git pull --ff-only
    else
        echo "Updating non-current ref $branchref from $remote..."
        git fetch "$remote" "$branchref:$branchref"
    fi
done

From the manpage for git-fetch:

   <refspec>
       The format of a <refspec> parameter is an optional plus +, followed by the source ref <src>,
       followed by a colon :, followed by the destination ref <dst>.

       The remote ref that matches <src> is fetched, and if <dst> is not empty string, the local ref
       that matches it is fast-forwarded using <src>. If the optional plus + is used, the local ref is
       updated even if it does not result in a fast-forward update.

By specifying git fetch <remote> <ref>:<ref> (without any +) we get a fetch that updates the local ref only when it can be fast-forwarded.

Note: this assumes the local and remote branches are named the same (and that you want to track all branches), it should really use information about which local branches you have and what they are set up to track.

How to reset selected file with input tag file type in Angular 2?

Short version Plunker:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `
      <input #myInput type="file" placeholder="File Name" name="filename">
      <button (click)="myInput.value = ''">Reset</button>
  `
})
export class AppComponent {


}

And i think more common case is to not using button but do reset automatically. Angular Template statements support chaining expressions so Plunker:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `
      <input #myInput type="file" (change)="onChange(myInput.value, $event); myInput.value = ''" placeholder="File Name" name="filename">
  `
})
export class AppComponent {

  onChange(files, event) {
    alert( files );
    alert( event.target.files[0].name );
  }

}

And interesting link about why there is no recursion on value change.

C++ pass an array by reference

Yes, but when argument matching for a reference, the implicit array to pointer isn't automatic, so you need something like:

void foo( double (&array)[42] );

or

void foo( double (&array)[] );

Be aware, however, that when matching, double [42] and double [] are distinct types. If you have an array of an unknown dimension, it will match the second, but not the first, and if you have an array with 42 elements, it will match the first but not the second. (The latter is, IMHO, very counter-intuitive.)

In the second case, you'll also have to pass the dimension, since there's no way to recover it once you're inside the function.

Java : Sort integer array without using Arrays.sort()

Simple sorting algorithm Bubble sort:

public static void main(String[] args) {
    int[] arr = new int[] { 6, 8, 7, 4, 312, 78, 54, 9, 12, 100, 89, 74 };

    for (int i = 0; i < arr.length; i++) {
        for (int j = i + 1; j < arr.length; j++) {
            int tmp = 0;
            if (arr[i] > arr[j]) {
                tmp = arr[i];
                arr[i] = arr[j];
                arr[j] = tmp;
            }
        }
    }
}

PHP: convert spaces in string into %20?

The plus sign is the historic encoding for a space character in URL parameters, as documented in the help for the urlencode() function.

That same page contains the answer you need - use rawurlencode() instead to get RFC 3986 compatible encoding.

Check for database connection, otherwise display message

Try this:

<?php
$servername   = "localhost";
$database = "database";
$username = "user";
$password = "password";

// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
   die("Connection failed: " . $conn->connect_error);
}
  echo "Connected successfully";
?>

JQuery get data from JSON array

try this

$.getJSON(url, function(data){
    $.each(data.response.venue.tips.groups.items, function (index, value) {
        console.log(this.text);
    });
});

What exactly does a jar file contain?

JD-GUI is a very handy tool for browsing and decompiling JARs

Does Python support short-circuiting?

Yes. Try the following in your python interpreter:

and

>>>False and 3/0
False
>>>True and 3/0
ZeroDivisionError: integer division or modulo by zero

or

>>>True or 3/0
True
>>>False or 3/0
ZeroDivisionError: integer division or modulo by zero

Java - How to convert type collection into ArrayList?

More information needed for a definitive answer, but this code

myNodeList = (ArrayList<MyNode>)this.getVertices();

will only work if this.getVertices() returns a (subtype of) List<MyNode>. If it is a different collection (like your Exception seems to indicate), you want to use

new ArrayList<MyNode>(this.getVertices())

This will work as long as a Collection type is returned by getVertices.

C#: How to make pressing enter in a text box trigger a button, yet still allow shortcuts such as "Ctrl+A" to get through?

If you want the return to trigger an action only when the user is in the textbox, you can assign the desired button the AcceptButton control, like this.

    private void textBox_Enter(object sender, EventArgs e)
    {
        ActiveForm.AcceptButton = Button1; // Button1 will be 'clicked' when user presses return
    }

    private void textBox_Leave(object sender, EventArgs e)
    {
        ActiveForm.AcceptButton = null; // remove "return" button behavior
    }

How can I enable MySQL's slow query log without restarting MySQL?

This should work on mysql > 5.5

SHOW VARIABLES LIKE '%long%';

SET GLOBAL long_query_time = 1;

Convert string to integer type in Go?

If you control the input data, you can use the mini version

package main

import (
    "testing"
    "strconv"
)

func Atoi (s string) int {
    var (
        n uint64
        i int
        v byte
    )   
    for ; i < len(s); i++ {
        d := s[i]
        if '0' <= d && d <= '9' {
            v = d - '0'
        } else if 'a' <= d && d <= 'z' {
            v = d - 'a' + 10
        } else if 'A' <= d && d <= 'Z' {
            v = d - 'A' + 10
        } else {
            n = 0; break        
        }
        n *= uint64(10) 
        n += uint64(v)
    }
    return int(n)
}

func BenchmarkAtoi(b *testing.B) {
    for i := 0; i < b.N; i++ {
        in := Atoi("9999")
        _ = in
    }   
}

func BenchmarkStrconvAtoi(b *testing.B) {
    for i := 0; i < b.N; i++ {
        in, _ := strconv.Atoi("9999")
        _ = in
    }   
}

the fastest option (write your check if necessary). Result :

Path>go test -bench=. atoi_test.go
goos: windows
goarch: amd64
BenchmarkAtoi-2                 100000000               14.6 ns/op
BenchmarkStrconvAtoi-2          30000000                51.2 ns/op
PASS
ok      path     3.293s

How can I read the contents of an URL with Python?

I used the following code:

import urllib

def read_text():
      quotes = urllib.urlopen("https://s3.amazonaws.com/udacity-hosted-downloads/ud036/movie_quotes.txt")
      contents_file = quotes.read()
      print contents_file

read_text()

How can I convert byte size into a human-readable format in Java?

FileUtils.byteCountToDisplaySize(long size) would work if your project can depend on org.apache.commons.io.

JavaDoc for this method

C# Java HashMap equivalent

the answer is

Dictionary

take look at my function, its simple add uses most important member functions inside Dictionary

this function return false if the list contain Duplicates items

 public static bool HasDuplicates<T>(IList<T> items)
    {
        Dictionary<T, bool> mp = new Dictionary<T, bool>();
        for (int i = 0; i < items.Count; i++)
        {
            if (mp.ContainsKey(items[i]))
            {
                return true; // has duplicates
            }
            mp.Add(items[i], true);
        }
        return false; // no duplicates
    }

Can MySQL convert a stored UTC time to local timezone?

I am not sure what math can be done on a DATETIME data type, but if you are using PHP, I strongly recommend using the integer-based timestamps. Basically, you can store a 4-byte integer in the database using PHP's time() function. This makes doing math on it much more straightforward.

Altering user-defined table types in SQL Server

If you can use a Database project in Visual Studio, you can make your changes in the project and use schema compare to synchronize the changes to your database.

This way, dropping and recreating the dependent objects is handled by the change script.

Wait till a Function with animations is finished until running another Function

You can use the javascript Promise and async/await to implement a synchronized call of the functions.

Suppose you want to execute n number of functions in a synchronized manner that are stored in an array, here is my solution for that.

_x000D_
_x000D_
async function executeActionQueue(funArray) {_x000D_
  var length = funArray.length;_x000D_
  for(var i = 0; i < length; i++) {_x000D_
    await executeFun(funArray[i]);_x000D_
  }_x000D_
};_x000D_
_x000D_
function executeFun(fun) {_x000D_
  return new Promise((resolve, reject) => {_x000D_
    _x000D_
    // Execute required function here_x000D_
    _x000D_
    fun()_x000D_
      .then((data) => {_x000D_
        // do required with data _x000D_
        resolve(true);_x000D_
      })_x000D_
      .catch((error) => {_x000D_
      // handle error_x000D_
        resolve(true);_x000D_
      });_x000D_
  })_x000D_
};_x000D_
_x000D_
executeActionQueue(funArray);
_x000D_
_x000D_
_x000D_

Erase the current printed console line

under windows 10 one can use VT100 style by activating the VT100 mode in the current console to use escape sequences as follow :

#include <windows.h>
#include <iostream>

#define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
#define DISABLE_NEWLINE_AUTO_RETURN  0x0008

int main(){

  // enabling VT100 style in current console
  DWORD l_mode;
  HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
  GetConsoleMode(hStdout,&l_mode)
  SetConsoleMode( hStdout, l_mode |
            ENABLE_VIRTUAL_TERMINAL_PROCESSING |
            DISABLE_NEWLINE_AUTO_RETURN );

  // create a waiting loop with changing text every seconds
  while(true) {
    // erase current line and go to line begining 
    std::cout << "\x1B[2K\r";
    std::cout << "wait a second .";
    Sleep(1);
    std::cout << "\x1B[2K\r";
    std::cout << "wait a second ..";
    Sleep(1);
    std::cout << "\x1B[2K\r";
    std::cout << "wait a second ...";
    Sleep(1);
    std::cout << "\x1B[2K\r";
    std::cout << "wait a second ....";
 }

}

see following link : windows VT100

Code to loop through all records in MS Access

You should be able to do this with a pretty standard DAO recordset loop. You can see some examples at the following links:
http://msdn.microsoft.com/en-us/library/bb243789%28v=office.12%29.aspx
http://www.granite.ab.ca/access/email/recordsetloop.htm

My own standard loop looks something like this:

Dim rs As DAO.Recordset
Set rs = CurrentDb.OpenRecordset("SELECT * FROM Contacts")

'Check to see if the recordset actually contains rows
If Not (rs.EOF And rs.BOF) Then
    rs.MoveFirst 'Unnecessary in this case, but still a good habit
    Do Until rs.EOF = True
        'Perform an edit
        rs.Edit
        rs!VendorYN = True
        rs("VendorYN") = True 'The other way to refer to a field
        rs.Update

        'Save contact name into a variable
        sContactName = rs!FirstName & " " & rs!LastName

        'Move to the next record. Don't ever forget to do this.
        rs.MoveNext
    Loop
Else
    MsgBox "There are no records in the recordset."
End If

MsgBox "Finished looping through records."

rs.Close 'Close the recordset
Set rs = Nothing 'Clean up

Is it possible to use a div as content for Twitter's Popover

All of these answers miss a very important aspect!

By using .html or innerHtml or outerHtml you are not actually using the referenced element. You are using a copy of the element's html. This has some serious draw backs.

  1. You can't use any ids because the ids will be duplicated.
  2. If you load the contents every time that the popover is shown you will lose all of the user's input.

What you want to do is load the object itself into the popover.

https://jsfiddle.net/shrewmouse/ex6tuzm2/4/

HTML:

<h1> Test </h1>

<div><button id="target">click me</button></div>

<!-- This will be the contents of our popover -->
<div class='_content' id='blah'>
<h1>Extra Stuff</h1>
<input type='number' placeholder='number'/>
</div>

JQuery:

$(document).ready(function() {

    // We don't want to see the popover contents until the user clicks the target.
    // If you don't hide 'blah' first it will be visible outside of the popover.
    //
    $('#blah').hide();

    // Initialize our popover
    //
    $('#target').popover({
        content: $('#blah'), // set the content to be the 'blah' div
        placement: 'bottom',
        html: true
    });
    // The popover contents will not be set until the popover is shown.  Since we don't 
    // want to see the popover when the page loads, we will show it then hide it.
    //
    $('#target').popover('show');
    $('#target').popover('hide');

    // Now that the popover's content is the 'blah' dive we can make it visisble again.
    //
    $('#blah').show();


});

Exception of type 'System.OutOfMemoryException' was thrown.

I just restarted Visual Studio and did IISRESET which solved the problem.

Check if an image is loaded (no errors) with jQuery

As I understand the .complete property is non-standard. It may not be universal... I notice it seem to work differently in Firefox verses IE. I am loading a number of images in javascript then checking if complete. In Firefox, this seems to work great. In IE, it doesn't because the images appear to be loading on another thread. It works only if I put a delay between my assignment to image.src and when I check the image.complete property.

Using image.onload and image.onerror isn't working for me, either, because I need to pass a parameter to know which image I am talking about when the function is called. Any way of doing that seems to fail because it actually seems to pass the same function, not different instances of the same function. So the value I pass into it to identify the image always ends up being the last value in the loop. I cannot think of any way around this problem.

On Safari and Chrome, I am seeing the image.complete true and the naturalWidth set even when the error console shows a 404 for that image... and I intentionally removed that image to test this. But the above works well for Firefox and IE.

How to write DataFrame to postgres table?

This is how I did it.

It may be faster because it is using execute_batch:

# df is the dataframe
if len(df) > 0:
    df_columns = list(df)
    # create (col1,col2,...)
    columns = ",".join(df_columns)

    # create VALUES('%s', '%s",...) one '%s' per column
    values = "VALUES({})".format(",".join(["%s" for _ in df_columns])) 

    #create INSERT INTO table (columns) VALUES('%s',...)
    insert_stmt = "INSERT INTO {} ({}) {}".format(table,columns,values)

    cur = conn.cursor()
    psycopg2.extras.execute_batch(cur, insert_stmt, df.values)
    conn.commit()
    cur.close()

Fastest way to determine if record exists

Nothing can beat -

SELECT TOP 1 1 FROM products WHERE id = 'some value';

You don't need to count to know if there is a data in table. And don't use alias when not necessary.

getString Outside of a Context or Activity

I used getContext().getApplicationContext().getString(R.string.nameOfString); It works for me.

Nginx reverse proxy causing 504 Gateway Timeout

If nginx_ajp_module is used, try adding ajp_read_timeout 10m; in nginx.conf file.

Failed to instantiate module error in Angular js

For me the error occurred due to my browser using a cached version of the js file containing the module. Clearing the cache and reloading the page solved the problem.

Format datetime in asp.net mvc 4

Ahhhh, now it is clear. You seem to have problems binding back the value. Not with displaying it on the view. Indeed, that's the fault of the default model binder. You could write and use a custom one that will take into consideration the [DisplayFormat] attribute on your model. I have illustrated such a custom model binder here: https://stackoverflow.com/a/7836093/29407


Apparently some problems still persist. Here's my full setup working perfectly fine on both ASP.NET MVC 3 & 4 RC.

Model:

public class MyViewModel
{
    [DisplayName("date of birth")]
    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
    public DateTime? Birth { get; set; }
}

Controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new MyViewModel
        {
            Birth = DateTime.Now
        });
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        return View(model);
    }
}

View:

@model MyViewModel

@using (Html.BeginForm())
{
    @Html.LabelFor(x => x.Birth)
    @Html.EditorFor(x => x.Birth)
    @Html.ValidationMessageFor(x => x.Birth)
    <button type="submit">OK</button>
}

Registration of the custom model binder in Application_Start:

ModelBinders.Binders.Add(typeof(DateTime?), new MyDateTimeModelBinder());

And the custom model binder itself:

public class MyDateTimeModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var displayFormat = bindingContext.ModelMetadata.DisplayFormatString;
        var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

        if (!string.IsNullOrEmpty(displayFormat) && value != null)
        {
            DateTime date;
            displayFormat = displayFormat.Replace("{0:", string.Empty).Replace("}", string.Empty);
            // use the format specified in the DisplayFormat attribute to parse the date
            if (DateTime.TryParseExact(value.AttemptedValue, displayFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
            {
                return date;
            }
            else
            {
                bindingContext.ModelState.AddModelError(
                    bindingContext.ModelName,
                    string.Format("{0} is an invalid date format", value.AttemptedValue)
                );
            }
        }

        return base.BindModel(controllerContext, bindingContext);
    }
}

Now, no matter what culture you have setup in your web.config (<globalization> element) or the current thread culture, the custom model binder will use the DisplayFormat attribute's date format when parsing nullable dates.

Git Push ERROR: Repository not found

Also be sure to check whether you have desktop client installed. I double checked everything, my permission, SSH, but turns out my repo listed in the client was overriding the one I was inputting via terminal.

Maximize a window programmatically and prevent the user from changing the windows state

Change the property WindowState to System.Windows.Forms.FormWindowState.Maximized, in some cases if the older answers doesn't works.

So the window will be maximized, and the other parts are in the other answers.

Sort table rows In Bootstrap

These examples are minified because StackOverflow has a maximum character limit and links to external code are discouraged since links can break.

There are multiple plugins if you look: Bootstrap Sortable, Bootstrap Table or DataTables.

Bootstrap 3 with DataTables Example: Bootstrap Docs & DataTables Docs

_x000D_
_x000D_
$(document).ready(function() {
  $('#example').DataTable();
});
_x000D_
<link href=https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css rel=stylesheet><link href=https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.20/css/dataTables.bootstrap.min.css rel=stylesheet><div class=container><h1>Bootstrap 3 DataTables</h1><table cellspacing=0 class="table table-bordered table-hover table-striped"id=example width=100%><thead><tr><th>Name<th>Position<th>Office<th>Salary<tbody><tr><td>Tiger Nixon<td>System Architect<td>Edinburgh<td>$320,800<tr><td>Garrett Winters<td>Accountant<td>Tokyo<td>$170,750<tr><td>Ashton Cox<td>Junior Technical Author<td>San Francisco<td>$86,000<tr><td>Cedric Kelly<td>Senior Javascript Developer<td>Edinburgh<td>$433,060<tr><td>Airi Satou<td>Accountant<td>Tokyo<td>$162,700<tr><td>Brielle Williamson<td>Integration Specialist<td>New York<td>$372,000<tr><td>Herrod Chandler<td>Sales Assistant<td>San Francisco<td>$137,500<tr><td>Rhona Davidson<td>Integration Specialist<td>Tokyo<td>$327,900<tr><td>Colleen Hurst<td>Javascript Developer<td>San Francisco<td>$205,500<tr><td>Sonya Frost<td>Software Engineer<td>Edinburgh<td>$103,600<tr><td>Jena Gaines<td>Office Manager<td>London<td>$90,560<tr><td>Quinn Flynn<td>Support Lead<td>Edinburgh<td>$342,000<tr><td>Charde Marshall<td>Regional Director<td>San Francisco<td>$470,600<tr><td>Haley Kennedy<td>Senior Marketing Designer<td>London<td>$313,500<tr><td>Tatyana Fitzpatrick<td>Regional Director<td>London<td>$385,750<tr><td>Michael Silva<td>Marketing Designer<td>London<td>$198,500<tr><td>Paul Byrd<td>Chief Financial Officer (CFO)<td>New York<td>$725,000<tr><td>Gloria Little<td>Systems Administrator<td>New York<td>$237,500<tr><td>Bradley Greer<td>Software Engineer<td>London<td>$132,000<tr><td>Dai Rios<td>Personnel Lead<td>Edinburgh<td>$217,500<tr><td>Jenette Caldwell<td>Development Lead<td>New York<td>$345,000<tr><td>Yuri Berry<td>Chief Marketing Officer (CMO)<td>New York<td>$675,000<tr><td>Caesar Vance<td>Pre-Sales Support<td>New York<td>$106,450<tr><td>Doris Wilder<td>Sales Assistant<td>Sidney<td>$85,600<tr><td>Angelica Ramos<td>Chief Executive Officer (CEO)<td>London<td>$1,200,000<tr><td>Gavin Joyce<td>Developer<td>Edinburgh<td>$92,575<tr><td>Jennifer Chang<td>Regional Director<td>Singapore<td>$357,650<tr><td>Brenden Wagner<td>Software Engineer<td>San Francisco<td>$206,850<tr><td>Fiona Green<td>Chief Operating Officer (COO)<td>San Francisco<td>$850,000<tr><td>Shou Itou<td>Regional Marketing<td>Tokyo<td>$163,000<tr><td>Michelle House<td>Integration Specialist<td>Sidney<td>$95,400<tr><td>Suki Burks<td>Developer<td>London<td>$114,500<tr><td>Prescott Bartlett<td>Technical Author<td>London<td>$145,000<tr><td>Gavin Cortez<td>Team Leader<td>San Francisco<td>$235,500<tr><td>Martena Mccray<td>Post-Sales support<td>Edinburgh<td>$324,050<tr><td>Unity Butler<td>Marketing Designer<td>San Francisco<td>$85,675<tr><td>Howard Hatfield<td>Office Manager<td>San Francisco<td>$164,500<tr><td>Hope Fuentes<td>Secretary<td>San Francisco<td>$109,850<tr><td>Vivian Harrell<td>Financial Controller<td>San Francisco<td>$452,500<tr><td>Timothy Mooney<td>Office Manager<td>London<td>$136,200<tr><td>Jackson Bradshaw<td>Director<td>New York<td>$645,750<tr><td>Olivia Liang<td>Support Engineer<td>Singapore<td>$234,500<tr><td>Bruno Nash<td>Software Engineer<td>London<td>$163,500<tr><td>Sakura Yamamoto<td>Support Engineer<td>Tokyo<td>$139,575<tr><td>Thor Walton<td>Developer<td>New York<td>$98,540<tr><td>Finn Camacho<td>Support Engineer<td>San Francisco<td>$87,500<tr><td>Serge Baldwin<td>Data Coordinator<td>Singapore<td>$138,575<tr><td>Zenaida Frank<td>Software Engineer<td>New York<td>$125,250<tr><td>Zorita Serrano<td>Software Engineer<td>San Francisco<td>$115,000<tr><td>Jennifer Acosta<td>Junior Javascript Developer<td>Edinburgh<td>$75,650<tr><td>Cara Stevens<td>Sales Assistant<td>New York<td>$145,600<tr><td>Hermione Butler<td>Regional Director<td>London<td>$356,250<tr><td>Lael Greer<td>Systems Administrator<td>London<td>$103,500<tr><td>Jonas Alexander<td>Developer<td>San Francisco<td>$86,500<tr><td>Shad Decker<td>Regional Director<td>Edinburgh<td>$183,000<tr><td>Michael Bruce<td>Javascript Developer<td>Singapore<td>$183,000<tr><td>Donna Snider<td>Customer Support<td>New York<td>$112,000</table></div><script src=https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js></script><script src=https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.20/js/jquery.dataTables.min.js></script><script src=https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.20/js/dataTables.bootstrap.min.js></script>
_x000D_
_x000D_
_x000D_

Bootstrap 4 with DataTables Example: Bootstrap Docs & DataTables Docs

_x000D_
_x000D_
$(document).ready(function() {
  $('#example').DataTable();
});
_x000D_
<link href=https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css rel=stylesheet><link href=https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.20/css/dataTables.bootstrap4.min.css rel=stylesheet><div class=container><h1>Bootstrap 4 DataTables</h1><table cellspacing=0 class="table table-bordered table-hover table-inverse table-striped"id=example width=100%><thead><tr><th>Name<th>Position<th>Office<th>Age<th>Start date<th>Salary<tfoot><tr><th>Name<th>Position<th>Office<th>Age<th>Start date<th>Salary<tbody><tr><td>Tiger Nixon<td>System Architect<td>Edinburgh<td>61<td>2011/04/25<td>$320,800<tr><td>Garrett Winters<td>Accountant<td>Tokyo<td>63<td>2011/07/25<td>$170,750<tr><td>Ashton Cox<td>Junior Technical Author<td>San Francisco<td>66<td>2009/01/12<td>$86,000<tr><td>Cedric Kelly<td>Senior Javascript Developer<td>Edinburgh<td>22<td>2012/03/29<td>$433,060<tr><td>Airi Satou<td>Accountant<td>Tokyo<td>33<td>2008/11/28<td>$162,700<tr><td>Brielle Williamson<td>Integration Specialist<td>New York<td>61<td>2012/12/02<td>$372,000<tr><td>Herrod Chandler<td>Sales Assistant<td>San Francisco<td>59<td>2012/08/06<td>$137,500<tr><td>Rhona Davidson<td>Integration Specialist<td>Tokyo<td>55<td>2010/10/14<td>$327,900<tr><td>Colleen Hurst<td>Javascript Developer<td>San Francisco<td>39<td>2009/09/15<td>$205,500<tr><td>Sonya Frost<td>Software Engineer<td>Edinburgh<td>23<td>2008/12/13<td>$103,600<tr><td>Jena Gaines<td>Office Manager<td>London<td>30<td>2008/12/19<td>$90,560<tr><td>Quinn Flynn<td>Support Lead<td>Edinburgh<td>22<td>2013/03/03<td>$342,000<tr><td>Charde Marshall<td>Regional Director<td>San Francisco<td>36<td>2008/10/16<td>$470,600<tr><td>Haley Kennedy<td>Senior Marketing Designer<td>London<td>43<td>2012/12/18<td>$313,500<tr><td>Tatyana Fitzpatrick<td>Regional Director<td>London<td>19<td>2010/03/17<td>$385,750<tr><td>Michael Silva<td>Marketing Designer<td>London<td>66<td>2012/11/27<td>$198,500<tr><td>Paul Byrd<td>Chief Financial Officer (CFO)<td>New York<td>64<td>2010/06/09<td>$725,000<tr><td>Gloria Little<td>Systems Administrator<td>New York<td>59<td>2009/04/10<td>$237,500<tr><td>Bradley Greer<td>Software Engineer<td>London<td>41<td>2012/10/13<td>$132,000<tr><td>Dai Rios<td>Personnel Lead<td>Edinburgh<td>35<td>2012/09/26<td>$217,500<tr><td>Jenette Caldwell<td>Development Lead<td>New York<td>30<td>2011/09/03<td>$345,000<tr><td>Yuri Berry<td>Chief Marketing Officer (CMO)<td>New York<td>40<td>2009/06/25<td>$675,000<tr><td>Caesar Vance<td>Pre-Sales Support<td>New York<td>21<td>2011/12/12<td>$106,450<tr><td>Doris Wilder<td>Sales Assistant<td>Sidney<td>23<td>2010/09/20<td>$85,600<tr><td>Angelica Ramos<td>Chief Executive Officer (CEO)<td>London<td>47<td>2009/10/09<td>$1,200,000<tr><td>Gavin Joyce<td>Developer<td>Edinburgh<td>42<td>2010/12/22<td>$92,575<tr><td>Jennifer Chang<td>Regional Director<td>Singapore<td>28<td>2010/11/14<td>$357,650<tr><td>Brenden Wagner<td>Software Engineer<td>San Francisco<td>28<td>2011/06/07<td>$206,850<tr><td>Fiona Green<td>Chief Operating Officer (COO)<td>San Francisco<td>48<td>2010/03/11<td>$850,000<tr><td>Shou Itou<td>Regional Marketing<td>Tokyo<td>20<td>2011/08/14<td>$163,000<tr><td>Michelle House<td>Integration Specialist<td>Sidney<td>37<td>2011/06/02<td>$95,400<tr><td>Suki Burks<td>Developer<td>London<td>53<td>2009/10/22<td>$114,500<tr><td>Prescott Bartlett<td>Technical Author<td>London<td>27<td>2011/05/07<td>$145,000<tr><td>Gavin Cortez<td>Team Leader<td>San Francisco<td>22<td>2008/10/26<td>$235,500<tr><td>Martena Mccray<td>Post-Sales support<td>Edinburgh<td>46<td>2011/03/09<td>$324,050<tr><td>Unity Butler<td>Marketing Designer<td>San Francisco<td>47<td>2009/12/09<td>$85,675<tr><td>Howard Hatfield<td>Office Manager<td>San Francisco<td>51<td>2008/12/16<td>$164,500<tr><td>Hope Fuentes<td>Secretary<td>San Francisco<td>41<td>2010/02/12<td>$109,850<tr><td>Vivian Harrell<td>Financial Controller<td>San Francisco<td>62<td>2009/02/14<td>$452,500<tr><td>Timothy Mooney<td>Office Manager<td>London<td>37<td>2008/12/11<td>$136,200<tr><td>Jackson Bradshaw<td>Director<td>New York<td>65<td>2008/09/26<td>$645,750<tr><td>Olivia Liang<td>Support Engineer<td>Singapore<td>64<td>2011/02/03<td>$234,500<tr><td>Bruno Nash<td>Software Engineer<td>London<td>38<td>2011/05/03<td>$163,500<tr><td>Sakura Yamamoto<td>Support Engineer<td>Tokyo<td>37<td>2009/08/19<td>$139,575<tr><td>Thor Walton<td>Developer<td>New York<td>61<td>2013/08/11<td>$98,540<tr><td>Finn Camacho<td>Support Engineer<td>San Francisco<td>47<td>2009/07/07<td>$87,500<tr><td>Serge Baldwin<td>Data Coordinator<td>Singapore<td>64<td>2012/04/09<td>$138,575<tr><td>Zenaida Frank<td>Software Engineer<td>New York<td>63<td>2010/01/04<td>$125,250<tr><td>Zorita Serrano<td>Software Engineer<td>San Francisco<td>56<td>2012/06/01<td>$115,000<tr><td>Jennifer Acosta<td>Junior Javascript Developer<td>Edinburgh<td>43<td>2013/02/01<td>$75,650<tr><td>Cara Stevens<td>Sales Assistant<td>New York<td>46<td>2011/12/06<td>$145,600<tr><td>Hermione Butler<td>Regional Director<td>London<td>47<td>2011/03/21<td>$356,250<tr><td>Lael Greer<td>Systems Administrator<td>London<td>21<td>2009/02/27<td>$103,500<tr><td>Jonas Alexander<td>Developer<td>San Francisco<td>30<td>2010/07/14<td>$86,500<tr><td>Shad Decker<td>Regional Director<td>Edinburgh<td>51<td>2008/11/13<td>$183,000<tr><td>Michael Bruce<td>Javascript Developer<td>Singapore<td>29<td>2011/06/27<td>$183,000<tr><td>Donna Snider<td>Customer Support<td>New York<td>27<td>2011/01/25<td>$112,000</table></div><script src=https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js></script><script src=https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.20/js/jquery.dataTables.min.js></script><script src=https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.20/js/dataTables.bootstrap4.min.js></script>
_x000D_
_x000D_
_x000D_

Bootstrap 3 with Bootstrap Table Example: Bootstrap Docs & Bootstrap Table Docs

_x000D_
_x000D_
<link href=https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css rel=stylesheet><link href=https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.16.0/bootstrap-table.min.css rel=stylesheet><table data-sort-name=stargazers_count data-sort-order=desc data-toggle=table data-url="https://api.github.com/users/wenzhixin/repos?type=owner&sort=full_name&direction=asc&per_page=100&page=1"><thead><tr><th data-field=name data-sortable=true>Name<th data-field=stargazers_count data-sortable=true>Stars<th data-field=forks_count data-sortable=true>Forks<th data-field=description data-sortable=true>Description</thead></table><script src=https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js></script><script src=https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.16.0/bootstrap-table.min.js></script>
_x000D_
_x000D_
_x000D_

Bootstrap 3 with Bootstrap Sortable Example: Bootstrap Docs & Bootstrap Sortable Docs

_x000D_
_x000D_
function randomDate(t,e){return new Date(t.getTime()+Math.random()*(e.getTime()-t.getTime()))}function randomName(){return["Jack","Peter","Frank","Steven"][Math.floor(4*Math.random())]+" "+["White","Jackson","Sinatra","Spielberg"][Math.floor(4*Math.random())]}function newTableRow(){var t=moment(randomDate(new Date(2e3,0,1),new Date)).format("D.M.YYYY"),e=Math.round(Math.random()*Math.random()*100*100)/100,a=Math.round(Math.random()*Math.random()*100*100)/100,r=Math.round(Math.random()*Math.random()*100*100)/100;return"<tr><td>"+randomName()+"</td><td>"+e+"</td><td>"+a+"</td><td>"+r+"</td><td>"+Math.round(100*(e+a+r))/100+"</td><td data-dateformat='D-M-YYYY'>"+t+"</td></tr>"}function customSort(){alert("Custom sort.")}!function(t,e){"use strict";"function"==typeof define&&define.amd?define("tinysort",function(){return e}):t.tinysort=e}(this,function(){"use strict";function t(t,e){for(var a,r=t.length,o=r;o--;)e(t[a=r-o-1],a)}function e(t,e,a){for(var o in e)(a||t[o]===r)&&(t[o]=e[o]);return t}function a(t,e,a){u.push({prepare:t,sort:e,sortBy:a})}var r,o=!1,n=null,s=window,d=s.document,i=parseFloat,l=/(-?\d+\.?\d*)\s*$/g,c=/(\d+\.?\d*)\s*$/g,u=[],f=0,h=0,p=String.fromCharCode(4095),m={selector:n,order:"asc",attr:n,data:n,useVal:o,place:"org",returns:o,cases:o,natural:o,forceStrings:o,ignoreDashes:o,sortFunction:n,useFlex:o,emptyEnd:o};return s.Element&&function(t){t.matchesSelector=t.matchesSelector||t.mozMatchesSelector||t.msMatchesSelector||t.oMatchesSelector||t.webkitMatchesSelector||function(t){for(var e=this,a=(e.parentNode||e.document).querySelectorAll(t),r=-1;a[++r]&&a[r]!=e;);return!!a[r]}}(Element.prototype),e(a,{loop:t}),e(function(a,s){function v(t){var a=!!t.selector,r=a&&":"===t.selector[0],o=e(t||{},m);E.push(e({hasSelector:a,hasAttr:!(o.attr===n||""===o.attr),hasData:o.data!==n,hasFilter:r,sortReturnNumber:"asc"===o.order?1:-1},o))}function b(t,e,a){for(var r=a(t.toString()),o=a(e.toString()),n=0;r[n]&&o[n];n++)if(r[n]!==o[n]){var s=Number(r[n]),d=Number(o[n]);return s==r[n]&&d==o[n]?s-d:r[n]>o[n]?1:-1}return r.length-o.length}function g(t){for(var e,a,r=[],o=0,n=-1,s=0;e=(a=t.charAt(o++)).charCodeAt(0);){var d=46==e||e>=48&&57>=e;d!==s&&(r[++n]="",s=d),r[n]+=a}return r}function w(){return Y.forEach(function(t){F.appendChild(t.elm)}),F}function S(t){var e=t.elm,a=d.createElement("div");return t.ghost=a,e.parentNode.insertBefore(a,e),t}function y(t,e){var a=t.ghost,r=a.parentNode;r.insertBefore(e,a),r.removeChild(a),delete t.ghost}function C(t,e){var a,r=t.elm;return e.selector&&(e.hasFilter?r.matchesSelector(e.selector)||(r=n):r=r.querySelector(e.selector)),e.hasAttr?a=r.getAttribute(e.attr):e.useVal?a=r.value||r.getAttribute("value"):e.hasData?a=r.getAttribute("data-"+e.data):r&&(a=r.textContent),M(a)&&(e.cases||(a=a.toLowerCase()),a=a.replace(/\s+/g," ")),null===a&&(a=p),a}function M(t){return"string"==typeof t}M(a)&&(a=d.querySelectorAll(a)),0===a.length&&console.warn("No elements to sort");var x,N,F=d.createDocumentFragment(),D=[],Y=[],$=[],E=[],k=!0,A=a.length&&a[0].parentNode,T=A.rootNode!==document,R=a.length&&(s===r||!1!==s.useFlex)&&!T&&-1!==getComputedStyle(A,null).display.indexOf("flex");return function(){0===arguments.length?v({}):t(arguments,function(t){v(M(t)?{selector:t}:t)}),f=E.length}.apply(n,Array.prototype.slice.call(arguments,1)),t(a,function(t,e){N?N!==t.parentNode&&(k=!1):N=t.parentNode;var a=E[0],r=a.hasFilter,o=a.selector,n=!o||r&&t.matchesSelector(o)||o&&t.querySelector(o)?Y:$,s={elm:t,pos:e,posn:n.length};D.push(s),n.push(s)}),x=Y.slice(0),Y.sort(function(e,a){var n=0;for(0!==h&&(h=0);0===n&&f>h;){var s=E[h],d=s.ignoreDashes?c:l;if(t(u,function(t){var e=t.prepare;e&&e(s)}),s.sortFunction)n=s.sortFunction(e,a);else if("rand"==s.order)n=Math.random()<.5?1:-1;else{var p=o,m=C(e,s),v=C(a,s),w=""===m||m===r,S=""===v||v===r;if(m===v)n=0;else if(s.emptyEnd&&(w||S))n=w&&S?0:w?1:-1;else{if(!s.forceStrings){var y=M(m)?m&&m.match(d):o,x=M(v)?v&&v.match(d):o;y&&x&&m.substr(0,m.length-y[0].length)==v.substr(0,v.length-x[0].length)&&(p=!o,m=i(y[0]),v=i(x[0]))}n=m===r||v===r?0:s.natural&&(isNaN(m)||isNaN(v))?b(m,v,g):v>m?-1:m>v?1:0}}t(u,function(t){var e=t.sort;e&&(n=e(s,p,m,v,n))}),0==(n*=s.sortReturnNumber)&&h++}return 0===n&&(n=e.pos>a.pos?1:-1),n}),function(){var t=Y.length===D.length;if(k&&t)R?Y.forEach(function(t,e){t.elm.style.order=e}):N?N.appendChild(w()):console.warn("parentNode has been removed");else{var e=E[0].place,a="start"===e,r="end"===e,o="first"===e,n="last"===e;if("org"===e)Y.forEach(S),Y.forEach(function(t,e){y(x[e],t.elm)});else if(a||r){var s=x[a?0:x.length-1],d=s&&s.elm.parentNode,i=d&&(a&&d.firstChild||d.lastChild);i&&(i!==s.elm&&(s={elm:i}),S(s),r&&d.appendChild(s.ghost),y(s,w()))}else(o||n)&&y(S(x[o?0:x.length-1]),w())}}(),Y.map(function(t){return t.elm})},{plugin:a,defaults:m})}()),function(t,e){"function"==typeof define&&define.amd?define(["jquery","tinysort","moment"],e):e(t.jQuery,t.tinysort,t.moment||void 0)}(this,function(t,e,a){var r,o,n,s=t(document);function d(e){var s=void 0!==a;r=e.sign?e.sign:"arrow","default"==e.customSort&&(e.customSort=c),o=e.customSort||o||c,n=e.emptyEnd,t("table.sortable").each(function(){var r=t(this),o=!0===e.applyLast;r.find("span.sign").remove(),r.find("> thead [colspan]").each(function(){for(var e=parseFloat(t(this).attr("colspan")),a=1;a<e;a++)t(this).after('<th class="colspan-compensate">')}),r.find("> thead [rowspan]").each(function(){for(var e=t(this),a=parseFloat(e.attr("rowspan")),r=1;r<a;r++){var o=e.parent("tr"),n=o.next("tr"),s=o.children().index(e);n.children().eq(s).before('<th class="rowspan-compensate">')}}),r.find("> thead tr").each(function(e){t(this).find("th").each(function(a){var r=t(this);r.addClass("nosort").removeClass("up down"),r.attr("data-sortcolumn",a),r.attr("data-sortkey",a+"-"+e)})}),r.find("> thead .rowspan-compensate, .colspan-compensate").remove(),r.find("th").each(function(){var e=t(this);if(void 0!==e.attr("data-dateformat")&&s){var o=parseFloat(e.attr("data-sortcolumn"));r.find("td:nth-child("+(o+1)+")").each(function(){var r=t(this);r.attr("data-value",a(r.text(),e.attr("data-dateformat")).format("YYYY/MM/DD/HH/mm/ss"))})}else if(void 0!==e.attr("data-valueprovider")){o=parseFloat(e.attr("data-sortcolumn"));r.find("td:nth-child("+(o+1)+")").each(function(){var a=t(this);a.attr("data-value",new RegExp(e.attr("data-valueprovider")).exec(a.text())[0])})}}),r.find("td").each(function(){var e=t(this);void 0!==e.attr("data-dateformat")&&s?e.attr("data-value",a(e.text(),e.attr("data-dateformat")).format("YYYY/MM/DD/HH/mm/ss")):void 0!==e.attr("data-valueprovider")?e.attr("data-value",new RegExp(e.attr("data-valueprovider")).exec(e.text())[0]):void 0===e.attr("data-value")&&e.attr("data-value",e.text())});var n=l(r),d=n.bsSort;r.find('> thead th[data-defaultsort!="disabled"]').each(function(e){var a=t(this),r=a.closest("table.sortable");a.data("sortTable",r);var s=a.attr("data-sortkey"),i=o?n.lastSort:-1;d[s]=o?d[s]:a.attr("data-defaultsort"),void 0!==d[s]&&o===(s===i)&&(d[s]="asc"===d[s]?"desc":"asc",u(a,r))})})}function i(e){var a=t(e),r=a.data("sortTable")||a.closest("table.sortable");u(a,r)}function l(e){var a=e.data("bootstrap-sortable-context");return void 0===a&&(a={bsSort:[],lastSort:void 0},e.find('> thead th[data-defaultsort!="disabled"]').each(function(e){var r=t(this),o=r.attr("data-sortkey");a.bsSort[o]=r.attr("data-defaultsort"),void 0!==a.bsSort[o]&&(a.lastSort=o)}),e.data("bootstrap-sortable-context",a)),a}function c(t,a){e(t,a)}function u(e,a){a.trigger("before-sort");var s=parseFloat(e.attr("data-sortcolumn")),d=l(a),i=d.bsSort;if(e.attr("colspan")){var c=parseFloat(e.data("mainsort"))||0,f=parseFloat(e.data("sortkey").split("-").pop());if(a.find("> thead tr").length-1>f)return void u(a.find('[data-sortkey="'+(s+c)+"-"+(f+1)+'"]'),a);s+=c}var h=e.attr("data-defaultsign")||r;if(a.find("> thead th").each(function(){t(this).removeClass("up").removeClass("down").addClass("nosort")}),t.browser.mozilla){var p=a.find("> thead div.mozilla");void 0!==p&&(p.find(".sign").remove(),p.parent().html(p.html())),e.wrapInner('<div class="mozilla"></div>'),e.children().eq(0).append('<span class="sign '+h+'"></span>')}else a.find("> thead span.sign").remove(),e.append('<span class="sign '+h+'"></span>');var m=e.attr("data-sortkey"),v="desc"!==e.attr("data-firstsort")?"desc":"asc",b=i[m]||v;d.lastSort!==m&&void 0!==i[m]||(b="asc"===b?"desc":"asc"),i[m]=b,d.lastSort=m,"desc"===i[m]?(e.find("span.sign").addClass("up"),e.addClass("up").removeClass("down nosort")):e.addClass("down").removeClass("up nosort");var g=a.children("tbody").children("tr"),w=[];t(g.filter('[data-disablesort="true"]').get().reverse()).each(function(e,a){var r=t(a);w.push({index:g.index(r),row:r}),r.remove()});var S=g.not('[data-disablesort="true"]');if(0!=S.length){var y="asc"===i[m]&&n;o(S,{emptyEnd:y,selector:"td:nth-child("+(s+1)+")",order:i[m],data:"value"})}t(w.reverse()).each(function(t,e){0===e.index?a.children("tbody").prepend(e.row):a.children("tbody").children("tr").eq(e.index-1).after(e.row)}),a.find("> tbody > tr > td.sorted,> thead th.sorted").removeClass("sorted"),S.find("td:eq("+s+")").addClass("sorted"),e.addClass("sorted"),a.trigger("sorted")}if(t.bootstrapSortable=function(t){null==t?d({}):t.constructor===Boolean?d({applyLast:t}):void 0!==t.sortingHeader?i(t.sortingHeader):d(t)},s.on("click",'table.sortable>thead th[data-defaultsort!="disabled"]',function(t){i(this)}),!t.browser){t.browser={chrome:!1,mozilla:!1,opera:!1,msie:!1,safari:!1};var f=navigator.userAgent;t.each(t.browser,function(e){t.browser[e]=!!new RegExp(e,"i").test(f),t.browser.mozilla&&"mozilla"===e&&(t.browser.mozilla=!!new RegExp("firefox","i").test(f)),t.browser.chrome&&"safari"===e&&(t.browser.safari=!1)})}t(t.bootstrapSortable)}),function(){var t=$("table");t.append(newTableRow()),t.append(newTableRow()),$("button.add-row").on("click",function(){var e=$(this);t.append(newTableRow()),e.data("sort")?$.bootstrapSortable(!0):$.bootstrapSortable(!1)}),$("button.change-sort").on("click",function(){$(this).data("custom")?$.bootstrapSortable(!0,void 0,customSort):$.bootstrapSortable(!0,void 0,"default")}),t.on("sorted",function(){alert("Table was sorted.")}),$("#event").on("change",function(){$(this).is(":checked")?t.on("sorted",function(){alert("Table was sorted.")}):t.off("sorted")}),$("input[name=sign]:radio").change(function(){$.bootstrapSortable(!0,$(this).val())})}();
_x000D_
table.sortable span.sign { display: block; position: absolute; top: 50%; right: 5px; font-size: 12px; margin-top: -10px; color: #bfbfc1; } table.sortable th:after { display: block; position: absolute; top: 50%; right: 5px; font-size: 12px; margin-top: -10px; color: #bfbfc1; } table.sortable th.arrow:after { content: ''; } table.sortable span.arrow, span.reversed, th.arrow.down:after, th.reversedarrow.down:after, th.arrow.up:after, th.reversedarrow.up:after { border-style: solid; border-width: 5px; font-size: 0; border-color: #ccc transparent transparent transparent; line-height: 0; height: 0; width: 0; margin-top: -2px; } table.sortable span.arrow.up, th.arrow.up:after { border-color: transparent transparent #ccc transparent; margin-top: -7px; } table.sortable span.reversed, th.reversedarrow.down:after { border-color: transparent transparent #ccc transparent; margin-top: -7px; } table.sortable span.reversed.up, th.reversedarrow.up:after { border-color: #ccc transparent transparent transparent; margin-top: -2px; } table.sortable span.az:before, th.az.down:after { content: "a .. z"; } table.sortable span.az.up:before, th.az.up:after { content: "z .. a"; } table.sortable th.az.nosort:after, th.AZ.nosort:after, th._19.nosort:after, th.month.nosort:after { content: ".."; } table.sortable span.AZ:before, th.AZ.down:after { content: "A .. Z"; } table.sortable span.AZ.up:before, th.AZ.up:after { content: "Z .. A"; } table.sortable span._19:before, th._19.down:after { content: "1 .. 9"; } table.sortable span._19.up:before, th._19.up:after { content: "9 .. 1"; } table.sortable span.month:before, th.month.down:after { content: "jan .. dec"; } table.sortable span.month.up:before, th.month.up:after { content: "dec .. jan"; } table.sortable thead th:not([data-defaultsort=disabled]) { cursor: pointer; position: relative; top: 0; left: 0; } table.sortable thead th:hover:not([data-defaultsort=disabled]) { background: #efefef; } table.sortable thead th div.mozilla { position: relative; }
_x000D_
<link href=https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.1/css/all.min.css rel=stylesheet><link href=https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css rel=stylesheet><div class=container><div class=hero-unit><h1>Bootstrap Sortable</h1></div><table class="sortable table table-bordered table-striped"><thead><tr><th style=width:20%;vertical-align:middle data-defaultsign=nospan class=az data-defaultsort=asc rowspan=2><i class="fa fa-fw fa-map-marker"></i>Name<th style=text-align:center colspan=4 data-mainsort=3>Results<th data-defaultsort=disabled><tr><th style=width:20% colspan=2 data-mainsort=1 data-firstsort=desc>Round 1<th style=width:20%>Round 2<th style=width:20%>Total<t
                  

Read input from console in Ruby?

If you want to make interactive console:

#!/usr/bin/env ruby

require "readline"
addends = []
while addend_string = Readline.readline("> ", true)
  addends << addend_string.to_i
  puts "#{addends.join(' + ')} = #{addends.sum}"
end

Usage (assuming you put above snippet into summator file in current directory):

chmod +x summator
./summator
> 1
1 = 1
> 2
1 + 2 = 3

Use Ctrl + D to exit

Why use String.Format?

Besides being a bit easier to read and adding a few more operators, it's also beneficial if your application is internationalized. A lot of times the variables are numbers or key words which will be in a different order for different languages. By using String.Format, your code can remain unchanged while different strings will go into resource files. So, the code would end up being

String.Format(resource.GetString("MyResourceString"), str1, str2, str3);

While your resource strings end up being

English: "blah blah {0} blah blah {1} blah {2}"

Russian: "{0} blet blet blet {2} blet {1}"

Where Russian may have different rules on how things get addressed so the order is different or sentence structure is different.

Maven Error: Could not find or load main class

this worked for me....

I added the following line to properties in pom.xml

<properties>
    <maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
</properties>

How to check Oracle patches are installed?

I understand the original post is for Oracle 10 but this is for reference by anyone else who finds it via Google.

Under Oracle 12c, I found that that my registry$history is empty. This works instead:

select * from registry$sqlpatch;

Get table names using SELECT statement in MySQL

I think it may be helpful to point out that if you want to select tables that contain specific words you can easily do it using the SELECT (instead of SHOW). Below query easily narrows down the search to tables that contain "keyword"

SELECT *
FROM information_schema.tables
WHERE table_name like "%keyword%"

How do I run a node.js app as a background service?

For people using newer versions of the daemon npm module - you need to pass file descriptors instead of strings:

var fs = require('fs');
var stdoutFd = fs.openSync('output.log', 'a');
var stderrFd = fs.openSync('errors.log', 'a');
require('daemon')({
    stdout: stdoutFd, 
    stderr: stderrFd
});

How do I find files that do not contain a given string pattern?

Take a look at ack. It does the .svn exclusion for you automatically, gives you Perl regular expressions, and is a simple download of a single Perl program.

The equivalent of what you're looking for should be, in ack:

ack -L foo

AltGr key not working, instead I have to use Ctrl+AltGr

I found a solution for my problem while writing my question !

Going into my remote session i tried two key combinations, and it solved the problem on my Desktop : Alt+Enter and Ctrl+Enter (i don't know which one solved the problem though)

I tried to reproduce the problem, but i couldn't... but i'm almost sure it's one of the key combinations described in the question above (since i experienced this problem several times)

So it seems the problem comes from the use of RDP (windows7 and 8)

Update 2017: Problem occurs on Windows 10 aswell.

Is CSS Turing complete?

Turing-completeness is not only about "defining functions" or "have ifs/loops/etc". For example, Haskell doesn't have "loop", lambda-calculus don't have "ifs", etc...

For example, this site: http://experthuman.com/programming-with-nothing. The author uses Ruby and create a "FizzBuzz" program with only closures (no strings, numbers, or anything like that)...

There are examples when people compute some arithmetical functions on Scala using only the type system

So, yes, in my opinion, CSS3+HTML is turing-complete (even if you can't exactly do any real computation with then without becoming crazy)

How do I merge dictionaries together in Python?

I believe that, as stated above, using d2.update(d1) is the best approach and that you can also copy d2 first if you still need it.

Although, I want to point out that dict(d1, **d2) is actually a bad way to merge dictionnaries in general since keyword arguments need to be strings, thus it will fail if you have a dict such as:

{
  1: 'foo',
  2: 'bar'
}

show all tables in DB2 using the LIST command

have you installed a user db2inst2, i think, i remember, that db2inst1 is very administrative

set the iframe height automatically

Solomon's answer about bootstrap inspired me to add the CSS the bootstrap solution uses, which works really well for me.

.iframe-embed {
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    height: 100%;
    width: 100%;
    border: 0;
}
.iframe-embed-wrapper {
    position: relative;
    display: block;
    height: 0;
    padding: 0;
    overflow: hidden;
}
.iframe-embed-responsive-16by9 {
    padding-bottom: 56.25%;
}
<div class="iframe-embed-wrapper iframe-embed-responsive-16by9">
    <iframe class="iframe-embed" src="vid.mp4"></iframe>
</div>

How do I disable right click on my web page?

Disabling right click on your web page is simple. There are just a few lines of JavaScript code that will do this job. Below is the JavaScript code:

$("html").on("contextmenu",function(e){
   return false;
});

In the above code, I have selected the tag. After you add just that three lines of code, it will disable right click on your web page.

Source: Disable right click, copy, cut on web page using jQuery

Origin <origin> is not allowed by Access-Control-Allow-Origin

If you need a quick work around in Chrome for ajax requests, this chrome plugin automatically allows you to access any site from any source by adding the proper response header

Chrome Extension Allow-Control-Allow-Origin: *

Does Python have a ternary conditional operator?

For versions prior to 2.5, there's the trick:

[expression] and [on_true] or [on_false]

It can give wrong results when on_true has a false boolean value.1
Although it does have the benefit of evaluating expressions left to right, which is clearer in my opinion.

1. Is there an equivalent of C’s ”?:” ternary operator?

Getting error: ISO C++ forbids declaration of with no type

Your declaration is int ttTreeInsert(int value);

However, your definition/implementation is

ttTree::ttTreeInsert(int value)
{
}

Notice that the return type int is missing in the implementation. Instead it should be

int ttTree::ttTreeInsert(int value)
{
    return 1; // or some valid int
}

How do I find out what License has been applied to my SQL Server installation?

SQL Server does not track licensing. Customers are responsible for tracking the assignment of licenses to servers, following the rules in the Licensing Guide.

How to create temp table using Create statement in SQL Server?

Same thing, Just start the table name with # or ##:

CREATE TABLE #TemporaryTable          -- Local temporary table - starts with single #
(
    Col1 int,
    Col2 varchar(10)
    ....
);

CREATE TABLE ##GlobalTemporaryTable   -- Global temporary table - note it starts with ##.
(
    Col1 int,
    Col2 varchar(10)
    ....
);

Temporary table names start with # or ## - The first is a local temporary table and the last is a global temporary table.

Here is one of many articles describing the differences between them.

How to create JSON post to api using C#

Have you tried using the WebClient class?

you should be able to use

string result = "";
using (var client = new WebClient())
{
    client.Headers[HttpRequestHeader.ContentType] = "application/json"; 
    result = client.UploadString(url, "POST", json);
}
Console.WriteLine(result);

Documentation at

http://msdn.microsoft.com/en-us/library/system.net.webclient%28v=vs.110%29.aspx

http://msdn.microsoft.com/en-us/library/d0d3595k%28v=vs.110%29.aspx

jQuery Event : Detect changes to the html/text of a div

Using Javascript MutationObserver

  //More Details https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
 // select the target node
var target = document.querySelector('mydiv')
// create an observer instance
var observer = new MutationObserver(function(mutations) {
  console.log(target.innerText);   
});
// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true };
// pass in the target node, as well as the observer options
observer.observe(target, config);

How to get featured image of a product in woocommerce

The answers here, are way too complex. Here's something I've recently used:

<?php global $product; ?>
<img src="<?php echo wp_get_attachment_url( $product->get_image_id() ); ?>" />

Using wp_get_attachment_url() to display the

Converting BitmapImage to Bitmap and vice versa

using System.Windows.Interop; ...

 private BitmapImage Bitmap2BitmapImage(Bitmap bitmap)
        {                
            BitmapSource i = Imaging.CreateBitmapSourceFromHBitmap(
                           bitmap.GetHbitmap(),
                           IntPtr.Zero,
                           Int32Rect.Empty,
                           BitmapSizeOptions.FromEmptyOptions());
            return (BitmapImage)i;
        }

How to POST request using RestSharp

it is better to use json after post your resuest like below

  var clien = new RestClient("https://smple.com/");
  var request = new RestRequest("index", Method.POST);
  request.AddHeader("Sign", signinstance);    
  request.AddJsonBody(JsonConvert.SerializeObject(yourclass));
  var response = client.Execute<YourReturnclassSample>(request);
  if (response.StatusCode == System.Net.HttpStatusCode.Created)
   {
       return Ok(response.Content);
   }

How to remove backslash on json_encode() function?

I use the following to remove the slashes

echo json_decode($mystring, JSON_UNESCAPED_SLASHES);

Move view with keyboard using Swift

Here is a solution, without handling the switch from one textField to another:

 override func viewDidLoad() {
        super.viewDidLoad()
        NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name: UIKeyboardWillShowNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name: UIKeyboardWillHideNotification, object: nil)            
    }   

func keyboardWillShow(notification: NSNotification) {            
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.CGRectValue() {
        self.view.frame.origin.y -= keyboardSize.height
    }            
}

func keyboardWillHide(notification: NSNotification) {
    self.view.frame.origin.y = 0
}

To solve this, replace the two functions keyboardWillShow/Hide with these:

func keyboardWillShow(notification: NSNotification) {        
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.CGRectValue() {
        if view.frame.origin.y == 0 {
            self.view.frame.origin.y -= keyboardSize.height
        }
    }        
}

func keyboardWillHide(notification: NSNotification) {
    if view.frame.origin.y != 0 {
        self.view.frame.origin.y = 0
    }
}

EDIT FOR SWIFT 3.0:

override func viewDidLoad() {
    super.viewDidLoad()            
    NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)    
}

@objc func keyboardWillShow(notification: NSNotification) {        
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
        if self.view.frame.origin.y == 0 {
            self.view.frame.origin.y -= keyboardSize.height
        }
    }        
}

@objc func keyboardWillHide(notification: NSNotification) {
    if self.view.frame.origin.y != 0 {
        self.view.frame.origin.y = 0
    }
}

EDIT FOR SWIFT 4.0:

override func viewDidLoad() {
    super.viewDidLoad()            
    NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)    
}

@objc func keyboardWillShow(notification: NSNotification) {        
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
        if self.view.frame.origin.y == 0 {
            self.view.frame.origin.y -= keyboardSize.height
        }
    }        
}

@objc func keyboardWillHide(notification: NSNotification) {
    if self.view.frame.origin.y != 0 {
        self.view.frame.origin.y = 0
    }
}

EDIT FOR SWIFT 4.2:

override func viewDidLoad() {
    super.viewDidLoad()            
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
}

@objc func keyboardWillShow(notification: NSNotification) {
    if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
        if self.view.frame.origin.y == 0 {
            self.view.frame.origin.y -= keyboardSize.height
        }
    }
}

@objc func keyboardWillHide(notification: NSNotification) {
    if self.view.frame.origin.y != 0 {
        self.view.frame.origin.y = 0
    }
}