Programs & Examples On #Mappath

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

5 years later on and .NET Core 3.1 allows you to do specify the media type like this:

[HttpPost]
[Consumes("multipart/form-data")]
public IActionResult UploadLogo()
{
    return Ok();
}

Download file from an ASP.NET Web API method using AngularJS

Support for downloading binary files in using ajax is not great, it is very much still under development as working drafts.

Simple download method:

You can have the browser download the requested file simply by using the code below, and this is supported in all browsers, and will obviously trigger the WebApi request just the same.

$scope.downloadFile = function(downloadPath) { 
    window.open(downloadPath, '_blank', '');  
}

Ajax binary download method:

Using ajax to download the binary file can be done in some browsers and below is an implementation that will work in the latest flavours of Chrome, Internet Explorer, FireFox and Safari.

It uses an arraybuffer response type, which is then converted into a JavaScript blob, which is then either presented to save using the saveBlob method - though this is only currently present in Internet Explorer - or turned into a blob data URL which is opened by the browser, triggering the download dialog if the mime type is supported for viewing in the browser.

Internet Explorer 11 Support (Fixed)

Note: Internet Explorer 11 did not like using the msSaveBlob function if it had been aliased - perhaps a security feature, but more likely a flaw, So using var saveBlob = navigator.msSaveBlob || navigator.webkitSaveBlob ... etc. to determine the available saveBlob support caused an exception; hence why the code below now tests for navigator.msSaveBlob separately. Thanks? Microsoft

// Based on an implementation here: web.student.tuwien.ac.at/~e0427417/jsdownload.html
$scope.downloadFile = function(httpPath) {
    // Use an arraybuffer
    $http.get(httpPath, { responseType: 'arraybuffer' })
    .success( function(data, status, headers) {

        var octetStreamMime = 'application/octet-stream';
        var success = false;

        // Get the headers
        headers = headers();

        // Get the filename from the x-filename header or default to "download.bin"
        var filename = headers['x-filename'] || 'download.bin';

        // Determine the content type from the header or default to "application/octet-stream"
        var contentType = headers['content-type'] || octetStreamMime;

        try
        {
            // Try using msSaveBlob if supported
            console.log("Trying saveBlob method ...");
            var blob = new Blob([data], { type: contentType });
            if(navigator.msSaveBlob)
                navigator.msSaveBlob(blob, filename);
            else {
                // Try using other saveBlob implementations, if available
                var saveBlob = navigator.webkitSaveBlob || navigator.mozSaveBlob || navigator.saveBlob;
                if(saveBlob === undefined) throw "Not supported";
                saveBlob(blob, filename);
            }
            console.log("saveBlob succeeded");
            success = true;
        } catch(ex)
        {
            console.log("saveBlob method failed with the following exception:");
            console.log(ex);
        }

        if(!success)
        {
            // Get the blob url creator
            var urlCreator = window.URL || window.webkitURL || window.mozURL || window.msURL;
            if(urlCreator)
            {
                // Try to use a download link
                var link = document.createElement('a');
                if('download' in link)
                {
                    // Try to simulate a click
                    try
                    {
                        // Prepare a blob URL
                        console.log("Trying download link method with simulated click ...");
                        var blob = new Blob([data], { type: contentType });
                        var url = urlCreator.createObjectURL(blob);
                        link.setAttribute('href', url);

                        // Set the download attribute (Supported in Chrome 14+ / Firefox 20+)
                        link.setAttribute("download", filename);

                        // Simulate clicking the download link
                        var event = document.createEvent('MouseEvents');
                        event.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
                        link.dispatchEvent(event);
                        console.log("Download link method with simulated click succeeded");
                        success = true;

                    } catch(ex) {
                        console.log("Download link method with simulated click failed with the following exception:");
                        console.log(ex);
                    }
                }

                if(!success)
                {
                    // Fallback to window.location method
                    try
                    {
                        // Prepare a blob URL
                        // Use application/octet-stream when using window.location to force download
                        console.log("Trying download link method with window.location ...");
                        var blob = new Blob([data], { type: octetStreamMime });
                        var url = urlCreator.createObjectURL(blob);
                        window.location = url;
                        console.log("Download link method with window.location succeeded");
                        success = true;
                    } catch(ex) {
                        console.log("Download link method with window.location failed with the following exception:");
                        console.log(ex);
                    }
                }

            }
        }

        if(!success)
        {
            // Fallback to window.open method
            console.log("No methods worked for saving the arraybuffer, using last resort window.open");
            window.open(httpPath, '_blank', '');
        }
    })
    .error(function(data, status) {
        console.log("Request failed with status: " + status);

        // Optionally write the error out to scope
        $scope.errorDetails = "Request failed with status: " + status;
    });
};

Usage:

var downloadPath = "/files/instructions.pdf";
$scope.downloadFile(downloadPath);

Notes:

You should modify your WebApi method to return the following headers:

  • I have used the x-filename header to send the filename. This is a custom header for convenience, you could however extract the filename from the content-disposition header using regular expressions.

  • You should set the content-type mime header for your response too, so the browser knows the data format.

I hope this helps.

How do I to insert data into an SQL table using C# as well as implement an upload function?

using System;
using System.Data;
using System.Data.SqlClient;

namespace InsertingData
{
    class sqlinsertdata
    {
        static void Main(string[] args)
        {
            try
            { 
            SqlConnection conn = new SqlConnection("Data source=USER-PC; Database=Emp123;User Id=sa;Password=sa123");
            conn.Open();
                SqlCommand cmd = new SqlCommand("insert into <Table Name>values(1,'nagendra',10000);",conn);
                cmd.ExecuteNonQuery();
                Console.WriteLine("Inserting Data Successfully");
                conn.Close();
        }
            catch(Exception e)
            {
                Console.WriteLine("Exception Occre while creating table:" + e.Message + "\t"  + e.GetType());
            }
            Console.ReadKey();

    }
    }
}

Could not load file or assembly 'Newtonsoft.Json' or one of its dependencies. Manifest definition does not match the assembly reference

None of the answers, including the checked one did not work for me.

The solution was far more simple. I first removed the references from my BUS layer. Then deleted the dll's from the project (to make sure it's gone), then reinstalled JSON.NET from nuget packeges. And, the tricky part was, "turning it off and on again".

I just restarted visual studio, and there it worked!

So, if you try everything possible and still can't solve the problem, just try turning visual studio off and on again, it might help.

Getting Error 800a0e7a "Provider cannot be found. It may not be properly installed."

I got the same issue and It got solved by installing Oracle 11g client in my machine..

I have not installed any excclusive drivers for it. I am using windows7 with 64 bit. Interestignly, when I navigate into the path Start > Settings > Control Panel > Administrative Tools > DataSources(ODBC) > Drivers. I found only SQL server in it

Please Finc the attachment below for the same

Runtime error: Could not load file or assembly 'System.Web.WebPages.Razor, Version=3.0.0.0

in the new actionmailer, "razorengine" is a dependency. The latest version of Razorengine installs the dependency to System.Web.Razor 3.0.0.

If you use an earlier version in your application (i suppose you are using actionmailer in another project and that you reference the mail functionality from another project) than you get this issue of course.

In an earlier application, i had a webapplication MVC that uses system.web.Razor version 2.0.0. Of course, i got the issue to. How to fix? => Simple!

  1. Just uninstall the entire actionmailer in your actionmailer project.
  2. Install a previous version of RazorEngin

    Install-Package RazorEngine -Version 3.3.0 (because version 3.3.0 will reference system.web.razor 2.0.0)

  3. Install actionmailer again (it will not install the latest version of RazorEngin because you allready did that yourselve)
Succes!

ASP.NET file download from server

Try this set of code to download a CSV file from the server.

byte[] Content= File.ReadAllBytes(FilePath); //missing ;
Response.ContentType = "text/csv";
Response.AddHeader("content-disposition", "attachment; filename=" + fileName + ".csv");
Response.BufferOutput = true;
Response.OutputStream.Write(Content, 0, Content.Length);
Response.End();

Exception of type 'System.OutOfMemoryException' was thrown.

This problem usually occurs when some process such as loading huge data to memory stream and your system memory is not capable of storing so much of data. Try clearing temp folder by giving the command

start -> run -> %temp%

Microsoft Web API: How do you do a Server.MapPath?

I can't tell from the context you supply, but if it's something you just need to do at app startup, you can still use Server.MapPath in WebApiHttpApplication; e.g. in Application_Start().

I'm just answering your direct question; the already-mentioned HostingEnvironment.MapPath() is probably the preferred solution.

MVC 4 Razor File Upload

you just have to change the name of your input filed because same name is required in parameter and input field name just replace this line Your code working fine

 <input type="file" name="file" />

Could not load type 'System.Runtime.CompilerServices.ExtensionAttribute' from assembly 'mscorlib

We ran into this problem and tracked it down to the Geocoding.net NuGet package that we were using to help with our Google Maps views (Geocoding.net version 3.1.0 published 2/4/2014).

The Geocoding dll appears to be .Net 4.0 when you examine the package file or view it using Jet Brains’ Dot Peek application; however, a colleague of mine says that it was compiled using ilmerge so it is most likely related to the ilmerge problems listed above.

It was a long process to track it down. We fetched different changesets from TFS till we narrowed it down to the changeset that added the aforementioned NuGet package. After removing it, we were able to deploy to our .NET 4 server.

Could not load file or assembly 'Microsoft.Web.Infrastructure,

I had a similar problem. NuGet showed the package successfully installed, but the reference was not added to my project.

Running <PM> Install-Package Microsoft.Web.InfraStructure also didn't help as the package manager kept saying it's already installed

I finally added it manually by editing the csproj file and adding these lines:

 <Reference Include="Microsoft.Web.Infrastructure">
  <HintPath>..\packages\Microsoft.Web.Infrastructure.1.0.0.0\lib\net40\Microsoft.Web.Infrastructure.dll</HintPath>
  <Private>True</Private>
</Reference>

That solved the problem.

Error Microsoft.Web.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35

After installing Microsoft.Web.Infrastructure through Nuget-Package Manager

PM> Install-Package Microsoft.Web.Infrastructure

Copy the Microsoft.Web.Infrastructure.dll manually from the Nuget-Package folder on your web application and then paste it in your bin folder of your web application deployed on the web server.

packages\Microsoft.Web.Infrastructure.1.0.0.0\lib\net40\Microsoft.Web.Infrastructure.dll

It worked for me.

The module was expected to contain an assembly manifest

Check if the manifest is a valid xml file. I had the same problem by doing a DOS copy command at the end of the build, and it turns out that for some reason I can not understand "copy" was adding a strange character (->) at the end of the manifest files. The problem was solved by adding "/b" switch to force binary copy.

How to set downloading file name in ASP.NET Web API

This should do:

Response.AddHeader("Content-Disposition", "attachment;filename="+ YourFilename)

Pass a simple string from controller to a view MVC3

Why not create a viewmodel with a simple string parameter and then pass that to the view? It has the benefit of being extensible (i.e. you can then add any other things you may want to set in your controller) and it's fairly simple.

public class MyViewModel
{
    public string YourString { get; set; }
}

In the view

@model MyViewModel
@Html.Label(model => model.YourString)

In the controller

public ActionResult Index() 
{
     myViewModel = new MyViewModel();
     myViewModel.YourString = "However you are setting this."
     return View(myViewModel)
}

Cannot use Server.MapPath

you can try using this

    System.Web.HttpContext.Current.Server.MapPath(path);

or use HostingEnvironment.MapPath

    System.Web.Hosting.HostingEnvironment.MapPath(path);

Could not load file or assembly 'System.Web.WebPages.Razor, Version=2.0.0.0

For similar assembly binding errors , following steps may help:

  1. Right click on your Solution and click Manage Nuget Packages for Solution ...
  2. go to Consolidate Tab (last tab) and check if any any differences between packages installed in different projects inside your solution. specially pay attention to your referenced projects which may have lower versions because they usually are less noticed)
  3. consolidate specially packages related to your assembly error and note that many packages are dependent on some other packages like *.code & *.api & ...
  4. after resolving all suspected consolidations , rebuild and rerun the app and see if the assembly bindings are resolved.

How to write "Html.BeginForm" in Razor

The following code works fine:

@using (Html.BeginForm("Upload", "Upload", FormMethod.Post, 
                                      new { enctype = "multipart/form-data" }))
{
    @Html.ValidationSummary(true)
    <fieldset>
        Select a file <input type="file" name="file" />
        <input type="submit" value="Upload" />
    </fieldset>
}

and generates as expected:

<form action="/Upload/Upload" enctype="multipart/form-data" method="post">    
    <fieldset>
        Select a file <input type="file" name="file" />
        <input type="submit" value="Upload" />
    </fieldset>
</form>

On the other hand if you are writing this code inside the context of other server side construct such as an if or foreach you should remove the @ before the using. For example:

@if (SomeCondition)
{
    using (Html.BeginForm("Upload", "Upload", FormMethod.Post, 
                                      new { enctype = "multipart/form-data" }))
    {
        @Html.ValidationSummary(true)
        <fieldset>
            Select a file <input type="file" name="file" />
            <input type="submit" value="Upload" />
        </fieldset>
    }
}

As far as your server side code is concerned, here's how to proceed:

[HttpPost]
public ActionResult Upload(HttpPostedFileBase file) 
{
    if (file != null && file.ContentLength > 0) 
    {
        var fileName = Path.GetFileName(file.FileName);
        var path = Path.Combine(Server.MapPath("~/content/pics"), fileName);
        file.SaveAs(path);
    }
    return RedirectToAction("Upload");
}

"The given path's format is not supported."

I see that the originator found out that the error occurred when trying to save the filename with an entire path. Actually it's enough to have a ":" in the file name to get this error. If there might be ":" in your file name (for instance if you have a date stamp in your file name) make sure you replace these with something else. I.e:

string fullFileName = fileName.Split('.')[0] + "(" + DateTime.Now.ToString().Replace(':', '-') + ")." + fileName.Split('.')[1];

Merging multiple PDFs using iTextSharp in c#.net

I found the answer:

Instead of the 2nd Method, add more files to the first array of input files.

public static void CombineMultiplePDFs(string[] fileNames, string outFile)
{
    // step 1: creation of a document-object
    Document document = new Document();
    //create newFileStream object which will be disposed at the end
    using (FileStream newFileStream = new FileStream(outFile, FileMode.Create))
    {
       // step 2: we create a writer that listens to the document
       PdfCopy writer = new PdfCopy(document, newFileStream );
       if (writer == null)
       {
           return;
       }

       // step 3: we open the document
       document.Open();

       foreach (string fileName in fileNames)
       {
           // we create a reader for a certain document
           PdfReader reader = new PdfReader(fileName);
           reader.ConsolidateNamedDestinations();

           // step 4: we add content
           for (int i = 1; i <= reader.NumberOfPages; i++)
           {                
               PdfImportedPage page = writer.GetImportedPage(reader, i);
               writer.AddPage(page);
           }

           PRAcroForm form = reader.AcroForm;
           if (form != null)
           {
               writer.CopyAcroForm(reader);
           }

           reader.Close();
       }

       // step 5: we close the document and writer
       writer.Close();
       document.Close();
   }//disposes the newFileStream object
}

Data at the root level is invalid

This:

doc.LoadXml(HttpContext.Current.Server.MapPath("officeList.xml"));

should be:

doc.Load(HttpContext.Current.Server.MapPath("officeList.xml"));

LoadXml() is for loading an XML string, not a file name.

Download/Stream file from URL - asp.net

You could try using the DirectoryEntry class with the IIS path prefix:

using(DirectoryEntry de = new DirectoryEntry("IIS://Localhost/w3svc/1/root" + DOCUMENT_PATH))
{
    filePath = de.Properties["Path"].Value;
}

if (!File.Exists(filePath))
        return;

var fileInfo = new System.IO.FileInfo(filePath);
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", String.Format("attachment;filename=\"{0}\"", filePath));
Response.AddHeader("Content-Length", fileInfo.Length.ToString());
Response.WriteFile(filePath);
Response.End();

converting a base 64 string to an image and saving it

In my case it works only with two line of code. Test the below C# code:

String dirPath = "C:\myfolder\";
String imgName = "my_mage_name.bmp";

byte[] imgByteArray = Convert.FromBase64String("your_base64_string");
File.WriteAllBytes(dirPath + imgName, imgByteArray);

That's it. Kindly up vote if you really find this solution works for you. Thanks in advance.

Server.MapPath - Physical path given, virtual path expected

if you already know your folder is: E:\ftproot\sales then you do not need to use Server.MapPath, this last one is needed if you only have a relative virtual path like ~/folder/folder1 and you want to know the real path in the disk...

XmlDocument - load from string?

XmlDocument doc = new XmlDocument();
doc.LoadXml(str);

Where str is your XML string. See the MSDN article for more info.

MVC 3 file upload and model binding

For multiple files; note the newer "multiple" attribute for input:

Form:

@using (Html.BeginForm("FileImport","Import",FormMethod.Post, new {enctype = "multipart/form-data"}))
{
    <label for="files">Filename:</label>
    <input type="file" name="files" multiple="true" id="files" />
    <input type="submit"  />
}

Controller:

[HttpPost]
public ActionResult FileImport(IEnumerable<HttpPostedFileBase> files)
{
    return View();
}

Using Server.MapPath() inside a static field in ASP.NET MVC

Try HostingEnvironment.MapPath, which is static.

See this SO question for confirmation that HostingEnvironment.MapPath returns the same value as Server.MapPath: What is the difference between Server.MapPath and HostingEnvironment.MapPath?

"Invalid JSON primitive" in Ajax processing

Just a guess what does the variable json contain after

var json = Sys.Serialization.JavaScriptSerializer.serialize(obj);?

If it is a valid json object like {'foo':'foovalue', 'bar':'barvalue'} then jQuery might not send it as json data but instead serialize it to foor=foovalue&bar=barvalue thus you get the error "Invalid JSON primitive: foo"

Try instead setting the data as string

$.ajax({
    ...
    data: "{'foo':'foovalue', 'bar':'barvalue'}", //note the additional quotation marks
    ...
})

This way jQuery should leave the data alone and send the string as is to the server which should allow ASP.NET to parse the json server side.

Java: How to check if object is null?

It's probably slightly more efficient to catch a NullPointerException. The above methods mean that the runtime is checking for null pointers twice.

Could not load file or assembly 'System.Data.SQLite'

I have a 64 bit dev machine and 32 bit build server. I used this code prior to NHibernate initialisation. Works a charm on any architecture (well the 2 I have tested)

Hope this helps someone.

Guido

        private static void LoadSQLLiteAssembly()
        {
            Uri dir = new Uri(Assembly.GetExecutingAssembly().CodeBase);
            FileInfo fi = new FileInfo(dir.AbsolutePath);           
            string binFile = fi.Directory.FullName + "\\System.Data.SQLite.DLL";
            if (!File.Exists(binFile)) File.Copy(GetAppropriateSQLLiteAssembly(), binFile, false);
        }

        private static string GetAppropriateSQLLiteAssembly()
        {
            string pa = Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE");
            string arch = ((String.IsNullOrEmpty(pa) || String.Compare(pa, 0, "x86", 0, 3, true) == 0) ? "32" : "64");
            return GetLibsDir() + "\\NUnit\\System.Data.SQLite.x" + arch + ".DLL";
        }

How to call a Web Service Method?

write return(secondmethod) inside of the first method

enter image description here

Server.Mappath in C# classlibrary

HostingEnvironment.MapPath
System.Web.Hosting.HostingEnvironment.MapPath(path);

Using Server.MapPath in external C# Classes in ASP.NET

This one helped for me

//System.Web.HttpContext.Current.Server.MapPath //        
FileStream fileStream = new FileStream(System.Web.HttpContext.Current.Server.MapPath("~/File.txt"),
FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);

How to Deserialize XML document

If you're getting errors using xsd.exe to create your xsd file, then use the XmlSchemaInference class as mentioned on msdn. Here's a unit test to demonstrate:

using System.Xml;
using System.Xml.Schema;

[TestMethod]
public void GenerateXsdFromXmlTest()
{
    string folder = @"C:\mydir\mydata\xmlToCSharp";
    XmlReader reader = XmlReader.Create(folder + "\some_xml.xml");
    XmlSchemaSet schemaSet = new XmlSchemaSet();
    XmlSchemaInference schema = new XmlSchemaInference();

    schemaSet = schema.InferSchema(reader);


    foreach (XmlSchema s in schemaSet.Schemas())
    {
        XmlWriter xsdFile = new XmlTextWriter(folder + "\some_xsd.xsd", System.Text.Encoding.UTF8);
        s.Write(xsdFile);
        xsdFile.Close();
    }
}

// now from the visual studio command line type: xsd some_xsd.xsd /classes

Server.MapPath("."), Server.MapPath("~"), Server.MapPath(@"\"), Server.MapPath("/"). What is the difference?

1) Server.MapPath(".") -- Returns the "Current Physical Directory" of the file (e.g. aspx) being executed.

Ex. Suppose D:\WebApplications\Collage\Departments

2) Server.MapPath("..") -- Returns the "Parent Directory"

Ex. D:\WebApplications\Collage

3) Server.MapPath("~") -- Returns the "Physical Path to the Root of the Application"

Ex. D:\WebApplications\Collage

4) Server.MapPath("/") -- Returns the physical path to the root of the Domain Name

Ex. C:\Inetpub\wwwroot

Difference between checkout and export in SVN

svn export simply extracts all the files from a revision and does not allow revision control on it. It also does not litter each directory with .svn directories.

svn checkout allows you to use version control in the directory made, e.g. your standard commands such as svn update and svn commit.

clear data inside text file in c++

If you simply open the file for writing with the truncate-option, you'll delete the content.

std::ofstream ofs;
ofs.open("test.txt", std::ofstream::out | std::ofstream::trunc);
ofs.close();

http://www.cplusplus.com/reference/fstream/ofstream/open/

Java array assignment (multiple values)

Yes:

float[] values = {0.1f, 0.2f, 0.3f};

This syntax is only permissible in an initializer. You cannot use it in an assignment, where the following is the best you can do:

values = new float[3];

or

values = new float[] {0.1f, 0.2f, 0.3f};

Trying to find a reference in the language spec for this, but it's as unreadable as ever. Anyone else find one?

Returning Month Name in SQL Server Query

Select SUBSTRING (convert(varchar,S0.OrderDateTime,100),1,3) from your Table Name

jQuery 'if .change() or .keyup()'

Write a single function and call it for both of them.

function yourHandler(e){
    alert( 'something happened!' );        
}
jQuery(':input').change(yourHandler).keyup(yourHandler);

The change() and keyup() event registration functions return the original set, so they can be chained.

How to set opacity in parent div and not affect in child div?

You can't do that, unless you take the child out of the parent and place it via positioning.

The only way I know and it actually works, is to use a translucid image (.png with transparency) for the parent's background. The only disavantage is that you can't control the opacity via CSS, other than that it works!

Removing cordova plugins from the project

As far as I remember from Cordova, you should have an xml file in "res" folder containing the list of plugins used in your project. You probably need to remove those unused plugins from list. And also you should remove related files.

Best way to convert text files between character sets?

Stand-alone utility approach

iconv -f ISO-8859-1 -t UTF-8 in.txt > out.txt
-f ENCODING  the encoding of the input
-t ENCODING  the encoding of the output

You don't have to specify either of these arguments. They will default to your current locale, which is usually UTF-8.

What does the Visual Studio "Any CPU" target mean?

"Any CPU" means that when the program is started, the .NET Framework will figure out, based on the OS bitness, whether to run your program in 32 bits or 64 bits.

There is a difference between x86 and Any CPU: on a x64 system, your executable compiled for X86 will run as a 32-bit executable.

As far as your suspicions go, just go to the Visual Studio 2008 command line and run the following.

dumpbin YourProgram.exe /headers

It will tell you the bitness of your program, plus a whole lot more.

'module' object is not callable - calling method in another file

  • from a directory_of_modules, you can import a specific_module.py
  • this specific_module.py, can contain a Class with some_methods() or just functions()
  • from a specific_module.py, you can instantiate a Class or call functions()
  • from this Class, you can execute some_method()

Example:

#!/usr/bin/python3
from directory_of_modules import specific_module
instance = specific_module.DbConnect("username","password")
instance.login()

Excerpts from PEP 8 - Style Guide for Python Code:

Modules should have short and all-lowercase names.

Notice: Underscores can be used in the module name if it improves readability.

A Python module is simply a source file(*.py), which can expose:

  • Class: names using the "CapWords" convention.

  • Function: names in lowercase, words separated by underscores.

  • Global Variables: the conventions are about the same as those for Functions.

T-SQL CASE Clause: How to specify WHEN NULL

Given your query you can also do this:

SELECT first_name + ' ' + ISNULL(last_name, '') AS Name FROM dbo.person

How to concatenate two strings in SQL Server 2005

DECLARE @COMBINED_STRINGS AS VARCHAR(50),
        @STRING1 AS VARCHAR(20),
        @STRING2 AS VARCHAR(20);

SET @STRING1 = 'rupesh''s';
SET @STRING2 = 'malviya';
SET @COMBINED_STRINGS = @STRING1 + @STRING2;

SELECT @COMBINED_STRINGS;

SELECT '2' + '3';

I typed this in a sql file named TEST.sql and I run it. I got the following out put.

+-------------------+
| @COMBINED_STRINGS |
+-------------------+
|                 0 |
+-------------------+
1 row in set (0.00 sec)

+-----------+
| '2' + '3' |
+-----------+
|         5 |
+-----------+
1 row in set (0.00 sec)

After looking into this issue a bit more I found the best and sure sort way for string concatenation in SQL is by using CONCAT method. So I made the following changes in the same file.

#DECLARE @COMBINED_STRINGS AS VARCHAR(50),
 #       @STRING1 AS VARCHAR(20),
 #       @STRING2 AS VARCHAR(20);

SET @STRING1 = 'rupesh''s';
SET @STRING2 = 'malviya';
#SET @COMBINED_STRINGS = @STRING1 + @STRING2;
SET @COMBINED_STRINGS = (SELECT CONCAT(@STRING1, @STRING2));

SELECT @COMBINED_STRINGS;

#SELECT '2' + '3';
SELECT CONCAT('2','3');

and after executing the file this was the output.

+-------------------+
| @COMBINED_STRINGS |
+-------------------+
| rupesh'smalviya   |
+-------------------+
1 row in set (0.00 sec)

+-----------------+
| CONCAT('2','3') |
+-----------------+
| 23              |
+-----------------+
1 row in set (0.00 sec)

SQL version I am using is: 14.14

The ALTER TABLE statement conflicted with the FOREIGN KEY constraint

I encounter some issue in my project.

enter image description here

In child table, there isn't any record Id equals 1 and 11

mage

I inserted DEAL_ITEM_THIRD_PARTY_PO table which Id equals 1 and 11 then I can create FK

error: expected primary-expression before ')' token (C)

You should create a variable of the type SelectionneNonSelectionne.

struct SelectionneNonSelectionne var;

After that pass that variable to the function like

characterSelection(screen, var);

The error is caused since you are passing the type name SelectionneNonSelectionne

How to check if IsNumeric

You could write an extension method:

public static class Extension
{
    public static bool IsNumeric(this string s)
    {
        float output;
        return float.TryParse(s, out output);
    }
}

how to remove empty strings from list, then remove duplicate values from a list

Amiram's answer is correct, but Distinct() as implemented is an N2 operation; for each item in the list, the algorithm compares it to all the already processed elements, and returns it if it's unique or ignores it if not. We can do better.

A sorted list can be deduped in linear time; if the current element equals the previous element, ignore it, otherwise return it. Sorting is NlogN, so even having to sort the collection, we get some benefit:

public static IEnumerable<T> SortAndDedupe<T>(this IEnumerable<T> input)
{
   var toDedupe = input.OrderBy(x=>x);

   T prev;
   foreach(var element in toDedupe)
   {
      if(element == prev) continue;

      yield return element;
      prev = element;      
   }
}

//Usage
dtList  = dtList.Where(s => !string.IsNullOrWhitespace(s)).SortAndDedupe().ToList();

This returns the same elements; they're just sorted.

Should switch statements always contain a default clause?

The default case may not necessary in the switch used by enum. when switch contained all value, the default case will never execute. So in this case, it is not necessary.

How to avoid pressing Enter with getchar() for reading a single character only?

You could include the 'ncurses' library, and use getch() instead of getchar().

Beamer: How to show images as step-by-step images

You can simply specify a series of images like this:

\includegraphics<1>{A}
\includegraphics<2>{B}
\includegraphics<3>{C}

This will produce three slides with the images A to C in exactly the same position.

Convert DataTable to IEnumerable<T>

There's also a DataSetExtension method called "AsEnumerable()" (in System.Data) that takes a DataTable and returns an Enumerable. See the MSDN doc for more details, but it's basically as easy as:

dataTable.AsEnumerable()

The downside is that it's enumerating DataRow, not your custom class. A "Select()" LINQ call could convert the row data, however:

private IEnumerable<TankReading> ConvertToTankReadings(DataTable dataTable)
{
    return dataTable.AsEnumerable().Select(row => new TankReading      
            {      
                TankReadingsID = Convert.ToInt32(row["TRReadingsID"]),      
                TankID = Convert.ToInt32(row["TankID"]),      
                ReadingDateTime = Convert.ToDateTime(row["ReadingDateTime"]),      
                ReadingFeet = Convert.ToInt32(row["ReadingFeet"]),      
                ReadingInches = Convert.ToInt32(row["ReadingInches"]),      
                MaterialNumber = row["MaterialNumber"].ToString(),      
                EnteredBy = row["EnteredBy"].ToString(),      
                ReadingPounds = Convert.ToDecimal(row["ReadingPounds"]),      
                MaterialID = Convert.ToInt32(row["MaterialID"]),      
                Submitted = Convert.ToBoolean(row["Submitted"]),      
            });
}

Can I pass an array as arguments to a method with variable arguments in Java?

It's ok to pass an array - in fact it amounts to the same thing

String.format("%s %s", "hello", "world!");

is the same as

String.format("%s %s", new Object[] { "hello", "world!"});

It's just syntactic sugar - the compiler converts the first one into the second, since the underlying method is expecting an array for the vararg parameter.

See

How to convert any Object to String?

If the class does not have toString() method, then you can use ToStringBuilder class from org.apache.commons:commons-lang3

pom.xml:

<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-lang3</artifactId>
  <version>3.10</version>
</dependency>

code:

ToStringBuilder.reflectionToString(yourObject)

In C++, what is a virtual base class?

A virtual base class is a class that cannot be instantiated : you cannot create direct object out of it.

I think you are confusing two very different things. Virtual inheritance is not the same thing as an abstract class. Virtual inheritance modifies the behaviour of function calls; sometimes it resolves function calls that otherwise would be ambiguous, sometimes it defers function call handling to a class other than that one would expect in a non-virtual inheritance.

Execute specified function every X seconds

You can do this easily by adding a Timer to your form (from the designer) and setting it's Tick-function to run your isonline-function.

Jenkins: Can comments be added to a Jenkinsfile?

You can use block (/***/) or single line comment (//) for each line. You should use "#" in sh command.

Block comment

_x000D_
_x000D_
/*  _x000D_
post {_x000D_
    success {_x000D_
      mail to: "[email protected]", _x000D_
      subject:"SUCCESS: ${currentBuild.fullDisplayName}", _x000D_
      body: "Yay, we passed."_x000D_
    }_x000D_
    failure {_x000D_
      mail to: "[email protected]", _x000D_
      subject:"FAILURE: ${currentBuild.fullDisplayName}", _x000D_
      body: "Boo, we failed."_x000D_
    }_x000D_
  }_x000D_
*/
_x000D_
_x000D_
_x000D_

Single Line

_x000D_
_x000D_
// post {_x000D_
//     success {_x000D_
//       mail to: "[email protected]", _x000D_
//       subject:"SUCCESS: ${currentBuild.fullDisplayName}", _x000D_
//       body: "Yay, we passed."_x000D_
//     }_x000D_
//     failure {_x000D_
//       mail to: "[email protected]", _x000D_
//       subject:"FAILURE: ${currentBuild.fullDisplayName}", _x000D_
//       body: "Boo, we failed."_x000D_
//     }_x000D_
// }
_x000D_
_x000D_
_x000D_

Comment in 'sh' command

_x000D_
_x000D_
        stage('Unit Test') {_x000D_
            steps {_x000D_
                ansiColor('xterm'){_x000D_
                  sh '''_x000D_
                  npm test_x000D_
                  # this is a comment in sh_x000D_
                  '''_x000D_
                }_x000D_
            }_x000D_
        }
_x000D_
_x000D_
_x000D_

What exactly is an instance in Java?

basically object and instance are the two words used interchangeably. A class is template for an object and an object is an instance of a class.

HTML 5 Favicon - Support?

No, not all browsers support the sizes attribute:

Note that some platforms define specific sizes:

How to change to an older version of Node.js

*NIX (Linux, OS X, ...)

Use n, an extremely simple Node version manager that can be installed via npm.

Say you want Node.js v0.10.x to build Atom.

npm install -g n   # Install n globally
n 0.10.33          # Install and use v0.10.33
Usage:
n                            # Output versions installed
n latest                     # Install or activate the latest node release
n stable                     # Install or activate the latest stable node release
n <version>                  # Install node <version>
n use <version> [args ...]   # Execute node <version> with [args ...]
n bin <version>              # Output bin path for <version>
n rm <version ...>           # Remove the given version(s)
n --latest                   # Output the latest node version available
n --stable                   # Output the latest stable node version available
n ls                         # Output the versions of node available

 

Windows

Use nvm-windows, it's like nvm but for Windows. Download and run the installer, then:

nvm install v0.10.33         # Install v0.10.33
nvm use v0.10.33             # Use v0.10.33
Usage:
nvm install [version]        # Download and install [version]
nvm uninstall [version]      # Uninstall [version]
nvm use [version]            # Switch to use [version]
nvm list                     # List installed versions

How to clear all input fields in a specific div with jQuery?

Change this:

 <div class=fetch_results>

To this:

 <div id="fetch_results">

Then the following should work:

$("#fetch_results input").each(function() {
      this.value = "";
  })?

http://jsfiddle.net/NVqeR/

iOS Simulator to test website on Mac

You could also download Xcode to your mac and use iPhone simulator.

Where to find htdocs in XAMPP Mac

Click volumes, then explore, and then that should open lampp which has htdocs in it.

How do I set a fixed background image for a PHP file?

I found my answer.

<?php
$profpic = "bg.jpg";
?>

<html>
<head>
<style type="text/css">

body {
background-image: url('<?php echo $profpic;?>');
}
</style>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Hey</title>
</head>
<body>
</body>
</html>

How to SELECT in Oracle using a DBLINK located in a different schema?

I had the same problem I used the solution offered above - I dropped the SYNONYM, created a VIEW with the same name as the synonym. it had a select using the dblink , and gave GRANT SELECT to the other schema It worked great.

Read SQL Table into C# DataTable

var table = new DataTable();    
using (var da = new SqlDataAdapter("SELECT * FROM mytable", "connection string"))
{      
    da.Fill(table);
}

How to read specific lines from a file (by line number)?

You can do a seek() call which positions your read head to a specified byte within the file. This won't help you unless you know exactly how many bytes (characters) are written in the file before the line you want to read. Perhaps your file is strictly formatted (each line is X number of bytes?) or, you could count the number of characters yourself (remember to include invisible characters like line breaks) if you really want the speed boost.

Otherwise, you do have to read every line prior to the line you desire, as per one of the many solutions already proposed here.

How to convert int to QString?

Use QString::number():

int i = 42;
QString s = QString::number(i);

Programmatically add new column to DataGridView

Add new column to DataTable and use column Expression property to set your Status expression.

Here you can find good example: DataColumn.Expression Property

DataTable and DataColumn Expressions in ADO.NET - Calculated Columns

UPDATE

Code sample:

DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("colBestBefore", typeof(DateTime)));
dt.Columns.Add(new DataColumn("colStatus", typeof(string)));

dt.Columns["colStatus"].Expression = String.Format("IIF(colBestBefore < #{0}#, 'Ok','Not ok')", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

dt.Rows.Add(DateTime.Now.AddDays(-1));
dt.Rows.Add(DateTime.Now.AddDays(1));
dt.Rows.Add(DateTime.Now.AddDays(2));
dt.Rows.Add(DateTime.Now.AddDays(-2));

demoGridView.DataSource = dt;

UPDATE #2

dt.Columns["colStatus"].Expression = String.Format("IIF(CONVERT(colBestBefore, 'System.DateTime') < #{0}#, 'Ok','Not ok')", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

JavaScript: client-side vs. server-side validation

You must always validate on the server.

Also having validation on the client is nice for users, but is utterly insecure.

How to disable Django's CSRF validation?

If you just need some views not to use CSRF, you can use @csrf_exempt:

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def my_view(request):
    return HttpResponse('Hello world')

You can find more examples and other scenarios in the Django documentation:

Error: Cannot pull with rebase: You have unstaged changes

If you want to automatically stash your changes and unstash them for every rebase, you can do this:

git config --global rebase.autoStash true

How to read barcodes with the camera on Android?

You can also use barcodefragmentlib which is an extension of zxing but provides barcode scanning as fragment library, so can be very easily integrated.

Here is the supporting documentation for usage of library

Java Can't connect to X11 window server using 'localhost:10.0' as the value of the DISPLAY variable

This fixed my problem

xhost +

but Be aware that xhost + completely deactivates authentication and allows everyone to access all application on your screen.

xhost +si:localuser:root seems to work similar with proper authentication.

Jquery- Get the value of first td in table

If you need to get all td's inside tr without defining id for them, you can use the code below :

var items = new Array();

$('#TABLE_ID td:nth-child(1)').each(function () {
      items.push($(this).html());
});

The code above will add all first cells inside the Table into an Array variable.

you can change nth-child(1) which means the first cell to any cell number you need.

hope this code helps you.

Make a DIV fill an entire table cell

div height=100% in table cell will work only when table has height attribute itself.

_x000D_
_x000D_
<table border="1" style="height:300px; width: 100px;">
 <tr><td>cell1</td><td>cell2</td></tr>
 <tr>
   <td style="height: 100%">
     <div style="height: 100%; width: 100%; background-color:pink;"></div>
   </td>
   <td>long text long text long text long text long text long text</td>
 </tr>
</table>
_x000D_
_x000D_
_x000D_

UPD in FireFox you should also set height=100% value to the parent TD element

Validating a Textbox field for only numeric input.

I agree with Int.TryParse but as an alternative you could use Regex.

 Regex nonNumericRegex = new Regex(@"\D");
 if (nonNumericRegex.IsMatch(txtEvDistance.Text))
 {
   //Contains non numeric characters.
   return false;
 }

Make A List Item Clickable (HTML/CSS)

Ditch the <a href="...">. Put the onclick (all lowercase) handler on the <li> tag itself.

Add hover text without javascript like we hover on a user's reputation

You're looking for tooltip

For the basic tooltip, you want:

<div title="This is my tooltip">

For a fancier javascript version, you can look into:

http://www.designer-daily.com/jquery-prototype-mootool-tooltips-12632

The above link gives you 12 options for tooltips.

Help with packages in java - import does not work

Yes, this is a classpath issue. You need to tell the compiler and runtime that the directory where your .class files live is part of the CLASSPATH. The directory that you need to add is the parent of the "com" directory at the start of your package structure.

You do this using the -classpath argument for both javac.exe and java.exe.

Should also ask how the 3rd party classes you're using are packaged. If they're in a JAR, and I'd recommend that you have them in one, you add the .jar file to the classpath:

java -classpath .;company.jar foo.bar.baz.YourClass

Google for "Java classpath". It'll find links like this.

One more thing: "import" isn't loading classes. All it does it save you typing. When you include an import statement, you don't have to use the fully-resolved class name in your code - you can type "Foo" instead of "com.company.thing.Foo". That's all it's doing.

Incorrect string value: '\xF0\x9F\x8E\xB6\xF0\x9F...' MySQL

According to the create table statement, the default charset of the table is already utf8mb4. It seems that you have a wrong connection charset.

In Java, set the datasource url like this: jdbc:mysql://127.0.0.1:3306/testdb?useUnicode=true&characterEncoding=utf-8.

"?useUnicode=true&characterEncoding=utf-8" is necessary for using utf8mb4.

It works for my application.

How do I declare a namespace in JavaScript?

I like Jaco Pretorius' solution, but I wanted to make the "this" keyword a bit more useful by pointing it to the module/namespace object. My version of skillet:

(function ($, undefined) {

    console.log(this);

}).call(window.myNamespace = window.myNamespace || {}, jQuery);

JS file gets a net::ERR_ABORTED 404 (Not Found)

As mentionned in comments: you need a way to send your static files to the client. This can be achieved with a reverse proxy like Nginx, or simply using express.static().

Put all your "static" (css, js, images) files in a folder dedicated to it, different from where you put your "views" (html files in your case). I'll call it static for the example. Once it's done, add this line in your server code:

app.use("/static", express.static('./static/'));

This will effectively serve every file in your "static" folder via the /static route.

Querying your index.js file in the client thus becomes:

<script src="static/index.js"></script>

How can I introduce multiple conditions in LIKE operator?

Even u can try this

Function

CREATE  FUNCTION [dbo].[fn_Split](@text varchar(8000), @delimiter varchar(20))
RETURNS @Strings TABLE
(   
  position int IDENTITY PRIMARY KEY,
  value varchar(8000)  
)
AS
BEGIN

DECLARE @index int
SET @index = -1

WHILE (LEN(@text) > 0)
  BEGIN 
    SET @index = CHARINDEX(@delimiter , @text) 
    IF (@index = 0) AND (LEN(@text) > 0) 
      BEGIN  
        INSERT INTO @Strings VALUES (@text)
          BREAK 
      END 
    IF (@index > 1) 
      BEGIN  
        INSERT INTO @Strings VALUES (LEFT(@text, @index - 1))  
        SET @text = RIGHT(@text, (LEN(@text) - @index)) 
      END 
    ELSE
      SET @text = RIGHT(@text, (LEN(@text) - @index))
    END
  RETURN
END

Query

select * from my_table inner join (select value from fn_split('ABC,MOP',','))
as split_table on my_table.column_name like '%'+split_table.value+'%';

ORA-28040: No matching authentication protocol exception

Adding

SQLNET.ALLOWED_LOGON_VERSION_SERVER = 8

is the perfect solution sql.ora directory ..\product\12.1.0\dbhome_1\NETWORK\ADMIN

Log4net does not write the log in the log file

Do you call

log4net.Config.XmlConfigurator.Configure();

somewhere to make log4net read your configuration? E.g. in Global.asax:

void Application_Start(object sender, EventArgs e) 
{
    // Code that runs on application startup

    // Initialize log4net.
    log4net.Config.XmlConfigurator.Configure();
}

Android: Vertical alignment for multi line EditText (Text area)

Now a day use of gravity start is best choise:

android:gravity="start"

For EditText (textarea):

<EditText
    android:id="@+id/EditText02"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:lines="5"
    android:gravity="start"
    android:inputType="textMultiLine"
/>

Difference between number and integer datatype in oracle dictionary views

the best explanation i've found is this:

What is the difference betwen INTEGER and NUMBER? When should we use NUMBER and when should we use INTEGER? I just wanted to update my comments here...

NUMBER always stores as we entered. Scale is -84 to 127. But INTEGER rounds to whole number. The scale for INTEGER is 0. INTEGER is equivalent to NUMBER(38,0). It means, INTEGER is constrained number. The decimal place will be rounded. But NUMBER is not constrained.

  • INTEGER(12.2) => 12
  • INTEGER(12.5) => 13
  • INTEGER(12.9) => 13
  • INTEGER(12.4) => 12
  • NUMBER(12.2) => 12.2
  • NUMBER(12.5) => 12.5
  • NUMBER(12.9) => 12.9
  • NUMBER(12.4) => 12.4

INTEGER is always slower then NUMBER. Since integer is a number with added constraint. It takes additional CPU cycles to enforce the constraint. I never watched any difference, but there might be a difference when we load several millions of records on the INTEGER column. If we need to ensure that the input is whole numbers, then INTEGER is best option to go. Otherwise, we can stick with NUMBER data type.

Here is the link

Wordpress plugin install: Could not create directory

For me the problem was FTP server that WP is using to upload update. It had writting disabled in configuration, so just enabling it fixed the problem.

Shame on WordPress for providing such misleading error message.

List files committed for a revision

From remote repo:

svn log -v -r 42 --stop-on-copy --non-interactive --no-auth-cache --username USERNAME --password PASSWORD http://repourl/projectname/

Can't find file executable in your configured search path for gnc gcc compiler

Here's an easy way for Windows users.

  1. Uninstall the existing codeblocks from your system.
  2. Restart system.
  3. Go to http://www.codeblocks.org/downloads/26
  4. Download the codeblocks-16.01mingw-setup.exe file. It includes the GCC/G++ compiler and GDB debugger from TDM-GCC (version 4.9.2, 32 bit, SJLJ).

Recursively list all files in a directory including files in symlink directories

ls -R -L

-L dereferences symbolic links. This will also make it impossible to see any symlinks to files, though - they'll look like the pointed-to file.

Download a file with Android, and showing the progress in a ProgressDialog

Important

AsyncTask is deprecated in Android 11.

For more information please checkout following posts

Probably should move to concorency Framework as suggested by google

HTTP POST with URL query parameters -- good idea or not?

I agree - it's probably safer to use a GET request if you're just passing data in the URL and not in the body. See this similar question for some additional views on the whole POST+GET concept.

Java "?" Operator for checking null - What is it? (Not Ternary!)

There you have it, null-safe invocation in Java 8:

public void someMethod() {
    String userName = nullIfAbsent(new Order(), t -> t.getAccount().getUser()
        .getName());
}

static <T, R> R nullIfAbsent(T t, Function<T, R> funct) {
    try {
        return funct.apply(t);
    } catch (NullPointerException e) {
        return null;
    }
}

How can I autoplay a video using the new embed code style for Youtube?

Okay this is an example for the new embed code for youtube videos.

<iframe title="YouTube video player" class="youtube-player" type="text/html" width="560" height="345" src="http://www.youtube.com/embed/8v_4O44sfjM" frameborder="0" allowFullScreen></iframe>

if you want to autoplay it, at the src="http://www.youtube.com/embed/8v_4O44sfjM" add the ?autoplay=1 parameter

So the code will look like this:

<iframe title="YouTube video player" class="youtube-player" type="text/html" width="560" height="345" src="http://www.youtube.com/embed/8v_4O44sfjM?autoplay=1" frameborder="0" allowFullScreen></iframe>

i tried this on my blog and it works ! Hope this help (:

Popup window in winform c#

If you mean to create a new form when a button is clicked, the below code may be of some use to you:

private void settingsButton_Click(Object sender, EventArgs e)
{
    // Create a new instance of the Form2 class
    Form2 settingsForm = new Form2();

    // Show the settings form
    settingsForm.Show();
}

From here, you could also use the 'Show Dialog' method

CSS I want a div to be on top of everything

You need to add position:relative; to the menu. Z-index only works when you have a non static positioning scheme.

Text overflow ellipsis on two lines

          text-overflow: ellipsis;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          line-height: 36px;
          max-height: 18px;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;

I've found a combo of both line-clamp and line-height works :D

How do I declare a model class in my Angular 2 component using TypeScript?

In your case you are having model on same page, but you have it declared after your Component class, so that's you need to use forwardRef to refer to Class. Don't prefer to do this, always have model object in separate file.

export class testWidget {
    constructor(@Inject(forwardRef(() => Model)) private service: Model) {}
}

Additionally you have to change you view interpolation to refer to correct object

{{model?.param1}}

Better thing you should do is, you can have your Model Class define in different file & then import it as an when you require it by doing. Also have export before you class name, so that you can import it.

import { Model } from './model';

Angular2 module has no exported member

This error can also occur if your interface name is different than the file it is contained in. Read about ES6 modules for details. If the SignInComponent was an interface, as was in my case, then

SignInComponent

should be in a file named SignInComponent.ts.

How to open the terminal in Atom?

For Windows follow the below steps

(1)go to file>setting and click on install enter image description here

(2) then type "platformio-ide-terminal" in packages and hit install enter image description here (3) after finish install restart atom and press

 ctrl + ~ for opening the terminal `~` is the key below `Esc`

enter image description here

welcome ;-)

Flask SQLAlchemy query, specify column names

You can use load_only function:

from sqlalchemy.orm import load_only

fields = ['name', 'addr', 'phone', 'url']
companies = session.query(SomeModel).options(load_only(*fields)).all()

How do you make an array of structs in C?

Solution using pointers:

#include<stdio.h>
#include<stdlib.h>
#define n 3
struct body
{
    double p[3];//position
    double v[3];//velocity
    double a[3];//acceleration
    double radius;
    double *mass;
};


int main()
{
    struct body *bodies = (struct body*)malloc(n*sizeof(struct body));
    int a, b;
     for(a = 0; a < n; a++)
     {
            for(b = 0; b < 3; b++)
            {
                bodies[a].p[b] = 0;
                bodies[a].v[b] = 0;
                bodies[a].a[b] = 0;
            }
            bodies[a].mass = 0;
            bodies[a].radius = 1.0;
     }

    return 0;
}

Razor-based view doesn't see referenced assemblies

None of these https://stackoverflow.com/a/7597360/808128 do work for me. Even "adding assembly referecene to system.web/compilation/assemblies section of the root web.config file". So the two ways remains for me: 1) to add a public wrap class for my assembly that Razor code can access to this assembly through this wrap; 2) just add assembly logic to a public class in the same assembly where the Razor's code is located.

How to catch integer(0)?

You can easily catch integer(0) with function identical(x,y)

x = integer(0)
identical(x, integer(0))
[1] TRUE

foo = function(x){identical(x, integer(0))}
foo(x)
[1] TRUE

foo(0)
[1] FALSE

Redirect From Action Filter Attribute

Set filterContext.Result

With the route name:

filterContext.Result = new RedirectToRouteResult("SystemLogin", routeValues);

You can also do something like:

filterContext.Result = new ViewResult
{
    ViewName = SharedViews.SessionLost,
    ViewData = filterContext.Controller.ViewData
};

If you want to use RedirectToAction:

You could make a public RedirectToAction method on your controller (preferably on its base controller) that simply calls the protected RedirectToAction from System.Web.Mvc.Controller. Adding this method allows for a public call to your RedirectToAction from the filter.

public new RedirectToRouteResult RedirectToAction(string action, string controller)
{
    return base.RedirectToAction(action, controller);
}

Then your filter would look something like:

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
    var controller = (SomeControllerBase) filterContext.Controller;
    filterContext.Result = controller.RedirectToAction("index", "home");
}

Rails 3.1 and Image Assets

For what it's worth, when I did this I found that no folder should be include in the path in the css file. For instance if I have app/assets/images/example.png, and I put this in my css file...

div.example { background: url('example.png'); }

... then somehow it magically works. I figured this out by running the rake assets:precompile task, which just sucks everything out of all your load paths and dumps it in a junk drawer folder: public/assets. That's ironic, IMO...

In any case this means you don't need to put any folder paths, everything in your assets folders will all end up living in one huge directory. How this system resolves file name conflicts is unclear, you may need to be careful about that.

Kind of frustrating there aren't better docs out there for this big of a change.

Move view with keyboard using Swift

Use following code for view Up on UITextField Clicked

func textFieldDidBeginEditing(textField: UITextField) {
    ViewUpanimateMoving(true, upValue: 100)
}
func textFieldDidEndEditing(textField: UITextField) {
    ViewUpanimateMoving(false, upValue: 100)
}
func ViewUpanimateMoving (up:Bool, upValue :CGFloat){
    var durationMovement:NSTimeInterval = 0.3
    var movement:CGFloat = ( up ? -upValue : upValue)
    UIView.beginAnimations( "animateView", context: nil)
    UIView.setAnimationBeginsFromCurrentState(true)
    UIView.setAnimationDuration(durationMovement)
    self.view.frame = CGRectOffset(self.view.frame, 0,  movement)
    UIView.commitAnimations()
}

How to get a list of all files that changed between two Git commits?

For files changed between a given SHA and your current commit:

git diff --name-only <starting SHA> HEAD

or if you want to include changed-but-not-yet-committed files:

git diff --name-only <starting SHA>

More generally, the following syntax will always tell you which files changed between two commits (specified by their SHAs or other names):

git diff --name-only <commit1> <commit2>

Support for "border-radius" in IE

SOLVED - not rendering border radius correctly in IE 10 and 11

For those not getting the -ms-border-radius: or the border-radius: to work in IE 10,11 And it renders all square then follow these steps:

  1. Click on the gear wheel at the top right of the IE browser
  2. Click on Compatibility view settings
  3. Now uncheck the 2 boxes that are checked by default.

Ensure that the boxes are unchecked as in pic

How to sort pandas data frame using values from several columns?

I have found this to be really useful:

df = pd.DataFrame({'A' : range(0,10) * 2, 'B' : np.random.randint(20,30,20)})

# A ascending, B descending
df.sort(**skw(columns=['A','-B']))

# A descending, B ascending
df.sort(**skw(columns=['-A','+B']))

Note that unlike the standard columns=,ascending= arguments, here column names and their sort order are in the same place. As a result your code gets a lot easier to read and maintain.

Note the actual call to .sort is unchanged, skw (sortkwargs) is just a small helper function that parses the columns and returns the usual columns= and ascending= parameters for you. Pass it any other sort kwargs as you usually would. Copy/paste the following code into e.g. your local utils.py then forget about it and just use it as above.

# utils.py (or anywhere else convenient to import)
def skw(columns=None, **kwargs):
    """ get sort kwargs by parsing sort order given in column name """
    # set default order as ascending (+)
    sort_cols = ['+' + col if col[0] != '-' else col for col in columns]
    # get sort kwargs
    columns, ascending = zip(*[(col.replace('+', '').replace('-', ''), 
                                False if col[0] == '-' else True) 
                               for col in sort_cols])
    kwargs.update(dict(columns=list(columns), ascending=ascending))
    return kwargs

UIImageView aspect fit and center

You can achieve this by setting content mode of image view to UIViewContentModeScaleAspectFill.

Then use following method method to get the resized uiimage object.

- (UIImage*)setProfileImage:(UIImage *)imageToResize onImageView:(UIImageView *)imageView
{
    CGFloat width = imageToResize.size.width;
    CGFloat height = imageToResize.size.height;
    float scaleFactor;
    if(width > height)
    {
        scaleFactor = imageView.frame.size.height / height;
    }
    else
    {
        scaleFactor = imageView.frame.size.width / width;
    }

    UIGraphicsBeginImageContextWithOptions(CGSizeMake(width * scaleFactor, height * scaleFactor), NO, 0.0);
    [imageToResize drawInRect:CGRectMake(0, 0, width * scaleFactor, height * scaleFactor)];
    UIImage *resizedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return resizedImage;
}

Edited Here (Swift Version)

func setProfileImage(imageToResize: UIImage, onImageView: UIImageView) -> UIImage
{
    let width = imageToResize.size.width
    let height = imageToResize.size.height

    var scaleFactor: CGFloat

    if(width > height)
    {
        scaleFactor = onImageView.frame.size.height / height;
    }
    else
    {
        scaleFactor = onImageView.frame.size.width / width;
    }

    UIGraphicsBeginImageContextWithOptions(CGSizeMake(width * scaleFactor, height * scaleFactor), false, 0.0)
    imageToResize.drawInRect(CGRectMake(0, 0, width * scaleFactor, height * scaleFactor))
    let resizedImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return resizedImage;
}

How can I center <ul> <li> into div

Just add text-align: center; to your <ul>. Problem solved.

How to append text to a text file in C++?

You need to specify the append open mode like

#include <fstream>

int main() {  
  std::ofstream outfile;

  outfile.open("test.txt", std::ios_base::app); // append instead of overwrite
  outfile << "Data"; 
  return 0;
}

Swift_TransportException Connection could not be established with host smtp.gmail.com

In my case, I had trouble with GoDaddy and SSL encryption.

Setting the encryption to Null and Port to 80 (Or any supportive port) did the job.

Insert ellipsis (...) into HTML tag if content too wide

I've got a solution working in FF3, Safari and IE6+ with single and multiline text

.ellipsis {
    white-space: nowrap;
    overflow: hidden;
}

.ellipsis.multiline {
    white-space: normal;
}

<div class="ellipsis" style="width: 100px; border: 1px solid black;">Lorem ipsum dolor sit amet, consectetur adipisicing elit</div>
<div class="ellipsis multiline" style="width: 100px; height: 40px; border: 1px solid black; margin-bottom: 100px">Lorem ipsum dolor sit amet, consectetur adipisicing elit</div>

<script type="text/javascript" src="/js/jquery.ellipsis.js"></script>
<script type="text/javascript">
$(".ellipsis").ellipsis();
</script>

jquery.ellipsis.js

(function($) {
    $.fn.ellipsis = function()
    {
        return this.each(function()
        {
            var el = $(this);

            if(el.css("overflow") == "hidden")
            {
                var text = el.html();
                var multiline = el.hasClass('multiline');
                var t = $(this.cloneNode(true))
                    .hide()
                    .css('position', 'absolute')
                    .css('overflow', 'visible')
                    .width(multiline ? el.width() : 'auto')
                    .height(multiline ? 'auto' : el.height())
                    ;

                el.after(t);

                function height() { return t.height() > el.height(); };
                function width() { return t.width() > el.width(); };

                var func = multiline ? height : width;

                while (text.length > 0 && func())
                {
                    text = text.substr(0, text.length - 1);
                    t.html(text + "...");
                }

                el.html(t.html());
                t.remove();
            }
        });
    };
})(jQuery);

pandas GroupBy columns with NaN (missing) values

I answered this already, but some reason the answer was converted to a comment. Nevertheless, this is the most efficient solution:

Not being able to include (and propagate) NaNs in groups is quite aggravating. Citing R is not convincing, as this behavior is not consistent with a lot of other things. Anyway, the dummy hack is also pretty bad. However, the size (includes NaNs) and the count (ignores NaNs) of a group will differ if there are NaNs.

dfgrouped = df.groupby(['b']).a.agg(['sum','size','count'])

dfgrouped['sum'][dfgrouped['size']!=dfgrouped['count']] = None

When these differ, you can set the value back to None for the result of the aggregation function for that group.

PHP: How to remove specific element from an array?

A better approach would maybe be to keep your values as keys in an associative array, and then call array_keys() on it when you want to actual array. That way you don't need to use array_search to find your element.

Converting a value to 2 decimal places within jQuery

You need to use the .toFixed() method

It takes as a parameter the number of digits to show after the decimal point.

$(document).ready(function() {
  $('.add').click(function() {
     var value = parseFloat($('#total').text()) + parseFloat($(this).data('amount'))/100
     $('#total').text( value.toFixed(2) );
  });
})

Is it possible to GROUP BY multiple columns using MySQL?

To use a simple example, I had a counter that needed to summarise unique IP addresses per visited page on a site. Which is basically grouping by pagename and then by IP. I solved it with a combination of DISTINCT and GROUP BY.

SELECT pagename, COUNT(DISTINCT ipaddress) AS visit_count FROM log_visitors GROUP BY pagename ORDER BY visit_count DESC;

What does the error "arguments imply differing number of rows: x, y" mean?

I had the same error message so I went googling a bit I managed to fix it with the following code.

df<-data.frame(words = unlist(words))

words is a character list.

This just in case somebody else needs the output to be a data frame.

There is no argument given that corresponds to the required formal parameter - .NET Error

You have a constructor which takes 2 parameters. You should write something like:

new ErrorEventArg(errorMsv, lastQuery)

It's less code and easier to read.

EDIT

Or, in order for your way to work, you can try writing a default constructor for ErrorEventArg which would have no parameters, like this:

public ErrorEventArg() {}

Passing struct to function

Instead of:

void addStudent(person)
{
    return;
}

try this:

void addStudent(student person)
{
    return;
}

Since you have already declared a structure called 'student' you don't necessarily have to specify so in the function implementation as in:

void addStudent(struct student person)
{
    return;
}

DataSet panel (Report Data) in SSRS designer is gone

With a report (rdl) file selected in your solution, select View and then Report Data.

It is a shortcut of Ctrl+Alt+D.

enter image description here

Xcode warning: "Multiple build commands for output file"

For me the Target > Build Settings > Packaging > Product Name was set to the same thing as another value referenced in a .plist file which was custom to my app. Eventually due to our build process this creates duplicate files.

How to get dictionary values as a generic list

Dictionary<string, MyType> myDico = GetDictionary();

var items = myDico.Select(d=> d.Value).ToList();

TortoiseGit save user authentication / credentials

None of the above answers worked for me using git version 1.8.3.msysgit.0 and TortoiseGit 1.8.4.0.

In my particular situation, I have to connect to the remote git repo over HTTPS, using a full blown e-mail address as username. In this situation, wincred did not appear to work.

Using the email address as a part of the repo URL also did not work, as the software seems to be confused by the double appearance of the '@' character in the URL.

I did manage to overcome the problem using winstore. Here is what I did:

This will copy the git-credential-winstore.exe to a local directory and add two lines to your global .gitconfig. You can verify this by examining your global .gitconfig. This is easiest done via right mouse button on a folder, "TortoiseGit > Settings > Git > Edit global .gitconfig". The file should contain two lines like:

    [credential]
        helper = !'C:\\Users\\yourlogin\\AppData\\Roaming\\GitCredStore\\git-credential-winstore.exe'
  • No other TortoiseGit settings are needed under "Network" or "Credential". In particular: the "Credential helper" pull down menu under "Credential" will have gone blank as a result of these configuration lines, since TortoiseGit does not recognize the new helper. Do not set the pull down menu to another value or the global .gitconfig will be overwritten with an incorrect value! (*)

You are now ready to go:

  • Try to pull from the remote repository. You will notice an authentication popup asking your username and password, the popup should be visually different from the default TortoiseGit popup. This is a good sign and means winstore works. Enter the correct authentication and the pull should succeed.
  • Try the same pull again, and your username and password should no longer be asked.

Done! Enjoy your interactions with the remote repo while winstore takes care of the authentication.

(*) Alternatively, if you don't like the blank selection in the TortoiseGit Credential settings helper pull down menu, you can use the "Advanced" option:

  • Go to "TortoiseGit > Settings > Credential"
  • Select Credential helper "Advanced"
  • Click on the "G" (for global) under Helpers
  • Enter the Helper path as below. Note: a regular Windows path notation (e.g. "C:\Users...") will not work here, you have to replicate the exact line that installing winstore created in the global .gitconf without the "helper =" bit.

    !'C:\\Users\\yourlogin\\AppData\\Roaming\\GitCredStore\\git-credential-winstore.exe'
    
  • Click the "Add New/Save" button

Is putting a div inside an anchor ever correct?

The W3C doc doesn't use concepts like wrong and sin, but it does use those like provide the means, may be appropriate and discouraged.

Actually, in the second paragraph of section 4, the 4.01 spec itemizes its words as follows

The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in [RFC2119]. However, for readability, these words do not appear in all uppercase letters in this specification.

With that in mind, I believe the definitive statement is in 7.5.3 Block-level and inline elements, where it says

Generally, inline elements may contain only data and other inline elements.

The condition "generally" appears to introduce enough ambiguity to say that HTML 4.01 does allow inline elements to contain block elements.

Certainly, CSS2 has a display property value, inline-block, that appears to be suited to the purpose you describe. I'm not sure if it was ever widely supported, but it seems that someone anticipated the need for that kind of behavior.

The DTD appear to be less forgiving here, but the text of the DTD defers to the spec:

The HTML 4.01 specification includes additional syntactic constraints that cannot be expressed within the DTDs.

In another comment, you suggest that you want to make a block active by wrapping it in an anchor. I don't believe HTML prohibits that, and CSS clearly allows it. So to answer the title question about whether it is ever correct, I say yes. By the standards, it is sometimes correct.

Undefined reference to static class member

No idea why the cast works, but Foo::MEMBER isn't allocated until the first time Foo is loaded, and since you're never loading it, it's never allocated. If you had a reference to a Foo somewhere, it would probably work.

How to show an empty view with a RecyclerView?

RVEmptyObserver

Instead of using a custom RecyclerView, extending an AdapterDataObserver is a simpler solution that allows setting a custom View that is displayed when there are no items in the list:

Example Usage:

RVEmptyObserver observer = new RVEmptyObserver(recyclerView, emptyView)
rvAdapter.registerAdapterDataObserver(observer);

Class:

public class RVEmptyObserver extends RecyclerView.AdapterDataObserver {
    private View emptyView;
    private RecyclerView recyclerView;

    public RVEmptyObserver(RecyclerView rv, View ev) {
        this.recyclerView = rv;
        this.emptyView    = ev;
        checkIfEmpty();
    }

    private void checkIfEmpty() {
        if (emptyView != null && recyclerView.getAdapter() != null) {
            boolean emptyViewVisible = recyclerView.getAdapter().getItemCount() == 0;
            emptyView.setVisibility(emptyViewVisible ? View.VISIBLE : View.GONE);
            recyclerView.setVisibility(emptyViewVisible ? View.GONE : View.VISIBLE);
        }
    }

    public void onChanged() { checkIfEmpty(); }
    public void onItemRangeInserted(int positionStart, int itemCount) { checkIfEmpty(); }
    public void onItemRangeRemoved(int positionStart, int itemCount) { checkIfEmpty(); }
}

VB.net Need Text Box to Only Accept Numbers

Simplest ever solution for TextBox Validation in VB.NET

TextBox Validation for Visual Basic (VB.NET)

First, add new VB code file in your project.

  1. Go To Solution Explorer
  2. Right Click to your project
  3. Select Add > New item...
  4. Add new VB code file (i.e. example.vb)

or press Ctrl+Shift+A

COPY & PASTE following code into this file and give it a suitable name. (i.e. KeyValidation.vb)

Imports System.Text.RegularExpressions
Module Module1
    Public Enum ValidationType
        Only_Numbers = 1
        Only_Characters = 2
        Not_Null = 3
        Only_Email = 4
        Phone_Number = 5
    End Enum
    Public Sub AssignValidation(ByRef CTRL As Windows.Forms.TextBox, ByVal Validation_Type As ValidationType)
        Dim txt As Windows.Forms.TextBox = CTRL
        Select Case Validation_Type
            Case ValidationType.Only_Numbers
                AddHandler txt.KeyPress, AddressOf number_Leave
            Case ValidationType.Only_Characters
                AddHandler txt.KeyPress, AddressOf OCHAR_Leave
            Case ValidationType.Not_Null
                AddHandler txt.Leave, AddressOf NotNull_Leave
            Case ValidationType.Only_Email
                AddHandler txt.Leave, AddressOf Email_Leave
            Case ValidationType.Phone_Number
                AddHandler txt.KeyPress, AddressOf Phonenumber_Leave
        End Select
    End Sub
    Public Sub number_Leave(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
        Dim numbers As Windows.Forms.TextBox = sender
        If InStr("1234567890.", e.KeyChar) = 0 And Asc(e.KeyChar) <> 8 Or (e.KeyChar = "." And InStr(numbers.Text, ".") > 0) Then
            e.KeyChar = Chr(0)
            e.Handled = True
        End If
    End Sub
    Public Sub Phonenumber_Leave(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
        Dim numbers As Windows.Forms.TextBox = sender
        If InStr("1234567890.()-+ ", e.KeyChar) = 0 And Asc(e.KeyChar) <> 8 Or (e.KeyChar = "." And InStr(numbers.Text, ".") > 0) Then
            e.KeyChar = Chr(0)
            e.Handled = True
        End If
    End Sub
    Public Sub OCHAR_Leave(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
        If InStr("1234567890!@#$%^&*()_+=-", e.KeyChar) > 0 Then
            e.KeyChar = Chr(0)
            e.Handled = True
        End If
    End Sub
    Public Sub NotNull_Leave(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim No As Windows.Forms.TextBox = sender
        If No.Text.Trim = "" Then
            MsgBox("This field Must be filled!")
            No.Focus()
        End If
    End Sub
    Public Sub Email_Leave(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim Email As Windows.Forms.TextBox = sender
        If Email.Text <> "" Then
            Dim rex As Match = Regex.Match(Trim(Email.Text), "^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,3})$", RegexOptions.IgnoreCase)
            If rex.Success = False Then
                MessageBox.Show("Please Enter a valid Email Address", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information)
                Email.BackColor = Color.Red
                Email.Focus()
                Exit Sub
            Else
                Email.BackColor = Color.White
            End If
        End If
    End Sub
End Module

Now use following code to Form Load Event like below.

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        AssignValidation(Me.TextBox1, ValidationType.Only_Digits)
        AssignValidation(Me.TextBox2, ValidationType.Only_Characters)
        AssignValidation(Me.TextBox3, ValidationType.No_Blank)
        AssignValidation(Me.TextBox4, ValidationType.Only_Email)
End Sub

Done..!

How do I run a Python program in the Command Prompt in Windows 7?

press start button then type cmd. - Note you will need to run the command prompt as 'Adminstrator'.

write setx -m path "%path%;C:\Python27" then press enter.

[here -m for giving accessing permission to all users and in Python27 27 is version 2.7]

%path%; will prevent the original value from destroying. C:\Python27 will be appended to the current Path value.

that's it,you are done.

How to escape a JSON string containing newline characters using JavaScript?

EDIT: Check if the api you’re interacting with is set to Content-Type: application/json, &/or if your client http library is both stringify-ing and parsing the http request body behind the scenes. My client library was generated by swagger, and was the reason I needed to apply these hacks, as the client library was stringifying my pre-stringified body (body: “jsonString”, instead of body: { ...normal payload }). All I had to do was change the api to Content-Type: text/plain, which removed the JSON stringify/parsing on that route, and then none of these hacks were needed. You can also change only the "consumes" or "produces" portion of the api, see here.

ORIGINAL: If your Googles keep landing you here and your api throws errors unless your JSON double quotes are escaped ("{\"foo\": true}"), all you need to do is stringify twice e.g. JSON.stringify(JSON.stringify(bar))

Biggest differences of Thrift vs Protocol Buffers?

Protocol Buffers seems to have a more compact representation, but that's only an impression I get from reading the Thrift whitepaper. In their own words:

We decided against some extreme storage optimizations (i.e. packing small integers into ASCII or using a 7-bit continuation format) for the sake of simplicity and clarity in the code. These alterations can easily be made if and when we encounter a performance-critical use case that demands them.

Also, it may just be my impression, but Protocol Buffers seems to have some thicker abstractions around struct versioning. Thrift does have some versioning support, but it takes a bit of effort to make it happen.

Simulating ENTER keypress in bash script

Here is sample usage using expect:

#!/usr/bin/expect
set timeout 360
spawn my_command # Replace with your command.
expect "Do you want to continue?" { send "\r" }

Check: man expect for further information.

Deleting records before a certain date

To show result till yesterday

WHERE DATE(date_time) < CURDATE()

To show results of 10 days

WHERE date_time < NOW() - INTERVAL 10 DAY

To show results before 10 days

WHERE DATE(date_time) < DATE(NOW() - INTERVAL 10 DAY)

These will work for you

You can find dates like this

SELECT DATE(NOW() - INTERVAL 11 DAY)

Getting time elapsed in Objective-C

You should not rely on [NSDate date] for timing purposes since it can over- or under-report the elapsed time. There are even cases where your computer will seemingly time-travel since the elapsed time will be negative! (E.g. if the clock moved backwards during timing.)

According to Aria Haghighi in the "Advanced iOS Gesture Recognition" lecture of the Winter 2013 Stanford iOS course (34:00), you should use CACurrentMediaTime() if you need an accurate time interval.

Objective-C:

#import <QuartzCore/QuartzCore.h>
CFTimeInterval startTime = CACurrentMediaTime();
// perform some action
CFTimeInterval elapsedTime = CACurrentMediaTime() - startTime;

Swift:

let startTime = CACurrentMediaTime()
// perform some action
let elapsedTime = CACurrentMediaTime() - startTime

The reason is that [NSDate date] syncs on the server, so it could lead to "time-sync hiccups" which can lead to very difficult-to-track bugs. CACurrentMediaTime(), on the other hand, is a device time that doesn't change with these network syncs.

You will need to add the QuartzCore framework to your target's settings.

How to send POST in angularjs with multiple params?

You can also send (POST) multiple params within {} and add it.

Example:

$http.post(config.url+'/api/assign-badge/', {employeeId:emp_ID,bType:selectedCat,badge:selectedBadge})
    .then(function(response) {
        NotificationService.displayNotification('Info', 'Successfully Assigned!', true);
    }, function(response) {
});

where employeeId, bType (Badge Catagory), and badge are three parameters.

Can I use DIV class and ID together in CSS?

Yes, in one single division you can use both but it's not very common. While styling you will call both so it will cause some ambiguity if you don't properly choose "x" and "y". Use # for ID and . for class. And for overall division you will either do separate styling or write: #x .y for styling purposes.

How to convert a single char into an int

Any problems with the following way of doing it?

int CharToInt(const char c)
{
    switch (c)
    {
    case '0':
        return 0;
    case '1':
        return 1;
    case '2':
        return 2;
    case '3':
        return 3;
    case '4':
        return 4;
    case '5':
        return 5;
    case '6':
        return 6;
    case '7':
        return 7;
    case '8':
        return 8;
    case '9':
        return 9;
    default:
        return 0;
    }
}

How can I know if Object is String type object?

Either use instanceof or method Class.isAssignableFrom(Class<?> cls).

What is the equivalent to a JavaScript setInterval/setTimeout in Android/Java?

The first answer is definitely the correct answer and is what I based this lambda version off of, which is much shorter in syntax. Since Runnable has only 1 override method "run()", we can use a lambda:

this.m_someBoolFlag = false;
new android.os.Handler().postDelayed(() -> this.m_someBoolFlag = true, 300);

What is the difference between 'E', 'T', and '?' for Java generics?

A type variable, <T>, can be any non-primitive type you specify: any class type, any interface type, any array type, or even another type variable.

The most commonly used type parameter names are:

  • E - Element (used extensively by the Java Collections Framework)
  • K - Key
  • N - Number
  • T - Type
  • V - Value

In Java 7 it is permitted to instantiate like this:

Foo<String, Integer> foo = new Foo<>(); // Java 7
Foo<String, Integer> foo = new Foo<String, Integer>(); // Java 6

Iterating over ResultSet and adding its value in an ArrayList

If I've understood your problem correctly, there are two possible problems here:

  • resultset is null - I assume that this can't be the case as if it was you'd get an exception in your while loop and nothing would be output.
  • The second problem is that resultset.getString(i++) will get columns 1,2,3 and so on from each subsequent row.

I think that the second point is probably your problem here.

Lets say you only had 1 row returned, as follows:

Col 1, Col 2, Col 3 
A    ,     B,     C

Your code as it stands would only get A - it wouldn't get the rest of the columns.

I suggest you change your code as follows:

ResultSet resultset = ...;
ArrayList<String> arrayList = new ArrayList<String>(); 
while (resultset.next()) {                      
    int i = 1;
    while(i <= numberOfColumns) {
        arrayList.add(resultset.getString(i++));
    }
    System.out.println(resultset.getString("Col 1"));
    System.out.println(resultset.getString("Col 2"));
    System.out.println(resultset.getString("Col 3"));                    
    System.out.println(resultset.getString("Col n"));
}

Edit:

To get the number of columns:

ResultSetMetaData metadata = resultset.getMetaData();
int numberOfColumns = metadata.getColumnCount();

How to place div in top right hand corner of page

You can use css float

<div style='float: left;'><a href="login.php">Log in</a></div>

<div style='float: right;'><a href="home.php">Back to Home</a></div>

Have a look at this CSS Positioning

sklearn plot confusion matrix with labels

As hinted in this question, you have to "open" the lower-level artist API, by storing the figure and axis objects passed by the matplotlib functions you call (the fig, ax and cax variables below). You can then replace the default x- and y-axis ticks using set_xticklabels/set_yticklabels:

from sklearn.metrics import confusion_matrix

labels = ['business', 'health']
cm = confusion_matrix(y_test, pred, labels)
print(cm)
fig = plt.figure()
ax = fig.add_subplot(111)
cax = ax.matshow(cm)
plt.title('Confusion matrix of the classifier')
fig.colorbar(cax)
ax.set_xticklabels([''] + labels)
ax.set_yticklabels([''] + labels)
plt.xlabel('Predicted')
plt.ylabel('True')
plt.show()

Note that I passed the labels list to the confusion_matrix function to make sure it's properly sorted, matching the ticks.

This results in the following figure:

enter image description here

In Maven how to exclude resources from the generated jar?

Exclude specific pattern of file during creation of maven jar using maven-jar-plugin.

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-jar-plugin</artifactId>
  <version>2.3</version>
  <configuration>
    <excludes>
      <exclude>**/*.properties</exclude>
      <exclude>**/*.xml</exclude>
      <exclude>**/*.exe</exclude>
      <exclude>**/*.java</exclude>
      <exclude>**/*.xls</exclude>
    </excludes>
  </configuration>
</plugin>

Android - how do I investigate an ANR?

my issue with ANR , after much work i found out that a thread was calling a resource that did not exist in the layout, instead of returning an exception , i got ANR ...

How to convert the following json string to java object?

Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonObject object = (JsonObject) parser.parse(response);// response will be the json String
YourPojo emp = gson.fromJson(object, YourPojo.class); 

Unable to access JSON property with "-" dash

In addition to this answer, note that in Node.js if you access JSON with the array syntax [] all nested JSON keys should follow that syntax

This is the wrong way

json.first.second.third['comment']

and will will give you the 'undefined' error.

This is the correct way

json['first']['second']['third']['comment'] 

Insert, on duplicate update in PostgreSQL?

I custom "upsert" function above, if you want to INSERT AND REPLACE :

`

 CREATE OR REPLACE FUNCTION upsert(sql_insert text, sql_update text)

 RETURNS void AS
 $BODY$
 BEGIN
    -- first try to insert and after to update. Note : insert has pk and update not...

    EXECUTE sql_insert;
    RETURN;
    EXCEPTION WHEN unique_violation THEN
    EXECUTE sql_update; 
    IF FOUND THEN 
        RETURN; 
    END IF;
 END;
 $BODY$
 LANGUAGE plpgsql VOLATILE
 COST 100;
 ALTER FUNCTION upsert(text, text)
 OWNER TO postgres;`

And after to execute, do something like this :

SELECT upsert($$INSERT INTO ...$$,$$UPDATE... $$)

Is important to put double dollar-comma to avoid compiler errors

  • check the speed...

Reading a json file in Android

Put that file in assets.

For project created in Android Studio project you need to create assets folder under the main folder.

Read that file as:

public String loadJSONFromAsset(Context context) {
        String json = null;
        try {
            InputStream is = context.getAssets().open("file_name.json");

            int size = is.available();

            byte[] buffer = new byte[size];

            is.read(buffer);

            is.close();

            json = new String(buffer, "UTF-8");


        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
        return json;

    }

and then you can simply read this string return by this function as

JSONObject obj = new JSONObject(json_return_by_the_function);

For further details regarding JSON see http://www.vogella.com/articles/AndroidJSON/article.html

Hope you will get what you want.

Loading DLLs at runtime in C#

Right now, you're creating an instance of every type defined in the assembly. You only need to create a single instance of Class1 in order to call the method:

class Program
{
    static void Main(string[] args)
    {
        var DLL = Assembly.LoadFile(@"C:\visual studio 2012\Projects\ConsoleApplication1\ConsoleApplication1\DLL.dll");

        var theType = DLL.GetType("DLL.Class1");
        var c = Activator.CreateInstance(theType);
        var method = theType.GetMethod("Output");
        method.Invoke(c, new object[]{@"Hello"});

        Console.ReadLine();
    }
}

Resource files not found from JUnit test cases

The test Resource files(src/test/resources) are loaded to target/test-classes sub folder. So we can use the below code to load the test resource files.

String resource = "sample.txt";
File file = new File(getClass().getClassLoader().getResource(resource).getFile());

System.out.println(file.getAbsolutePath());

Note : Here the sample.txt file should be placed under src/test/resources folder.

For more details refer options_to_load_test_resources

How to split a string between letters and digits (or between digits and letters)?

Use two different patterns: [0-9]* and [a-zA-Z]* and split twice by each of them.

Swift Bridging Header import issue

Set Precompile Bridging Header to No fix the problem for me.

How to Initialize char array from a string

const char S[] = "ABCD";

This should work. i use this notation only and it works perfectly fine for me. I don't know how you are using.

How to find tags with only certain attributes - BeautifulSoup

Adding a combination of Chris Redford's and Amr's answer, you can also search for an attribute name with any value with the select command:

from bs4 import BeautifulSoup as Soup
html = '<td valign="top">.....</td>\
    <td width="580" valign="top">.......</td>\
    <td>.....</td>'
soup = Soup(html, 'lxml')
results = soup.select('td[valign]')

How to find/identify large commits in git history?

Step 1 Write all file SHA1s to a text file:

git rev-list --objects --all | sort -k 2 > allfileshas.txt

Step 2 Sort the blobs from biggest to smallest and write results to text file:

git gc && git verify-pack -v .git/objects/pack/pack-*.idx | egrep "^\w+ blob\W+[0-9]+ [0-9]+ [0-9]+$" | sort -k 3 -n -r > bigobjects.txt

Step 3a Combine both text files to get file name/sha1/size information:

for SHA in `cut -f 1 -d\  < bigobjects.txt`; do
echo $(grep $SHA bigobjects.txt) $(grep $SHA allfileshas.txt) | awk '{print $1,$3,$7}' >> bigtosmall.txt
done;

Step 3b If you have file names or path names containing spaces try this variation of Step 3a. It uses cut instead of awk to get the desired columns incl. spaces from column 7 to end of line:

for SHA in `cut -f 1 -d\  < bigobjects.txt`; do
echo $(grep $SHA bigobjects.txt) $(grep $SHA allfileshas.txt) | cut -d ' ' -f'1,3,7-' >> bigtosmall.txt
done;

Now you can look at the file bigtosmall.txt in order to decide which files you want to remove from your Git history.

Step 4 To perform the removal (note this part is slow since it's going to examine every commit in your history for data about the file you identified):

git filter-branch --tree-filter 'rm -f myLargeFile.log' HEAD

Source

Steps 1-3a were copied from Finding and Purging Big Files From Git History

EDIT

The article was deleted sometime in the second half of 2017, but an archived copy of it can still be accessed using the Wayback Machine.

React JS onClick event handler

This is a non-standard (but not so uncommon) React pattern that doesn't use JSX, instead putting everything inline. Also, it's Coffeescript.

The 'React-way' to do this would be with the component's own state:

(c = console.log.bind console)

mock_items: [
    {
        name: 'item_a'
        uid: shortid()
    }
    {
        name: 'item_b'
        uid: shortid()
    }
    {
        name: 'item_c'
        uid: shortid()
    }
]
getInitialState: ->
    lighted_item: null
render: ->
    div null,
        ul null,
            for item, idx in @mock_items
                uid = item.uid
                li
                    key: uid
                    onClick: do (idx, uid) =>
                        (e) =>
                            # justf to illustrate these are bound in closure by the do lambda,
                            c idx
                            c uid
                            @setState
                                lighted_item: uid
                    style:
                        cursor: 'pointer'
                        background: do (uid) =>
                            c @state.lighted_item
                            c 'and uid', uid
                            if @state.lighted_item is uid then 'magenta' else 'chartreuse'
                        # background: 'chartreuse'
                    item.name

This example works -- I tested it locally. You can check out this example code exactly at my github. Originally the env was only local for my own whiteboard r&d purposes but I posted it to Github for this. It may get written over at some point but you can check out the commit from Sept 8, 2016 to see this.

More generally, if you want to see how this CS/no-JSX pattern for React works, check out some recent work here. It's possible I will have time to fully implement a POC for this app idea, the stack for which includes NodeJS, Primus, Redis, & React.

How to set-up a favicon?

Try put this in the head of the document: <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico"/>

#1055 - Expression of SELECT list is not in GROUP BY clause and contains nonaggregated column this is incompatible with sql_mode=only_full_group_by

You have to aggregate by anything NOT IN the group by clause.

So,there are two options...Add Credit_Initial and Disponible_v to the group by

OR

Change them to MAX( Credit_Initial ) as Credit_Initial, MAX( Disponible_v ) as Disponible_v if you know the values are constant anyhow and have no other impact.

Effective swapping of elements of an array in Java

public class SwapElements {

public static void main(String[] args) {

    int[] arr1 = new int[5];
    int[] arr2 = {10,20,30,40};

    System.out.println("arr1 Before Swapping " + Arrays.toString(arr1));
    System.out.println("arr2 Before Swapping " + Arrays.toString(arr2));

    int temp[];
    arr1[3] = 5;
    arr1[0] = 2;
    arr1[1] = 3;
    arr1[2] = 6;
    arr1[4] = 10;

    temp = arr1;
    arr1 = arr2;
    arr2 = temp;
    System.out.println("arr1 after Swapping " + Arrays.toString(arr1));
    System.out.println("arr2 after Swapping " + Arrays.toString(arr2));
}

}

Custom Date/Time formatting in SQL Server

If dt is your datetime column, then

For 1:

SUBSTRING(CONVERT(varchar, dt, 13), 1, 2)
    + UPPER(SUBSTRING(CONVERT(varchar, dt, 13), 4, 3))

For 2:

SUBSTRING(CONVERT(varchar, dt, 100), 13, 2)
    + SUBSTRING(CONVERT(varchar, dt, 100), 16, 3)

Substring a string from the end of the string

string s = "Hello Marco !";
s = s.Remove(s.length - 2, 2);

Laravel check if collection is empty

Starting from Laravel 5.3 you can simply use :

if ($mentor->isNotEmpty()) {
//do something.
}

Documentation https://laravel.com/docs/5.5/collections#method-isnotempty

using if else with eval in aspx page

 <%if (System.Configuration.ConfigurationManager.AppSettings["OperationalMode"] != "live") {%>
                        &nbsp;[<%=System.Environment.MachineName%>]
                        <%}%>

Press TAB and then ENTER key in Selenium WebDriver

Using Java:

private WebDriver driver = new FirefoxDriver();
WebElement element = driver.findElement(By.id("<ElementID>"));//Enter ID for the element. You can use Name, xpath, cssSelector whatever you like
element.sendKeys(Keys.TAB);
element.sendKeys(Keys.ENTER);

Using C#:

private IWebDriver driver = new FirefoxDriver();
IWebElement element = driver.FindElement(By.Name("q"));
element.SendKeys(Keys.Tab);
element.SendKeys(Keys.Enter);

Selecting text in an element (akin to highlighting with your mouse)

You can use the following function to select content of any element:

jQuery.fn.selectText = function(){
    this.find('input').each(function() {
        if($(this).prev().length == 0 || !$(this).prev().hasClass('p_copy')) { 
            $('<p class="p_copy" style="position: absolute; z-index: -1;"></p>').insertBefore($(this));
        }
        $(this).prev().html($(this).val());
    });
    var doc = document;
    var element = this[0];
    console.log(this, element);
    if (doc.body.createTextRange) {
        var range = document.body.createTextRange();
        range.moveToElementText(element);
        range.select();
    } else if (window.getSelection) {
        var selection = window.getSelection();        
        var range = document.createRange();
        range.selectNodeContents(element);
        selection.removeAllRanges();
        selection.addRange(range);
    }
};

This function can be called as follows:

$('#selectme').selectText();

Function to get yesterday's date in Javascript in format DD/MM/YYYY

You override $today in the if statement.

if($dd<10){$dd='0'+dd} if($mm<10){$mm='0'+$mm} $today = $dd+'/'+$mm+'/'+$yyyy;

It is then not a Date() object anymore - hence the error.

How to pick a new color for each plotted line within a figure in matplotlib?

You can also change the default color cycle in your matplotlibrc file. If you don't know where that file is, do the following in python:

import matplotlib
matplotlib.matplotlib_fname()

This will show you the path to your currently used matplotlibrc file. In that file you will find amongst many other settings also the one for axes.color.cycle. Just put in your desired sequence of colors and you will find it in every plot you make. Note that you can also use all valid html color names in matplotlib.

Should I check in folder "node_modules" to Git when creating a Node.js app on Heroku?

I believe that npm install should not run in a production environment. There are several things that can go wrong - npm outage, download of newer dependencies (shrinkwrap seems to have solved this) are two of them.

On the other hand, folder node_modules should not be committed to Git. Apart from their big size, commits including them can become distracting.

The best solutions would be this: npm install should run in a CI environment that is similar to the production environment. All tests will run and a zipped release file will be created that will include all dependencies.

What is a superfast way to read large files line-by-line in VBA?

'you can modify above and read full file in one go and then display each line as shown below

Option Explicit

Public Function QuickRead(FName As String) As Variant
    Dim i As Integer
    Dim res As String
    Dim l As Long
    Dim v As Variant

    i = FreeFile
    l = FileLen(FName)
    res = Space(l)
    Open FName For Binary Access Read As #i
    Get #i, , res
    Close i
    'split the file with vbcrlf
    QuickRead = Split(res, vbCrLf)
End Function

Sub Test()
    ' you can replace file for "c:\writename.txt to any file name you desire
    Dim strFilePathName As String: strFilePathName = "C:\writename.txt"
    Dim strFileLine As String
    Dim v As Variant
    Dim i As Long
    v = QuickRead(strFilePathName)
    For i = 0 To UBound(v)
        MsgBox v(i)
    Next
End Sub

Detect enter press in JTextField

Add an event for KeyPressed.

private void jTextField1KeyPressed(java.awt.event.KeyEvent evt) {
  if(evt.getKeyCode() == KeyEvent.VK_ENTER) {
      // Enter was pressed. Your code goes here.
   }
} 

Is there an equivalent of 'which' on the Windows command line?

I have created tool similar to Ned Batchelder:

Searching .dll and .exe files in PATH

While my tool is primarly for searching of various dll versions it shows more info (date, size, version) but it do not use PATHEXT (I hope to update my tool soon).

Append column to pandas dataframe

You can also use:

dat1 = pd.concat([dat1, dat2], axis=1)

MongoDB running but can't connect using shell

I think there is some default config what is missing in this version of mongoDb client. Try to run:

mongo 127.0.0.1:27017

It's strange, but then I've experienced the issue went away :) (so the simple command 'mongo' w/o any params started to work again for me)

[Ubuntu Linux 11.10 x64 / MongoDB 2.0.1]

Using OR in SQLAlchemy

This has been really helpful. Here is my implementation for any given table:

def sql_replace(self, tableobject, dictargs):

    #missing check of table object is valid
    primarykeys = [key.name for key in inspect(tableobject).primary_key]

    filterargs = []
    for primkeys in primarykeys:
        if dictargs[primkeys] is not None:
            filterargs.append(getattr(db.RT_eqmtvsdata, primkeys) == dictargs[primkeys])
        else:
            return

    query = select([db.RT_eqmtvsdata]).where(and_(*filterargs))

    if self.r_ExecuteAndErrorChk2(query)[primarykeys[0]] is not None:
        # update
        filter = and_(*filterargs)
        query = tableobject.__table__.update().values(dictargs).where(filter)
        return self.w_ExecuteAndErrorChk2(query)

    else:
        query = tableobject.__table__.insert().values(dictargs)
        return self.w_ExecuteAndErrorChk2(query)

# example usage
inrow = {'eqmtvs_id': eqmtvsid, 'datetime': dtime, 'param_id': paramid}

self.sql_replace(tableobject=db.RT_eqmtvsdata, dictargs=inrow)

Why is the GETDATE() an invalid identifier

I think you want SYSDATE, not GETDATE(). Try it:

UPDATE TableName SET LastModifiedDate = (SELECT SYSDATE FROM DUAL);

Android appcompat v7:23

As seen in the revision column of the Android SDK Manager, the latest published version of the Support Library is 22.2.1. You'll have to wait until 23.0.0 is published.

Edit: API 23 is already published. So u can use 23.0.0

Converting from a string to boolean in Python?

def str2bool(str):
  if isinstance(str, basestring) and str.lower() in ['0','false','no']:
    return False
  else:
    return bool(str)

idea: check if you want the string to be evaluated to False; otherwise bool() returns True for any non-empty string.

Best /Fastest way to read an Excel Sheet into a DataTable?

This is the way to read from excel oledb

try
{
    System.Data.OleDb.OleDbConnection MyConnection;
    System.Data.DataSet DtSet;
    System.Data.OleDb.OleDbDataAdapter MyCommand;
    string strHeader7 = "";
    strHeader7 = (hdr7) ? "Yes" : "No";
    MyConnection = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fn + ";Extended Properties=\"Excel 12.0;HDR=" + strHeader7 + ";IMEX=1\"");
    MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [" + wks + "$]", MyConnection);
    MyCommand.TableMappings.Add("Table", "TestTable");
    DtSet = new System.Data.DataSet();
    MyCommand.Fill(DtSet);
    dgv7.DataSource = DtSet.Tables[0];
    MyConnection.Close();
}
catch (Exception ex)
{
    MessageBox.Show(ex.ToString());
}

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

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

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

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

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

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

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

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

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

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

For this:

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

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

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

What does the Java assert keyword do, and when should it be used?

Assertions are disabled by default. To enable them we must run the program with -ea options (granularity can be varied). For example, java -ea AssertionsDemo.

There are two formats for using assertions:

  1. Simple: eg. assert 1==2; // This will raise an AssertionError.
  2. Better: assert 1==2: "no way.. 1 is not equal to 2"; This will raise an AssertionError with the message given displayed too and is thus better. Although the actual syntax is assert expr1:expr2 where expr2 can be any expression returning a value, I have used it more often just to print a message.

How to save a data frame as CSV to a user selected location using tcltk

write.csv([enter name of dataframe here],file = file.choose(new = T))

After running above script this window will open :

enter image description here

Type the new file name with extension in the File name field and click Open, it'll ask you to create a new file to which you should select Yes and the file will be created and saved in the desired location.

I just assigned a variable, but echo $variable shows something else

You may want to know why this is happening. Together with the great explanation by that other guy, find a reference of Why does my shell script choke on whitespace or other special characters? written by Gilles in Unix & Linux:

Why do I need to write "$foo"? What happens without the quotes?

$foo does not mean “take the value of the variable foo”. It means something much more complex:

  • First, take the value of the variable.
  • Field splitting: treat that value as a whitespace-separated list of fields, and build the resulting list. For example, if the variable contains foo * bar ? then the result of this step is the 3-element list foo, *, bar.
  • Filename generation: treat each field as a glob, i.e. as a wildcard pattern, and replace it by the list of file names that match this pattern. If the pattern doesn't match any files, it is left unmodified. In our example, this results in the list containing foo, following by the list of files in the current directory, and finally bar. If the current directory is empty, the result is foo, *, bar.

Note that the result is a list of strings. There are two contexts in shell syntax: list context and string context. Field splitting and filename generation only happen in list context, but that's most of the time. Double quotes delimit a string context: the whole double-quoted string is a single string, not to be split. (Exception: "$@" to expand to the list of positional parameters, e.g. "$@" is equivalent to "$1" "$2" "$3" if there are three positional parameters. See What is the difference between $* and $@?)

The same happens to command substitution with $(foo) or with `foo`. On a side note, don't use `foo`: its quoting rules are weird and non-portable, and all modern shells support $(foo) which is absolutely equivalent except for having intuitive quoting rules.

The output of arithmetic substitution also undergoes the same expansions, but that isn't normally a concern as it only contains non-expandable characters (assuming IFS doesn't contain digits or -).

See When is double-quoting necessary? for more details about the cases when you can leave out the quotes.

Unless you mean for all this rigmarole to happen, just remember to always use double quotes around variable and command substitutions. Do take care: leaving out the quotes can lead not just to errors but to security holes.

keycode 13 is for which key

Check an ASCII table.

It stands for CR, or Carriage Return, AKA the Return key.

In a javascript array, how do I get the last 5 elements, excluding the first element?

Here is one I haven't seen that's even shorter

arr.slice(1).slice(-5)

Run the code snippet below for proof of it doing what you want

_x000D_
_x000D_
var arr1 = [0, 1, 2, 3, 4, 5, 6, 7],_x000D_
  arr2 = [0, 1, 2, 3];_x000D_
_x000D_
document.body.innerHTML = 'ARRAY 1: ' + arr1.slice(1).slice(-5) + '<br/>ARRAY 2: ' + arr2.slice(1).slice(-5);
_x000D_
_x000D_
_x000D_

Another way to do it would be using lodash https://lodash.com/docs#rest - that is of course if you don't mind having to load a huge javascript minified file if your trying to do it from your browser.

_.slice(_.rest(arr), -5)

Populate a Drop down box from a mySQL table in PHP

No need to do this:

while ($row = mysqli_fetch_array($result)) {
    $rows[] = $row;
}

You can directly do this:

while ($row = mysqli_fetch_array($result)) {
        echo "<option value='" . $row['value'] . "'>" . $row['value'] . "</option>";
    }

Determining image file size + dimensions via Javascript?

var img = new Image();
img.src = sYourFilePath;
var iSize = img.fileSize;

SQL multiple column ordering

Multiple column ordering depends on both column's corresponding values: Here is my table example where are two columns named with Alphabets and Numbers and the values in these two columns are asc and desc orders.

enter image description here

Now I perform Order By in these two columns by executing below command:

enter image description here

Now again I insert new values in these two columns, where Alphabet value in ASC order:

enter image description here

and the columns in Example table look like this. Now again perform the same operation:

enter image description here

You can see the values in the first column are in desc order but second column is not in ASC order.

Open fancybox from function

Make argument object extends from <a> , and use open function of fancybox in click event via delegate.

    var paramsFancy={
         'autoScale': true,
         'transitionIn': 'elastic',
         'transitionOut': 'elastic',
         'speedIn': 500,
         'speedOut': 300,
         'autoDimensions': true,
         'centerOnScroll': true,
         'href' : '#contentdiv'
      };

    $(document).delegate('a[href=#modalMine]','click',function(){
               /*Now you can call your function ,
   you can change fields of paramsFancy via this function */
                 myfunction(this);

                paramsFancy.href=$(this).attr('href');
                $.fancybox.open(paramsFancy);

    });

Bootstrap row class contains margin-left and margin-right which creates problems

I was facing this same issue and initially, I removed the row's right and left -ve margin and it removed the horizontal scroll, but it wasn't good. Then after 45 minutes of inspecting and searching, I found out that I was using container-fluid and was removing the padding and its inner row had left and right negative margins. So I gave container-fluid it's padding back and everything went back to normal.

If you do need to remove container-fluid padding, don't just remove every row's left and right negative margin in your project instead introduce a class and use that on your desired container

How to set variable from a SQL query?

You can use this, but remember that your query gives 1 result, multiple results will throw the exception.

declare @ModelID uniqueidentifer
Set @ModelID = (select Top(1) modelid from models where areaid = 'South Coast')

Another way:

Select Top(1)@ModelID = modelid from models where areaid = 'South Coast'

SQL Query Where Date = Today Minus 7 Days

Use the built in functions:

SELECT URLX, COUNT(URLx) AS Count
FROM ExternalHits
WHERE datex BETWEEN DATE_SUB(NOW(), INTERVAL 7 DAY) AND NOW()
GROUP BY URLx
ORDER BY Count DESC; 

How to convert a string with comma-delimited items to a list in Python?

All answers are good, there is another way of doing, which is list comprehension, see the solution below.

u = "UUUDDD"

lst = [x for x in u]

for comma separated list do the following

u = "U,U,U,D,D,D"

lst = [x for x in u.split(',')]

Spring: How to get parameters from POST body?

You can get param from request.

@ResponseBody
public ResponseEntity<Boolean> saveData(HttpServletRequest request,
            HttpServletResponse response, Model model){
   String jsonString = request.getParameter("json");
}

Filter Excel pivot table using VBA

You could check this if you like. :)

Use this code if SavedFamilyCode is in the Report Filter:

 Sub FilterPivotTable()
   Application.ScreenUpdating = False
   ActiveSheet.PivotTables("PivotTable2").ManualUpdate = True

   ActiveSheet.PivotTables("PivotTable2").PivotFields("SavedFamilyCode").ClearAllFilters

   ActiveSheet.PivotTables("PivotTable2").PivotFields("SavedFamilyCode").CurrentPage = _
      "K123223"

  ActiveSheet.PivotTables("PivotTable2").ManualUpdate = False
  Application.ScreenUpdating = True
  End Sub

But if the SavedFamilyCode is in the Column or Row Labels use this code:

 Sub FilterPivotTable()
     Application.ScreenUpdating = False
     ActiveSheet.PivotTables("PivotTable2").ManualUpdate = True

      ActiveSheet.PivotTables("PivotTable2").PivotFields("SavedFamilyCode").ClearAllFilters

      ActiveSheet.PivotTables("PivotTable2").PivotFields("SavedFamilyCode").PivotFilters. _
    Add Type:=xlCaptionEquals, Value1:="K123223"

  ActiveSheet.PivotTables("PivotTable2").ManualUpdate = False
  Application.ScreenUpdating = True
  End Sub

Hope this helps you.

add new element in laravel collection object

I have solved this if you are using array called for 2 tables. Example you have, $tableA['yellow'] and $tableA['blue'] . You are getting these 2 values and you want to add another element inside them to separate them by their type.

foreach ($tableA['yellow'] as $value) {
    $value->type = 'YELLOW';  //you are adding new element named 'type'
}

foreach ($tableA['blue'] as $value) {
    $value->type = 'BLUE';  //you are adding new element named 'type'
}

So, both of the tables value will have new element called type.

How can I capture the right-click event in JavaScript?

Use the oncontextmenu event.

Here's an example:

<div oncontextmenu="javascript:alert('success!');return false;">
    Lorem Ipsum
</div>

And using event listeners (credit to rampion from a comment in 2011):

el.addEventListener('contextmenu', function(ev) {
    ev.preventDefault();
    alert('success!');
    return false;
}, false);

Don't forget to return false, otherwise the standard context menu will still pop up.

If you are going to use a function you've written rather than javascript:alert("Success!"), remember to return false in BOTH the function AND the oncontextmenu attribute.

How to switch from POST to GET in PHP CURL

Make sure that you're putting your query string at the end of your URL when doing a GET request.

$qry_str = "?x=10&y=20";
$ch = curl_init();

// Set query data here with the URL
curl_setopt($ch, CURLOPT_URL, 'http://example.com/test.php' . $qry_str); 

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 3);
$content = trim(curl_exec($ch));
curl_close($ch);
print $content;
With a POST you pass the data via the CURLOPT_POSTFIELDS option instead 
of passing it in the CURLOPT__URL.
-------------------------------------------------------------------------

$qry_str = "x=10&y=20";
curl_setopt($ch, CURLOPT_URL, 'http://example.com/test.php');  
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 3);

// Set request method to POST
curl_setopt($ch, CURLOPT_POST, 1);

// Set query data here with CURLOPT_POSTFIELDS
curl_setopt($ch, CURLOPT_POSTFIELDS, $qry_str);

$content = trim(curl_exec($ch));
curl_close($ch);
print $content;

Note from the curl_setopt() docs for CURLOPT_HTTPGET (emphasis added):

[Set CURLOPT_HTTPGET equal to] TRUE to reset the HTTP request method to GET.
Since GET is the default, this is only necessary if the request method has been changed.

Get protocol + host name from URL

Pure string operations :):

>>> url = "http://stackoverflow.com/questions/9626535/get-domain-name-from-url"
>>> url.split("//")[-1].split("/")[0].split('?')[0]
'stackoverflow.com'
>>> url = "stackoverflow.com/questions/9626535/get-domain-name-from-url"
>>> url.split("//")[-1].split("/")[0].split('?')[0]
'stackoverflow.com'
>>> url = "http://foo.bar?haha/whatever"
>>> url.split("//")[-1].split("/")[0].split('?')[0]
'foo.bar'

That's all, folks.

Jquery resizing image

Great Start. Here's what I came up with:

$('img.resize').each(function(){
    $(this).load(function(){
        var maxWidth = $(this).width(); // Max width for the image
        var maxHeight = $(this).height();   // Max height for the image
        $(this).css("width", "auto").css("height", "auto"); // Remove existing CSS
        $(this).removeAttr("width").removeAttr("height"); // Remove HTML attributes
        var width = $(this).width();    // Current image width
        var height = $(this).height();  // Current image height

        if(width > height) {
            // Check if the current width is larger than the max
            if(width > maxWidth){
                var ratio = maxWidth / width;   // get ratio for scaling image
                $(this).css("width", maxWidth); // Set new width
                $(this).css("height", height * ratio);  // Scale height based on ratio
                height = height * ratio;    // Reset height to match scaled image
            }
        } else {
            // Check if current height is larger than max
            if(height > maxHeight){
                var ratio = maxHeight / height; // get ratio for scaling image
                $(this).css("height", maxHeight);   // Set new height
                $(this).css("width", width * ratio);    // Scale width based on ratio
                width = width * ratio;  // Reset width to match scaled image
            }
        }
    });
});

This has the benefit of allowing you to specify both width and height while allowing the image to still scale proportionally.

print arraylist element?

If you want to print an arraylist with integer numbers, as an example you can use below code.

class Test{
    public static void main(String[] args){
        ArrayList<Integer> arraylist = new ArrayList<Integer>();

        for(int i=0; i<=10; i++){
            arraylist .add(i);
        }
       for (Integer n : arraylist ){
            System.out.println(n);
       }
   }
}

The output is above code:

0
1
2
3
4
5
6
7
8
9
10

MySQL integer field is returned as string in PHP

$mysqli->options(MYSQLI_OPT_INT_AND_FLOAT_NATIVE, TRUE);

Try this - worked for me.

Fixing a systemd service 203/EXEC failure (no such file or directory)

If that is a copy/paste from your script, you've permuted this line:

#!/usr/env/bin bash

There's no #!/usr/env/bin, you meant #!/usr/bin/env.

Bootstrap full responsive navbar with logo or brand name text

I set .navbar-brand { min-height: inherit } which solved the issue for me (thanks @creimers for inspiration).

Creating C formatted strings (not printing them)

It sounds to me like you want to be able to easily pass a string created using printf-style formatting to the function you already have that takes a simple string. You can create a wrapper function using stdarg.h facilities and vsnprintf() (which may not be readily available, depending on your compiler/platform):

#include <stdarg.h>
#include <stdio.h>

// a function that accepts a string:

void foo( char* s);

// You'd like to call a function that takes a format string 
//  and then calls foo():

void foofmt( char* fmt, ...)
{
    char buf[100];     // this should really be sized appropriately
                       // possibly in response to a call to vsnprintf()
    va_list vl;
    va_start(vl, fmt);

    vsnprintf( buf, sizeof( buf), fmt, vl);

    va_end( vl);

    foo( buf);
}



int main()
{
    int val = 42;

    foofmt( "Some value: %d\n", val);
    return 0;
}

For platforms that don't provide a good implementation (or any implementation) of the snprintf() family of routines, I've successfully used a nearly public domain snprintf() from Holger Weiss.

Java: convert List<String> to a String

All the references to Apache Commons are fine (and that is what most people use) but I think the Guava equivalent, Joiner, has a much nicer API.

You can do the simple join case with

Joiner.on(" and ").join(names)

but also easily deal with nulls:

Joiner.on(" and ").skipNulls().join(names);

or

Joiner.on(" and ").useForNull("[unknown]").join(names);

and (useful enough as far as I'm concerned to use it in preference to commons-lang), the ability to deal with Maps:

Map<String, Integer> ages = .....;
String foo = Joiner.on(", ").withKeyValueSeparator(" is ").join(ages);
// Outputs:
// Bill is 25, Joe is 30, Betty is 35

which is extremely useful for debugging etc.

1052: Column 'id' in field list is ambiguous

If the format of the id's in the two table varies then you want to join them, as such you can select to use an id from one-main table, say if you have table_customes and table_orders, and tha id for orders is like "101","102"..."110", just use one for customers

select customers.id, name, amount, date from customers.orders;

How to know if an object has an attribute in Python

I think what you are looking for is hasattr. However, I'd recommend something like this if you want to detect python properties-

try:
    getattr(someObject, 'someProperty')         
except AttributeError:
    print "Doesn't exist"
else
    print "Exists"

The disadvantage here is that attribute errors in the properties __get__ code are also caught.

Otherwise, do-

if hasattr(someObject, 'someProp'):
    #Access someProp/ set someProp
    pass

Docs:http://docs.python.org/library/functions.html
Warning:
The reason for my recommendation is that hasattr doesn't detect properties.
Link:http://mail.python.org/pipermail/python-dev/2005-December/058498.html

What is recursion and when should I use it?

This is an old question, but I want to add an answer from logistical point of view (i.e not from algorithm correctness point of view or performance point of view).

I use Java for work, and Java doesn't support nested function. As such, if I want to do recursion, I might have to define an external function (which exists only because my code bumps against Java's bureaucratic rule), or I might have to refactor the code altogether (which I really hate to do).

Thus, I often avoid recursion, and use stack operation instead, because recursion itself is essentially a stack operation.

Relationship between hashCode and equals method in Java

A contract is: If two objects are equal then they should have the same hashcode and if two objects are not equal then they may or may not have same hash code.

Try using your object as key in HashMap (edited after comment from joachim-sauer), and you will start facing trouble. A contract is a guideline, not something forced upon you.

How to get the size of a range in Excel

The Range object has both width and height properties, which are measured in points.

Hibernate Union alternatives

Use VIEW. The same classes can be mapped to different tables/views using entity name, so you won't even have much of a duplication. Being there, done that, works OK.

Plain JDBC has another hidden problem: it's unaware of Hibernate session cache, so if something got cached till the end of the transaction and not flushed from Hibernate session, JDBC query won't find it. Could be very puzzling sometimes.

Activity, AppCompatActivity, FragmentActivity, and ActionBarActivity: When to Use Which?

There is a lot of confusion here, especially if you read outdated sources.

The basic one is Activity, which can show Fragments. You can use this combination if you're on Android version > 4.

However, there is also a support library which encompasses the other classes you mentioned: FragmentActivity, ActionBarActivity and AppCompat. Originally they were used to support fragments on Android versions < 4, but actually they're also used to backport functionality from newer versions of Android (material design for example).

The latest one is AppCompat, the other 2 are older. The strategy I use is to always use AppCompat, so that the app will be ready in case of backports from future versions of Android.

How do I get the current date in JavaScript?

Use new Date() to generate a new Date object containing the current date and time.

_x000D_
_x000D_
var today = new Date();_x000D_
var dd = String(today.getDate()).padStart(2, '0');_x000D_
var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!_x000D_
var yyyy = today.getFullYear();_x000D_
_x000D_
today = mm + '/' + dd + '/' + yyyy;_x000D_
document.write(today);
_x000D_
_x000D_
_x000D_

This will give you today's date in the format of mm/dd/yyyy.

Simply change today = mm +'/'+ dd +'/'+ yyyy; to whatever format you wish.

Use of PUT vs PATCH methods in REST API real life scenarios

A very nice explanation is here-

https://blog.segunolalive.com/posts/restful-api-design-%E2%80%94-put-vs-patch/#:~:text=RFC%205789,not%20required%20to%20be%20idempotent.

A Normal Payload- // House on plot 1 { address: 'plot 1', owner: 'segun', type: 'duplex', color: 'green', rooms: '5', kitchens: '1', windows: 20 } PUT For Updated- // PUT request payload to update windows of House on plot 1 { address: 'plot 1', owner: 'segun', type: 'duplex', color: 'green', rooms: '5', kitchens: '1', windows: 21 } Note: In above payload we are trying to update windows from 20 to 21.

Now see the PATH payload- // Patch request payload to update windows on the House { windows: 21 }

Since PATCH is not idempotent, failed requests are not automatically re-attempted on the network. Also, if a PATCH request is made to a non-existent url e.g attempting to replace the front door of a non-existent building, it should simply fail without creating a new resource unlike PUT, which would create a new one using the payload. Come to think of it, it’ll be odd having a lone door at a house address.

How to cut a string after a specific character in unix

You don't say which shell you're using. If it's a POSIX-compatible one such as Bash, then parameter expansion can do what you want:

Parameter Expansion

...

${parameter#word}

Remove Smallest Prefix Pattern.
The word is expanded to produce a pattern. The parameter expansion then results in parameter, with the smallest portion of the prefix matched by the pattern deleted.

In other words, you can write

$var="${var#*:}"

which will remove anything matching *: from $var (i.e. everything up to and including the first :). If you want to match up to the last :, then you could use ## in place of #.

This is all assuming that the part to remove does not contain : (true for IPv4 addresses, but not for IPv6 addresses)

Having the output of a console application in Visual Studio instead of the console

You have three possibilities to do this, but it's not trivial. The main idea of all IDEs is that all of them are the parents of the child (debug) processes. In this case, it is possible to manipulate with standard input, output and error handler. So IDEs start child applications and redirect out into the internal output window. I know about one more possibility, but it will come in future

  1. You could implement your own debug engine for Visual Studio. Debug Engine control starting and debugging for application. Examples for this you could find how to do this on docs.microsoft.com (Visual Studio Debug engine)
  2. Redirect form application using duplication of std handler for c++ or use Console.SetOut(TextWriter) for c#. If you need to print into the output window you need to use Visual Studio extension SDK. Example of the second variant you could find on Github.
  3. Start application that uses System.Diagnostics.Debug.WriteLine (for printing into output) and than it will start child application. On starting a child, you need to redirect stdout into parent with pipes. You could find an example on MSDN. But I think this is not the best way.

Is there an XSL "contains" directive?

<xsl:if test="not contains(hhref,'1234')">

Youtube autoplay not working on mobile devices with embedded HTML5 player

Preview The official statement "Due to this restriction, functions and parameters such as autoplay, playVideo(), loadVideoById() won't work in all mobile environments.

Reference: https://developers.google.com/youtube/iframe_api_reference

Pull request vs Merge request

GitLab 12.1 (July 2019) introduces a difference:

"Merge Requests for Confidential Issues"

When discussing, planning and resolving confidential issues, such as security vulnerabilities, it can be particularly challenging for open source projects to remain efficient since the Git repository is public.

https://about.gitlab.com/images/12_1/mr-confidential.png

As of 12.1, it is now possible for confidential issues in a public project to be resolved within a streamlined workflow using the Create confidential merge request button, which helps you create a merge request in a private fork of the project.

See "Confidential issues" from issue 58583.

A similar feature exists in GitHub, but involves the creation of a special private fork, called "maintainer security advisory".


GitLab 13.5 (Oct. 2020) will add reviewers, which was already available for GitHub before.

display data from SQL database into php/ html table

Here's a simple function I wrote to display tabular data without having to input each column name: (Also, be aware: Nested looping)

function display_data($data) {
    $output = '<table>';
    foreach($data as $key => $var) {
        $output .= '<tr>';
        foreach($var as $k => $v) {
            if ($key === 0) {
                $output .= '<td><strong>' . $k . '</strong></td>';
            } else {
                $output .= '<td>' . $v . '</td>';
            }
        }
        $output .= '</tr>';
    }
    $output .= '</table>';
    echo $output;
}

UPDATED FUNCTION BELOW

Hi Jack,

your function design is fine, but this function always misses the first dataset in the array. I tested that.

Your function is so fine, that many people will use it, but they will always miss the first dataset. That is why I wrote this amendment.

The missing dataset results from the condition if key === 0. If key = 0 only the columnheaders are written, but not the data which contains $key 0 too. So there is always missing the first dataset of the array.

You can avoid that by moving the if condition above the second foreach loop like this:

function display_data($data) {
    $output = "<table>";
    foreach($data as $key => $var) {
        //$output .= '<tr>';
        if($key===0) {
            $output .= '<tr>';
            foreach($var as $col => $val) {
                $output .= "<td>" . $col . '</td>';
            }
            $output .= '</tr>';
            foreach($var as $col => $val) {
                $output .= '<td>' . $val . '</td>';
            }
            $output .= '</tr>';
        }
        else {
            $output .= '<tr>';
            foreach($var as $col => $val) {
                $output .= '<td>' . $val . '</td>';
            }
            $output .= '</tr>';
        }
    }
    $output .= '</table>';
    echo $output;
}

Best regards and thanks - Axel Arnold Bangert - Herzogenrath 2016

and another update that removes redundant code blocks that hurt maintainability of the code.

function display_data($data) {
$output = '<table>';
foreach($data as $key => $var) {
    $output .= '<tr>';
    foreach($var as $k => $v) {
        if ($key === 0) {
            $output .= '<td><strong>' . $k . '</strong></td>';
        } else {
            $output .= '<td>' . $v . '</td>';
        }
    }
    $output .= '</tr>';
}
$output .= '</table>';
echo $output;

}

What's the scope of a variable initialized in an if statement?

Scope in python follows this order:

  • Search the local scope

  • Search the scope of any enclosing functions

  • Search the global scope

  • Search the built-ins

(source)

Notice that if and other looping/branching constructs are not listed - only classes, functions, and modules provide scope in Python, so anything declared in an if block has the same scope as anything decleared outside the block. Variables aren't checked at compile time, which is why other languages throw an exception. In python, so long as the variable exists at the time you require it, no exception will be thrown.

Why am I getting string does not name a type Error?

Your using declaration is in game.cpp, not game.h where you actually declare string variables. You intended to put using namespace std; into the header, above the lines that use string, which would let those lines find the string type defined in the std namespace.

As others have pointed out, this is not good practice in headers -- everyone who includes that header will also involuntarily hit the using line and import std into their namespace; the right solution is to change those lines to use std::string instead

Which regular expression operator means 'Don't' match this character?

You can use negated character classes to exclude certain characters: for example [^abcde] will match anything but a,b,c,d,e characters.

Instead of specifying all the characters literally, you can use shorthands inside character classes: [\w] (lowercase) will match any "word character" (letter, numbers and underscore), [\W] (uppercase) will match anything but word characters; similarly, [\d] will match the 0-9 digits while [\D] matches anything but the 0-9 digits, and so on.

If you use PHP you can take a look at the regex character classes documentation.