Programs & Examples On #Servlet 3.0

Java Servlets 3.0 is a new API that supports extensibility/pluggability, Ease of Development (EoD) using the newer language features, Async and Comet support, Security, and other features being as part of the revision for Java EE 6.

The server encountered an internal error that prevented it from fulfilling this request - in servlet 3.0

I found solution. It works fine when I throw away next line from form:

enctype="multipart/form-data"

And now it pass all parameters at request ok:

 <form action="/registration" method="post">
   <%-- error messages --%>
   <div class="form-group">
    <c:forEach items="${registrationErrors}" var="error">
    <p class="error">${error}</p>
     </c:forEach>
   </div>

Recommended way to save uploaded files in a servlet application

Store it anywhere in an accessible location except of the IDE's project folder aka the server's deploy folder, for reasons mentioned in the answer to Uploaded image only available after refreshing the page:

  1. Changes in the IDE's project folder does not immediately get reflected in the server's work folder. There's kind of a background job in the IDE which takes care that the server's work folder get synced with last updates (this is in IDE terms called "publishing"). This is the main cause of the problem you're seeing.

  2. In real world code there are circumstances where storing uploaded files in the webapp's deploy folder will not work at all. Some servers do (either by default or by configuration) not expand the deployed WAR file into the local disk file system, but instead fully in the memory. You can't create new files in the memory without basically editing the deployed WAR file and redeploying it.

  3. Even when the server expands the deployed WAR file into the local disk file system, all newly created files will get lost on a redeploy or even a simple restart, simply because those new files are not part of the original WAR file.

It really doesn't matter to me or anyone else where exactly on the local disk file system it will be saved, as long as you do not ever use getRealPath() method. Using that method is in any case alarming.

The path to the storage location can in turn be definied in many ways. You have to do it all by yourself. Perhaps this is where your confusion is caused because you somehow expected that the server does that all automagically. Please note that @MultipartConfig(location) does not specify the final upload destination, but the temporary storage location for the case file size exceeds memory storage threshold.

So, the path to the final storage location can be definied in either of the following ways:

  • Hardcoded:

      File uploads = new File("/path/to/uploads");
    
  • Environment variable via SET UPLOAD_LOCATION=/path/to/uploads:

      File uploads = new File(System.getenv("UPLOAD_LOCATION"));
    
  • VM argument during server startup via -Dupload.location="/path/to/uploads":

      File uploads = new File(System.getProperty("upload.location"));
    
  • *.properties file entry as upload.location=/path/to/uploads:

      File uploads = new File(properties.getProperty("upload.location"));
    
  • web.xml <context-param> with name upload.location and value /path/to/uploads:

      File uploads = new File(getServletContext().getInitParameter("upload.location"));
    
  • If any, use the server-provided location, e.g. in JBoss AS/WildFly:

      File uploads = new File(System.getProperty("jboss.server.data.dir"), "uploads");
    

Either way, you can easily reference and save the file as follows:

File file = new File(uploads, "somefilename.ext");

try (InputStream input = part.getInputStream()) {
    Files.copy(input, file.toPath());
}

Or, when you want to autogenerate an unique file name to prevent users from overwriting existing files with coincidentally the same name:

File file = File.createTempFile("somefilename-", ".ext", uploads);

try (InputStream input = part.getInputStream()) {
    Files.copy(input, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
}

How to obtain part in JSP/Servlet is answered in How to upload files to server using JSP/Servlet? and how to obtain part in JSF is answered in How to upload file using JSF 2.2 <h:inputFile>? Where is the saved File?

Note: do not use Part#write() as it interprets the path relative to the temporary storage location defined in @MultipartConfig(location).

See also:

Can't import javax.servlet.annotation.WebServlet

If you are using IBM RAD, then ensure the to remove any j2ee.jar in your projects build path -> libraries tab, and then click on "add external jar" and select the j2ee.jar that is shipped with RAD.

What is difference between @RequestBody and @RequestParam?

Here is an example with @RequestBody, First look at the controller !!

  public ResponseEntity<Void> postNewProductDto(@RequestBody NewProductDto newProductDto) {

   ...
        productService.registerProductDto(newProductDto);
        return new ResponseEntity<>(HttpStatus.CREATED);
   ....

}

And here is angular controller

function postNewProductDto() {
                var url = "/admin/products/newItem";
                $http.post(url, vm.newProductDto).then(function () {
                            //other things go here...
                            vm.newProductMessage = "Product successful registered";
                        }
                        ,
                        function (errResponse) {
                            //handling errors ....
                        }
                );
            }

And a short look at form

 <label>Name: </label>
 <input ng-model="vm.newProductDto.name" />

<label>Price </label> 
 <input ng-model="vm.newProductDto.price"/>

 <label>Quantity </label>
  <input ng-model="vm.newProductDto.quantity"/>

 <label>Image </label>
 <input ng-model="vm.newProductDto.photo"/>

 <Button ng-click="vm.postNewProductDto()" >Insert Item</Button>

 <label > {{vm.newProductMessage}} </label>

When using .net MVC RadioButtonFor(), how do you group so only one selection can be made?

In my case, I had a collection of radio buttons that needed to be in a group. I just included a 'Selected' property in the model. Then, in the loop to output the radiobuttons just do...

@Html.RadioButtonFor(m => Model.Selected, Model.Categories[i].Title)

This way, the name is the same for all radio buttons. When the form is posted, the 'Selected' property is equal to the category title (or id or whatever) and this can be used to update the binding on the relevant radiobutton, like this...

model.Categories.Find(m => m.Title.Equals(model.Selected)).Selected = true;

May not be the best way, but it does work.

react-native - Fit Image in containing View, not the whole screen size

Anyone over here who wants his image to fit in full screen without any crop (in both portrait and landscape mode), use this:

image: {
    flex: 1,
    width: '100%',
    height: '100%',
    resizeMode: 'contain',
},

SQL select statements with multiple tables

select P.*,
A.Street,
A.City,
A.State
from Preson P
inner join Address A on P.id=A.Person_id
where A.Zip=97229
Order by A.Street,A.City,A.State

Popup window in winform c#

This is not so easy because basically popups are not supported in windows forms. Although windows forms is based on win32 and in win32 popup are supported. If you accept a few tricks, following code will set you going with a popup. You decide if you want to put it to good use :

class PopupWindow : Control
{
    private const int WM_ACTIVATE = 0x0006;
    private const int WM_MOUSEACTIVATE = 0x0021;

    private Control ownerControl;

    public PopupWindow(Control ownerControl)
        :base()
    {
        this.ownerControl = ownerControl;
        base.SetTopLevel(true);
    }

    public Control OwnerControl
    {
        get
        {
            return (this.ownerControl as Control);
        }
        set
        {
            this.ownerControl = value;
        }
    }

    protected override CreateParams CreateParams
    {
        get
        {
            CreateParams createParams = base.CreateParams;

            createParams.Style = WindowStyles.WS_POPUP |
                                 WindowStyles.WS_VISIBLE |
                                 WindowStyles.WS_CLIPSIBLINGS |
                                 WindowStyles.WS_CLIPCHILDREN |
                                 WindowStyles.WS_MAXIMIZEBOX |
                                 WindowStyles.WS_BORDER;
            createParams.ExStyle = WindowsExtendedStyles.WS_EX_LEFT |
                                   WindowsExtendedStyles.WS_EX_LTRREADING |
                                   WindowsExtendedStyles.WS_EX_RIGHTSCROLLBAR | 
                                   WindowsExtendedStyles.WS_EX_TOPMOST;

            createParams.Parent = (this.ownerControl != null) ? this.ownerControl.Handle : IntPtr.Zero;
            return createParams;
        }
    }

    [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
    public static extern IntPtr SetActiveWindow(HandleRef hWnd);

    protected override void WndProc(ref Message m)
    {
        switch (m.Msg)
        {
            case WM_ACTIVATE:
                {
                    if ((int)m.WParam == 1)
                    {
                        //window is being activated
                        if (ownerControl != null)
                        {
                            SetActiveWindow(new HandleRef(this, ownerControl.FindForm().Handle));
                        }
                    }
                    break;
                }
            case WM_MOUSEACTIVATE:
                {
                    m.Result = new IntPtr(MouseActivate.MA_NOACTIVATE);
                    return;
                    //break;
                }
        }
        base.WndProc(ref m);
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
        e.Graphics.FillRectangle(SystemBrushes.Info, 0, 0, Width, Height);
        e.Graphics.DrawString((ownerControl as VerticalDateScrollBar).FirstVisibleDate.ToLongDateString(), this.Font, SystemBrushes.InfoText, 2, 2);
    }
}

Experiment with it a bit, you have to play around with its position and its size. Use it wrong and nothing shows.

TypeError: module.__init__() takes at most 2 arguments (3 given)

Even after @Mickey Perlstein's answer and his 3 hours of detective work, it still took me a few more minutes to apply this to my own mess. In case anyone else is like me and needs a little more help, here's what was going on in my situation.

  • responses is a module
  • Response is a base class within the responses module
  • GeoJsonResponse is a new class derived from Response

Initial GeoJsonResponse class:

from pyexample.responses import Response

class GeoJsonResponse(Response):

    def __init__(self, geo_json_data):

Looks fine. No problems until you try to debug the thing, which is when you get a bunch of seemingly vague error messages like this:

from pyexample.responses import GeoJsonResponse ..\pyexample\responses\GeoJsonResponse.py:12: in (module) class GeoJsonResponse(Response):

E TypeError: module() takes at most 2 arguments (3 given)

=================================== ERRORS ====================================

___________________ ERROR collecting tests/test_geojson.py ____________________

test_geojson.py:2: in (module) from pyexample.responses import GeoJsonResponse ..\pyexample\responses \GeoJsonResponse.py:12: in (module)

class GeoJsonResponse(Response): E TypeError: module() takes at most 2 arguments (3 given)

ERROR: not found: \PyExample\tests\test_geojson.py::TestGeoJson::test_api_response

C:\Python37\lib\site-packages\aenum__init__.py:163

(no name 'PyExample\ tests\test_geojson.py::TestGeoJson::test_api_response' in any of [])

The errors were doing their best to point me in the right direction, and @Mickey Perlstein's answer was dead on, it just took me a minute to put it all together in my own context:

I was importing the module:

from pyexample.responses import Response

when I should have been importing the class:

from pyexample.responses.Response import Response

Hope this helps someone. (In my defense, it's still pretty early.)

Copy folder recursively in Node.js

I know so many answers are already here, but no one answered it in a simple way.

Regarding fs-exra official documentation, you can do it very easy.

const fs = require('fs-extra')

// Copy file
fs.copySync('/tmp/myfile', '/tmp/mynewfile')

// Copy directory, even if it has subdirectories or files
fs.copySync('/tmp/mydir', '/tmp/mynewdir')

How do I set the default font size in Vim?

Try a \<Space> before 12, like so:

:set guifont=Monospace\ 12

How to Load an Assembly to AppDomain with all references recursively?

Once you pass the assembly instance back to the caller domain, the caller domain will try to load it! This is why you get the exception. This happens in your last line of code:

domain.Load(AssemblyName.GetAssemblyName(path));

Thus, whatever you want to do with the assembly, should be done in a proxy class - a class which inherit MarshalByRefObject.

Take in count that the caller domain and the new created domain should both have access to the proxy class assembly. If your issue is not too complicated, consider leaving the ApplicationBase folder unchanged, so it will be same as the caller domain folder (the new domain will only load Assemblies it needs).

In simple code:

public void DoStuffInOtherDomain()
{
    const string assemblyPath = @"[AsmPath]";
    var newDomain = AppDomain.CreateDomain("newDomain");
    var asmLoaderProxy = (ProxyDomain)newDomain.CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().FullName, typeof(ProxyDomain).FullName);

    asmLoaderProxy.GetAssembly(assemblyPath);
}

class ProxyDomain : MarshalByRefObject
{
    public void GetAssembly(string AssemblyPath)
    {
        try
        {
            Assembly.LoadFrom(AssemblyPath);
            //If you want to do anything further to that assembly, you need to do it here.
        }
        catch (Exception ex)
        {
            throw new InvalidOperationException(ex.Message, ex);
        }
    }
}

If you do need to load the assemblies from a folder which is different than you current app domain folder, create the new app domain with specific dlls search path folder.

For example, the app domain creation line from the above code should be replaced with:

var dllsSearchPath = @"[dlls search path for new app domain]";
AppDomain newDomain = AppDomain.CreateDomain("newDomain", new Evidence(), dllsSearchPath, "", true);

This way, all the dlls will automaically be resolved from dllsSearchPath.

ORDER BY items must appear in the select list if SELECT DISTINCT is specified

When you define concatenation you need to use an ALIAS for the new column if you want to order on it combined with DISTINCT Some Ex with sql 2008

--this works 

    SELECT DISTINCT (c.FirstName + ' ' + c.LastName) as FullName 
    from SalesLT.Customer c 
    order by FullName

--this works too

    SELECT DISTINCT (c.FirstName + ' ' + c.LastName) 
    from SalesLT.Customer c 
    order by 1

-- this doesn't 

    SELECT DISTINCT (c.FirstName + ' ' + c.LastName) as FullName 
    from SalesLT.Customer c 
    order by c.FirstName, c.LastName

-- the problem the DISTINCT needs an order on the new concatenated column, here I order on the singular column
-- this works

    SELECT DISTINCT (c.FirstName + ' ' + c.LastName) 
        as FullName, CustomerID 
        from SalesLT.Customer c 

order by 1, CustomerID

-- this doesn't

    SELECT DISTINCT (c.FirstName + ' ' + c.LastName) as FullName 
     from SalesLT.Customer c 
      order by 1, CustomerID

How do I select an element with its name attribute in jQuery?

jQuery("[name='test']") 

Although you should avoid it and if possible select by ID (e.g. #myId) as this has better performance because it invokes the native getElementById.

Can't accept license agreement Android SDK Platform 24

This issue is surfacing when already an old version of SDK Manager is in the machine from where the approach of Android build is Changed which requires "android studio". I faced this in Visual Studio that was repeatedly halted with Error Message, "You have not accepted the License for version 25". The solution for this is "Install the Android Studio" and then "go to Environment Variables" and set the ANDROID_HOME to "C:\Users\\AppData\Local\Android\Sdk" (This path can be picked from Android Studio, Menu >> Tools >> SDK Manager. Also use the same in "path" of Environment Variables. This way, the new SDK manager is mapped for pickup by Visual Studio Build for Cordova Application.

This just took my 2 days effort second time

Wish others don't waste their time in this mess.

How to edit Docker container files from the host?

The best way is:

  $ docker cp CONTAINER:FILEPATH LOCALFILEPATH
  $ vi LOCALFILEPATH
  $ docker cp LOCALFILEPATH CONTAINER:FILEPATH

Limitations with $ docker exec: it can only attach to a running container.

Limitations with $ docker run: it will create a new container.

How to add /usr/local/bin in $PATH on Mac

I've had the same problem with you.

cd to ../etc/ then use ls to make sure your "paths" file is in , vim paths, add "/usr/local/bin" at the end of the file.

How can Print Preview be called from Javascript?

I think the best that's possible in cross-browser JavaScript is window.print(), which (in Firefox 3, for me) brings up the 'print' dialog and not the print preview dialog.

FYI, the print dialog is your computer's Print popup, what you get when you do Ctrl-p. The print preview is Firefox's own Preview window, and it has more options. It's what you get with Firefox Menu > Print...

How to automate drag & drop functionality using Selenium WebDriver Java

Drag and drop can be implemented like this...

public ObjectPage filter(int lowerThreshold, int highThreshold) {
    Actions action = new Actions(getWebDriver());
    action.dragAndDropBy(findElement(".className .thumbMin"), lowerThreshold, 0).perform();
    waitFor(elementIsNotDisplayed("#waiting_dialog"));

    action.dragAndDropBy(findElement(".className .thumbMax"), highThreshold, 0).perform();
    waitFor(elementIsNotDisplayed("#waiting_dialog"));
    return this;
}

Hope that helps!

How to find whether a ResultSet is empty or not in Java?

Immediately after your execute statement you can have an if statement. For example

ResultSet rs = statement.execute();
if (!rs.next()){
//ResultSet is empty
}

SQL User Defined Function Within Select

Yes, you can do almost that:

SELECT dbo.GetBusinessDays(a.opendate,a.closedate) as BusinessDays
FROM account a
WHERE...

Using AES encryption in C#

Try this code, maybe useful.
1.Create New C# Project and add follows code to Form1:

using System;
using System.Windows.Forms;
using System.Security.Cryptography;

namespace ExampleCrypto
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string strOriginalData = string.Empty;
            string strEncryptedData = string.Empty;
            string strDecryptedData = string.Empty;

            strOriginalData = "this is original data 1234567890"; // your original data in here
            MessageBox.Show("ORIGINAL DATA:\r\n" + strOriginalData);

            clsCrypto aes = new clsCrypto();
            aes.IV = "this is your IV";     // your IV
            aes.KEY = "this is your KEY";    // your KEY      
            strEncryptedData = aes.Encrypt(strOriginalData, CipherMode.CBC);    // your cipher mode
            MessageBox.Show("ENCRYPTED DATA:\r\n" + strEncryptedData);

            strDecryptedData = aes.Decrypt(strEncryptedData, CipherMode.CBC);
            MessageBox.Show("DECRYPTED DATA:\r\n" + strDecryptedData);
        }

    }
}

2.Create clsCrypto.cs and copy paste follows code in your class and run your code. I used MD5 to generated Initial Vector(IV) and KEY of AES.

using System;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Runtime.Remoting.Metadata.W3cXsd2001;

namespace ExampleCrypto
{
    public class clsCrypto
    {
        private string _KEY = string.Empty;
        protected internal string KEY
        {
            get
            {
                return _KEY;
            }
            set
            {
                if (!string.IsNullOrEmpty(value))
                {
                    _KEY = value;
                }
            }
        }

        private string _IV = string.Empty;
        protected internal string IV
        {
            get
            {
                return _IV;
            }
            set
            {
                if (!string.IsNullOrEmpty(value))
                {
                    _IV = value;
                }
            }
        }

        private string CalcMD5(string strInput)
        {
            string strOutput = string.Empty;
            if (!string.IsNullOrEmpty(strInput))
            {
                try
                {
                    StringBuilder strHex = new StringBuilder();
                    using (MD5 md5 = MD5.Create())
                    {
                        byte[] bytArText = Encoding.Default.GetBytes(strInput);
                        byte[] bytArHash = md5.ComputeHash(bytArText);
                        for (int i = 0; i < bytArHash.Length; i++)
                        {
                            strHex.Append(bytArHash[i].ToString("X2"));
                        }
                        strOutput = strHex.ToString();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            return strOutput;
        }

        private byte[] GetBytesFromHexString(string strInput)
        {
            byte[] bytArOutput = new byte[] { };
            if ((!string.IsNullOrEmpty(strInput)) && strInput.Length % 2 == 0)
            {
                SoapHexBinary hexBinary = null;
                try
                {
                    hexBinary = SoapHexBinary.Parse(strInput);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                bytArOutput = hexBinary.Value;
            }
            return bytArOutput;
        }

        private byte[] GenerateIV()
        {
            byte[] bytArOutput = new byte[] { };
            try
            {
                string strIV = CalcMD5(IV);
                bytArOutput = GetBytesFromHexString(strIV);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return bytArOutput;
        }

        private byte[] GenerateKey()
        {
            byte[] bytArOutput = new byte[] { };
            try
            {
                string strKey = CalcMD5(KEY);
                bytArOutput = GetBytesFromHexString(strKey);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return bytArOutput;
        }

        protected internal string Encrypt(string strInput, CipherMode cipherMode)
        {
            string strOutput = string.Empty;
            if (!string.IsNullOrEmpty(strInput))
            {
                try
                {
                    byte[] bytePlainText = Encoding.Default.GetBytes(strInput);
                    using (RijndaelManaged rijManaged = new RijndaelManaged())
                    {
                        rijManaged.Mode = cipherMode;
                        rijManaged.BlockSize = 128;
                        rijManaged.KeySize = 128;
                        rijManaged.IV = GenerateIV();
                        rijManaged.Key = GenerateKey();
                        rijManaged.Padding = PaddingMode.Zeros;
                        ICryptoTransform icpoTransform = rijManaged.CreateEncryptor(rijManaged.Key, rijManaged.IV);
                        using (MemoryStream memStream = new MemoryStream())
                        {
                            using (CryptoStream cpoStream = new CryptoStream(memStream, icpoTransform, CryptoStreamMode.Write))
                            {
                                cpoStream.Write(bytePlainText, 0, bytePlainText.Length);
                                cpoStream.FlushFinalBlock();
                            }
                            strOutput = Encoding.Default.GetString(memStream.ToArray());
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            return strOutput;
        }

        protected internal string Decrypt(string strInput, CipherMode cipherMode)
        {
            string strOutput = string.Empty;
            if (!string.IsNullOrEmpty(strInput))
            {
                try
                {
                    byte[] byteCipherText = Encoding.Default.GetBytes(strInput);
                    byte[] byteBuffer = new byte[strInput.Length];
                    using (RijndaelManaged rijManaged = new RijndaelManaged())
                    {
                        rijManaged.Mode = cipherMode;
                        rijManaged.BlockSize = 128;
                        rijManaged.KeySize = 128;
                        rijManaged.IV = GenerateIV();
                        rijManaged.Key = GenerateKey();
                        rijManaged.Padding = PaddingMode.Zeros;
                        ICryptoTransform icpoTransform = rijManaged.CreateDecryptor(rijManaged.Key, rijManaged.IV);
                        using (MemoryStream memStream = new MemoryStream(byteCipherText))
                        {
                            using (CryptoStream cpoStream = new CryptoStream(memStream, icpoTransform, CryptoStreamMode.Read))
                            {
                                cpoStream.Read(byteBuffer, 0, byteBuffer.Length);
                            }
                            strOutput = Encoding.Default.GetString(byteBuffer);
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            return strOutput;
        }

    }
}

Python way to clone a git repository

This is the sample code for gitpull and gitpush using gitpython module.

import os.path
from git import *
import git, os, shutil
# create local Repo/Folder
UPLOAD_FOLDER = "LocalPath/Folder"
if not os.path.exists(UPLOAD_FOLDER):
  os.makedirs(UPLOAD_FOLDER)
  print(UPLOAD_FOLDER)
new_path = os.path.join(UPLOADFOLDER)
DIR_NAME = new_path
REMOTE_URL = "GitURL"  # if you already connected with server you dont need to give 
any credential
# REMOTE_URL looks "[email protected]:path of Repo"
# code for clone
class git_operation_clone():
  try:
    def __init__(self):
        self.DIR_NAME = DIR_NAME
        self.REMOTE_URL = REMOTE_URL

    def git_clone(self):

        if os.path.isdir(DIR_NAME):
            shutil.rmtree(DIR_NAME)
        os.mkdir(DIR_NAME)
        repo = git.Repo.init(DIR_NAME)
        origin = repo.create_remote('origin', REMOTE_URL)
        origin.fetch()
        origin.pull(origin.refs[0].remote_head)
  except Exception as e:
      print(str(e))
# code for push
class git_operation_push():
  def git_push_file(self):
    try:
        repo = Repo(DIR_NAME)
        commit_message = 'work in progress'
        # repo.index.add(u=True)
        repo.git.add('--all')
        repo.index.commit(commit_message)
        origin = repo.remote('origin')
        origin.push('master')
        repo.git.add(update=True)
        print("repo push succesfully")
    except Exception as e:
        print(str(e))
if __name__ == '__main__':
   a = git_operation_push()
   git_operation_push.git_push_file('')
   git_operation_clone()
   git_operation_clone.git_clone('')

Build error: You must add a reference to System.Runtime

i added System.Runtime.dll to bin project and it worked :)

How to set delay in vbscript

The following line will make your script to sleep for 5 mins.

WScript.Sleep 5*60*1000

Note that the value passed to sleep call is in milli seconds.

SQL conditional SELECT

In SQL, you do it this way:

SELECT  CASE WHEN @selectField1 = 1 THEN Field1 ELSE NULL END,
        CASE WHEN @selectField2 = 1 THEN Field2 ELSE NULL END
FROM    Table

Relational model does not imply dynamic field count.

Instead, if you are not interested in a field value, you just select a NULL instead and parse it on the client.

How to create a inset box-shadow only on one side?

Literally you can't do such a thing, but you should try this CSS trick:

box-shadow: inset 0 3vw 6vw rgba(0,0,0,0.6), inset 0 -3vw 6vw rgba(0,0,0,0.6);

Best way to unselect a <select> in jQuery?

$("#selectID option:selected").each(function(){
  $(this).removeAttr("selected");
});

This would iterate through each item and unselect only the ones which are checked

What is the correct syntax of ng-include?

Maybe this will help for beginners

<!doctype html>
<html lang="en" ng-app>
  <head>
    <meta charset="utf-8">
    <title></title>
    <link rel="icon" href="favicon.ico">
    <link rel="stylesheet" href="custom.css">
  </head>
  <body>
    <div ng-include src="'view/01.html'"></div>
    <div ng-include src="'view/02.html'"></div>
    <script src="angular.min.js"></script>
  </body>
</html>

How to auto adjust table td width from the content

Remove all widths set using CSS and set white-space to nowrap like so:

.content-loader tr td {
    white-space: nowrap;
}

I would also remove the fixed width from the container (or add overflow-x: scroll to the container) if you want the fields to display in their entirety without it looking odd...

See more here: http://www.w3schools.com/cssref/pr_text_white-space.asp

Setting SMTP details for php mail () function

Under Windows only: You may try to use ini_set() functionDocs for the SMTPDocs and smtp_portDocs settings:

ini_set('SMTP', 'mysmtphost'); 
ini_set('smtp_port', 25); 

Java: how do I get a class literal from a generic type?

To expound on cletus' answer, at runtime all record of the generic types is removed. Generics are processed only in the compiler and are used to provide additional type safety. They are really just shorthand that allows the compiler to insert typecasts at the appropriate places. For example, previously you'd have to do the following:

List x = new ArrayList();
x.add(new SomeClass());
Iterator i = x.iterator();
SomeClass z = (SomeClass) i.next();

becomes

List<SomeClass> x = new ArrayList<SomeClass>();
x.add(new SomeClass());
Iterator<SomeClass> i = x.iterator();
SomeClass z = i.next();

This allows the compiler to check your code at compile-time, but at runtime it still looks like the first example.

Center Oversized Image in Div

I found this to be a more elegant solution, without flex:

.wrapper {
    overflow: hidden;
}
.wrapper img {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    /* height: 100%; */ /* optional */
}

What is the correct XPath for choosing attributes that contain "foo"?

If you also need to match the content of the link itself, use text():

//a[contains(@href,"/some_link")][text()="Click here"]

What's the difference between KeyDown and KeyPress in .NET?

There is apparently a lot of misunderstanding about this!

The only practical difference between KeyDown and KeyPress is that KeyPress relays the character resulting from a keypress, and is only called if there is one.

In other words, if you press A on your keyboard, you'll get this sequence of events:

  1. KeyDown: KeyCode=Keys.A, KeyData=Keys.A, Modifiers=Keys.None
  2. KeyPress: KeyChar='a'
  3. KeyUp: KeyCode=Keys.A

But if you press Shift+A, you'll get:

  1. KeyDown: KeyCode=Keys.ShiftKey, KeyData=Keys.ShiftKey, Shift, Modifiers=Keys.Shift
  2. KeyDown: KeyCode=Keys.A, KeyData=Keys.A | Keys.Shift, Modifiers=Keys.Shift
  3. KeyPress: KeyChar='A'
  4. KeyUp: KeyCode=Keys.A
  5. KeyUp: KeyCode=Keys.ShiftKey

If you hold down the keys for a while, you'll get something like:

  1. KeyDown: KeyCode=Keys.ShiftKey, KeyData=Keys.ShiftKey, Shift, Modifiers=Keys.Shift
  2. KeyDown: KeyCode=Keys.ShiftKey, KeyData=Keys.ShiftKey, Shift, Modifiers=Keys.Shift
  3. KeyDown: KeyCode=Keys.ShiftKey, KeyData=Keys.ShiftKey, Shift, Modifiers=Keys.Shift
  4. KeyDown: KeyCode=Keys.ShiftKey, KeyData=Keys.ShiftKey, Shift, Modifiers=Keys.Shift
  5. KeyDown: KeyCode=Keys.ShiftKey, KeyData=Keys.ShiftKey, Shift, Modifiers=Keys.Shift
  6. KeyDown: KeyCode=Keys.A, KeyData=Keys.A | Keys.Shift, Modifiers=Keys.Shift
  7. KeyPress: KeyChar='A'
  8. KeyDown: KeyCode=Keys.A, KeyData=Keys.A | Keys.Shift, Modifiers=Keys.Shift
  9. KeyPress: KeyChar='A'
  10. KeyDown: KeyCode=Keys.A, KeyData=Keys.A | Keys.Shift, Modifiers=Keys.Shift
  11. KeyPress: KeyChar='A'
  12. KeyDown: KeyCode=Keys.A, KeyData=Keys.A | Keys.Shift, Modifiers=Keys.Shift
  13. KeyPress: KeyChar='A'
  14. KeyDown: KeyCode=Keys.A, KeyData=Keys.A | Keys.Shift, Modifiers=Keys.Shift
  15. KeyPress: KeyChar='A'
  16. KeyUp: KeyCode=Keys.A
  17. KeyUp: KeyCode=Keys.ShiftKey

Notice that KeyPress occurs in between KeyDown and KeyUp, not after KeyUp, as many of the other answers have stated, that KeyPress is not called when a character isn't generated, and that KeyDown is repeated while the key is held down, also contrary to many of the other answers.

Examples of keys that do not directly result in calls to KeyPress:

  • Shift, Ctrl, Alt
  • F1 through F12
  • Arrow keys

Examples of keys that do result in calls to KeyPress:

  • A through Z, 0 through 9, etc.
  • Spacebar
  • Tab (KeyChar='\t', ASCII 9)
  • Enter (KeyChar='\r', ASCII 13)
  • Esc (KeyChar='\x1b', ASCII 27)
  • Backspace (KeyChar='\b', ASCII 8)

For the curious, KeyDown roughly correlates to WM_KEYDOWN, KeyPress to WM_CHAR, and KeyUp to WM_KEYUP. WM_KEYDOWN can be called fewer than the the number of key repeats, but it sends a repeat count, which, IIRC, WinForms uses to generate exactly one KeyDown per repeat.

int value under 10 convert to string two digit number

I can't believe nobody suggested this:

int i = 9;
i.ToString("D2"); // Will give you the string "09"

or

i.ToString("D8"); // Will give you the string "00000009"

If you want hexadecimal:

byte b = 255;
b.ToString("X2"); // Will give you the string "FF"

You can even use just "C" to display as currency if you locale currency symbol. See here: https://docs.microsoft.com/en-us/dotnet/api/system.int32.tostring?view=netframework-4.7.2#System_Int32_ToString_System_String_

Compare two dates with JavaScript

Hi Here is my code to compare dates . In my case i am doing a check to not allow to select past dates.

var myPickupDate = <pick up date> ;
var isPastPickupDateSelected = false;
var currentDate = new Date();

if(currentDate.getFullYear() <= myPickupDate.getFullYear()){
    if(currentDate.getMonth()+1 <= myPickupDate.getMonth()+1 || currentDate.getFullYear() < myPickupDate.getFullYear()){
                        if(currentDate.getDate() <= myPickupDate.getDate() || currentDate.getMonth()+1 < myPickupDate.getMonth()+1 || currentDate.getFullYear() < myPickupDate.getFullYear()){
                                            isPastPickupDateSelected = false;
                                            return;
                                        }
                    }
}
console.log("cannot select past pickup date");
isPastPickupDateSelected = true;

Find most frequent value in SQL column

Try something like:

SELECT       `column`
    FROM     `your_table`
    GROUP BY `column`
    ORDER BY COUNT(*) DESC
    LIMIT    1;

Why can't I change my input value in React even with the onChange listener

In react, state will not change until you do it by using this.setState({});. That is why your console message showing old values.

Passing parameter to controller action from a Html.ActionLink

You are using the incorrect overload of ActionLink. Try this

<%= Html.ActionLink("Create New Part", "CreateParts", "PartList", new { parentPartId = 0 }, null)%>

The HTTP request is unauthorized with client authentication scheme 'Ntlm'. The authentication header received from the server was 'Negotiate,NTLM'

You can eliminate the client from the problem by using wftech, this is an old tool but I have found it useful in diagnosing authentication issues. wfetch allows you to specify NTLM, Negotiate and kerberos, this may well help you better understand your problem. As you are trying to call a service and wfetch knows nothing about WCF, I would suggest applying your endpoint binding (PROVIDERSSoapBinding) to the serviceMetadata then you can do an HTTP GET of the WSDL for the service with the same security settings.

Another option, which may be available to you is to force the server to use NTLM, you can do this by either editing the metabase (IIS 6) and removing the Negotiate setting, more details at http://support.microsoft.com/kb/215383.

If you are using IIS 7.x then the approach is slightly different, details of how to configure the authentication providers are here http://www.iis.net/configreference/system.webserver/security/authentication/windowsauthentication.

I notice that you have blocked out the server address with xxx.xx.xx.xxx, so I'm guessing that this is an IP address rather than a server name, this may cause issues with authentication, so if possible try targeting the machine name.

Sorry that I haven't given you the answer but rather pointers for getting closer to the issue, but I hope it helps.

I'll finish by saying that I have experienced this same issue and my only recourse was to use Kerberos rather than NTLM, don't forget you'll need to register an SPN for the service if you do go down this route.

Get last key-value pair in PHP array

try to use

end($array);

Resizable table columns with jQuery

:-) Once I found myself in the same situation, there was no jQuery plugin matching my requeriments, so I spend some time developing my own one: colResizable
 

About colResizable

colResizable is a free jQuery plugin to resize table columns dragging them manually. It is compatible with both mouse and touch devices and has some nice features such as layout persistence after page refresh or postback. It works with both percentage and pixel-based table layouts.

It is tiny in size (colResizable 1.0 is only 2kb) and it is fully compatible with all major browsers (IE7+, Firefox, Chrome and Opera).

enter image description here

Features

colResizable was developed since no other similar plugin with the below listed features was found:

  • Compatible with mouse and touch devices (PC, tablets, and mobile phones)
  • Compatibility with both percentage and pixel-based table layouts
  • Column resizing not altering total table width (optional)
  • No external resources needed (such as images or stylesheets)
  • Optional layout persistence after page refresh or postback
  • Customization of column anchors
  • Small footprint
  • Cross-browser compatibility (IE7+, Chrome, Safari, Firefox)
  • Events

Comparison with other plugins

colResizable is the most polished plugin to resize table columns out there. It has plenty of customization possibilities and it is also compatible with touch devices. But probably the most interesting feature which is making colResizable the greatest choice is that it is compatible with both pixel-based and fluid percentage table layouts. But, what does it mean?

If the width of a table is set to, lets say 90%, and the column widths are modified using colResizable, when the browser is resized columns widths are resized proportionally. While other plugins does behave odd, colResizable does its job just as expected.

colResizable is also compatible with table max-width attribute: if the sum of all columns exceed the table's max-width, they are automatically fixed and updated.

Another great advantage compared with other plugins is that it is compatible with page refresh, postbacks and even partial postbacks if the table is located inside of an updatePanel. It is compatible with all major browsers (IE7+, Firefox, Chrome and Opera), while other plugins fail with old IE versions.

See samples and JSFiddle.

Code sample

$("#sample").colResizable({
        liveDrag:true
});

Use Ant for running program with command line arguments

Extending Richard Cook's answer.

Here's the ant task to run any program (including, but not limited to Java programs):

<target name="run">
   <exec executable="name-of-executable">
      <arg value="${arg0}"/>
      <arg value="${arg1}"/>
   </exec>
</target>

Here's the task to run a Java program from a .jar file:

<target name="run-java">
   <java jar="path for jar">
      <arg value="${arg0}"/>
      <arg value="${arg1}"/>
   </java>
</target>

You can invoke either from the command line like this:

ant -Darg0=Hello -Darg1=World run

Make sure to use the -Darg syntax; if you ran this:

ant run arg0 arg1

then ant would try to run targets arg0 and arg1.

Best way to center a <div> on a page vertically and horizontally?

I know I am late to the party but here is a way to center a div with unknown dimension inside a parent of unknown dimension.

style:

<style>

    .table {
      display: table;
      height: 100%;
      margin: 0 auto;
    }
    .table-cell {
      display: table-cell;
      vertical-align: middle;      
    }
    .centered {
      background-color: red;
    }
  </style>

HTML:

<div class="table">
    <div class="table-cell"><div class="centered">centered</div></div>
</div>

DEMO:

Check out this demo.

Can't concatenate 2 arrays in PHP

Try saying

$array[] = array('Item 2'); 

Although it looks like you're trying to add an array into an array, thus $array[][] but that's not what your title suggests.

java.lang.IllegalArgumentException: View not attached to window manager

Here is my "bullet proof" solution, which is compilation of all good answers that I found on this topic (thanks to @Damjan and @Kachi). Here the exception is swallowed only if all other ways of detection did not succeeded. In my case I need to close the dialog automatically and this is the only way to protect the app from crash. I hope it will help you! Please, vote and leave comments if you have remarks or better solution. Thank you!

public void dismissWithCheck(Dialog dialog) {
        if (dialog != null) {
            if (dialog.isShowing()) {

                //get the Context object that was used to great the dialog
                Context context = ((ContextWrapper) dialog.getContext()).getBaseContext();

                // if the Context used here was an activity AND it hasn't been finished or destroyed
                // then dismiss it
                if (context instanceof Activity) {

                    // Api >=17
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                        if (!((Activity) context).isFinishing() && !((Activity) context).isDestroyed()) {
                            dismissWithTryCatch(dialog);
                        }
                    } else {

                        // Api < 17. Unfortunately cannot check for isDestroyed()
                        if (!((Activity) context).isFinishing()) {
                            dismissWithTryCatch(dialog);
                        }
                    }
                } else
                    // if the Context used wasn't an Activity, then dismiss it too
                    dismissWithTryCatch(dialog);
            }
            dialog = null;
        }
    }

    public void dismissWithTryCatch(Dialog dialog) {
        try {
            dialog.dismiss();
        } catch (final IllegalArgumentException e) {
            // Do nothing.
        } catch (final Exception e) {
            // Do nothing.
        } finally {
            dialog = null;
        }
    }

"Register" an .exe so you can run it from any command line in Windows

Use a 1 line batch file in your install:

SETX PATH "C:\Windows"

run the bat file

Now place your .exe in c:\windows, and you're done.

you may type the 'exename' in command-line and it'll run it.

How to replace string in Groovy

You need to escape the backslash \:

println yourString.replace("\\", "/")

Custom date format with jQuery validation plugin

Here is an example for a new validation method that will validate almost any date format, including:

  • dd/mm/yy or dd/mm/yyyy
  • dd.mm.yy or dd.mm.yyyy
  • dd,mm,yy or dd,mm,yyyy
  • dd mm yy or dd mm yyyy
  • dd-mm-yy or dd-mm-yyyy

Then, when you pass the value to the php you can convert it with strtotime

Here is how to add the method:

    $.validator.addMethod("anyDate",
    function(value, element) {
        return value.match(/^(0?[1-9]|[12][0-9]|3[0-1])[/., -](0?[1-9]|1[0-2])[/., -](19|20)?\d{2}$/);
    },
    "Please enter a date in the format!"
);

Then you add the new filter with:

$('#myForm')
.validate({
    rules : {
        field: {
            anyDate: true
        }
    }
})

;

C++ error : terminate called after throwing an instance of 'std::bad_alloc'

The problem in your code is that you can't store the memory address of a local variable (local to a function, for example) in a globlar variable:

RectInvoice rect(vect,im,x, y, w ,h);
this->rectInvoiceVector.push_back(&rect);

There, &rect is a temporary address (stored in the function's activation registry) and will be destroyed when that function end.

The code should create a dynamic variable:

RectInvoice *rect =  new RectInvoice(vect,im,x, y, w ,h);
this->rectInvoiceVector.push_back(rect);

There you are using a heap address that will not be destroyed in the end of the function's execution. Tell me if it worked for you.

Cheers

Git will not init/sync/update new submodules

Please check your submodules directory.

If there is only a .git file in it, then delete it.

Now execute git submodule update --remote --init

TypeError: a bytes-like object is required, not 'str'

Whenever you encounter an error with this message use my_string.encode().

(where my_string is the string you're passing to a function/method).

The encode method of str objects returns the encoded version of the string as a bytes object which you can then use. In this specific instance, socket methods such as .send expect a bytes object as the data to be sent, not a string object.

Since you have an object of type str and you're passing it to a function/method that expects an object of type bytes, an error is raised that clearly explains that:

TypeError: a bytes-like object is required, not 'str'

So the encode method of strings is needed, applied on a str value and returning a bytes value:

>>> s = "Hello world"
>>> print(type(s))
<class 'str'>
>>> byte_s = s.encode()
>>> print(type(byte_s))
<class 'bytes'>
>>> print(byte_s)
b"Hello world"

Here the prefix b in b'Hello world' denotes that this is indeed a bytes object. You can then pass it to whatever function is expecting it in order for it to run smoothly.

How to call function that takes an argument in a Django template?

I'm passing to Django's template a function, which returns me some records

Why don't you pass to Django template the variable storing function's return value, instead of the function?


I've tried to set fuction's return value to a variable and iterate over variable, but there seems to be no way to set variable in Django template.

You should set variables in Django views instead of templates, and then pass them to the template.

SQLAlchemy: how to filter date field?

if you want to get the whole period:

    from sqlalchemy import and_, func

    query = DBSession.query(User).filter(and_(func.date(User.birthday) >= '1985-01-17'),\
                                              func.date(User.birthday) <= '1988-01-17'))

That means range: 1985-01-17 00:00 - 1988-01-17 23:59

Change the mouse pointer using JavaScript

With regards to @CrazyJugglerDrummer second method it would be:

elementsToChange.style.cursor = "http://wiki-devel.sugarlabs.org/images/e/e2/Arrow.cur";

How to get the file extension in PHP?

How about

$ext = array_pop($userfile_extn);

Why should Java 8's Optional not be used in arguments

There are almost no good reasons for not using Optional as parameters. The arguments against this rely on arguments from authority (see Brian Goetz - his argument is we can't enforce non null optionals) or that the Optional arguments may be null (essentially the same argument). Of course, any reference in Java can be null, we need to encourage rules being enforced by the compiler, not programmers memory (which is problematic and does not scale).

Functional programming languages encourage Optional parameters. One of the best ways of using this is to have multiple optional parameters and using liftM2 to use a function assuming the parameters are not empty and returning an optional (see http://www.functionaljava.org/javadoc/4.4/functionaljava/fj/data/Option.html#liftM2-fj.F-). Java 8 has unfortunately implemented a very limited library supporting optional.

As Java programmers we should only be using null to interact with legacy libraries.

Storing Objects in HTML5 localStorage

Extending the Storage object is an awesome solution. For my API, I have created a facade for localStorage and then check if it is an object or not while setting and getting.

var data = {
  set: function(key, value) {
    if (!key || !value) {return;}

    if (typeof value === "object") {
      value = JSON.stringify(value);
    }
    localStorage.setItem(key, value);
  },
  get: function(key) {
    var value = localStorage.getItem(key);

    if (!value) {return;}

    // assume it is an object that has been stringified
    if (value[0] === "{") {
      value = JSON.parse(value);
    }

    return value;
  }
}

COUNT DISTINCT with CONDITIONS

Code counts the unique/distinct combination of Tag & Entry ID when [Entry Id]>0

select count(distinct(concat(tag,entryId)))
from customers
where id>0

In the output it will display the count of unique values Hope this helps

Strange PostgreSQL "value too long for type character varying(500)"

Character varying is different than text. Try running

ALTER TABLE product_product ALTER COLUMN code TYPE text;

That will change the column type to text, which is limited to some very large amount of data (you would probably never actually hit it.)

ElasticSearch - Return Unique Values

To had to distinct by two fields (derivative_id & vehicle_type) and to sort by cheapest car. Had to nest aggs.

GET /cars/_search
{
  "size": 0,
  "aggs": {
    "distinct_by_derivative_id": {
      "terms": { 
        "field": "derivative_id"
      },
      "aggs": {
        "vehicle_type": {
          "terms": {
            "field": "vehicle_type"
          },
          "aggs": {
            "cheapest_vehicle": {
              "top_hits": {
                "sort": [
                  { "rental": { "order": "asc" } }
                ],
                "_source": { "includes": [ "manufacturer_name",
                  "rental",
                  "vehicle_type" 
                  ]
                },
                "size": 1
              }
            }
          }
        }
      }
    }
  }
}

Result:

{
  "took" : 3,
  "timed_out" : false,
  "_shards" : {
    "total" : 5,
    "successful" : 5,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 8,
      "relation" : "eq"
    },
    "max_score" : null,
    "hits" : [ ]
  },
  "aggregations" : {
    "distinct_by_derivative_id" : {
      "doc_count_error_upper_bound" : 0,
      "sum_other_doc_count" : 0,
      "buckets" : [
        {
          "key" : "04",
          "doc_count" : 3,
          "vehicle_type" : {
            "doc_count_error_upper_bound" : 0,
            "sum_other_doc_count" : 0,
            "buckets" : [
              {
                "key" : "CAR",
                "doc_count" : 2,
                "cheapest_vehicle" : {
                  "hits" : {
                    "total" : {
                      "value" : 2,
                      "relation" : "eq"
                    },
                    "max_score" : null,
                    "hits" : [
                      {
                        "_index" : "cars",
                        "_type" : "_doc",
                        "_id" : "8",
                        "_score" : null,
                        "_source" : {
                          "vehicle_type" : "CAR",
                          "manufacturer_name" : "Renault",
                          "rental" : 89.99
                        },
                        "sort" : [
                          89.99
                        ]
                      }
                    ]
                  }
                }
              },
              {
                "key" : "LCV",
                "doc_count" : 1,
                "cheapest_vehicle" : {
                  "hits" : {
                    "total" : {
                      "value" : 1,
                      "relation" : "eq"
                    },
                    "max_score" : null,
                    "hits" : [
                      {
                        "_index" : "cars",
                        "_type" : "_doc",
                        "_id" : "7",
                        "_score" : null,
                        "_source" : {
                          "vehicle_type" : "LCV",
                          "manufacturer_name" : "Ford",
                          "rental" : 99.99
                        },
                        "sort" : [
                          99.99
                        ]
                      }
                    ]
                  }
                }
              }
            ]
          }
        },
        {
          "key" : "01",
          "doc_count" : 2,
          "vehicle_type" : {
            "doc_count_error_upper_bound" : 0,
            "sum_other_doc_count" : 0,
            "buckets" : [
              {
                "key" : "CAR",
                "doc_count" : 1,
                "cheapest_vehicle" : {
                  "hits" : {
                    "total" : {
                      "value" : 1,
                      "relation" : "eq"
                    },
                    "max_score" : null,
                    "hits" : [
                      {
                        "_index" : "cars",
                        "_type" : "_doc",
                        "_id" : "1",
                        "_score" : null,
                        "_source" : {
                          "vehicle_type" : "CAR",
                          "manufacturer_name" : "Ford",
                          "rental" : 599.99
                        },
                        "sort" : [
                          599.99
                        ]
                      }
                    ]
                  }
                }
              },
              {
                "key" : "LCV",
                "doc_count" : 1,
                "cheapest_vehicle" : {
                  "hits" : {
                    "total" : {
                      "value" : 1,
                      "relation" : "eq"
                    },
                    "max_score" : null,
                    "hits" : [
                      {
                        "_index" : "cars",
                        "_type" : "_doc",
                        "_id" : "2",
                        "_score" : null,
                        "_source" : {
                          "vehicle_type" : "LCV",
                          "manufacturer_name" : "Ford",
                          "rental" : 599.99
                        },
                        "sort" : [
                          599.99
                        ]
                      }
                    ]
                  }
                }
              }
            ]
          }
        },
        {
          "key" : "02",
          "doc_count" : 2,
          "vehicle_type" : {
            "doc_count_error_upper_bound" : 0,
            "sum_other_doc_count" : 0,
            "buckets" : [
              {
                "key" : "CAR",
                "doc_count" : 2,
                "cheapest_vehicle" : {
                  "hits" : {
                    "total" : {
                      "value" : 2,
                      "relation" : "eq"
                    },
                    "max_score" : null,
                    "hits" : [
                      {
                        "_index" : "cars",
                        "_type" : "_doc",
                        "_id" : "4",
                        "_score" : null,
                        "_source" : {
                          "vehicle_type" : "CAR",
                          "manufacturer_name" : "Audi",
                          "rental" : 499.99
                        },
                        "sort" : [
                          499.99
                        ]
                      }
                    ]
                  }
                }
              }
            ]
          }
        },
        {
          "key" : "03",
          "doc_count" : 1,
          "vehicle_type" : {
            "doc_count_error_upper_bound" : 0,
            "sum_other_doc_count" : 0,
            "buckets" : [
              {
                "key" : "CAR",
                "doc_count" : 1,
                "cheapest_vehicle" : {
                  "hits" : {
                    "total" : {
                      "value" : 1,
                      "relation" : "eq"
                    },
                    "max_score" : null,
                    "hits" : [
                      {
                        "_index" : "cars",
                        "_type" : "_doc",
                        "_id" : "5",
                        "_score" : null,
                        "_source" : {
                          "vehicle_type" : "CAR",
                          "manufacturer_name" : "Audi",
                          "rental" : 399.99
                        },
                        "sort" : [
                          399.99
                        ]
                      }
                    ]
                  }
                }
              }
            ]
          }
        }
      ]
    }
  }
}

How can I write output from a unit test?

Try using TestContext.WriteLine() which outputs text in test results.

Example:

[TestClass]
public class UnitTest1
{
    private TestContext testContextInstance;

    /// <summary>
    /// Gets or sets the test context which provides
    /// information about and functionality for the current test run.
    /// </summary>
    public TestContext TestContext
    {
        get { return testContextInstance; }
        set { testContextInstance = value; }
    }

    [TestMethod]
    public void TestMethod1()
    {
        TestContext.WriteLine("Message...");
    }
}

The "magic" is described in MSDN:

To use TestContext, create a member and property within your test class [...] The test framework automatically sets the property, which you can then use in unit tests.

How to validate an email address in PHP

If you're just looking for an actual regex that allows for various dots, underscores and dashes, it as follows: [a-zA-z0-9.-]+\@[a-zA-z0-9.-]+.[a-zA-Z]+. That will allow a fairly stupid looking email like tom_anderson.1-neo@my-mail_matrix.com to be validated.

GSON - Date format

Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ").create();

Above format seems better to me as it has precision up to millis.

How do you create different variable names while in a loop?

for x in range(9):
    exec("string" + str(x) + " = 'hello'")

This should work.

Check if element at position [x] exists in the list

int? here = (list.ElementAtOrDefault(2) != 0 ? list[2]:(int?) null);

Why cannot change checkbox color whatever I do?

Yes, you can. Based on knowledge from colleagues here and researching on web, here you have the best solution for styling a checkbox without any third-party plugin:

_x000D_
_x000D_
input[type='checkbox']{
  width: 14px !important;
  height: 14px !important;
  margin: 5px;
  -webkit-appearance: none;
  -moz-appearance: none;
  -o-appearance: none;
  appearance: none;
  outline: 1px solid gray;
  box-shadow: none;
  font-size: 0.8em;
  text-align: center;
  line-height: 1em;
  background: red;
}

input[type='checkbox']:checked:after {
  content: '?';
  color: white;
}
_x000D_
<input type='checkbox'>
_x000D_
_x000D_
_x000D_

Find the location of a character in string

To only find the first locations, use lapply() with min():

my_string <- c("test1", "test1test1", "test1test1test1")

unlist(lapply(gregexpr(pattern = '1', my_string), min))
#> [1] 5 5 5

# or the readable tidyverse form
my_string %>%
  gregexpr(pattern = '1') %>%
  lapply(min) %>%
  unlist()
#> [1] 5 5 5

To only find the last locations, use lapply() with max():

unlist(lapply(gregexpr(pattern = '1', my_string), max))
#> [1]  5 10 15

# or the readable tidyverse form
my_string %>%
  gregexpr(pattern = '1') %>%
  lapply(max) %>%
  unlist()
#> [1]  5 10 15

BitBucket - download source as ZIP

In Bitbucket Server you can do a download by clicking on ... next to the branch and then Download

Bitbucket Server download

For more info see Download an archive from Bitbucket Server

How do I add a library path in cmake?

might fail working with link_directories, then add each static library like following:

target_link_libraries(foo /path_to_static_library/libbar.a)

How to create local notifications?

I am assuming that you have requested for authorisation and registered your app for notification.

Here is the code to create local notifications

@available(iOS 10.0, *)
    func send_Noti()
    {
        //Create content for your notification 
        let content = UNMutableNotificationContent()
        content.title = "Test"
        content.body = "This is to test triggering of notification"

        //Use it to define trigger condition
        var date = DateComponents()
        date.calendar = Calendar.current
        date.weekday = 5 //5 means Friday
        date.hour = 14 //Hour of the day
        date.minute = 10 //Minute at which it should be sent


        let trigger = UNCalendarNotificationTrigger(dateMatching: date, repeats: true)
        let uuid = UUID().uuidString
        let req = UNNotificationRequest(identifier: uuid, content: content, trigger: trigger)

        let notificationCenter = UNUserNotificationCenter.current()
        notificationCenter.add(req) { (error) in
            print(error)
        }
    }

how to open popup window using jsp or jquery?

Can be done with in jquery-

<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" />
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
    <link rel="stylesheet" href="/resources/demos/style.css" />
    <script>
    $(function() {
    $( "#dialog" ).dialog();
    });
    </script>

    <div id="dialog" title="Basic dialog">
    //your form layout
    </div>

Chart won't update in Excel (2007)

I faced the same issue. The issue is due to restriction in no. of calculated formulas in your sheet. you can solved it using two ways:

Manual force re-calculate:

Press SHEFT + F9

Macro to force re-calculate: add below code to the end of the function which changes the data

Activesheet.Calculate

I found the solution of it: From excel options make sure to change the calculation options as below. It changed sometimes to manual after heavy work in excel.

Auto Calculation

What is the size of an enum in C?

In C language, an enum is guaranteed to be of size of an int. There is a compile time option (-fshort-enums) to make it as short (This is mainly useful in case the values are not more than 64K). There is no compile time option to increase its size to 64 bit.

Set output of a command as a variable (with pipes)

THIS DOESN'T USE PIPEs, but requires a single tempfile
I used this to put simplified timestamps into a lowtech daily maintenance batfile

We have already Short-formatted our System-Time to HHmm, (which is 2245 for 10:45PM)
I direct output of Maint-Routines to logfiles with a $DATE%@%TIME% timestamp;
. . . but %TIME% is a long ugly string (ex. 224513.56, for down to the hundredths of a sec)

SOLUTION OVERVIEW:
1. Use redirection (">") to send the command "TIME /T" everytime to OVERWRITE a temp-file in the %TEMP% DIRECTORY
2. Then use that tempfile as the input to set a new variable (I called it NOW)
3. Replace

echo $DATE%@%TIME% blah-blah-blah >> %logfile%
      with
echo $DATE%@%NOW% blah-blah-blah >> %logfile%


====DIFFERENCE IN OUTPUT:
BEFORE:
SUCCESSFUL TIMESYNCH [email protected]
AFTER:
SUCCESSFUL TIMESYNCH 29Dec14@2252


ACTUAL CODE:

TIME /T > %TEMP%\DailyTemp.txt
SET /p NOW=<%TEMP%\DailyTemp.txt
echo $DATE%@%NOW% blah-blah-blah >> %logfile%


AFTERMATH:
All that remains afterwards is the appended logfile, and constantly overwritten tempfile. And if the Tempfile is ever deleted, it will be re-created as necessary.

Efficient way to determine number of digits in an integer

int numberOfDigits(int n){

    if(n<=9){
        return 1;
    }
    return 1 + numberOfDigits(n/10);
}

This is what i would do, if you want it for base 10.Its pretty fast and you prolly wont get a stack overflock buy counting integers

Linq: GroupBy, Sum and Count

sometimes you need to select some fields by FirstOrDefault() or singleOrDefault() you can use the below query:

List<ResultLine> result = Lines
    .GroupBy(l => l.ProductCode)
    .Select(cl => new Models.ResultLine
            {
                ProductName = cl.select(x=>x.Name).FirstOrDefault(),
                Quantity = cl.Count().ToString(),
                Price = cl.Sum(c => c.Price).ToString(),
            }).ToList();

Tkinter understanding mainloop

tk.mainloop() blocks. It means that execution of your Python commands halts there. You can see that by writing:

while 1:
    ball.draw()
    tk.mainloop()
    print("hello")   #NEW CODE
    time.sleep(0.01)

You will never see the output from the print statement. Because there is no loop, the ball doesn't move.

On the other hand, the methods update_idletasks() and update() here:

while True:
    ball.draw()
    tk.update_idletasks()
    tk.update()

...do not block; after those methods finish, execution will continue, so the while loop will execute over and over, which makes the ball move.

An infinite loop containing the method calls update_idletasks() and update() can act as a substitute for calling tk.mainloop(). Note that the whole while loop can be said to block just like tk.mainloop() because nothing after the while loop will execute.

However, tk.mainloop() is not a substitute for just the lines:

tk.update_idletasks()
tk.update()

Rather, tk.mainloop() is a substitute for the whole while loop:

while True:
    tk.update_idletasks()
    tk.update()

Response to comment:

Here is what the tcl docs say:

Update idletasks

This subcommand of update flushes all currently-scheduled idle events from Tcl's event queue. Idle events are used to postpone processing until “there is nothing else to do”, with the typical use case for them being Tk's redrawing and geometry recalculations. By postponing these until Tk is idle, expensive redraw operations are not done until everything from a cluster of events (e.g., button release, change of current window, etc.) are processed at the script level. This makes Tk seem much faster, but if you're in the middle of doing some long running processing, it can also mean that no idle events are processed for a long time. By calling update idletasks, redraws due to internal changes of state are processed immediately. (Redraws due to system events, e.g., being deiconified by the user, need a full update to be processed.)

APN As described in Update considered harmful, use of update to handle redraws not handled by update idletasks has many issues. Joe English in a comp.lang.tcl posting describes an alternative:

So update_idletasks() causes some subset of events to be processed that update() causes to be processed.

From the update docs:

update ?idletasks?

The update command is used to bring the application “up to date” by entering the Tcl event loop repeatedly until all pending events (including idle callbacks) have been processed.

If the idletasks keyword is specified as an argument to the command, then no new events or errors are processed; only idle callbacks are invoked. This causes operations that are normally deferred, such as display updates and window layout calculations, to be performed immediately.

KBK (12 February 2000) -- My personal opinion is that the [update] command is not one of the best practices, and a programmer is well advised to avoid it. I have seldom if ever seen a use of [update] that could not be more effectively programmed by another means, generally appropriate use of event callbacks. By the way, this caution applies to all the Tcl commands (vwait and tkwait are the other common culprits) that enter the event loop recursively, with the exception of using a single [vwait] at global level to launch the event loop inside a shell that doesn't launch it automatically.

The commonest purposes for which I've seen [update] recommended are:

  1. Keeping the GUI alive while some long-running calculation is executing. See Countdown program for an alternative. 2) Waiting for a window to be configured before doing things like geometry management on it. The alternative is to bind on events such as that notify the process of a window's geometry. See Centering a window for an alternative.

What's wrong with update? There are several answers. First, it tends to complicate the code of the surrounding GUI. If you work the exercises in the Countdown program, you'll get a feel for how much easier it can be when each event is processed on its own callback. Second, it's a source of insidious bugs. The general problem is that executing [update] has nearly unconstrained side effects; on return from [update], a script can easily discover that the rug has been pulled out from under it. There's further discussion of this phenomenon over at Update considered harmful.

.....

Is there any chance I can make my program work without the while loop?

Yes, but things get a little tricky. You might think something like the following would work:

class Ball:
    def __init__(self, canvas, color):
        self.canvas = canvas
        self.id = canvas.create_oval(10, 10, 25, 25, fill=color)
        self.canvas.move(self.id, 245, 100)

    def draw(self):
        while True:
           self.canvas.move(self.id, 0, -1)

ball = Ball(canvas, "red")
ball.draw()
tk.mainloop()

The problem is that ball.draw() will cause execution to enter an infinite loop in the draw() method, so tk.mainloop() will never execute, and your widgets will never display. In gui programming, infinite loops have to be avoided at all costs in order to keep the widgets responsive to user input, e.g. mouse clicks.

So, the question is: how do you execute something over and over again without actually creating an infinite loop? Tkinter has an answer for that problem: a widget's after() method:

from Tkinter import *
import random
import time

tk = Tk()
tk.title = "Game"
tk.resizable(0,0)
tk.wm_attributes("-topmost", 1)

canvas = Canvas(tk, width=500, height=400, bd=0, highlightthickness=0)
canvas.pack()

class Ball:
    def __init__(self, canvas, color):
        self.canvas = canvas
        self.id = canvas.create_oval(10, 10, 25, 25, fill=color)
        self.canvas.move(self.id, 245, 100)

    def draw(self):
        self.canvas.move(self.id, 0, -1)
        self.canvas.after(1, self.draw)  #(time_delay, method_to_execute)


       

ball = Ball(canvas, "red")
ball.draw()  #Changed per Bryan Oakley's comment
tk.mainloop()

The after() method doesn't block (it actually creates another thread of execution), so execution continues on in your python program after after() is called, which means tk.mainloop() executes next, so your widgets get configured and displayed. The after() method also allows your widgets to remain responsive to other user input. Try running the following program, and then click your mouse on different spots on the canvas:

from Tkinter import *
import random
import time

root = Tk()
root.title = "Game"
root.resizable(0,0)
root.wm_attributes("-topmost", 1)

canvas = Canvas(root, width=500, height=400, bd=0, highlightthickness=0)
canvas.pack()

class Ball:
    def __init__(self, canvas, color):
        self.canvas = canvas
        self.id = canvas.create_oval(10, 10, 25, 25, fill=color)
        self.canvas.move(self.id, 245, 100)

        self.canvas.bind("<Button-1>", self.canvas_onclick)
        self.text_id = self.canvas.create_text(300, 200, anchor='se')
        self.canvas.itemconfig(self.text_id, text='hello')

    def canvas_onclick(self, event):
        self.canvas.itemconfig(
            self.text_id, 
            text="You clicked at ({}, {})".format(event.x, event.y)
        )

    def draw(self):
        self.canvas.move(self.id, 0, -1)
        self.canvas.after(50, self.draw)


       

ball = Ball(canvas, "red")
ball.draw()  #Changed per Bryan Oakley's comment.
root.mainloop()

How to produce a range with step n in bash? (generate a sequence of numbers with increments)

$ seq 4
1
2
3
4

$ seq 2 5
2
3
4
5

$ seq 4 2 12
4
6
8
10
12

$ seq -w 4 2 12
04
06
08
10
12

$ seq -s, 4 2 12
4,6,8,10,12

How do I mock a static method that returns void with PowerMock?

You can stub a static void method like this:

PowerMockito.doNothing().when(StaticResource.class, "getResource", anyString());

Although I'm not sure why you would bother, because when you call mockStatic(StaticResource.class) all static methods in StaticResource are by default stubbed

More useful, you can capture the value passed to StaticResource.getResource() like this:

ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
PowerMockito.doNothing().when(
               StaticResource.class, "getResource", captor.capture());

Then you can evaluate the String that was passed to StaticResource.getResource like this:

String resourceName = captor.getValue();

Automatically running a batch file as an administrator

If you're trying to invoke a Windows UAC prompt (the one that puts the whole screen black and asks if you're granting administrator privileges to the following task), RUNAS is not the smoothest way to do it, since:

  1. You're not going to get prompted for UAC authorization, even if logged in as the administrator and
  2. RUNAS expects that you have the administrator password, even if your user is setup as a local administrator, in which case the former password is not a sound security practice, specially in work environments.

Instead, try to copy & paste the following code to ensure that your batch file runs with administrator privileges:

@echo off

>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"

if '%errorlevel%' NEQ '0' (
    echo Requesting Admin access...
    goto goUAC )
    else goto goADMIN

:goUAC
    echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
    set params = %*:"=""
    echo UAC.ShellExecute "cmd.exe", "/c %~s0 %params%", "", "runas", 1 >> "%temp%\getadmin.vbs"
    "%temp%\getadmin.vbs"
    del "%temp%\getadmin.vbs"
    exit /B

:goADMIN
    pushd "%CD%"
    CD /D "%~dp0"

rem --- FROM HERE PASTE YOUR ADMIN-ENABLED BATCH SCRIPT ---
echo Stopping some Microsoft Service...
net stop sqlserveragent
rem --- END OF BATCH ----

This solution works 100% under Windows 7, 8.1 and 10 setups with UAC enabled.

How do I resolve a path relative to an ASP.NET MVC 4 application root?

I find this code useful when I need a path outside of a controller, such as when I'm initializing components in Global.asax.cs:

HostingEnvironment.MapPath("~/Data/data.html")

How to Navigate from one View Controller to another using Swift

Swift 4

You can switch the screen by pushing navigation controller first of all you have to set the navigation controller with UIViewController

let vc = self.storyboard?.instantiateViewController(withIdentifier: "YourStoryboardID") as! swiftClassName

self.navigationController?.pushViewController(vc, animated: true)

Is there a date format to display the day of the week in java?

Yep - 'E' does the trick

http://download.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html

Date date = new Date();
DateFormat df = new SimpleDateFormat("yyyy-MM-E");
System.out.println(df.format(date));

Stop embedded youtube iframe?

Here's a pure javascript solution,

<iframe 
width="100%" 
height="443" 
class="yvideo" 
id="p1QgNF6J1h0"
src="http://www.youtube.com/embed/p1QgNF6J1h0?rel=0&controls=0&hd=1&showinfo=0&enablejsapi=1"
frameborder="0" 
allowfullscreen>
</iframe>
<button id="myStopClickButton">Stop</button>


<script>
document.getElementById("myStopClickButton").addEventListener("click",    function(evt){
var video = document.getElementsByClassName("yvideo");
for (var i=0; i<video.length; i++) {
   video.item(i).contentWindow.postMessage('{"event":"command","func":"stopVideo","args":""}', '*');
}

});

Setting mime type for excel document

I was setting MIME type from .NET code as below -

File(generatedFileName, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")

My application generates excel using OpenXML SDK. This MIME type worked -

vnd.openxmlformats-officedocument.spreadsheetml.sheet

Pass array to ajax request in $.ajax()

info = [];
info[0] = 'hi';
info[1] = 'hello';


$.ajax({
   type: "POST",
   data: {info:info},
   url: "index.php",
   success: function(msg){
     $('.answer').html(msg);
   }
});

What does `unsigned` in MySQL mean and when to use it?

MySQL says:

All integer types can have an optional (nonstandard) attribute UNSIGNED. Unsigned type can be used to permit only nonnegative numbers in a column or when you need a larger upper numeric range for the column. For example, if an INT column is UNSIGNED, the size of the column's range is the same but its endpoints shift from -2147483648 and 2147483647 up to 0 and 4294967295.

When do I use it ?

Ask yourself this question: Will this field ever contain a negative value?
If the answer is no, then you want an UNSIGNED data type.

A common mistake is to use a primary key that is an auto-increment INT starting at zero, yet the type is SIGNED, in that case you’ll never touch any of the negative numbers and you are reducing the range of possible id's to half.

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

Truncating a table in a stored procedure

try the below code

execute immediate 'truncate table tablename' ;

What is the best way to tell if a character is a letter or number in Java without using regexes?

Compare its value. It should be between the value of 'a' and 'z', 'A' and 'Z', '0' and '9'

Why I get 'list' object has no attribute 'items'?

You have a dictionary within a list. You must first extract the dictionary from the list and then process the items in the dictionary.

If your list contained multiple dictionaries and you wanted the value from each dictionary stored in a list as you have shown do this:

result_list = [[int(v) for k,v in d.items()] for d in qs]

Which is the same as:

result_list = []
for d in qs:
    result_list.append([int(v) for k,v in d.items()])

The above will keep the values from each dictionary in their own separate list. If you just want all the values in one big list you can do this:

result_list = [int(v) for d in qs for k,v in d.items()]

How to write to a CSV line by line?

To complement the previous answers, I whipped up a quick class to write to CSV files. It makes it easier to manage and close open files and achieve consistency and cleaner code if you have to deal with multiple files.

class CSVWriter():

    filename = None
    fp = None
    writer = None

    def __init__(self, filename):
        self.filename = filename
        self.fp = open(self.filename, 'w', encoding='utf8')
        self.writer = csv.writer(self.fp, delimiter=';', quotechar='"', quoting=csv.QUOTE_ALL, lineterminator='\n')

    def close(self):
        self.fp.close()

    def write(self, elems):
        self.writer.writerow(elems)

    def size(self):
        return os.path.getsize(self.filename)

    def fname(self):
        return self.filename

Example usage:

mycsv = CSVWriter('/tmp/test.csv')
mycsv.write((12,'green','apples'))
mycsv.write((7,'yellow','bananas'))
mycsv.close()
print("Written %d bytes to %s" % (mycsv.size(), mycsv.fname()))

Have fun

unique object identifier in javascript

Update My original answer below was written 6 years ago in a style befitting the times and my understanding. In response to some conversation in the comments, a more modern approach to this is as follows:

_x000D_
_x000D_
    (function() {
        if ( typeof Object.id == "undefined" ) {
            var id = 0;

            Object.id = function(o) {
                if ( typeof o.__uniqueid == "undefined" ) {
                    Object.defineProperty(o, "__uniqueid", {
                        value: ++id,
                        enumerable: false,
                        // This could go either way, depending on your 
                        // interpretation of what an "id" is
                        writable: false
                    });
                }

                return o.__uniqueid;
            };
        }
    })();
    
    var obj = { a: 1, b: 1 };
    
    console.log(Object.id(obj));
    console.log(Object.id([]));
    console.log(Object.id({}));
    console.log(Object.id(/./));
    console.log(Object.id(function() {}));

    for (var k in obj) {
        if (obj.hasOwnProperty(k)) {
            console.log(k);
        }
    }
    // Logged keys are `a` and `b`
_x000D_
_x000D_
_x000D_

If you have archaic browser requirements, check here for browser compatibility for Object.defineProperty.

The original answer is kept below (instead of just in the change history) because I think the comparison is valuable.


You can give the following a spin. This also gives you the option to explicitly set an object's ID in its constructor or elsewhere.

_x000D_
_x000D_
    (function() {
        if ( typeof Object.prototype.uniqueId == "undefined" ) {
            var id = 0;
            Object.prototype.uniqueId = function() {
                if ( typeof this.__uniqueid == "undefined" ) {
                    this.__uniqueid = ++id;
                }
                return this.__uniqueid;
            };
        }
    })();
    
    var obj1 = {};
    var obj2 = new Object();
    
    console.log(obj1.uniqueId());
    console.log(obj2.uniqueId());
    console.log([].uniqueId());
    console.log({}.uniqueId());
    console.log(/./.uniqueId());
    console.log((function() {}).uniqueId());
_x000D_
_x000D_
_x000D_

Take care to make sure that whatever member you use to internally store the unique ID doesn't collide with another automatically created member name.

iPhone App Development on Ubuntu

Many of the other solutions will work, but they all make use of the open-toolchain for the iPhone SDK. So, yes, you can write software for the iPhone on other platforms... BUT...

Since you specify that you want your app to end up on the App Store, then, no, there's not really any way to do this. There's certainly no time effective way to do this. Even if you only value your own time at $20/hr, it will be far more efficient to buy a used intel Mac, and download the free SDK.

How to solve Permission denied (publickey) error when using Git?

In addition to Rufinus' reply, the shortcut to copy your ssh key to the clipboard in Windows is:

  • type id_rsa.pub | clip

Refs:

Creating a list of pairs in java

You can use the Entry<U,V> class that HashMap uses but you'll be stuck with its semantics of getKey and getValue:

List<Entry<Float,Short>> pairList = //...

My preference would be to create your own simple Pair class:

public class Pair<L,R> {
    private L l;
    private R r;
    public Pair(L l, R r){
        this.l = l;
        this.r = r;
    }
    public L getL(){ return l; }
    public R getR(){ return r; }
    public void setL(L l){ this.l = l; }
    public void setR(R r){ this.r = r; }
}

Then of course make a List using this new class, e.g.:

List<Pair<Float,Short>> pairList = new ArrayList<Pair<Float,Short>>();

You can also always make a Lists of Lists, but it becomes difficult to enforce sizing (that you have only pairs) and you would be required, as with arrays, to have consistent typing.

How do I install pip on macOS or OS X?

For those who have both python2 & python3 installed, here's the solution:

python2.7 -m ensurepip --default-pip

Additionally, if you wanna install pip for python3.6:

wget https://bootstrap.pypa.io/get-pip.py
sudo python3.6 get-pip.py

What datatype to use when storing latitude and longitude data in SQL databases?

I think it depends on the operations you'll be needing to do most frequently.

If you need the full value as a decimal number, then use decimal with appropriate precision and scale. Float is way beyond your needs, I believe.

If you'll be converting to/from degºmin'sec"fraction notation often, I'd consider storing each value as an integer type (smallint, tinyint, tinyint, smallint?).

redirect to current page in ASP.Net

http://en.wikipedia.org/wiki/Post/Redirect/Get

The most common way to implement this pattern in ASP.Net is to use Response.Redirect(Request.RawUrl)

Consider the differences between Redirect and Transfer. Transfer really isn't telling the browser to forward to a clear form, it's simply returning a cleared form. That may or may not be what you want.

Response.Redirect() does not a waste round trip. If you post to a script that clears the form by Server.Transfer() and reload you will be asked to repost by most browsers since the last action was a HTTP POST. This may cause your users to unintentionally repeat some action, eg. place a second order which will have to be voided later.

How can I create a correlation matrix in R?

There are other ways to achieve this here: (Plot correlation matrix into a graph), but I like your version with the correlations in the boxes. Is there a way to add the variable names to the x and y column instead of just those index numbers? For me, that would make this a perfect solution. Thanks!

edit: I was trying to comment on the post by [Marc in the box], but I clearly don't know what I'm doing. However, I did manage to answer this question for myself.

if d is the matrix (or the original data frame) and the column names are what you want, then the following works:

axis(1, 1:dim(d)[2], colnames(d), las=2)
axis(2, 1:dim(d)[2], colnames(d), las=2)

las=0 would flip the names back to their normal position, mine were long, so I used las=2 to make them perpendicular to the axis.

edit2: to suppress the image() function printing numbers on the grid (otherwise they overlap your variable labels), add xaxt='n', e.g.:

image(x=seq(dim(x)[2]), y=seq(dim(y)[2]), z=COR, col=rev(heat.colors(20)), xlab="x column", ylab="y column", xaxt='n')

JPA Hibernate One-to-One relationship

I think you still need the primary key property in the OtherInfo class.

@Entity
public class OtherInfo {
    @Id
    public int id;

    @OneToOne(mappedBy="otherInfo")
    public Person person;

    rest of attributes ...
}

Also, you may need to add the @PrimaryKeyJoinColumn annotation to the other side of the mapping. I know that Hibernate uses this by default. But then I haven't used JPA annotations, which seem to require you to specify how the association wokrs.

How do I round to the nearest 0.5?

I had difficulty with this problem as well. I code mainly in Actionscript 3.0 which is base coding for the Adobe Flash Platform, but there are simularities in the Languages:

The solution I came up with is the following:

//Code for Rounding to the nearest 0.05
var r:Number = Math.random() * 10;  // NUMBER - Input Your Number here
var n:int = r * 10;   // INTEGER - Shift Decimal 2 places to right
var f:int = Math.round(r * 10 - n) * 5;// INTEGER - Test 1 or 0 then convert to 5
var d:Number = (n + (f / 10)) / 10; //  NUMBER - Re-assemble the number

trace("ORG No: " + r);
trace("NEW No: " + d);

Thats pretty much it. Note the use of 'Numbers' and 'Integers' and the way they are processed.

Good Luck!

Transform only one axis to log10 scale with ggplot2

Another solution using scale_y_log10 with trans_breaks, trans_format and annotation_logticks()

library(ggplot2)

m <- ggplot(diamonds, aes(y = price, x = color))

m + geom_boxplot() +
  scale_y_log10(
    breaks = scales::trans_breaks("log10", function(x) 10^x),
    labels = scales::trans_format("log10", scales::math_format(10^.x))
  ) +
  theme_bw() +
  annotation_logticks(sides = 'lr') +
  theme(panel.grid.minor = element_blank())

SQL Server replace, remove all after certain character

Use CHARINDEX to find the ";". Then use SUBSTRING to just return the part before the ";".

Homebrew refusing to link OpenSSL

The solution might be updating some tools.

Here's my scenario from 2020 with Ruby and Python:

I needed to install Python 3 on Mac and things escalated. In the end, updating homebrew, node and python lead to the problem with openssl. I did not have openssl 1.0 anymore, so I couldn't "brew switch" to it.
So what was still trying to use that old 1.0 version?

It tuned out it was Ruby 2.5.5.
So I just installed Ruby 2.5.8 and removed the old one.

Other things you can try if this is not enough: Use rbenv and pyenv. Clean up gems and formulas. Update homebrew, node, yarn. Upgrade bundler. Make sure your .bash_profile (or equivalent) is set up according to each tool's instructions. Reopen the terminal.

How to access the ith column of a NumPy multidimensional array?

>>> test[:,0]
array([1, 3, 5])

Similarly,

>>> test[1,:]
array([3, 4])

lets you access rows. This is covered in Section 1.4 (Indexing) of the NumPy reference. This is quick, at least in my experience. It's certainly much quicker than accessing each element in a loop.

How can I find the OWNER of an object in Oracle?

You can query the ALL_OBJECTS view:

select owner
     , object_name
     , object_type
  from ALL_OBJECTS
 where object_name = 'FOO'

To find synonyms:

select *
  from ALL_SYNONYMS
 where synonym_name = 'FOO'

Just to clarify, if a user user's SQL statement references an object name with no schema qualification (e.g. 'FOO'), Oracle FIRST checks the user's schema for an object of that name (including synonyms in that user's schema). If Oracle can't resolve the reference from the user's schema, Oracle then checks for a public synonym.

If you are looking specifically for constraints on a particular table_name:

select c.*
  from all_constraints c 
 where c.table_name = 'FOO'
 union all
select cs.*
  from all_constraints cs
  join all_synonyms s 
    on (s.table_name = cs.table_name
     and s.table_owner = cs.owner 
     and s.synonym_name = 'FOO'
       )

HTH

-- addendum:

If your user is granted access to the DBA_ views (e.g. if your user has been granted SELECT_CATALOG_ROLE), you can substitute 'DBA_' in place of 'ALL_' in the preceding SQL examples. The ALL_x views only show objects which you have been granted privileges. The DBA_x views will show all database objects, whether you have privileges on them or not.

How to set up a Web API controller for multipart/form-data

I normally use the HttpPostedFileBase parameter only in Mvc Controllers. When dealing with ApiControllers try checking the HttpContext.Current.Request.Files property for incoming files instead:

[HttpPost]
public string UploadFile()
{
    var file = HttpContext.Current.Request.Files.Count > 0 ?
        HttpContext.Current.Request.Files[0] : null;

    if (file != null && file.ContentLength > 0)
    {
        var fileName = Path.GetFileName(file.FileName);

        var path = Path.Combine(
            HttpContext.Current.Server.MapPath("~/uploads"),
            fileName
        );

        file.SaveAs(path);
    }

    return file != null ? "/uploads/" + file.FileName : null;
}

How can I read and parse CSV files in C++?

Parsing CSV file lines with Stream

I wrote a small example of parsing CSV file lines, it can be developed with for and while loops if desired:

#include <iostream>
#include <fstream>
#include <string.h>

using namespace std;

int main() {


ifstream fin("Infile.csv");
ofstream fout("OutFile.csv");
string strline, strremain, strCol1 , strout;

string delimeter =";";

int d1;

to continue until the end of the file:

while (!fin.eof()){ 

get first line from InFile :

    getline(fin,strline,'\n');      

find delimeter position in line:

    d1 = strline.find(';');

and parse first column:

    strCol1 = strline.substr(0,d1); // parse first Column
    d1++;
    strremain = strline.substr(d1); // remaining line

create output line in CSV format:

    strout.append(strCol1);
    strout.append(delimeter);

write line to Out File:

    fout << strout << endl; //out file line

} 

fin.close();
fout.close();

return(0);
}

This code is compiled and running. Good luck!

How to find the location of the Scheduled Tasks folder

There are multiple issues with the MMC however as on almost every PC in my business the ask scheduler API will not open and has somehow been corrupted. So you cannot edit, delete or otherwise modify tasks that were developed before the API decided not to run anymore. The only way we have found to fix that issue is to totally wipe away a persons profile under the C:\Users\ area and force the system to recreate the log in once the person logs back in. This seems to fix the API issue and it works again, however the tasks are often not visible anymore to that user since the tasks developed are specific to the user and not the machine in Windows 7. The other odd thing is that sometimes, although not with any frequency that can be analyzed, the tasks still run even though the API is corrupted and will not open. The cause of this issue is apparently not known but there are many "fixes" described on various websites, but the user profile deletion and adding anew seems to work every time for at least a little while. The tasks are saved as XML now in WIN 7, so if you do find them in the system32/tasks folder you can delete them, or copy them to a new drive and then import them back into task scheduler. We went with the system scheduler software from Splinterware though since we had the same corruption issue multiple times even with the fix that does not seem to be permanent.

Check if table exists in SQL Server

IF OBJECT_ID('mytablename') IS NOT NULL 

How to remove stop words using nltk or python

In case your data are stored as a Pandas DataFrame, you can use remove_stopwords from textero that use the NLTK stopwords list by default.

import pandas as pd
import texthero as hero
df['text_without_stopwords'] = hero.remove_stopwords(df['text'])

css - position div to bottom of containing div

Assign position:relative to .outside, and then position:absolute; bottom:0; to your .inside.

Like so:

.outside {
    position:relative;
}
.inside {
    position: absolute;
    bottom: 0;
}

How to create an infinite loop in Windows batch file?

How about using good(?) old goto?

:loop

echo Ooops

goto loop

See also this for a more useful example.

Cannot catch toolbar home button click event

For anyone looking for a Xamarin implementation (since events are done differently in C#), I simply created this NavClickHandler class as follows:

public class NavClickHandler : Java.Lang.Object, View.IOnClickListener
{
    private Activity mActivity;
    public NavClickHandler(Activity activity)
    {
        this.mActivity = activity;
    }
    public void OnClick(View v)
    {
        DrawerLayout drawer = (DrawerLayout)mActivity.FindViewById(Resource.Id.drawer_layout);
        if (drawer.IsDrawerOpen(GravityCompat.Start))
        {
            drawer.CloseDrawer(GravityCompat.Start);
        }
        else
        {
            drawer.OpenDrawer(GravityCompat.Start);
        }
    }
}

Then, assigned a custom hamburger menu button like this:

        SupportActionBar.SetDisplayHomeAsUpEnabled(true);
        SupportActionBar.SetDefaultDisplayHomeAsUpEnabled(false);
        this.drawerToggle.DrawerIndicatorEnabled = false;
        this.drawerToggle.SetHomeAsUpIndicator(Resource.Drawable.MenuButton);

And finally, assigned the drawer menu toggler a ToolbarNavigationClickListener of the class type I created earlier:

        this.drawerToggle.ToolbarNavigationClickListener = new NavClickHandler(this);

And then you've got a custom menu button, with click events handled.

Initialize/reset struct to zero/null

The way to do such a thing when you have modern C (C99) is to use a compound literal.

a = (const struct x){ 0 };

This is somewhat similar to David's solution, only that you don't have to worry to declare an the empty structure or whether to declare it static. If you use the const as I did, the compiler is free to allocate the compound literal statically in read-only storage if appropriate.

undefined reference to WinMain@16 (codeblocks)

You should create a new project in Code::Blocks, and make sure it's 'Console Application'.

Add your .cpp files into the project so they are all compiled and linked together.

FAIL - Application at context path /Hello could not be started

You need to close the XML with </web-app>, not with <web-app>.

req.query and req.param in ExpressJS

req.query will return a JS object after the query string is parsed.

/user?name=tom&age=55 - req.query would yield {name:"tom", age: "55"}

req.params will return parameters in the matched route. If your route is /user/:id and you make a request to /user/5 - req.params would yield {id: "5"}

req.param is a function that peels parameters out of the request. All of this can be found here.

UPDATE

If the verb is a POST and you are using bodyParser, then you should be able to get the form body in you function with req.body. That will be the parsed JS version of the POSTed form.

How can I iterate over files in a given directory?

You can use glob for referring the directory and the list :

import glob
import os

#to get the current working directory name
cwd = os.getcwd()
#Load the images from images folder.
for f in glob.glob('images\*.jpg'):   
    dir_name = get_dir_name(f)
    image_file_name = dir_name + '.jpg'
    #To print the file name with path (path will be in string)
    print (image_file_name)

To get the list of all directory in array you can use os :

os.listdir(directory)

Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schema/security]

You need a spring-security-config.jar on your classpath.

The exception means that the security: xml namescape cannot be handled by spring "parsers". They are implementations of the NamespaceHandler interface, so you need a handler that knows how to process <security: tags. That's the SecurityNamespaceHandler located in spring-security-config

How to get the html of a div on another page with jQuery ajax?

Ok, You should "construct" the html and find the .content div.

like this:

$.ajax({
   url:href,
   type:'GET',
   success: function(data){
       $('#content').html($(data).find('#content').html());
   }
});

Simple!

'if' statement in jinja2 template

Why the loop?

You could simply do this:

{% if 'priority' in data %}
    <p>Priority: {{ data['priority'] }}</p>
{% endif %}

When you were originally doing your string comparison, you should have used == instead.

await vs Task.Wait - Deadlock?

Based on what I read from different sources:

An await expression does not block the thread on which it is executing. Instead, it causes the compiler to sign up the rest of the async method as a continuation on the awaited task. Control then returns to the caller of the async method. When the task completes, it invokes its continuation, and execution of the async method resumes where it left off.

To wait for a single task to complete, you can call its Task.Wait method. A call to the Wait method blocks the calling thread until the single class instance has completed execution. The parameterless Wait() method is used to wait unconditionally until a task completes. The task simulates work by calling the Thread.Sleep method to sleep for two seconds.

This article is also a good read.

SQL Server IN vs. EXISTS Performance

I've done some testing on SQL Server 2005 and 2008, and on both the EXISTS and the IN come back with the exact same actual execution plan, as other have stated. The Optimizer is optimal. :)

Something to be aware of though, EXISTS, IN, and JOIN can sometimes return different results if you don't phrase your query just right: http://weblogs.sqlteam.com/mladenp/archive/2007/05/18/60210.aspx

SQL Server - Convert date field to UTC

If you have to convert dates other than today to different timezones you have to deal with daylight savings. I wanted a solution that could be done without worrying about database version, without using stored functions and something that could easily be ported to Oracle.

I think Warren is on the right track with getting the correct dates for daylight time, but to make it more useful for multiple time zone and different rules for countries and even the rule that changed in the US between 2006 and 2007, here a variation on the above solution. Notice that this not only has us time zones, but also central Europe. Central Europe follow the last sunday of april and last sunday of october. You will also notice that the US in 2006 follows the old first sunday in april, last sunday in october rule.

This SQL code may look a little ugly, but just copy and paste it into SQL Server and try it. Notice there are 3 section for years, timezones and rules. If you want another year, just add it to the year union. Same for another time zone or rule.

select yr, zone, standard, daylight, rulename, strule, edrule, yrstart, yrend,
    dateadd(day, (stdowref + stweekadd), stmonthref) dstlow,
    dateadd(day, (eddowref + edweekadd), edmonthref)  dsthigh
from (
  select yrs.yr, z.zone, z.standard, z.daylight, z.rulename, r.strule, r.edrule, 
    yrs.yr + '-01-01 00:00:00' yrstart,
    yrs.yr + '-12-31 23:59:59' yrend,
    yrs.yr + r.stdtpart + ' ' + r.cngtime stmonthref,
    yrs.yr + r.eddtpart + ' ' + r.cngtime edmonthref,
    case when r.strule in ('1', '2', '3') then case when datepart(dw, yrs.yr + r.stdtpart) = '1' then 0 else 8 - datepart(dw, yrs.yr + r.stdtpart) end
    else (datepart(dw, yrs.yr + r.stdtpart) - 1) * -1 end stdowref,
    case when r.edrule in ('1', '2', '3') then case when datepart(dw, yrs.yr + r.eddtpart) = '1' then 0 else 8 - datepart(dw, yrs.yr + r.eddtpart) end
    else (datepart(dw, yrs.yr + r.eddtpart) - 1) * -1 end eddowref,
    datename(dw, yrs.yr + r.stdtpart) stdow,
    datename(dw, yrs.yr + r.eddtpart) eddow,
    case when r.strule in ('1', '2', '3') then (7 * CAST(r.strule AS Integer)) - 7 else 0 end stweekadd,
    case when r.edrule in ('1', '2', '3') then (7 * CAST(r.edrule AS Integer)) - 7 else 0 end edweekadd
from (
    select '2005' yr union select '2006' yr -- old us rules
    UNION select '2007' yr UNION select '2008' yr UNION select '2009' yr UNION select '2010' yr UNION select '2011' yr
    UNION select '2012' yr UNION select '2013' yr UNION select '2014' yr UNION select '2015' yr UNION select '2016' yr
    UNION select '2017' yr UNION select '2018' yr UNION select '2019' yr UNION select '2020' yr UNION select '2021' yr
    UNION select '2022' yr UNION select '2023' yr UNION select '2024' yr UNION select '2025' yr UNION select '2026' yr
) yrs
cross join (
    SELECT 'ET' zone, '-05:00' standard, '-04:00' daylight, 'US' rulename
    UNION SELECT 'CT' zone, '-06:00' standard, '-05:00' daylight, 'US' rulename
    UNION SELECT 'MT' zone, '-07:00' standard, '-06:00' daylight, 'US' rulename
    UNION SELECT 'PT' zone, '-08:00' standard, '-07:00' daylight, 'US' rulename
    UNION SELECT 'CET' zone, '+01:00' standard, '+02:00' daylight, 'EU' rulename
) z
join (
    SELECT 'US' rulename, '2' strule, '-03-01' stdtpart, '1' edrule, '-11-01' eddtpart, 2007 firstyr, 2099 lastyr, '02:00:00' cngtime
    UNION SELECT 'US' rulename, '1' strule, '-04-01' stdtpart, 'L' edrule, '-10-31' eddtpart, 1900 firstyr, 2006 lastyr, '02:00:00' cngtime
    UNION SELECT  'EU' rulename, 'L' strule, '-03-31' stdtpart, 'L' edrule, '-10-31' eddtpart, 1900 firstyr, 2099 lastyr, '01:00:00' cngtime
) r on r.rulename = z.rulename
    and datepart(year, yrs.yr) between firstyr and lastyr
) dstdates

For the rules, use 1, 2, 3 or L for first, second, third or last sunday. The date part gives the month and depending on the rule, the first day of the month or the last day of the month for rule type L.

I put the above query into a view. Now, anytime I want a date with the time zone offset or converted to UTC time, I just join to this view and select get the date in the date format. Instead of datetime, I converted these to datetimeoffset.

select createdon, dst.zone
    , case when createdon >= dstlow and createdon < dsthigh then dst.daylight else dst.standard end pacificoffsettime
    , TODATETIMEOFFSET(createdon, case when createdon >= dstlow and createdon < dsthigh then dst.daylight else dst.standard end) pacifictime
    , SWITCHOFFSET(TODATETIMEOFFSET(createdon, case when createdon >= dstlow and createdon < dsthigh then dst.daylight else dst.standard end), '+00:00')  utctime
from (select '2014-01-01 12:00:00' createdon union select '2014-06-01 12:00:00' createdon) photos
left join US_DAYLIGHT_DATES dst on createdon between yrstart and yrend and zone = 'PT'

How to write log to file

To help others, I create a basic log function to handle the logging in both cases, if you want the output to stdout, then turn debug on, its straight forward to do a switch flag so you can choose your output.

func myLog(msg ...interface{}) {
    defer func() { r := recover(); if r != nil { fmt.Print("Error detected logging:", r) } }()
    if conf.DEBUG {
        fmt.Println(msg)
    } else {
        logfile, err := os.OpenFile(conf.LOGDIR+"/"+conf.AppName+".log", os.O_RDWR | os.O_CREATE | os.O_APPEND,0666)
        if !checkErr(err) {
            log.SetOutput(logfile)
            log.Println(msg)
        }
        defer logfile.Close()
    }
}




no target device found android studio 2.1.1

On the phone

  1. Have you enabled Developer Mode?

  2. Have you enabled USB debugging within the Developer Tools menu in settings (this menu doesn't appear unless you've enabled Developer Mode)

  3. Do you have a good and securely connected USB cable?

In Android Studio

  1. In Edit Run/Debug Configurations, do you have "Target: USB Device"?

  2. It may help to download the latest version of the USB driver for that particular phone.

It's also helpful to know whether your phone appears as a recognised device at the operating system level. And when in doubt, reboot everything you can think of.

Is a view faster than a simple query?

Generally speaking, no. Views are primarily used for convenience and security, and won't (by themselves) produce any speed benefit.

That said, SQL Server 2000 and above do have a feature called Indexed Views that can greatly improve performance, with a few caveats:

  1. Not every view can be made into an indexed view; they have to follow a specific set of guidelines, which (among other restrictions) means you can't include common query elements like COUNT, MIN, MAX, or TOP.
  2. Indexed views use physical space in the database, just like indexes on a table.

This article describes additional benefits and limitations of indexed views:

You Can…

  • The view definition can reference one or more tables in the same database.
  • Once the unique clustered index is created, additional nonclustered indexes can be created against the view.
  • You can update the data in the underlying tables – including inserts, updates, deletes, and even truncates.

You Can’t…

  • The view definition can’t reference other views, or tables in other databases.
  • It can’t contain COUNT, MIN, MAX, TOP, outer joins, or a few other keywords or elements.
  • You can’t modify the underlying tables and columns. The view is created with the WITH SCHEMABINDING option.
  • You can’t always predict what the query optimizer will do. If you’re using Enterprise Edition, it will automatically consider the unique clustered index as an option for a query – but if it finds a “better” index, that will be used. You could force the optimizer to use the index through the WITH NOEXPAND hint – but be cautious when using any hint.

How to add SHA-1 to android application

If you are using Google Play App Signing, you don't need to add your SHA-1 keys manually, just login into Firebase go into "project settings"->"integration" and press a button to link Google Play with firebase, SHA-1 will be added automatically.

How to Create a real one-to-one relationship in SQL Server

I'm pretty sure it is technically impossible in SQL Server to have a True 1 to 1 relationship, as that would mean you would have to insert both records at the same time (otherwise you'd get a constraint error on insert), in both tables, with both tables having a foreign key relationship to each other.

That being said, your database design described with a foreign key is a 1 to 0..1 relationship. There is no constrain possible that would require a record in tableB. You can have a pseudo-relationship with a trigger that creates the record in tableB.

So there are a few pseudo-solutions

First, store all the data in a single table. Then you'll have no issues in EF.

Or Secondly, your entity must be smart enough to not allow an insert unless it has an associated record.

Or thirdly, and most likely, you have a problem you are trying to solve, and you are asking us why your solution doesn't work instead of the actual problem you are trying to solve (an XY Problem).

UPDATE

To explain in REALITY how 1 to 1 relationships don't work, I'll use the analogy of the Chicken or the egg dilemma. I don't intend to solve this dilemma, but if you were to have a constraint that says in order to add a an Egg to the Egg table, the relationship of the Chicken must exist, and the chicken must exist in the table, then you couldn't add an Egg to the Egg table. The opposite is also true. You cannot add a Chicken to the Chicken table without both the relationship to the Egg and the Egg existing in the Egg table. Thus no records can be every made, in a database without breaking one of the rules/constraints.

Database nomenclature of a one-to-one relationship is misleading. All relationships I've seen (there-fore my experience) would be more descriptive as one-to-(zero or one) relationships.

Toolbar navigation icon never set

I tried to set up toolbar like @Gabriele Mariotti, but I had some problem with title. So then I set order to

toolbar.setTitle("Title")
setSupportActionBar(toolbar);
toolbar.setNavigationIcon(R.drawable.ic_good);

and it works.

MySQL select statement with CASE or IF ELSEIF? Not sure how to get the result

Syntax:

CASE value WHEN [compare_value] THEN result 
[WHEN [compare_value] THEN result ...] 
[ELSE result] 
END

Alternative: CASE WHEN [condition] THEN result [WHEN [condition] THEN result ...]

mysql> SELECT CASE  WHEN 2>3 THEN 'this is true' ELSE 'this is false' END; 
+-------------------------------------------------------------+
| CASE  WHEN 2>3 THEN 'this is true' ELSE 'this is false' END |
+-------------------------------------------------------------+
| this is false                                               | 
+-------------------------------------------------------------+

I am use:

SELECT  act.*,
    CASE 
        WHEN (lises.session_date IS NOT NULL AND ses.session_date IS NULL) THEN lises.location_id
        WHEN (lises.session_date IS NULL AND ses.session_date IS NOT NULL) THEN ses.location_id
        WHEN (lises.session_date IS NOT NULL AND ses.session_date IS NOT NULL AND lises.session_date>ses.session_date) THEN ses.location_id
        WHEN (lises.session_date IS NOT NULL AND ses.session_date IS NOT NULL AND lises.session_date<ses.session_date) THEN lises.location_id
    END AS location_id
FROM activity AS act
LEFT JOIN li_sessions AS lises ON lises.activity_id = act.id AND  lises.session_date >= now()
LEFT JOIN session AS ses ON  ses.activity_id = act.id AND  ses.session_date >= now()
WHERE act.id

HTML Script tag: type or language (or omit both)?

The language attribute has been deprecated for a long time, and should not be used.

When W3C was working on HTML5, they discovered all browsers have "text/javascript" as the default script type, so they standardized it to be the default value. Hence, you don't need type either.

For pages in XHTML 1.0 or HTML 4.01 omitting type is considered invalid. Try validating the following:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script src="http://example.com/test.js"></script>
</head>
<body/>
</html>

You will be informed of the following error:

Line 4, Column 41: required attribute "type" not specified

So if you're a fan of standards, use it. It should have no practical effect, but, when in doubt, may as well go by the spec.

Check if an array is empty or exists

optional chaining

As optional chaining proposal reached stage 4 and is getting wider support, there is a very elegant way to do this

if(image_array?.length){

  // image_array is defined and has at least one element

}

HTTP Status 504

CheckUpDown has a nice explanation of the 504 error:

A server (not necessarily a Web server) is acting as a gateway or proxy to fulfil the request by the client (e.g. your Web browser or our CheckUpDown robot) to access the requested URL. This server did not receive a timely response from an upstream server it accessed to deal with your HTTP request.

This usually means that the upstream server is down (no response to the gateway/proxy), rather than that the upstream server and the gateway/proxy do not agree on the protocol for exchanging data.

This problem is entirely due to slow IP communication between back-end computers, possibly including the Web server. Only the people who set up the network at the site which hosts the Web server can fix this problem.

Sum values from an array of key-value pairs in JavaScript

If you want to discard the array at the same time as summing, you could do (say, stack is the array):

var stack = [1,2,3],
    sum = 0;
while(stack.length > 0) { sum += stack.pop() };

How to generate a Makefile with source in sub-directories using just one makefile

This will do it without painful manipulation or multiple command sequences:

build/%.o: src/%.cpp
src/%.o: src/%.cpp
%.o:
    $(CC) -c $< -o $@

build/test.exe: build/widgets/apple.o build/widgets/knob.o build/tests/blend.o src/ui/flash.o
    $(LD) $^ -o $@

JasperE has explained why "%.o: %.cpp" won't work; this version has one pattern rule (%.o:) with commands and no prereqs, and two pattern rules (build/%.o: and src/%.o:) with prereqs and no commands. (Note that I put in the src/%.o rule to deal with src/ui/flash.o, assuming that wasn't a typo for build/ui/flash.o, so if you don't need it you can leave it out.)

build/test.exe needs build/widgets/apple.o,
build/widgets/apple.o looks like build/%.o, so it needs src/%.cpp (in this case src/widgets/apple.cpp),
build/widgets/apple.o also looks like %.o, so it executes the CC command and uses the prereqs it just found (namely src/widgets/apple.cpp) to build the target (build/widgets/apple.o)

How to ignore a property in class if null, using json.net

In .Net Core this is much easier now. In your startup.cs just add json options and you can configure the settings there.


public void ConfigureServices(IServiceCollection services)

....

services.AddMvc().AddJsonOptions(options =>
{
   options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;               
});

multiple axis in matplotlib with different scales

Bootstrapping something fast to chart multiple y-axes sharing an x-axis using @joe-kington's answer: enter image description here

# d = Pandas Dataframe, 
# ys = [ [cols in the same y], [cols in the same y], [cols in the same y], .. ] 
def chart(d,ys):

    from itertools import cycle
    fig, ax = plt.subplots()

    axes = [ax]
    for y in ys[1:]:
        # Twin the x-axis twice to make independent y-axes.
        axes.append(ax.twinx())

    extra_ys =  len(axes[2:])

    # Make some space on the right side for the extra y-axes.
    if extra_ys>0:
        temp = 0.85
        if extra_ys<=2:
            temp = 0.75
        elif extra_ys<=4:
            temp = 0.6
        if extra_ys>5:
            print 'you are being ridiculous'
        fig.subplots_adjust(right=temp)
        right_additive = (0.98-temp)/float(extra_ys)
    # Move the last y-axis spine over to the right by x% of the width of the axes
    i = 1.
    for ax in axes[2:]:
        ax.spines['right'].set_position(('axes', 1.+right_additive*i))
        ax.set_frame_on(True)
        ax.patch.set_visible(False)
        ax.yaxis.set_major_formatter(matplotlib.ticker.OldScalarFormatter())
        i +=1.
    # To make the border of the right-most axis visible, we need to turn the frame
    # on. This hides the other plots, however, so we need to turn its fill off.

    cols = []
    lines = []
    line_styles = cycle(['-','-','-', '--', '-.', ':', '.', ',', 'o', 'v', '^', '<', '>',
               '1', '2', '3', '4', 's', 'p', '*', 'h', 'H', '+', 'x', 'D', 'd', '|', '_'])
    colors = cycle(matplotlib.rcParams['axes.color_cycle'])
    for ax,y in zip(axes,ys):
        ls=line_styles.next()
        if len(y)==1:
            col = y[0]
            cols.append(col)
            color = colors.next()
            lines.append(ax.plot(d[col],linestyle =ls,label = col,color=color))
            ax.set_ylabel(col,color=color)
            #ax.tick_params(axis='y', colors=color)
            ax.spines['right'].set_color(color)
        else:
            for col in y:
                color = colors.next()
                lines.append(ax.plot(d[col],linestyle =ls,label = col,color=color))
                cols.append(col)
            ax.set_ylabel(', '.join(y))
            #ax.tick_params(axis='y')
    axes[0].set_xlabel(d.index.name)
    lns = lines[0]
    for l in lines[1:]:
        lns +=l
    labs = [l.get_label() for l in lns]
    axes[0].legend(lns, labs, loc=0)

    plt.show()

Save the plots into a PDF

If someone ends up here from google, looking to convert a single figure to a .pdf (that was what I was looking for):

import matplotlib.pyplot as plt

f = plt.figure()
plt.plot(range(10), range(10), "o")
plt.show()

f.savefig("foo.pdf", bbox_inches='tight')

JQuery/Javascript: check if var exists

To test for existence there are two methods.

a. "property" in object

This method checks the prototype chain for existence of the property.

b. object.hasOwnProperty( "property" )

This method does not go up the prototype chain to check existence of the property, it must exist in the object you are calling the method on.

var x; // variable declared in global scope and now exists

"x" in window; // true
window.hasOwnProperty( "x" ); //true

If we were testing using the following expression then it would return false

typeof x !== 'undefined'; // false

PHP array: count or sizeof?

According to the website, sizeof() is an alias of count(), so they should be running the same code. Perhaps sizeof() has a little bit of overhead because it needs to resolve it to count()? It should be very minimal though.

multi line comment vb.net in Visual studio 2010

I just learned this trick from a friend. Put your code inside these 2 statements and it will be commented out.

#if false

#endif

Excel - Button to go to a certain sheet

Any reason they can't just click on the tab for your sheet when they want it?

What do the different readystates in XMLHttpRequest mean, and how can I use them?

onreadystatechange Stores a function (or the name of a function) to be called automatically each time the readyState property changes readyState Holds the status of the XMLHttpRequest. Changes from 0 to 4:

0: request not initialized

1: server connection established

2: request received

3: processing request

4: request finished and response is ready

status 200: "OK"

404: Page not found

How to check whether an array is empty using PHP?

Some decent answers, but just thought I'd expand a bit to explain more clearly when PHP determines if an array is empty.


Main Notes:

An array with a key (or keys) will be determined as NOT empty by PHP.

As array values need keys to exist, having values or not in an array doesn't determine if it's empty, only if there are no keys (AND therefore no values).

So checking an array with empty() doesn't simply tell you if you have values or not, it tells you if the array is empty, and keys are part of an array.


So consider how you are producing your array before deciding which checking method to use.
EG An array will have keys when a user submits your HTML form when each form field has an array name (ie name="array[]").
A non empty array will be produced for each field as there will be auto incremented key values for each form field's array.

Take these arrays for example:

/* Assigning some arrays */

// Array with user defined key and value
$ArrayOne = array("UserKeyA" => "UserValueA", "UserKeyB" => "UserValueB");

// Array with auto increment key and user defined value
// as a form field would return with user input
$ArrayTwo[] = "UserValue01";
$ArrayTwo[] = "UserValue02";

// Array with auto incremented key and no value
// as a form field would return without user input
$ArrayThree[] = '';
$ArrayThree[] = '';

If you echo out the array keys and values for the above arrays, you get the following:

ARRAY ONE:
[UserKeyA] => [UserValueA]
[UserKeyB] => [UserValueB]

ARRAY TWO:
[0] => [UserValue01]
[1] => [UserValue02]

ARRAY THREE:
[0] => []
[1] => []

And testing the above arrays with empty() returns the following results:

ARRAY ONE:
$ArrayOne is not empty

ARRAY TWO:
$ArrayTwo is not empty

ARRAY THREE:
$ArrayThree is not empty

An array will always be empty when you assign an array but don't use it thereafter, such as:

$ArrayFour = array();

This will be empty, ie PHP will return TRUE when using if empty() on the above.

So if your array has keys - either by eg a form's input names or if you assign them manually (ie create an array with database column names as the keys but no values/data from the database), then the array will NOT be empty().

In this case, you can loop the array in a foreach, testing if each key has a value. This is a good method if you need to run through the array anyway, perhaps checking the keys or sanitising data.

However it is not the best method if you simply need to know "if values exist" returns TRUE or FALSE. There are various methods to determine if an array has any values when it's know it will have keys. A function or class might be the best approach, but as always it depends on your environment and exact requirements, as well as other things such as what you currently do with the array (if anything).


Here's an approach which uses very little code to check if an array has values:

Using array_filter():
Iterates over each value in the array passing them to the callback function. If the callback function returns true, the current value from array is returned into the result array. Array keys are preserved.

$EmptyTestArray = array_filter($ArrayOne);

if (!empty($EmptyTestArray))
  {
    // do some tests on the values in $ArrayOne
  }
else
  {
    // Likely not to need an else, 
    // but could return message to user "you entered nothing" etc etc
  }

Running array_filter() on all three example arrays (created in the first code block in this answer) results in the following:

ARRAY ONE:
$arrayone is not empty

ARRAY TWO:
$arraytwo is not empty

ARRAY THREE:
$arraythree is empty

So when there are no values, whether there are keys or not, using array_filter() to create a new array and then check if the new array is empty shows if there were any values in the original array.
It is not ideal and a bit messy, but if you have a huge array and don't need to loop through it for any other reason, then this is the simplest in terms of code needed.


I'm not experienced in checking overheads, but it would be good to know the differences between using array_filter() and foreach checking if a value is found.

Obviously benchmark would need to be on various parameters, on small and large arrays and when there are values and not etc.

How to "inverse match" with regex?

(?! is useful in practice. Although strictly speaking, looking ahead is not regular expression as defined mathematically.

You can write an invert regular expression manually.

Here is a program to calculate the result automatically. Its result is machine generated, which is usually much more complex than hand writing one. But the result works.

How to automatically update your docker containers, if base-images are updated

have you tried this: https://github.com/v2tec/watchtower. it's a simple tool running in docker container watching other containers, if their base image changed, it will pull and redeploy.

How to get input textfield values when enter key is pressed in react js?

Use onKeyDown event, and inside that check the key code of the key pressed by user. Key code of Enter key is 13, check the code and put the logic there.

Check this example:

_x000D_
_x000D_
class CartridgeShell extends React.Component {_x000D_
_x000D_
   constructor(props) {_x000D_
      super(props);_x000D_
      this.state = {value:''}_x000D_
_x000D_
      this.handleChange = this.handleChange.bind(this);_x000D_
      this.keyPress = this.keyPress.bind(this);_x000D_
   } _x000D_
 _x000D_
   handleChange(e) {_x000D_
      this.setState({ value: e.target.value });_x000D_
   }_x000D_
_x000D_
   keyPress(e){_x000D_
      if(e.keyCode == 13){_x000D_
         console.log('value', e.target.value);_x000D_
         // put the login here_x000D_
      }_x000D_
   }_x000D_
_x000D_
   render(){_x000D_
      return(_x000D_
         <input value={this.state.value} onKeyDown={this.keyPress} onChange={this.handleChange} fullWidth={true} />_x000D_
      )_x000D_
    }_x000D_
}_x000D_
_x000D_
ReactDOM.render(<CartridgeShell/>, document.getElementById('app'))
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
_x000D_
_x000D_
<div id = 'app' />
_x000D_
_x000D_
_x000D_

Note: Replace the input element by Material-Ui TextField and define the other properties also.

RequestDispatcher.forward() vs HttpServletResponse.sendRedirect()

The RequestDispatcher interface allows you to do a server side forward/include whereas sendRedirect() does a client side redirect. In a client side redirect, the server will send back an HTTP status code of 302 (temporary redirect) which causes the web browser to issue a brand new HTTP GET request for the content at the redirected location. In contrast, when using the RequestDispatcher interface, the include/forward to the new resource is handled entirely on the server side.

Shell Script: How to write a string to file and to stdout on console?

You can use >> to print in another file.

echo "hello" >> logfile.txt

How to make div's percentage width relative to parent div and not viewport

Specifying a non-static position, e.g., position: absolute/relative on a node means that it will be used as the reference for absolutely positioned elements within it http://jsfiddle.net/E5eEk/1/

See https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Positioning#Positioning_contexts

We can change the positioning context — which element the absolutely positioned element is positioned relative to. This is done by setting positioning on one of the element's ancestors.

_x000D_
_x000D_
#outer {_x000D_
  min-width: 2000px; _x000D_
  min-height: 1000px; _x000D_
  background: #3e3e3e; _x000D_
  position:relative_x000D_
}_x000D_
_x000D_
#inner {_x000D_
  left: 1%; _x000D_
  top: 45px; _x000D_
  width: 50%; _x000D_
  height: auto; _x000D_
  position: absolute; _x000D_
  z-index: 1;_x000D_
}_x000D_
_x000D_
#inner-inner {_x000D_
  background: #efffef;_x000D_
  position: absolute; _x000D_
  height: 400px; _x000D_
  right: 0px; _x000D_
  left: 0px;_x000D_
}
_x000D_
<div id="outer">_x000D_
  <div id="inner">_x000D_
    <div id="inner-inner"></div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to convert CLOB to VARCHAR2 inside oracle pl/sql

This is my aproximation:

  Declare 
  Variableclob Clob;
  Temp_Save Varchar2(32767); //whether it is greater than 4000

  Begin
  Select reportClob Into Temp_Save From Reporte Where Id=...;
  Variableclob:=To_Clob(Temp_Save);
  Dbms_Output.Put_Line(Variableclob);


  End;

How do I import .sql files into SQLite 3?

You can also do:

sqlite3 database.db -init dump.sql

Set UITableView content inset permanently

Probably it was some sort of my mistake because of me messing with autolayouts and storyboard but I found an answer.

You have to take care of this little guy in View Controller's Attribute Inspector asvi

It must be unchecked so the default contentInset wouldn't be set after any change. After that it is just adding one-liner to viewDidLoad:

[self.tableView setContentInset:UIEdgeInsetsMake(108, 0, 0, 0)]; // 108 is only example

iOS 11, Xcode 9 update

Looks like the previous solution is no longer a correct one if it comes to iOS 11 and Xcode 9. automaticallyAdjustsScrollViewInsets has been deprecated and right now to achieve similar effect you have to go to Size Inspector where you can find this: enter image description here
Also, you can achieve the same in code:

if #available(iOS 11.0, *) {
    scrollView.contentInsetAdjustmentBehavior = .never
} else {
    automaticallyAdjustsScrollViewInsets = false
}

How do I set response headers in Flask?

This work for me

from flask import Flask
from flask import Response

app = Flask(__name__)

@app.route("/")
def home():
    return Response(headers={'Access-Control-Allow-Origin':'*'})

if __name__ == "__main__":
    app.run()

Set a Fixed div to 100% width of the parent container

You could use absolute positioning to pin the footer to the base of the parent div. I have also added 10px padding-bottom to the wrap (match the height of the footer). The absolute positioning is relative to the parent div rather than outside of the flow since you have already given it the position relative attribute.

body{ height:20000px }
#wrapper {padding:10%;}
#wrap{ 
    float: left;
    padding-bottom: 10px;
    position: relative;
    width: 40%; 
    background:#ccc; 
}
#fixed{ 
    position:absolute;
    width:100%;
    left: 0;
    bottom: 0;
    padding:0px;
    height:10px;
    background-color:#333;

}

http://jsfiddle.net/C93mk/497/

ASP.NET MVC controller actions that return JSON or partial html

For folks who have upgraded to MVC 3 here is a neat way Using MVC3 and Json

How do I use the lines of a file as arguments of a command?

As already mentioned, you can use the backticks or $(cat filename).

What was not mentioned, and I think is important to note, is that you must remember that the shell will break apart the contents of that file according to whitespace, giving each "word" it finds to your command as an argument. And while you may be able to enclose a command-line argument in quotes so that it can contain whitespace, escape sequences, etc., reading from the file will not do the same thing. For example, if your file contains:

a "b c" d

the arguments you will get are:

a
"b
c"
d

If you want to pull each line as an argument, use the while/read/do construct:

while read i ; do command_name $i ; done < filename

What is the difference between MOV and LEA?

If you only specify a literal, there is no difference. LEA has more abilities, though, and you can read about them here:

http://www.oopweb.com/Assembly/Documents/ArtOfAssembly/Volume/Chapter_6/CH06-1.html#HEADING1-136

Insert a background image in CSS (Twitter Bootstrap)

isn't the problem the following line is incorrect as the statement for background-repeat isn't closed before the next statement for display...

background-repeat:no-repeatdisplay: compact;

Shouldn't this be

background-repeat:no-repeat;
display: compact;

adding or removing quotes (in my experience) makes no difference if the URL is correct. Is the path to the image correct? If you give a relative path to a resource in a CSS it's relative to the CSS file, not the file including the CSS.

What does `void 0` mean?

What does void 0 mean?

void[MDN] is a prefix keyword that takes one argument and always returns undefined.

Examples

void 0
void (0)
void "hello"
void (new Date())
//all will return undefined

What's the point of that?

It seems pretty useless, doesn't it? If it always returns undefined, what's wrong with just using undefined itself?

In a perfect world we would be able to safely just use undefined: it's much simpler and easier to understand than void 0. But in case you've never noticed before, this isn't a perfect world, especially when it comes to Javascript.

The problem with using undefined was that undefined is not a reserved word (it is actually a property of the global object [wtfjs]). That is, undefined is a permissible variable name, so you could assign a new value to it at your own caprice.

alert(undefined); //alerts "undefined"
var undefined = "new value";
alert(undefined) // alerts "new value"

Note: This is no longer a problem in any environment that supports ECMAScript 5 or newer (i.e. in practice everywhere but IE 8), which defines the undefined property of the global object as read-only (so it is only possible to shadow the variable in your own local scope). However, this information is still useful for backwards-compatibility purposes.

alert(window.hasOwnProperty('undefined')); // alerts "true"
alert(window.undefined); // alerts "undefined"
alert(undefined === window.undefined); // alerts "true"
var undefined = "new value";
alert(undefined); // alerts "new value"
alert(undefined === window.undefined); // alerts "false"

void, on the other hand, cannot be overidden. void 0 will always return undefined. undefined, on the other hand, can be whatever Mr. Javascript decides he wants it to be.

Why void 0, specifically?

Why should we use void 0? What's so special about 0? Couldn't we just as easily use 1, or 42, or 1000000 or "Hello, world!"?

And the answer is, yes, we could, and it would work just as well. The only benefit of passing in 0 instead of some other argument is that 0 is short and idiomatic.

Why is this still relevant?

Although undefined can generally be trusted in modern JavaScript environments, there is one trivial advantage of void 0: it's shorter. The difference is not enough to worry about when writing code but it can add up enough over large code bases that most code minifiers replace undefined with void 0 to reduce the number of bytes sent to the browser.

How to get a web page's source code from Java

URL yahoo = new URL("http://www.yahoo.com/");
BufferedReader in = new BufferedReader(
            new InputStreamReader(
            yahoo.openStream()));

String inputLine;

while ((inputLine = in.readLine()) != null)
    System.out.println(inputLine);

in.close();

Check if a value exists in pandas dataframe index

This should do the trick

'g' in df.index

Drag and drop menuitems

jQuery UI draggable and droppable are the two plugins I would use to achieve this effect. As for the insertion marker, I would investigate modifying the div (or container) element that was about to have content dropped into it. It should be possible to modify the border in some way or add a JavaScript/jQuery listener that listens for the hover (element about to be dropped) event and modifies the border or adds an image of the insertion marker in the right place.

Laravel Pagination links not including other GET parameters

Be aware of the Input::all() , it will Include the previous ?page= values again and again in each page you open !
for example if you are in ?page=1 and you open the next page, it will open ?page=1&page=2
So the last value page takes will be the page you see ! not the page you want to see

Solution : use Input::except(array('page'))

How to hash a string into 8 digits?

Yes, you can use the built-in hashlib module or the built-in hash function. Then, chop-off the last eight digits using modulo operations or string slicing operations on the integer form of the hash:

>>> s = 'she sells sea shells by the sea shore'

>>> # Use hashlib
>>> import hashlib
>>> int(hashlib.sha1(s.encode("utf-8")).hexdigest(), 16) % (10 ** 8)
58097614L

>>> # Use hash()
>>> abs(hash(s)) % (10 ** 8)
82148974

Java: Reading a file into an array

import java.io.File;

import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;

import java.util.List;

// ...

Path filePath = new File("fileName").toPath();
Charset charset = Charset.defaultCharset();        
List<String> stringList = Files.readAllLines(filePath, charset);
String[] stringArray = stringList.toArray(new String[]{});

How to send email to multiple recipients using python smtplib?

I figured this out a few months back and blogged about it. The summary is:

If you want to use smtplib to send email to multiple recipients, use email.Message.add_header('To', eachRecipientAsString) to add them, and then when you invoke the sendmail method, use email.Message.get_all('To') send the message to all of them. Ditto for Cc and Bcc recipients.

return SQL table as JSON in python

I knocked together a short script that dumps all data from all tables, as dicts of column name : value. Unlike other solutions, it doesn't require any info about what the tables or columns are, it just finds everything and dumps it. Hope someone finds it useful!

from contextlib import closing
from datetime import datetime
import json
import MySQLdb
DB_NAME = 'x'
DB_USER = 'y'
DB_PASS = 'z'

def get_tables(cursor):
    cursor.execute('SHOW tables')
    return [r[0] for r in cursor.fetchall()] 

def get_rows_as_dicts(cursor, table):
    cursor.execute('select * from {}'.format(table))
    columns = [d[0] for d in cursor.description]
    return [dict(zip(columns, row)) for row in cursor.fetchall()]

def dump_date(thing):
    if isinstance(thing, datetime):
        return thing.isoformat()
    return str(thing)


with closing(MySQLdb.connect(user=DB_USER, passwd=DB_PASS, db=DB_NAME)) as conn, closing(conn.cursor()) as cursor:
    dump = {}
    for table in get_tables(cursor):
        dump[table] = get_rows_as_dicts(cursor, table)
    print(json.dumps(dump, default=dump_date, indent=2))

Removing unwanted table cell borders with CSS

to remove the border , juste using css like this :

td {
 border-style : hidden!important;
}

How to fix HTTP 404 on Github Pages?

I bound my domain before this problem appeared. I committed and pushed the branch gh-pages and it solved my problem. New commits force jekyll to rebuild your pages.

Split string into array

Use the .split() method. When specifying an empty string as the separator, the split() method will return an array with one element per character.

entry = prompt("Enter your name")
entryArray = entry.split("");

Number to String in a formula field

CSTR({number_field}, 0, '')

The second placeholder is for decimals.

The last placeholder is for thousands separator.

Check object empty

I have a way, you guys tell me how good it is.

Create a new object of the class and compare it with your object (which you want to check for emptiness).

To be correctly able to do it :

Override the hashCode() and equals() methods of your model class and also of the classes, objects of whose are members of your class, for example :

Person class (primary model class) :

public class Person {

    private int age;
    private String firstName;
    private String lastName;
    private Address address;

    //getters and setters

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((address == null) ? 0 : address.hashCode());
        result = prime * result + age;
        result = prime * result + ((firstName == null) ? 0 : firstName.hashCode());
        result = prime * result + ((lastName == null) ? 0 : lastName.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Person other = (Person) obj;
        if (address == null) {
            if (other.address != null)
                return false;
        } else if (!address.equals(other.address))
            return false;
        if (age != other.age)
            return false;
        if (firstName == null) {
            if (other.firstName != null)
                return false;
        } else if (!firstName.equals(other.firstName))
            return false;
        if (lastName == null) {
            if (other.lastName != null)
                return false;
        } else if (!lastName.equals(other.lastName))
            return false;
        return true;
    }

    @Override
    public String toString() {
        return "Person [age=" + age + ", firstName=" + firstName + ", lastName=" + lastName + ", address=" + address
                + "]";
    }

}

Address class (used inside Person class) :

public class Address {

    private String line1;
    private String line2;

    //getters and setters

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((line1 == null) ? 0 : line1.hashCode());
        result = prime * result + ((line2 == null) ? 0 : line2.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Address other = (Address) obj;
        if (line1 == null) {
            if (other.line1 != null)
                return false;
        } else if (!line1.equals(other.line1))
            return false;
        if (line2 == null) {
            if (other.line2 != null)
                return false;
        } else if (!line2.equals(other.line2))
            return false;
        return true;
    }

    @Override
    public String toString() {
        return "Address [line1=" + line1 + ", line2=" + line2 + "]";
    }

}

Now in the main class :

    Person person1 = new Person();
    person1.setAge(20);

    Person person2 = new Person();

    Person person3 = new Person();

if(person1.equals(person2)) --> this will be false

if(person2.equals(person3)) --> this will be true

I hope this is the best way instead of putting if conditions on each and every member variables.

Let me know !

Passing arguments forward to another javascript function

Use .apply() to have the same access to arguments in function b, like this:

function a(){
    b.apply(null, arguments);
}
function b(){
   alert(arguments); //arguments[0] = 1, etc
}
a(1,2,3);?

You can test it out here.

Inserting multiple rows in mysql

// db table name / blog_post / menu /  site_title
// Insert into Table (column names separated with comma)
$sql = "INSERT INTO product_cate (site_title, sub_title) 
  VALUES ('$site_title', '$sub_title')";

// db table name / blog_post / menu /  site_title
// Insert into Table (column names separated with comma)
$sql = "INSERT INTO menu (menu_title, sub_menu)
  VALUES ('$menu_title', '$sub_menu', )";

// db table name / blog_post /  menu /  site_title
// Insert into Table (column names separated with comma)
$sql = "INSERT INTO blog_post (post_title, post_des, post_img)
  VALUES ('$post_title ', '$post_des', '$post_img')";

Excel Formula which places date/time in cell when data is entered in another cell in the same row

This can be accomplished with a simple VBA function. Excel has support for a Worksheet Change Sub which can be programmed to put a date in a related column every time it fires.

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Column = 2 And Target.Offset(0, 3).Value = "" Then
        Target.Offset(0, 3) = Format(Now(), "HH:MM:SS")
    End If
End Sub

A quick explanation. The following "if" statement checks for two things: (1) if it is the second column that changed (Column B), and (2) if the cell 3 columns over (Column E) is currently empty.

If Target.Column = 2 And Target.Offset(0, 3).Value = "" Then

If both conditions are true, then it puts the date into the cell in Column E with the NOW() function.

Target.Offset(0, 3) = Format(Now(), "HH:MM:SS")

Range.Offset

Range.Column

"Could not find a version that satisfies the requirement opencv-python"

A way to do this is to install Anaconda on your computer.

Then you should be able to do:

pip install opencv-python

or

conda install opencv

LD_LIBRARY_PATH vs LIBRARY_PATH

LIBRARY_PATH is used by gcc before compilation to search directories containing static and shared libraries that need to be linked to your program.

LD_LIBRARY_PATH is used by your program to search directories containing shared libraries after it has been successfully compiled and linked.

EDIT: As pointed below, your libraries can be static or shared. If it is static then the code is copied over into your program and you don't need to search for the library after your program is compiled and linked. If your library is shared then it needs to be dynamically linked to your program and that's when LD_LIBRARY_PATH comes into play.

Force IE10 to run in IE10 Compatibility View?

I had the same problem. The problem is a bug in MSIE 10, so telling people to fix their issues isn't helpful. Neither is telling visitors to your site to add your site to compatibility view, bleh. In my case, the problem was that the following code displayed no text:

document.write ('<P>'); 
document.write ('Blah, blah, blah... ');
document.write ('</P>');

After much trial and error, I determined that removing the <P> and </P> tags caused the text to appear properly on the page (thus, the problem IS with document mode rather than browser mode, at least in my case). Removing the <P> tags when userAgent is MSIE is not a "fix" I want to put into my pages.

The solution, as others have said, is:

<!DOCTYPE HTML whatever doctype you're using....> 
<HTML>
 <HEAD>
  <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8">
  <TITLE>Blah...

Yes, the meta tag has to be the FIRST tag after HEAD.

gdb: how to print the current line or find the current line number?

The 'frame' command will give you what you are looking for. (This can be abbreviated just 'f'). Here is an example:

(gdb) frame
\#0  zmq::xsub_t::xrecv (this=0x617180, msg_=0x7ffff00008e0) at xsub.cpp:139
139         int rc = fq.recv (msg_);
(gdb)

Without an argument, 'frame' just tells you where you are at (with an argument it changes the frame). More information on the frame command can be found here.

PHP returning JSON to JQUERY AJAX CALL

You can return json in PHP this way:

header('Content-Type: application/json');
echo json_encode(array('foo' => 'bar'));
exit;

Getting new Twitter API consumer and secret keys

To get Consumer Key & Consumer Secret, you have to create an app in Twitter via

https://developer.twitter.com/en/apps

Then you'll be taken to a page containing Consumer Key & Consumer Secret.

Hopefully this information will clarify OAuth essentials for Twitter:

  1. Create a Twitter account if you don't already have one
  2. Visit 'https://apps.twitter.com' and follow the required prompts to create a developer project (Twitter requires you to answer some questions before they will approve your account. Approval was nearly instant in my case.)
  3. Requesting the API key and secret via the Developer Portal causes Twitter to produce the following three things:
  • API key (this is your 'consumer key')
  • API secret key (this is your 'consumer secret')
  • Bearer token
  1. Next, visit the 'Authentication Tokens' area of the Developer Portal and generate an 'Access token & secret'. This will provide you with the following two items:
  • Access token (this is your 'token key')
  • Access token secret (this is your 'token secret')
  1. The consumer key, consumer secret, token key, and token secret should be sufficient to do Twitter API calls (they were for me). Good luck!

What is the difference between CSS and SCSS?

Sass is a language that provides features to make it easier to deal with complex styling compared to editing raw .css. An example of such a feature is allowing definition of variables that can be re-used in different styles.

The language has two alternative syntaxes:

  • A JSON like syntax that is kept in files ending with .scss
  • A YAML like syntax that is kept in files ending with .sass

Either of these must be compiled to .css files which are recognized by browsers.

See https://sass-lang.com/ for further information.

Missing `server' JVM (Java\jre7\bin\server\jvm.dll.)

To Fix The "Missing "server" JVM at C:\Program Files\Java\jre7\bin\server\jvm­­.dll, please install or use the JRE or JDK that contains these missing components.

Follow these steps:

Go to oracle.com and install Java JRE7 (Check if Java 6 is not installed already)

After that, go to C:/Program files/java/jre7/bin

Here, create an folder called Server

Now go into the C:/Program files/java/jre7/bin/client folder

Copy all the data in this folder into the new C:/Program files/java/jre7/bin/Server folder

How to populate a dropdownlist with json data in jquery?

To populate ComboBox with JSON, you can consider using the: jqwidgets combobox, too.

Reading rows from a CSV file in Python

Reading it columnwise is harder?

Anyway this reads the line and stores the values in a list:

for line in open("csvfile.csv"):
    csv_row = line.split() #returns a list ["1","50","60"]

Modern solution:

# pip install pandas
import pandas as pd 
df = pd.read_table("csvfile.csv", sep=" ")

How to define an enumerated type (enum) in C?

My favorite and only used construction always was:

typedef enum MyBestEnum
{
    /* good enough */
    GOOD = 0,
    /* even better */
    BETTER,
    /* divine */
    BEST
};

I believe that this will remove your problem you have. Using new type is from my point of view right option.

Use Robocopy to copy only changed files?

You can use robocopy to copy files with an archive flag and reset the attribute. Use /M command line, this is my backup script with few extra tricks.

This script needs NirCmd tool to keep mouse moving so that my machine won't fall into sleep. Script is using a lockfile to tell when backup script is completed and mousemove.bat script is closed. You may leave this part out.

Another is 7-Zip tool for splitting virtualbox files smaller than 4GB files, my destination folder is still FAT32 so this is mandatory. I should use NTFS disk but haven't converted backup disks yet.

backup-robocopy.bat

@REM https://technet.microsoft.com/en-us/library/cc733145.aspx
@REM http://www.skonet.com/articles_archive/robocopy_job_template.aspx

set basedir=%~dp0
del /Q %basedir%backup-robocopy-log.txt

set dt=%date%_%time:~0,8%
echo "%dt% robocopy started" > %basedir%backup-robocopy-lock.txt
start "Keep system awake" /MIN /LOW  cmd.exe /C %basedir%backup-robocopy-movemouse.bat

set dest=E:\backup

call :BACKUP "Program Files\MariaDB 5.5\data"
call :BACKUP "projects"
call :BACKUP "Users\Myname"

:SPLIT
@REM Split +4GB file to multiple files to support FAT32 destination disk,
@REM splitted files must be stored outside of the robocopy destination folder.
set srcfile=C:\Users\Myname\VirtualBox VMs\Ubuntu\Ubuntu.vdi
set dstfile=%dest%\Users\Myname\VirtualBox VMs\Ubuntu\Ubuntu.vdi
set dstfile2=%dest%\non-robocopy\Users\Myname\VirtualBox VMs\Ubuntu\Ubuntu.vdi
IF NOT EXIST "%dstfile%" (
  IF NOT EXIST "%dstfile2%.7z.001" attrib +A "%srcfile%"
  dir /b /aa "%srcfile%" && (
    del /Q "%dstfile2%.7z.*"
    c:\apps\commands\7za.exe -mx0 -v4000m u "%dstfile2%.7z"  "%srcfile%"
    attrib -A "%srcfile%"
    @set dt=%date%_%time:~0,8%
    @echo %dt% Splitted %srcfile% >> %basedir%backup-robocopy-log.txt
  )
)

del /Q %basedir%backup-robocopy-lock.txt
GOTO :END


:BACKUP
TITLE Backup %~1
robocopy.exe "c:\%~1" "%dest%\%~1" /JOB:%basedir%backup-robocopy-job.rcj
GOTO :EOF


:END
@set dt=%date%_%time:~0,8%
@echo %dt% robocopy completed >> %basedir%backup-robocopy-log.txt
@echo %dt% robocopy completed
@pause

backup-robocopy-job.rcj

:: Robocopy Job Parameters
:: robocopy.exe "c:\projects" "E:\backup\projects" /JOB:backup-robocopy-job.rcj


:: Source Directory (this is given in command line)
::/SD:c:\examplefolder

:: Destination Directory (this is given in command line)
::/DD:E:\backup\examplefolder

:: Include files matching these names
/IF
    *.*

/M      :: copy only files with the Archive attribute and reset it.
/XJD    :: eXclude Junction points for Directories.

:: Exclude Directories
/XD
    C:\projects\bak
    C:\projects\old
    C:\project\tomcat\logs
    C:\project\tomcat\work
    C:\Users\Myname\.eclipse
    C:\Users\Myname\.m2
    C:\Users\Myname\.thumbnails
    C:\Users\Myname\AppData
    C:\Users\Myname\Favorites
    C:\Users\Myname\Links
    C:\Users\Myname\Saved Games
    C:\Users\Myname\Searches

:: Exclude files matching these names
/XF 
    C:\Users\Myname\ntuser.dat  
    *.~bpl

:: Exclude files with any of the given Attributes set
:: S=System, H=Hidden
/XA:SH      

:: Copy options
/S          :: copy Subdirectories, but not empty ones.
/E          :: copy subdirectories, including Empty ones.
/COPY:DAT   :: what to COPY for files (default is /COPY:DAT).
/DCOPY:T    :: COPY Directory Timestamps.
/PURGE      :: delete dest files/dirs that no longer exist in source.

:: Retry Options
/R:0        :: number of Retries on failed copies: default 1 million.
/W:1        :: Wait time between retries: default is 30 seconds.

:: Logging Options (LOG+ append)
/NDL        :: No Directory List - don't log directory names.
/NP         :: No Progress - don't display percentage copied.
/TEE        :: output to console window, as well as the log file.
/LOG+:c:\apps\commands\backup-robocopy-log.txt :: append to logfile

backup-robocopy-movemouse.bat

@echo off
@REM Move mouse to prevent maching from sleeping 
@rem while running a backup script

echo Keep system awake while robocopy is running,
echo this script moves a mouse once in a while.

set basedir=%~dp0
set IDX=0

:LOOP
IF NOT EXIST "%basedir%backup-robocopy-lock.txt" GOTO :EOF
SET /A IDX=%IDX% + 1
IF "%IDX%"=="240" (
  SET IDX=0
  echo Move mouse to keep system awake
  c:\apps\commands\nircmdc.exe sendmouse move 5 5
  c:\apps\commands\nircmdc.exe sendmouse move -5 -5
)
c:\apps\commands\nircmdc.exe wait 1000
GOTO :LOOP

How to convert time milliseconds to hours, min, sec format in JavaScript?

I needed time only up to one day, 24h, this was my take:

_x000D_
_x000D_
const milliseconds = 5680000;_x000D_
_x000D_
const hours = `0${new Date(milliseconds).getHours() - 1}`.slice(-2);_x000D_
const minutes = `0${new Date(milliseconds).getMinutes()}`.slice(-2);_x000D_
const seconds = `0${new Date(milliseconds).getSeconds()}`.slice(-2);_x000D_
_x000D_
const time = `${hours}:${minutes}:${seconds}`_x000D_
console.log(time);
_x000D_
_x000D_
_x000D_

you could get days this way as well if needed.

Format date as dd/MM/yyyy using pipes

If anyone can looking to display date with time in AM or PM in angular 6 then this is for you.

{{date | date: 'dd/MM/yyyy hh:mm a'}}

Output

enter image description here

Pre-defined format options

Examples are given in en-US locale.

'short': equivalent to 'M/d/yy, h:mm a' (6/15/15, 9:03 AM).
'medium': equivalent to 'MMM d, y, h:mm:ss a' (Jun 15, 2015, 9:03:01 AM).
'long': equivalent to 'MMMM d, y, h:mm:ss a z' (June 15, 2015 at 9:03:01 AM GMT+1).
'full': equivalent to 'EEEE, MMMM d, y, h:mm:ss a zzzz' (Monday, June 15, 2015 at 9:03:01 AM GMT+01:00).
'shortDate': equivalent to 'M/d/yy' (6/15/15).
'mediumDate': equivalent to 'MMM d, y' (Jun 15, 2015).
'longDate': equivalent to 'MMMM d, y' (June 15, 2015).
'fullDate': equivalent to 'EEEE, MMMM d, y' (Monday, June 15, 2015).
'shortTime': equivalent to 'h:mm a' (9:03 AM).
'mediumTime': equivalent to 'h:mm:ss a' (9:03:01 AM).
'longTime': equivalent to 'h:mm:ss a z' (9:03:01 AM GMT+1).
'fullTime': equivalent to 'h:mm:ss a zzzz' (9:03:01 AM GMT+01:00).

Reference Link

How can I change the default Mysql connection timeout when connecting through python?

I know this is an old question but just for the record this can also be done by passing appropriate connection options as arguments to the _mysql.connect call. For example,

con = _mysql.connect(host='localhost', user='dell-pc', passwd='', db='test',
          connect_timeout=1000)

Notice the use of keyword parameters (host, passwd, etc.). They improve the readability of your code.

For detail about different arguments that you can pass to _mysql.connect, see MySQLdb API documentation

What are the differences between LinearLayout, RelativeLayout, and AbsoluteLayout?

LinearLayout - In LinearLayout, views are organized either in vertical or horizontal orientation.

RelativeLayout - RelativeLayout is way more complex than LinearLayout, hence provides much more functionalities. Views are placed, as the name suggests, relative to each other.

FrameLayout - It behaves as a single object and its child views are overlapped over each other. FrameLayout takes the size of as per the biggest child element.

Coordinator Layout - This is the most powerful ViewGroup introduced in Android support library. It behaves as FrameLayout and has a lot of functionalities to coordinate amongst its child views, for example, floating button and snackbar, Toolbar with scrollable view.

Difference between 2 dates in SQLite

This answer is a little long-winded, and the documentation will not tell you this (because they assume you are storing your dates as UTC dates in the database), but the answer to this question depends largely on the timezone that your dates are stored in. You also don't use Date('now'), but use the julianday() function, to calculate both dates back against a common date, then subtract the difference of those results from each other.

If your dates are stored in UTC:

SELECT julianday('now') - julianday(DateCreated) FROM Payment;

This is what the top-ranked answer has, and is also in the documentation. It is only part of the picture, and a very simplistic answer, if you ask me.

If your dates are stored in local time, using the above code will make your answer WRONG by the number of hours your GMT offset is. If you are in the Eastern U.S. like me, which is GMT -5, your result will have 5 hours added onto it. And if you try making DateCreated conform to UTC because julianday('now') goes against a GMT date:

SELECT julianday('now') - julianday(DateCreated, 'utc') FROM Payment;

This has a bug where it will add an hour for a DateCreated that is during Daylight Savings Time (March-November). Say that "now" is at noon on a non-DST day, and you created something back in June (during DST) at noon, your result will give 1 hour apart, instead of 0 hours, for the hours portion. You'd have to write a function in your application's code that is displaying the result to modify the result and subtract an hour from DST dates. I did that, until I realized there's a better solution to that problem that I was having: SQLite vs. Oracle - Calculating date differences - hours

Instead, as was pointed out to me, for dates stored in local time, make both match to local time:

SELECT julianday('now', 'localtime') - julianday(DateCreated) FROM Payment;

Or append 'Z' to local time:

julianday(datetime('now', 'localtime')||'Z') - julianday(CREATED_DATE||'Z')

Both of these seem to compensate and do not add the extra hour for DST dates and do straight subtraction - so that item created at noon on a DST day, when checking at noon on a non-DST day, will not get an extra hour when performing the calculation.

And while I recognize most will say don't store dates in local time in your database, and to store them in UTC so you don't run into this, well not every application has a world-wide audience, and not every programmer wants to go through the conversion of EVERY date in their system to UTC and back again every time they do a GET or SET in the database and deal with figuring out if something is local or in UTC.

How to run a script file remotely using SSH

I was able to invoke a shell script using this command:

ssh ${serverhost} "./sh/checkScript.ksh"

Of course, checkScript.ksh must exist in the $HOME/sh directory.

Convert ASCII TO UTF-8 Encoding

Using iconv looks like best solution but i my case I have Notice form this function: "Detected an illegal character in input string in" (without igonore). I use 2 functions to manipulate ASCII strings convert it to array of ASCII code and then serialize:

public static function ToAscii($string) {
    $strlen = strlen($string);
    $charCode = array();
    for ($i = 0; $i < $strlen; $i++) {
        $charCode[] = ord(substr($string, $i, 1));
    }
    $result = json_encode($charCode);
    return $result;
}

public static function fromAscii($string) {
    $charCode = json_decode($string);
    $result = '';
    foreach ($charCode as $code) {
        $result .= chr($code);
    };
    return $result;
}

Java, Check if integer is multiple of a number

Use modulo

whenever a number x is a multiple of some number y, then always x % y equal to 0, which can be used as a check. So use

if (j % 4 == 0) 

Center a H1 tag inside a DIV

On the hX tag

width: 100px;
margin-left: auto;
margin-right: auto;

Get real path from URI, Android KitKat new storage access framework

Note: This answer addresses part of the problem. For a complete solution (in the form of a library), look at Paul Burke's answer.

You could use the URI to obtain document id, and then query either MediaStore.Images.Media.EXTERNAL_CONTENT_URI or MediaStore.Images.Media.INTERNAL_CONTENT_URI (depending on the SD card situation).

To get document id:

// Will return "image:x*"
String wholeID = DocumentsContract.getDocumentId(uriThatYouCurrentlyHave);

// Split at colon, use second item in the array
String id = wholeID.split(":")[1];

String[] column = { MediaStore.Images.Media.DATA };     

// where id is equal to             
String sel = MediaStore.Images.Media._ID + "=?";

Cursor cursor = getContentResolver().
                          query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, 
                          column, sel, new String[]{ id }, null);

String filePath = "";

int columnIndex = cursor.getColumnIndex(column[0]);

if (cursor.moveToFirst()) {
    filePath = cursor.getString(columnIndex);
}   

cursor.close();

Reference: I'm not able to find the post that this solution is taken from. I wanted to ask the original poster to contribute here. Will look some more tonight.