Programs & Examples On #Upload

Upload refers to the sending of data from a local system to a remote system such as a server or another client with the intent that the remote system should store a copy of the data being transferred, or the initiation of such a process

Is there a Public FTP server to test upload and download?

I have found an FTP server and its working. I was successfully able to upload a file to this FTP server and then see file created by hitting same url. Visit here and read properly before use. Good luck...!

Edit: link is now dead, but the FTP server is still up! Connect with the username "anonymous" and an email address as a password: ftp://ftp.swfwmd.state.fl.us

BUT FIRST read this before using it

HTML5 Pre-resize images before uploading

Typescript

async resizeImg(file: Blob): Promise<Blob> {
    let img = document.createElement("img");
    img.src = await new Promise<any>(resolve => {
        let reader = new FileReader();
        reader.onload = (e: any) => resolve(e.target.result);
        reader.readAsDataURL(file);
    });
    await new Promise(resolve => img.onload = resolve)
    let canvas = document.createElement("canvas");
    let ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0);
    let MAX_WIDTH = 1000;
    let MAX_HEIGHT = 1000;
    let width = img.naturalWidth;
    let height = img.naturalHeight;
    if (width > height) {
        if (width > MAX_WIDTH) {
            height *= MAX_WIDTH / width;
            width = MAX_WIDTH;
        }
    } else {
        if (height > MAX_HEIGHT) {
            width *= MAX_HEIGHT / height;
            height = MAX_HEIGHT;
        }
    }
    canvas.width = width;
    canvas.height = height;
    ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0, width, height);
    let result = await new Promise<Blob>(resolve => { canvas.toBlob(resolve, 'image/jpeg', 0.95); });
    return result;
}

Upload file to SFTP using PowerShell

There isn't currently a built-in PowerShell method for doing the SFTP part. You'll have to use something like psftp.exe or a PowerShell module like Posh-SSH.

Here is an example using Posh-SSH:

# Set the credentials
$Password = ConvertTo-SecureString 'Password1' -AsPlainText -Force
$Credential = New-Object System.Management.Automation.PSCredential ('root', $Password)

# Set local file path, SFTP path, and the backup location path which I assume is an SMB path
$FilePath = "C:\FileDump\test.txt"
$SftpPath = '/Outbox'
$SmbPath = '\\filer01\Backup'

# Set the IP of the SFTP server
$SftpIp = '10.209.26.105'

# Load the Posh-SSH module
Import-Module C:\Temp\Posh-SSH

# Establish the SFTP connection
$ThisSession = New-SFTPSession -ComputerName $SftpIp -Credential $Credential

# Upload the file to the SFTP path
Set-SFTPFile -SessionId ($ThisSession).SessionId -LocalFile $FilePath -RemotePath $SftpPath

#Disconnect all SFTP Sessions
Get-SFTPSession | % { Remove-SFTPSession -SessionId ($_.SessionId) }

# Copy the file to the SMB location
Copy-Item -Path $FilePath -Destination $SmbPath

Some additional notes:

  • You'll have to download the Posh-SSH module which you can install to your user module directory (e.g. C:\Users\jon_dechiro\Documents\WindowsPowerShell\Modules) and just load using the name or put it anywhere and load it like I have in the code above.
  • If having the credentials in the script is not acceptable you'll have to use a credential file. If you need help with that I can update with some details or point you to some links.
  • Change the paths, IPs, etc. as needed.

That should give you a decent starting point.

Uploading Files in ASP.net without using the FileUpload server control

use the HTML control with a runat server attribute

 <input id="FileInput" runat="server" type="file" />

Then in asp.net Codebehind

 FileInput.PostedFile.SaveAs("DestinationPath");

There are also some 3'rd party options that will show progress if you intrested

on change event for file input element

Use the files filelist of the element instead of val()

$("input[type=file]").on('change',function(){
    alert(this.files[0].name);
});

How to upload a file in Django?

Extending on Henry's example:

import tempfile
import shutil

FILE_UPLOAD_DIR = '/home/imran/uploads'

def handle_uploaded_file(source):
    fd, filepath = tempfile.mkstemp(prefix=source.name, dir=FILE_UPLOAD_DIR)
    with open(filepath, 'wb') as dest:
        shutil.copyfileobj(source, dest)
    return filepath

You can call this handle_uploaded_file function from your view with the uploaded file object. This will save the file with a unique name (prefixed with filename of the original uploaded file) in filesystem and return the full path of saved file. You can save the path in database, and do something with the file later.

Show an image preview before upload

Here I did with jQuery using FileReader API.

Html Markup:

<input id="fileUpload" type="file" multiple />
<div id="image-holder"></div>

jQuery:

Here in jQuery code,first I check for file extension. i.e valid image file to be processed, then will check whether the browser support FileReader API is yes then only processed else display respected message

$("#fileUpload").on('change', function () {

     //Get count of selected files
     var countFiles = $(this)[0].files.length;

     var imgPath = $(this)[0].value;
     var extn = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();
     var image_holder = $("#image-holder");
     image_holder.empty();

     if (extn == "gif" || extn == "png" || extn == "jpg" || extn == "jpeg") {
         if (typeof (FileReader) != "undefined") {

             //loop for each file selected for uploaded.
             for (var i = 0; i < countFiles; i++) {

                 var reader = new FileReader();
                 reader.onload = function (e) {
                     $("<img />", {
                         "src": e.target.result,
                             "class": "thumb-image"
                     }).appendTo(image_holder);
                 }

                 image_holder.show();
                 reader.readAsDataURL($(this)[0].files[i]);
             }

         } else {
             alert("This browser does not support FileReader.");
         }
     } else {
         alert("Pls select only images");
     }
 });

Detailed Article: How to Preview Image before upload it, jQuery, HTML5 FileReader() with Live Demo

fileReader.readAsBinaryString to upload files

The best way in browsers that support it, is to send the file as a Blob, or using FormData if you want a multipart form. You do not need a FileReader for that. This is both simpler and more efficient than trying to read the data.

If you specifically want to send it as multipart/form-data, you can use a FormData object:

var xmlHttpRequest = new XMLHttpRequest();
xmlHttpRequest.open("POST", '/pushfile', true);
var formData = new FormData();
// This should automatically set the file name and type.
formData.append("file", file);
// Sending FormData automatically sets the Content-Type header to multipart/form-data
xmlHttpRequest.send(formData);

You can also send the data directly, instead of using multipart/form-data. See the documentation. Of course, this will need a server-side change as well.

// file is an instance of File, e.g. from a file input.
var xmlHttpRequest = new XMLHttpRequest();
xmlHttpRequest.open("POST", '/pushfile', true);

xmlHttpRequest.setRequestHeader("Content-Type", file.type);

// Send the binary data.
// Since a File is a Blob, we can send it directly.
xmlHttpRequest.send(file);

For browser support, see: http://caniuse.com/#feat=xhr2 (most browsers, including IE 10+).

How do I measure request and response times at once using cURL?

Here is the answer:

curl -X POST -d @file server:port -w %{time_connect}:%{time_starttransfer}:%{time_total}

All of the variables used with -w can be found in man curl.

How to solve this java.lang.NoClassDefFoundError: org/apache/commons/io/output/DeferredFileOutputStream?

just put all apache comons jar and file upload jar in lib folder of tomcat

Schedule automatic daily upload with FileZilla

FileZilla does not have any command line arguments (nor any other way) that allow an automatic transfer.

Some references:


Though you can use any other client that allows automation.

You have not specified, what protocol you are using. FTP or SFTP? You will definitely be able to use WinSCP, as it supports all protocols that FileZilla does (and more).

Combine WinSCP scripting capabilities with Windows Scheduler:

A typical WinSCP script for upload (with SFTP) looks like:

open sftp://user:[email protected]/ -hostkey="ssh-rsa 2048 xxxxxxxxxxx...="
put c:\mypdfs\*.pdf /home/user/
close

With FTP, just replace the sftp:// with the ftp:// and remove the -hostkey="..." switch.


Similarly for download: How to schedule an automatic FTP download on Windows?


WinSCP can even generate a script from an imported FileZilla session.

For details, see the guide to FileZilla automation.

(I'm the author of WinSCP)


Another option, if you are using SFTP, is the psftp.exe client from PuTTY suite.

Upload Progress Bar in PHP

If you have APC installed, it has a callback hook for upload progress.

Rasmus Lerdorf (PHP's creator) has a sample of this using YUI (oh, and here's the PHP source).

See the documentation here.

Html helper for <input type="file" />

This also works:

Model:

public class ViewModel
{         
    public HttpPostedFileBase File{ get; set; }
}

View:

@using (Html.BeginForm("Action", "Controller", FormMethod.Post, new 
                                       { enctype = "multipart/form-data" }))
{
    @Html.TextBoxFor(m => m.File, new { type = "file" })       
}

Controller action:

[HttpPost]
public ActionResult Action(ViewModel model)
{
    if (ModelState.IsValid)
    {
        var postedFile = Request.Files["File"];

       // now you can get and validate the file type:
        var isFileSupported= IsFileSupported(postedFile);

    }
}

public bool IsFileSupported(HttpPostedFileBase file)
            {
                var isSupported = false;

                switch (file.ContentType)
                {

                    case ("image/gif"):
                        isSupported = true;
                        break;

                    case ("image/jpeg"):
                        isSupported = true;
                        break;

                    case ("image/png"):
                        isSupported = true;
                        break;


                    case ("audio/mp3"):  
                        isSupported = true;
                        break;

                    case ("audio/wav"):  
                        isSupported = true;
                        break;                                 
                }

                return isSupported;
            }

List of contentTypes

How do I Validate the File Type of a File Upload?

Well - you won't be able to do it server-side on post-back as the file will get submitted (uploaded) during the post-back.

I think you may be able to do it on the client using JavaScript. Personally, I use a third party component called radUpload by Telerik. It has a good client-side and server-side API, and it provides a progress bar for big file uploads.

I'm sure there are open source solutions available, too.

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

If you are trying to save a file to the file system. Path.Combine is not bullet proof as it won't help you if the file name contains invalid characters. Here is an extension method that strips out invalid characters from file names:

public static string ToSafeFileName(this string s)
{
        return s
            .Replace("\\", "")
            .Replace("/", "")
            .Replace("\"", "")
            .Replace("*", "")
            .Replace(":", "")
            .Replace("?", "")
            .Replace("<", "")
            .Replace(">", "")
            .Replace("|", "");
    }

And the usage can be:

Path.Combine(str_uploadpath, fileName.ToSafeFileName());

Changing upload_max_filesize on PHP

Since I just ran in to this problem on a shared host and was unable to add the values to my .htaccess file I thought I'd share my solution.

I made an ini file with the values in it. Simple as that:

Make a file called ".user.ini" and add your values

upload_max_filesize = 150M
post_max_size = 150M

Boom, problem solved.

Using jQuery, Restricting File Size Before Uploading

It's not possible to verify the image size, width or height on the client side. You need to have this file uploaded on the server and use PHP to verify all this info. PHP has special functions like: getimagesize()

list($width, $height, $type, $attr) = getimagesize("img/flag.jpg");
echo "<img src=\"img/flag.jpg\" $attr alt=\"getimagesize() example\" />";

How to upload a project to Github

I think the easiest thing for you to do would be to install the git plugin for eclipse, works more or less the same as eclipse CVS and SVN plugins:

http://www.eclipse.org/egit/

GL!

Python Script Uploading files via FTP

To avoid getting the encryption error you can also try out below commands

ftp = ftplib.FTP_TLS("ftps.dummy.com")
ftp.login("username", "password")
ftp.prot_p()
file = open("filename", "rb")
ftp.storbinary("STOR filename", file)
file.close()
ftp.close()

ftp.prot_p() ensure that your connections are encrypted

PHP upload image

This code is very easy to upload file by php. In this code I am performing uploading task in same page that mean our html and php both code resides in the same file. This code generates new name of image name.

first of all see the html code

<form action="index.php" method="post" enctype="multipart/form-data">
 <input type="file" name="banner_image" >
 <input type="submit" value="submit">
 </form>

now see the php code

<?php
$image_name=$_FILES['banner_image']['name'];
       $temp = explode(".", $image_name);
        $newfilename = round(microtime(true)) . '.' . end($temp);
       $imagepath="uploads/".$newfilename;
       move_uploaded_file($_FILES["banner_image"]["tmp_name"],$imagepath);
?>

How do you upload a file to a document library in sharepoint?

if you get this error "Value does not fall within the expected range" in this line:

SPFolder myLibrary = oWeb.Folders[documentLibraryName];

use instead this to fix the error:

SPFolder myLibrary = oWeb.GetList(URL OR NAME).RootFolder;

Use always URl to get Lists or others because they are unique, names are not the best way ;)

how to upload file using curl with php

Use:

if (function_exists('curl_file_create')) { // php 5.5+
  $cFile = curl_file_create($file_name_with_full_path);
} else { // 
  $cFile = '@' . realpath($file_name_with_full_path);
}
$post = array('extra_info' => '123456','file_contents'=> $cFile);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$result=curl_exec ($ch);
curl_close ($ch);

You can also refer:

http://blog.derakkilgo.com/2009/06/07/send-a-file-via-post-with-curl-and-php/

Important hint for PHP 5.5+:

Now we should use https://wiki.php.net/rfc/curl-file-upload but if you still want to use this deprecated approach then you need to set curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);

How to instantiate a File object in JavaScript?

Now you can!

_x000D_
_x000D_
var parts = [_x000D_
  new Blob(['you construct a file...'], {type: 'text/plain'}),_x000D_
  ' Same way as you do with blob',_x000D_
  new Uint16Array([33])_x000D_
];_x000D_
_x000D_
// Construct a file_x000D_
var file = new File(parts, 'sample.txt', {_x000D_
    lastModified: new Date(0), // optional - default = now_x000D_
    type: "overide/mimetype" // optional - default = ''_x000D_
});_x000D_
_x000D_
var fr = new FileReader();_x000D_
_x000D_
fr.onload = function(evt){_x000D_
   document.body.innerHTML = evt.target.result + "<br><a href="+URL.createObjectURL(file)+" download=" + file.name + ">Download " + file.name + "</a><br>type: "+file.type+"<br>last modified: "+ file.lastModifiedDate_x000D_
}_x000D_
_x000D_
fr.readAsText(file);
_x000D_
_x000D_
_x000D_

Summernote image upload

This code worked well with new version (v0.8.12) (2019-05-21)

$('#summernote').summernote({
        callbacks: {
            onImageUpload: function(files) {
                for(let i=0; i < files.length; i++) {
                    $.upload(files[i]);
                }
            }
        },
        height: 500,
    });

    $.upload = function (file) {
        let out = new FormData();
        out.append('file', file, file.name);

        $.ajax({
            method: 'POST',
            url: 'upload.php',
            contentType: false,
            cache: false,
            processData: false,
            data: out,
            success: function (img) {
                $('#summernote').summernote('insertImage', img);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.error(textStatus + " " + errorThrown);
            }
        });
    };

PHP Code (upload.php)

if ($_FILES['file']['name']) {
 if (!$_FILES['file']['error']) {
    $name = md5(rand(100, 200));
    $ext = explode('.', $_FILES['file']['name']);
    $filename = $name . '.' . $ext[1];
    $destination = 'images/' . $filename; //change this directory
    $location = $_FILES["file"]["tmp_name"];
    move_uploaded_file($location, $destination);
    echo 'images/' . $filename;//change this URL
 }
 else
 {
  echo  $message = 'Ooops!  Your upload triggered the following error:  '.$_FILES['file']['error'];
 }
}

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

Remember also CHOWN or chgrp your website folder. Try myusername# chown -R myusername:_www uploads

How to find when a web page was last updated

Open your browsers console(?) and enter the following:

javascript:alert(document.lastModified)

Multiple files upload (Array) with CodeIgniter 2.0

As Carlos Rincones suggested; don't be affraid of playing with superglobals.

$files = $_FILES;

for($i=0; $i<count($files['userfile']['name']); $i++)
{
    $_FILES = array();
    foreach( $files['userfile'] as $k=>$v )
    {
        $_FILES['userfile'][$k] = $v[$i];                
    }

    $this->upload->do_upload('userfile')
}

HTML: How to limit file upload to be only images?

<script>

    function chng()
    {
        var typ=document.getElementById("fiile").value;
        var res = typ.match(".jp");

        if(res)
        {
            alert("sucess");
        }
        else
        {
            alert("Sorry only jpeg images are accepted");
            document.getElementById("fiile").value="; //clear the uploaded file
        }
    }

</script>

Now in the html part

<input type="file" onchange="chng()">

this code will check if the uploaded file is a jpg file or not and restricts the upload of other types

This application has no explicit mapping for /error

Change @Controller to @RestController in your controller class and everything should go smoothly.

How to limit the number of dropzone.js files uploaded?

Dropzone.options.dpzSingleFile = {
    paramName: "file", // The name that will be used to transfer the file
    maxFiles: 1,
    init: function() {
        this.on("maxfilesexceeded", function(file) {
            this.removeAllFiles();
            this.addFile(file);
        });
    }
};

Jquery and HTML FormData returns "Uncaught TypeError: Illegal invocation"

In my case, there was a mistake in the list of the parameters was not well formed. So make sure the parameters are well formed. For e.g. correct format of parameters

data: {'reporter': reporter,'partner': partner,'product': product}

How to upload files on server folder using jsp

public class FileUploadExample extends HttpServlet {
     protected void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);

            if (isMultipart) {
                // Create a factory for disk-based file items
                FileItemFactory factory = new DiskFileItemFactory();

                // Create a new file upload handler
                ServletFileUpload upload = new ServletFileUpload(factory);

                try {
                    // Parse the request
                    List items = upload.parseRequest(request);
                    Iterator iterator = items.iterator();
                    while (iterator.hasNext()) {
                        FileItem item = (FileItem) iterator.next();
                        if (!item.isFormField()) {
                            String fileName = item.getName();    
                            String root = getServletContext().getRealPath("/");
                            File path = new File(root + "/uploads");
                            if (!path.exists()) {
                                boolean status = path.mkdirs();
                            }

                            File uploadedFile = new File(path + "/" + fileName);
                            System.out.println(uploadedFile.getAbsolutePath());
                            item.write(uploadedFile);
                        }
                    }
                } catch (FileUploadException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

}

Uploading multiple files using formData()

Create a FormData object

const formData: any = new FormData();

And append to the same keyName

photos.forEach((_photoInfo: { localUri: string, file: File }) => {
    formData.append("file", _photoInfo.file);
});

and send it to server

// angular code
this.http.post(url, formData)

this will automatically create an array of object under file

if you are using nodejs

const files :File[] = req.files ? req.files.file : null;

move_uploaded_file gives "failed to open stream: Permission denied" error

The solution is so easy. Only right click the IMAGE (destination) folder, go to properties, click the permission tab, and change others access to Create and delete files.

HttpWebRequest-The remote server returned an error: (400) Bad Request

What type of authentication do you use? Send the credentials using the properties Ben said before and setup a cookie handler. You already allow redirection, check your webserver if any redirection occurs (NTLM auth does for sure). If there is a redirection you need to store the session which is mostly stored in a session cookie.

Upload files with HTTPWebrequest (multipart/form-data)

Modified @CristianRomanescu code to work with memory stream, accept file as a byte array, allow null nvc, return request response and work with Authorization-header. Tested the code with Web Api 2.

private string HttpUploadFile(string url, byte[] file, string fileName, string paramName, string contentType, NameValueCollection nvc, string authorizationHeader)
{
    string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
    byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

    HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
    wr.ContentType = "multipart/form-data; boundary=" + boundary;
    wr.Method = "POST";
    wr.Headers.Add("Authorization", authorizationHeader);
    wr.KeepAlive = true;

    Stream rs = wr.GetRequestStream();

    string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
    if (nvc != null)
    {
        foreach (string key in nvc.Keys)
        {
            rs.Write(boundarybytes, 0, boundarybytes.Length);
            string formitem = string.Format(formdataTemplate, key, nvc[key]);
            byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
            rs.Write(formitembytes, 0, formitembytes.Length);
        }
    }

    rs.Write(boundarybytes, 0, boundarybytes.Length);

    string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
    string header = string.Format(headerTemplate, paramName, fileName, contentType);
    byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
    rs.Write(headerbytes, 0, headerbytes.Length);

    rs.Write(file, 0, file.Length);

    byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
    rs.Write(trailer, 0, trailer.Length);
    rs.Close();

    WebResponse wresp = null;
    try
    {
        wresp = wr.GetResponse();
        Stream stream2 = wresp.GetResponseStream();
        StreamReader reader2 = new StreamReader(stream2);
        var response = reader2.ReadToEnd();
        return response;
    }
    catch (Exception ex)
    {
        if (wresp != null)
        {
            wresp.Close();
            wresp = null;
        }
        return null;
    }
    finally
    {
        wr = null;
    }
}

Testcode:

[HttpPost]
[Route("postformdata")]
public IHttpActionResult PostFormData()
{
    // Check if the request contains multipart/form-data.
    if (!Request.Content.IsMimeMultipartContent())
    {
        throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
    }

    var provider = new MultipartMemoryStreamProvider();

    try
    {
        // Read the form data.
        var result = Request.Content.ReadAsMultipartAsync(provider).Result;
        string response = "";
        // This illustrates how to get the file names.
        foreach (var file in provider.Contents)
        {
            var fileName = file.Headers.ContentDisposition.FileName.Trim('\"');
            var buffer =  file.ReadAsByteArrayAsync().Result;
            response = HttpUploadFile("https://localhost/api/v1/createfromfile", buffer, fileName, "file", "application/pdf", null, "AuthorizationKey");
        }
        return Ok(response);
    }
    catch (System.Exception e)
    {
        return InternalServerError();
    }
}

C# HttpClient 4.5 multipart/form-data upload

my result looks like this:

public static async Task<string> Upload(byte[] image)
{
     using (var client = new HttpClient())
     {
         using (var content =
             new MultipartFormDataContent("Upload----" + DateTime.Now.ToString(CultureInfo.InvariantCulture)))
         {
             content.Add(new StreamContent(new MemoryStream(image)), "bilddatei", "upload.jpg");

              using (
                 var message =
                     await client.PostAsync("http://www.directupload.net/index.php?mode=upload", content))
              {
                  var input = await message.Content.ReadAsStringAsync();

                  return !string.IsNullOrWhiteSpace(input) ? Regex.Match(input, @"http://\w*\.directupload\.net/images/\d*/\w*\.[a-z]{3}").Value : null;
              }
          }
     }
}

Multiple files upload in Codeigniter

_x000D_
_x000D_
<?php

if(isset($_FILES[$input_name]) && is_array($_FILES[$input_name]['name'])){
            $image_path = array();          
            $count = count($_FILES[$input_name]['name']);   
            for($key =0; $key <$count; $key++){     
                $_FILES['file']['name']     = $_FILES[$input_name]['name'][$key]; 
                $_FILES['file']['type']     = $_FILES[$input_name]['type'][$key]; 
                $_FILES['file']['tmp_name'] = $_FILES[$input_name]['tmp_name'][$key]; 
                $_FILES['file']['error']     = $_FILES[$input_name]['error'][$key]; 
                $_FILES['file']['size']     = $_FILES[$input_name]['size'][$key]; 
                    
                $config['file_name'] = $_FILES[$input_name]['name'][$key];                      
                $this->upload->initialize($config); 
                
                if($this->upload->do_upload('file')) {
                    $data = $this->upload->data();
                    $image_path[$key] = $path ."$data[file_name]";                  
                }else{
                    $error =  $this->upload->display_errors();
                $this->session->set_flashdata('msg_error',"image upload! ".$error);
                }   
            }
            return json_encode($image_path);
        }
    
    
   ?>
_x000D_
_x000D_
_x000D_

jQuery AJAX file upload PHP

**1. index.php**
<body>
    <span id="msg" style="color:red"></span><br/>
    <input type="file" id="photo"><br/>
  <script type="text/javascript" src="jquery-3.2.1.min.js"></script>
  <script type="text/javascript">
    $(document).ready(function(){
      $(document).on('change','#photo',function(){
        var property = document.getElementById('photo').files[0];
        var image_name = property.name;
        var image_extension = image_name.split('.').pop().toLowerCase();

        if(jQuery.inArray(image_extension,['gif','jpg','jpeg','']) == -1){
          alert("Invalid image file");
        }

        var form_data = new FormData();
        form_data.append("file",property);
        $.ajax({
          url:'upload.php',
          method:'POST',
          data:form_data,
          contentType:false,
          cache:false,
          processData:false,
          beforeSend:function(){
            $('#msg').html('Loading......');
          },
          success:function(data){
            console.log(data);
            $('#msg').html(data);
          }
        });
      });
    });
  </script>
</body>

**2.upload.php**
<?php
if($_FILES['file']['name'] != ''){
    $test = explode('.', $_FILES['file']['name']);
    $extension = end($test);    
    $name = rand(100,999).'.'.$extension;

    $location = 'uploads/'.$name;
    move_uploaded_file($_FILES['file']['tmp_name'], $location);

    echo '<img src="'.$location.'" height="100" width="100" />';
}

PHP post_max_size overrides upload_max_filesize

post_max_size:

  • Sets max size of post data allowed. This setting also affects file upload
  • To upload large files, this value must be larger than upload_max_filesize
  • Generally speaking, memory_limit should be larger than post_max_size.
  • PHP Default: 8M

upload_max_filesize:

  • The maximum size of an uploaded file
  • PHP Default: 2M

memory_limit > post_max_size > upload_max_filesize

PHP Default: 128M > 8M > 2M

By default, post_max_size should be 4 times greater than upload_max_filesize.
In turn memory_limit should be 16 times greater than post_max_size

How can I select and upload multiple files with HTML and PHP, using HTTP POST?

Full solution in Firefox 5:

<html>
<head>
</head>
<body>
 <form name="uploader" id="uploader" action="multifile.php" method="POST" enctype="multipart/form-data" >
  <input id="infile" name="infile[]" type="file" onBlur="submit();" multiple="true" ></input> 
 </form>

<?php
echo "No. files uploaded : ".count($_FILES['infile']['name'])."<br>"; 


$uploadDir = "images/";
for ($i = 0; $i < count($_FILES['infile']['name']); $i++) {

 echo "File names : ".$_FILES['infile']['name'][$i]."<br>";
 $ext = substr(strrchr($_FILES['infile']['name'][$i], "."), 1); 

 // generate a random new file name to avoid name conflict
 $fPath = md5(rand() * time()) . ".$ext";

 echo "File paths : ".$_FILES['infile']['tmp_name'][$i]."<br>";
 $result = move_uploaded_file($_FILES['infile']['tmp_name'][$i], $uploadDir . $fPath);

 if (strlen($ext) > 0){
  echo "Uploaded ". $fPath ." succefully. <br>";
 }
}
echo "Upload complete.<br>";
?>

</body>
</html>

How to upload, display and save images using node.js and express

First of all, you should make an HTML form containing a file input element. You also need to set the form's enctype attribute to multipart/form-data:

<form method="post" enctype="multipart/form-data" action="/upload">
    <input type="file" name="file">
    <input type="submit" value="Submit">
</form>

Assuming the form is defined in index.html stored in a directory named public relative to where your script is located, you can serve it this way:

const http = require("http");
const path = require("path");
const fs = require("fs");

const express = require("express");

const app = express();
const httpServer = http.createServer(app);

const PORT = process.env.PORT || 3000;

httpServer.listen(PORT, () => {
  console.log(`Server is listening on port ${PORT}`);
});

// put the HTML file containing your form in a directory named "public" (relative to where this script is located)
app.get("/", express.static(path.join(__dirname, "./public")));

Once that's done, users will be able to upload files to your server via that form. But to reassemble the uploaded file in your application, you'll need to parse the request body (as multipart form data).

In Express 3.x you could use express.bodyParser middleware to handle multipart forms but as of Express 4.x, there's no body parser bundled with the framework. Luckily, you can choose from one of the many available multipart/form-data parsers out there. Here, I'll be using multer:

You need to define a route to handle form posts:

const multer = require("multer");

const handleError = (err, res) => {
  res
    .status(500)
    .contentType("text/plain")
    .end("Oops! Something went wrong!");
};

const upload = multer({
  dest: "/path/to/temporary/directory/to/store/uploaded/files"
  // you might also want to set some limits: https://github.com/expressjs/multer#limits
});


app.post(
  "/upload",
  upload.single("file" /* name attribute of <file> element in your form */),
  (req, res) => {
    const tempPath = req.file.path;
    const targetPath = path.join(__dirname, "./uploads/image.png");

    if (path.extname(req.file.originalname).toLowerCase() === ".png") {
      fs.rename(tempPath, targetPath, err => {
        if (err) return handleError(err, res);

        res
          .status(200)
          .contentType("text/plain")
          .end("File uploaded!");
      });
    } else {
      fs.unlink(tempPath, err => {
        if (err) return handleError(err, res);

        res
          .status(403)
          .contentType("text/plain")
          .end("Only .png files are allowed!");
      });
    }
  }
);

In the example above, .png files posted to /upload will be saved to uploaded directory relative to where the script is located.

In order to show the uploaded image, assuming you already have an HTML page containing an img element:

<img src="/image.png" />

you can define another route in your express app and use res.sendFile to serve the stored image:

app.get("/image.png", (req, res) => {
  res.sendFile(path.join(__dirname, "./uploads/image.png"));
});

How to upload file using Selenium WebDriver in Java

First make sure that the input element is visible

As stated by Mark Collin in the discussion here:

Don't click on the browse button, it will trigger an OS level dialogue box and effectively stop your test dead.

Instead you can use:

driver.findElement(By.id("myUploadElement")).sendKeys("<absolutePathToMyFile>");

myUploadElement is the id of that element (button in this case) and in sendKeys you have to specify the absolute path of the content you want to upload (Image,video etc). Selenium will do the rest for you.

Keep in mind that the upload will work only If the element you send a file should be in the form <input type="file">

Upload DOC or PDF using PHP

One of your conditions is failing. Check the value of mime-type for your files.
Try using application/pdf, not text/pdf. Refer to Proper MIME media type for PDF files

PostgreSQL error: Fatal: role "username" does not exist

After trying many other people's solutions, and without success, this answer finally helped me.

https://stackoverflow.com/a/16974197/2433309

In short, running

sudo -u postgres createuser owning_user

creates a role with name owning_user (in this case, h9uest). After that you can run rake db:create from the terminal under whatever account name you set up without having to enter into the Postgres environment.

linux: kill background task

You need its pid... use "ps -A" to find it.

How to merge specific files from Git branches

What I've done is a bit manual, but I:

  1. Merged the branches normally; Reverted the merge with revert;
  2. Checked out all my files to HEAD~1, that is, their state in the merge commit;
  3. Rebased my commits to hide this hackery from the commit history.

Ugly? Yes. Easy to remember? Also yes.

How do you beta test an iphone app?

In 2014 along with iOS 8 and XCode 6 apple introduced Beta Testing of iOS App using iTunes Connect.

You can upload your build to iTunes connect and invite testers using their mail id's. You can invite up to 2000 external testers using just their email address. And they can install the beta app through TestFlight

Converting integer to binary in python

def int_to_bin(num, fill):
    bin_result = ''

    def int_to_binary(number):
        nonlocal bin_result
        if number > 1:
            int_to_binary(number // 2)
        bin_result = bin_result + str(number % 2)

    int_to_binary(num)
    return bin_result.zfill(fill)

How to open remote files in sublime text 3

On server

Install rsub:

wget -O /usr/local/bin/rsub \https://raw.github.com/aurora/rmate/master/rmate
chmod a+x /usr/local/bin/rsub

On local

  1. Install rsub Sublime3 package:

On Sublime Text 3, open Package Manager (Ctrl-Shift-P on Linux/Win, Cmd-Shift-P on Mac, Install Package), and search for rsub and install it

  1. Open command line and connect to remote server:

ssh -R 52698:localhost:52698 server_user@server_address

  1. after connect to server run this command on server:

rsub path_to_file/file.txt

  1. File opening auto in Sublime 3

As of today (2018/09/05) you should use : https://github.com/randy3k/RemoteSubl because you can find it in packagecontrol.io while "rsub" is not present.

Drag and drop menuitems

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

What are the most-used vim commands/keypresses?

tuxfiles.org holds a pretty good cheat sheet. I think there are a couple of points to learning the commands:

  • Read the cheat sheet regularly. Don't worry about using all of them, or remembering all the keys, just know that the command exists. Look up the command and use it when you find yourself doing something repetitive.
  • If you find yourself doing something regularly (like deleting an entire line after a particular character d$), go a quick google search to see if you can find a command for it.
  • Write down commands you think you'll find useful and keep that list where you can see it while you're writing your code. I would argue against printing something out and instead encourage you to use post it notes for just a few commands at a time.
  • If possible, watch other programmers use vim, and ask them what commands they are using as you see them do something interesting.

Besides these tips, there are some basic concepts you should understand.

  • vim will use the same character to represent the same function. For example, to delete a line after a character use d$. To highlight a line after a particular character use v$. So notice that $ indicates you will be doing something to the end of the line from where your cursor currently is.
  • u is undo, and ctrl+r is redo.
  • putting a number in front of a command will execute it repeatedly. 3dd will delete the line your cursor is on and the two lines that follow, similarly 3yy will copy the line your cursor is on and the two lines that follow.
  • understand how to navigate through the buffers use :ls to list the buffers, and :bn, :bp to cycle through them.
  • read through the tutorial found in :help This is probably the best way to 'learn the ropes', and the rest of the commands you will learn through usage.

How to get relative path of a file in visual studio?

I'm a little late, and I'm not sure if this is what you're looking for, but I thought I'd add it just in case someone else finds it useful.

Suppose this is your file structure:

/BulutDepoProject
    /bin
        Main.exe
    /FolderIcon
        Folder.ico
        Main.cs

You need to write your path relative to the Main.exe file. So, you want to access Folder.ico, in your Main.cs you can use:

String path = "..\\FolderIcon\\Folder.ico"

That seemed to work for me!

Update elements in a JSONObject

Hello I can suggest you universal method. use recursion.

    public static JSONObject function(JSONObject obj, String keyMain,String valueMain, String newValue) throws Exception {
    // We need to know keys of Jsonobject
    JSONObject json = new JSONObject()
    Iterator iterator = obj.keys();
    String key = null;
    while (iterator.hasNext()) {
        key = (String) iterator.next();
        // if object is just string we change value in key
        if ((obj.optJSONArray(key)==null) && (obj.optJSONObject(key)==null)) {
            if ((key.equals(keyMain)) && (obj.get(key).toString().equals(valueMain))) {
                // put new value
                obj.put(key, newValue);
                return obj;
            }
        }

        // if it's jsonobject
        if (obj.optJSONObject(key) != null) {
            function(obj.getJSONObject(key), keyMain, valueMain, newValue);
        }

        // if it's jsonarray
        if (obj.optJSONArray(key) != null) {
            JSONArray jArray = obj.getJSONArray(key);
            for (int i=0;i<jArray.length();i++) {
                    function(jArray.getJSONObject(i), keyMain, valueMain, newValue);
            }
        }
    }
    return obj;
}

It should work. If you have questions, go ahead.. I'm ready.

CS0120: An object reference is required for the nonstatic field, method, or property 'foo'

Your method must be static

static void setTextboxText(int result)
{
    if (this.InvokeRequired)
    {
        this.Invoke(new IntDelegate(SetTextboxTextSafe), new object[] { result }); 
    }
    else
    {
        SetTextboxTextSafe(result);
    }
}

jQuery removeClass wildcard

I've generalized this into a Jquery plugin which takes a regex as an argument.

Coffee:

$.fn.removeClassRegex = (regex) ->
  $(@).removeClass (index, classes) ->
    classes.split(/\s+/).filter (c) ->
      regex.test c
    .join ' '

Javascript:

$.fn.removeClassRegex = function(regex) {
  return $(this).removeClass(function(index, classes) {
    return classes.split(/\s+/).filter(function(c) {
      return regex.test(c);
    }).join(' ');
  });
};

So, for this case, usage would be (both Coffee and Javascript):

$('#hello').removeClassRegex(/^color-/)

Note that I'm using the Array.filter function which doesn't exist in IE<9. You could use Underscore's filter function instead or Google for a polyfill like this WTFPL one.

How can I select and upload multiple files with HTML and PHP, using HTTP POST?

There are a few things you need to do to create a multiple file upload, its pretty basic actually. You don't need to use Java, Ajax, Flash. Just build a normal file upload form starting off with:

<form enctype="multipart/form-data" action="post_upload.php" method="POST">

Then the key to success;

<input type="file" name="file[]" multiple />

do NOT forget those brackets! In the post_upload.php try the following:

<?php print_r($_FILES['file']['tmp_name']); ?>

Notice you get an array with tmp_name data, which will mean you can access each file with an third pair of brackets with the file 'number' example:

$_FILES['file']['tmp_name'][0]

You can use php count() to count the number of files that was selected. Goodluck widdit!

Getting list of files in documents folder

Swift 5

// Get the document directory url
let documentsUrl =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!

do {
    // Get the directory contents urls (including subfolders urls)
    let directoryContents = try FileManager.default.contentsOfDirectory(at: documentsUrl, includingPropertiesForKeys: nil)
    print(directoryContents)

    // if you want to filter the directory contents you can do like this:
    let mp3Files = directoryContents.filter{ $0.pathExtension == "mp3" }
    print("mp3 urls:",mp3Files)
    let mp3FileNames = mp3Files.map{ $0.deletingPathExtension().lastPathComponent }
    print("mp3 list:", mp3FileNames)

} catch {
    print(error)
}

Appending output of a Batch file To log file

Use log4j in your java program instead. Then you can output to multiple media, create rolling logs, etc. and include timestamps, class names and line numbers.

Why is synchronized block better than synchronized method?

It's not a matter of better, just different.

When you synchronize a method, you are effectively synchronizing to the object itself. In the case of a static method, you're synchronizing to the class of the object. So the following two pieces of code execute the same way:

public synchronized int getCount() {
    // ...
}

This is just like you wrote this.

public int getCount() {
    synchronized (this) {
        // ...
    }
}

If you want to control synchronization to a specific object, or you only want part of a method to be synchronized to the object, then specify a synchronized block. If you use the synchronized keyword on the method declaration, it will synchronize the whole method to the object or class.

ASP.net page without a code behind

yes on your aspx page include a script tag with runat=server

<script language="c#" runat="server">

public void Page_Load(object sender, EventArgs e)
{
  // some load code
}
</script>

You can also use classic ASP Syntax

<% if (this.MyTextBox.Visible) { %>
<span>Only show when myTextBox is visible</span>
<% } %>

How to cast ArrayList<> from List<>

The first approach is trying to cast the list but this would work only if the List<> were an ArrayList<>. That is not the case. So you need the second approach, that is building a new ArrayList<> with the elements of the List<>

Load and execute external js file in node.js with access to local variables?

Just do a require('./yourfile.js');

Declare all the variables that you want outside access as global variables. So instead of

var a = "hello" it will be

GLOBAL.a="hello" or just

a = "hello"

This is obviously bad. You don't want to be polluting the global scope. Instead the suggest method is to export your functions/variables.

If you want the MVC pattern take a look at Geddy.

TNS Protocol adapter error while starting Oracle SQL*Plus

Use this command, in command prompt

sqlplus userName/password@host/serviceName

How can I install a .ipa file to my iPhone simulator

For Xcode 10, here's an easy way that worked for me for a debug IPA (development profiles)

  1. Unzip the IPA to get the Payload folder.
  2. Within the Payload folder is the app executable.
  3. Drag and drop the app to an open simulator. (You might see a green add button when you drag it over the simulator)

It should install that app on that simulator.

How do I include image files in Django templates?

I tried various method it didn't work.But this worked.Hope it will work for you as well. The file/directory must be at this locations:

projec/your_app/templates project/your_app/static

settings.py

import os    
PROJECT_DIR = os.path.realpath(os.path.dirname(_____file_____))
STATIC_ROOT = '/your_path/static/'

example:

STATIC_ROOT = '/home/project_name/your_app/static/'    
STATIC_URL = '/static/'    
STATICFILES_DIRS =(     
PROJECT_DIR+'/static',    
##//don.t forget comma    
)
TEMPLATE_DIRS = (    
 PROJECT_DIR+'/templates/',    
)

proj/app/templates/filename.html

inside body

{% load staticfiles %}

//for image

img src="{% static "fb.png" %}" alt="image here"

//note that fb.png is at /home/project/app/static/fb.png

If fb.png was inside /home/project/app/static/image/fb.png then

img src="{% static "images/fb.png" %}" alt="image here" 

Execute a command line binary with Node.js

If you don't mind a dependency and want to use promises, child-process-promise works:

installation

npm install child-process-promise --save

exec Usage

var exec = require('child-process-promise').exec;

exec('echo hello')
    .then(function (result) {
        var stdout = result.stdout;
        var stderr = result.stderr;
        console.log('stdout: ', stdout);
        console.log('stderr: ', stderr);
    })
    .catch(function (err) {
        console.error('ERROR: ', err);
    });

spawn usage

var spawn = require('child-process-promise').spawn;

var promise = spawn('echo', ['hello']);

var childProcess = promise.childProcess;

console.log('[spawn] childProcess.pid: ', childProcess.pid);
childProcess.stdout.on('data', function (data) {
    console.log('[spawn] stdout: ', data.toString());
});
childProcess.stderr.on('data', function (data) {
    console.log('[spawn] stderr: ', data.toString());
});

promise.then(function () {
        console.log('[spawn] done!');
    })
    .catch(function (err) {
        console.error('[spawn] ERROR: ', err);
    });

Pointers in JavaScript?

Depending on what you would like to do, you could simply save the variable name, and then access it later on like so:

function toAccessMyVariable(variableName){
  alert(window[variableName]);
}

var myFavoriteNumber = 6; 

toAccessMyVariable("myFavoriteNumber");

To apply to your specific example, you could do something like this:

var x = 0;
var pointerToX = "x";

function a(variableName)
{
    window[variableName]++;
}
a(pointerToX);
alert(x); //Here I want to have 1 instead of 0

How to return more than one value from a function in Python?

Return as a tuple, e.g.

def foo (a):
    x=a
    y=a*2
    return (x,y)

Where can I find the Tomcat 7 installation folder on Linux AMI in Elastic Beanstalk?

Following environment variables worked for me on Debian Wheezy 7 and Tomcat 7:

CATALINA_HOME=/usr/share/tomcat7
CATALINA_BASE=/var/lib/tomcat7
CATALINA_TMPDIR=/tmp/tomcat7

(I did create /tmp/tomcat7 manually)

Connect to SQL Server through PDO using SQL Server Driver

This works for me, and in this case was a remote connection: Note: The port was IMPORTANT for me

$dsn = "sqlsrv:Server=server.dyndns.biz,1433;Database=DBNAME";
$conn = new PDO($dsn, "root", "P4sw0rd");
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

$sql = "SELECT * FROM Table";

foreach ($conn->query($sql) as $row) {
    print_r($row);
} 

Is it possible to decompile an Android .apk file?

Yes, there are tons of software available to decompile a .apk file.

Recently, I had compiled an ultimate list of 47 best APK decompilers on my website. I arranged them into 4 different sections.

  1. Open Source APK Decompilers
  2. Online APK Decompilers
  3. APK Decompiler for Windows, Mac or Linux
  4. APK Decompiler Apps

I hope this collection will be helpful to you.

Link: https://www.edopedia.com/blog/best-apk-decompilers/

Stash only one file out of multiple files that have changed with Git?

git stash push -p -m "my commit message"

-p let's you select the hunks that should be stashed; whole files can be selected as well.

You'll be prompted with a few actions for each hunk:

   y - stash this hunk
   n - do not stash this hunk
   q - quit; do not stash this hunk or any of the remaining ones
   a - stash this hunk and all later hunks in the file
   d - do not stash this hunk or any of the later hunks in the file
   g - select a hunk to go to
   / - search for a hunk matching the given regex
   j - leave this hunk undecided, see next undecided hunk
   J - leave this hunk undecided, see next hunk
   k - leave this hunk undecided, see previous undecided hunk
   K - leave this hunk undecided, see previous hunk
   s - split the current hunk into smaller hunks
   e - manually edit the current hunk
   ? - print help

var functionName = function() {} vs function functionName() {}

Difference function declaration and function expression:

Javascript has first class functions. This means that they can be treated just like any other variable. Functions can be passed as arguments in a function, be returned from a function, and can be stored in variables.

However storing function in a variable (function expression) isn't the only way to create a function, this can also be done via a function declaration. Here are the key differences:

  1. Function expressions can be anonymous whereas a function declaration must have a name.
  2. Both have a name property which is used to identify the function. A function expression's name property is the name of the variable which it is bound to, whereas the name of a function declaration is simply the given name.
  3. Function declarations are hoisted whereas, function expressions are not. Only the variable is hoisted to have the value of undefined.

Here is an example:

_x000D_
_x000D_
try {_x000D_
  functionOne();_x000D_
} catch (e) {_x000D_
  console.log('i cant run because im not hoisted');_x000D_
}_x000D_
_x000D_
functionTwo();_x000D_
_x000D_
// function expression, does not get hoisted_x000D_
let functionOne = function randomName() {_x000D_
    // Some code_x000D_
};_x000D_
_x000D_
// function declaration, gets hoisted_x000D_
function functionTwo() {_x000D_
   console.log('I get hoisted');_x000D_
}_x000D_
_x000D_
try {_x000D_
  randomName(); // this isn't the proper name, it is functionOne_x000D_
} catch (e) {_x000D_
  console.log('You cant call me with randomName my name is function one');_x000D_
}
_x000D_
_x000D_
_x000D_

:

White space at top of page

I Just put CSS in my <div> now working in code

position: relative; top: -22px;

Use RSA private key to generate public key?

here in this code first we are creating RSA key which is private but it has pair of its public key as well so to get your actual public key we simply do this

openssl rsa -in mykey.pem -pubout > mykey.pub

hope you get it for more info check this

close vs shutdown socket?

I've also had success under linux using shutdown() from one pthread to force another pthread currently blocked in connect() to abort early.

Under other OSes (OSX at least), I found calling close() was enough to get connect() fail.

How do you redirect HTTPS to HTTP?

all the above did not work when i used cloudflare, this one worked for me:

RewriteCond %{HTTP:X-Forwarded-Proto} =https
RewriteRule ^(.*)$ http://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

and this one definitely works without proxies in the way:

RewriteCond %{HTTPS} on
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

Index inside map() function

You will be able to get the current iteration's index for the map method through its 2nd parameter.

Example:

const list = [ 'h', 'e', 'l', 'l', 'o'];
list.map((currElement, index) => {
  console.log("The current iteration is: " + index);
  console.log("The current element is: " + currElement);
  console.log("\n");
  return currElement; //equivalent to list[index]
});

Output:

The current iteration is: 0 <br>The current element is: h

The current iteration is: 1 <br>The current element is: e

The current iteration is: 2 <br>The current element is: l

The current iteration is: 3 <br>The current element is: l 

The current iteration is: 4 <br>The current element is: o

See also: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Parameters

callback - Function that produces an element of the new Array, taking three arguments:

1) currentValue
The current element being processed in the array.

2) index
The index of the current element being processed in the array.

3) array
The array map was called upon.

MySQL, Check if a column exists in a table with SQL

This works well for me.

SHOW COLUMNS FROM `table` LIKE 'fieldname';

With PHP it would be something like...

$result = mysql_query("SHOW COLUMNS FROM `table` LIKE 'fieldname'");
$exists = (mysql_num_rows($result))?TRUE:FALSE;

How to show disable HTML select option in by default?

 selected disabled="true"

Use this. It will work in new browsers

How to create cron job using PHP?

In the same way you are trying to run cron.php, you can run another PHP script. You will have to do so via the CLI interface though.

#!/usr/bin/env php
<?php
# This file would be say, '/usr/local/bin/run.php'
// code
echo "this was run from CRON";

Then, add an entry to the crontab:

* * * * * /usr/bin/php -f /usr/local/bin/run.php &> /dev/null

If the run.php script had executable permissions, it could be listed directly in the crontab, without the /usr/bin/php part as well. The 'env php' part, in the script, would find the appropriate program to actually run the PHP code. So, for the 'executable' version - add executable permission to the file:

chmod +x /usr/local/bin/run.php

and then, add the following entry into crontab:

* * * * * /usr/local/bin/run.php &> /dev/null

how to implement a long click listener on a listview

or try this code:

listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

            public boolean onItemLongClick(AdapterView<?> arg0, View v,
                    int index, long arg3) {

    Toast.makeText(list.this,myList.getItemAtPosition(index).toString(), Toast.LENGTH_LONG).show();
                return false;
            }
}); 

Append to string variable

var str1 = 'abc';
var str2 = str1+' def'; // str2 is now 'abc def'

How do I add an "Add to Favorites" button or link on my website?

Credit to @Gert Grenander , @Alaa.Kh , and Ross Shanon

Trying to make some order:

it all works - all but the firefox bookmarking function. for some reason the 'window.sidebar.addPanel' is not a function for the debugger, though it is working fine.

The problem is that it takes its values from the calling <a ..> tag: title as the bookmark name and href as the bookmark address. so this is my code:

javascript:

$("#bookmarkme").click(function () {
  var url = 'http://' + location.host; // i'm in a sub-page and bookmarking the home page
  var name = "Snir's Homepage";

  if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1){ //chrome
    alert("In order to bookmark go to the homepage and press " 
        + (navigator.userAgent.toLowerCase().indexOf('mac') != -1 ? 
            'Command/Cmd' : 'CTRL') + "+D.")
  } 
  else if (window.sidebar) { // Mozilla Firefox Bookmark
    //important for firefox to add bookmarks - remember to check out the checkbox on the popup
    $(this).attr('rel', 'sidebar');
    //set the appropriate attributes
    $(this).attr('href', url);
    $(this).attr('title', name);

    //add bookmark:
    //  window.sidebar.addPanel(name, url, '');
    //  window.sidebar.addPanel(url, name, '');
    window.sidebar.addPanel('', '', '');
  } 
  else if (window.external) { // IE Favorite
        window.external.addFavorite(url, name);
  } 
  return;
});

html:

  <a id="bookmarkme" href="#" title="bookmark this page">Bookmark This Page</a>

In internet explorer there is a different between 'addFavorite': <a href="javascript:window.external.addFavorite('http://tiny.cc/snir','snir-site')">..</a> and 'AddFavorite': <span onclick="window.external.AddFavorite(location.href, document.title);">..</span>.

example here: http://www.yourhtmlsource.com/javascript/addtofavorites.html

Important, in chrome we can't add bookmarks using js (aspnet-i): http://www.codeproject.com/Questions/452899/How-to-add-bookmark-in-Google-Chrome-Opera-and-Saf

Can I embed a .png image into an html page?

The 64base method works for large images as well, I use that method to embed all the images into my website, and it works every time. I've done with files up to 2Mb size, jpg and png.

Format output string, right alignment

Simple tabulation of the output:

a = 0.3333333
b = 200/3
print("variable a    variable b")
print("%10.2f    %10.2f" % (a, b))

output:

variable a    variable b
      0.33         66.67

%10.2f: 10 is the minimum length and 2 is the number of decimal places.

How to get distinct values for non-key column fields in Laravel?

Though I am late to answer this, a better approach to get distinct records using Eloquent would be

$user_names = User::distinct()->get(['name']);

How can I make the browser wait to display the page until it's fully loaded?

Hope this code will help

 <html>  
    <head>
        <style type="text/css">
          .js #flash {display: none;}
        </style>
        <script type="text/javascript">
          document.documentElement.className = 'js';
        </script>
      </head>
      <body>
        <!-- the rest of your code goes here -->

        <script type="text/javascript" src="/scripts/jquery.js"></script>
        <script type="text/javascript">
          // Stuff to do as soon as the body finishes loading.
          // No need for $(document).ready() here.
        </script>
      </body>
    </html>

Increasing nesting function calls limit

Do you have Zend, IonCube, or xDebug installed? If so, that is probably where you are getting this error from.

I ran into this a few years ago, and it ended up being Zend putting that limit there, not PHP. Of course removing it will let you go past the 100 iterations, but you will eventually hit the memory limits.

Python element-wise tuple operations like sum

Yes. But you can't redefine built-in types. You have to subclass them:

class MyTuple(tuple):
    def __add__(self, other):
         if len(self) != len(other):
             raise ValueError("tuple lengths don't match")
         return MyTuple(x + y for (x, y) in zip(self, other))

How to position a Bootstrap popover?

Simply add an attribute to your popover! See my JSFiddle if you're in a hurry.

We want to add an ID or a class to a particular popover so that we may customize it the way we want via CSS.

Please note that we don't want to customize all popovers! This is terrible idea.

Here is a simple example - display the popover like this:

enter image description here

_x000D_
_x000D_
// We add the id 'my-popover'_x000D_
$("#my-button").popover({_x000D_
    html : true,_x000D_
    placement: 'bottom'_x000D_
}).data('bs.popover').tip().attr('id', 'my-popover');
_x000D_
#my-popover {_x000D_
    left: -169px!important;_x000D_
}_x000D_
#my-popover .arrow {_x000D_
    left: 90%_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>_x000D_
_x000D_
<button id="my-button" data-toggle="popover">My Button</button>
_x000D_
_x000D_
_x000D_

How to convert a currency string to a double with jQuery or Javascript?

This is my function. Works with all currencies..

function toFloat(num) {
    dotPos = num.indexOf('.');
    commaPos = num.indexOf(',');

    if (dotPos < 0)
        dotPos = 0;

    if (commaPos < 0)
        commaPos = 0;

    if ((dotPos > commaPos) && dotPos)
        sep = dotPos;
    else {
        if ((commaPos > dotPos) && commaPos)
            sep = commaPos;
        else
            sep = false;
    }

    if (sep == false)
        return parseFloat(num.replace(/[^\d]/g, ""));

    return parseFloat(
        num.substr(0, sep).replace(/[^\d]/g, "") + '.' + 
        num.substr(sep+1, num.length).replace(/[^0-9]/, "")
    );

}

Usage : toFloat("$1,100.00") or toFloat("1,100.00$")

Solving sslv3 alert handshake failure when trying to use a client certificate

Not a definite answer but too much to fit in comments:

I hypothesize they gave you a cert that either has a wrong issuer (although their server could use a more specific alert code for that) or a wrong subject. We know the cert matches your privatekey -- because both curl and openssl client paired them without complaining about a mismatch; but we don't actually know it matches their desired CA(s) -- because your curl uses openssl and openssl SSL client does NOT enforce that a configured client cert matches certreq.CAs.

Do openssl x509 <clientcert.pem -noout -subject -issuer and the same on the cert from the test P12 that works. Do openssl s_client (or check the one you did) and look under Acceptable client certificate CA names; the name there or one of them should match (exactly!) the issuer(s) of your certs. If not, that's most likely your problem and you need to check with them you submitted your CSR to the correct place and in the correct way. Perhaps they have different regimes in different regions, or business lines, or test vs prod, or active vs pending, etc.

If the issuer of your cert does match desiredCAs, compare its subject to the working (test-P12) one: are they in similar format? are there any components in the working one not present in yours? If they allow it, try generating and submitting a new CSR with a subject name exactly the same as the test-P12 one, or as close as you can get, and see if that produces a cert that works better. (You don't have to generate a new key to do this, but if you choose to, keep track of which certs match which keys so you don't get them mixed up.) If that doesn't help look at the certificate extensions with openssl x509 <cert -noout -text for any difference(s) that might reasonably be related to subject authorization, like KeyUsage, ExtendedKeyUsage, maybe Policy, maybe Constraints, maybe even something nonstandard.

If all else fails, ask the server operator(s) what their logs say about the problem, or if you have access look at the logs yourself.

How can I list the contents of a directory in Python?

The os module handles all that stuff.

os.listdir(path)

Return a list containing the names of the entries in the directory given by path. The list is in arbitrary order. It does not include the special entries '.' and '..' even if they are present in the directory.

Availability: Unix, Windows.

Excel select a value from a cell having row number calculated

You could use the INDIRECT function. This takes a string and converts it into a range

More info here

=INDIRECT("K"&A2)

But it's preferable to use INDEX as it is less volatile.

=INDEX(K:K,A2)

This returns a value or the reference to a value from within a table or range

More info here

Put either function into cell B2 and fill down.

Retrieving Android API version programmatically

Got it. Its using the getApplicationInfo() method of the Context class.

vertical & horizontal lines in matplotlib

If you want to add a bounding box, use a rectangle:

ax = plt.gca()
r = matplotlib.patches.Rectangle((.5, .5), .25, .1, fill=False)
ax.add_artist(r)

Rectangle doc

How to change the map center in Leaflet.js

For example:

map.panTo(new L.LatLng(40.737, -73.923));

Getting byte array through input type = file

[Edit]

As noted in comments above, while still on some UA implementations, readAsBinaryString method didn't made its way to the specs and should not be used in production. Instead, use readAsArrayBuffer and loop through it's buffer to get back the binary string :

_x000D_
_x000D_
document.querySelector('input').addEventListener('change', function() {_x000D_
_x000D_
  var reader = new FileReader();_x000D_
  reader.onload = function() {_x000D_
_x000D_
    var arrayBuffer = this.result,_x000D_
      array = new Uint8Array(arrayBuffer),_x000D_
      binaryString = String.fromCharCode.apply(null, array);_x000D_
_x000D_
    console.log(binaryString);_x000D_
_x000D_
  }_x000D_
  reader.readAsArrayBuffer(this.files[0]);_x000D_
_x000D_
}, false);
_x000D_
<input type="file" />_x000D_
<div id="result"></div>
_x000D_
_x000D_
_x000D_

For a more robust way to convert your arrayBuffer in binary string, you can refer to this answer.


[old answer] (modified)

Yes, the file API does provide a way to convert your File, in the <input type="file"/> to a binary string, thanks to the FileReader Object and its method readAsBinaryString.
[But don't use it in production !]

_x000D_
_x000D_
document.querySelector('input').addEventListener('change', function(){_x000D_
    var reader = new FileReader();_x000D_
    reader.onload = function(){_x000D_
        var binaryString = this.result;_x000D_
        document.querySelector('#result').innerHTML = binaryString;_x000D_
        }_x000D_
    reader.readAsBinaryString(this.files[0]);_x000D_
  }, false);
_x000D_
<input type="file"/>_x000D_
<div id="result"></div>
_x000D_
_x000D_
_x000D_

If you want an array buffer, then you can use the readAsArrayBuffer() method :

_x000D_
_x000D_
document.querySelector('input').addEventListener('change', function(){_x000D_
    var reader = new FileReader();_x000D_
    reader.onload = function(){_x000D_
        var arrayBuffer = this.result;_x000D_
      console.log(arrayBuffer);_x000D_
        document.querySelector('#result').innerHTML = arrayBuffer + '  '+arrayBuffer.byteLength;_x000D_
        }_x000D_
    reader.readAsArrayBuffer(this.files[0]);_x000D_
  }, false);
_x000D_
<input type="file"/>_x000D_
<div id="result"></div>
_x000D_
_x000D_
_x000D_

What is a clearfix?

The other (and perhaps simplest) option for acheiving a clearfix is to use overflow:hidden; on the containing element. For example

_x000D_
_x000D_
.parent {_x000D_
  background: red;_x000D_
  overflow: hidden;_x000D_
}_x000D_
.segment-a {_x000D_
  float: left;_x000D_
}_x000D_
.segment-b {_x000D_
  float: right;_x000D_
}
_x000D_
<div class="parent">_x000D_
  <div class="segment-a">_x000D_
    Float left_x000D_
  </div>_x000D_
  <div class="segment-b">_x000D_
    Float right_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Of course this can only be used in instances where you never wish the content to overflow.

Select from one table matching criteria in another?

I have a similar problem (at least I think it is similar). In one of the replies here the solution is as follows:

select
    A.*
from
    table_A A
inner join table_B B
    on A.id = B.id
where
    B.tag = 'chair'

That WHERE clause I would like to be:

WHERE B.tag = A.<col_name>

or, in my specific case:

WHERE B.val BETWEEN A.val1 AND A.val2

More detailed:

Table A carries status information of a fleet of equipment. Each status record carries with it a start and stop time of that status. Table B carries regularly recorded, timestamped data about the equipment, which I want to extract for the duration of the period indicated in table A.

Codesign wants to access key "access" in your keychain, I put in my login password but keeps asking me

For me, the problem was caps lock. and it seems it may ask you a couple of times to input your password or you will have to enter a password once and press always allow.

Basic communication between two fragments

Update

Ignore this answer. Not that it doesn't work. But there are better methods available. Moreover, Android emphatically discourage direct communication between fragments. See official doc. Thanks user @Wahib Ul Haq for the tip.

Original Answer

Well, you can create a private variable and setter in Fragment B, and set the value from Fragment A itself,

FragmentB.java

private String inputString;
....
....

public void setInputString(String string){
   inputString = string;
}

FragmentA.java

//go to fragment B

FragmentB frag  = new FragmentB();
frag.setInputString(YOUR_STRING);
//create your fragment transaction object, set animation etc
fragTrans.replace(ITS_ARGUMENTS)

Or you can use Activity as you suggested in question..

Transactions in .net

if you just need it for db-related stuff, some OR Mappers (e.g. NHibernate) support transactinos out of the box per default.

Set background image in CSS using jquery

You have to remove the semicolon in the css rule string:

$(this).parent().css("background", "url(/images/r-srchbg_white.png) no-repeat");

how to change the default positioning of modal in bootstrap?

I know it's a bit late but I had issues with a modal window not allowing some links on the menu bar to work, even when it has not been triggered. But I solved it by doing the following:

.modal{
display:none;
}

How to insert a new line in strings in Android

I would personally prefer using "\n". This just puts a line break in Linux or Android.

For example,

String str = "I am the first part of the info being emailed.\nI am the second part.\n\nI am the third part.";

Output

I am the first part of the info being emailed.
I am the second part.

I am the third part.

A more generalized way would be to use,

System.getProperty("line.separator")

For example,

String str = "I am the first part of the info being emailed." + System.getProperty("line.separator") + "I am the second part." + System.getProperty("line.separator") + System.getProperty("line.separator") + "I am the third part.";

brings the same output as above. Here, the static getProperty() method of the System class can be used to get the "line.seperator" for the particular OS.

But this is not necessary at all, as the OS here is fixed, that is, Android. So, calling a method every time is a heavy and unnecessary operation.

Moreover, this also increases your code length and makes it look kind of messy. A "\n" is sweet and simple.

Disable JavaScript error in WebBrowser control

None of the above solutions were suitable for my scenario, handling .Navigated and .FileDownload events seemed like a good fit but accessing the WebBrowser.Document property threw an UnauthorizedAccessException which is caused by cross frame scripting security (our web content contains frames - all on the same domain/address but frames have their own security holes that are being blocked).

The solution that worked was to override IOleCommandTarget and to catch the script error commands at that level. Here's the WebBrowser sub-class to achieve this:

/// <summary>
/// Subclassed WebBrowser that suppresses error pop-ups.
/// 
/// Notes.
/// ScriptErrorsSuppressed property is not used because this actually suppresses *all* pop-ups.
/// 
/// More info at:
/// http://stackoverflow.com/questions/2476360/disable-javascript-error-in-webbrowser-control
/// </summary>
public class WebBrowserEx : WebBrowser
{
    #region Constructor

    /// <summary>
    /// Default constructor.
    /// Initialise browser control and attach customer event handlers.
    /// </summary>
    public WebBrowserEx()
    {
        this.ScriptErrorsSuppressed = false;
    }

    #endregion

    #region Overrides

    /// <summary>
    /// Override to allow custom script error handling.
    /// </summary>
    /// <returns></returns>
    protected override WebBrowserSiteBase CreateWebBrowserSiteBase()
    {
        return new WebBrowserSiteEx(this);
    }

    #endregion

    #region Inner Class [WebBrowserSiteEx]

    /// <summary>
    /// Sub-class to allow custom script error handling.
    /// </summary>
    protected class WebBrowserSiteEx : WebBrowserSite, NativeMethods.IOleCommandTarget
    {
        /// <summary>
        /// Default constructor.
        /// </summary>
        public WebBrowserSiteEx(WebBrowserEx webBrowser) : base (webBrowser)
        {   
        }

        /// <summary>Queries the object for the status of one or more commands generated by user interface events.</summary>
        /// <param name="pguidCmdGroup">The GUID of the command group.</param>
        /// <param name="cCmds">The number of commands in <paramref name="prgCmds" />.</param>
        /// <param name="prgCmds">An array of OLECMD structures that indicate the commands for which the caller needs status information. This method fills the <paramref name="cmdf" /> member of each structure with values taken from the OLECMDF enumeration.</param>
        /// <param name="pCmdText">An OLECMDTEXT structure in which to return name and/or status information of a single command. This parameter can be null to indicate that the caller does not need this information.</param>
        /// <returns>This method returns S_OK on success. Other possible return values include the following.
        /// E_FAIL The operation failed.
        /// E_UNEXPECTED An unexpected error has occurred.
        /// E_POINTER The <paramref name="prgCmds" /> argument is null.
        /// OLECMDERR_E_UNKNOWNGROUP The <paramref name="pguidCmdGroup" /> parameter is not null but does not specify a recognized command group.</returns>
        public int QueryStatus(ref Guid pguidCmdGroup, int cCmds, NativeMethods.OLECMD prgCmds, IntPtr pCmdText)
        {
            if((int)NativeMethods.OLECMDID.OLECMDID_SHOWSCRIPTERROR == prgCmds.cmdID)
            {   // Do nothing (suppress script errors)
                return NativeMethods.S_OK;
            }

            // Indicate that command is unknown. The command will then be handled by another IOleCommandTarget.
            return NativeMethods.OLECMDERR_E_UNKNOWNGROUP;
        }

        /// <summary>Executes the specified command.</summary>
        /// <param name="pguidCmdGroup">The GUID of the command group.</param>
        /// <param name="nCmdID">The command ID.</param>
        /// <param name="nCmdexecopt">Specifies how the object should execute the command. Possible values are taken from the <see cref="T:Microsoft.VisualStudio.OLE.Interop.OLECMDEXECOPT" /> and <see cref="T:Microsoft.VisualStudio.OLE.Interop.OLECMDID_WINDOWSTATE_FLAG" /> enumerations.</param>
        /// <param name="pvaIn">The input arguments of the command.</param>
        /// <param name="pvaOut">The output arguments of the command.</param>
        /// <returns>This method returns S_OK on success. Other possible return values include 
        /// OLECMDERR_E_UNKNOWNGROUP The <paramref name="pguidCmdGroup" /> parameter is not null but does not specify a recognized command group.
        /// OLECMDERR_E_NOTSUPPORTED The <paramref name="nCmdID" /> parameter is not a valid command in the group identified by <paramref name="pguidCmdGroup" />.
        /// OLECMDERR_E_DISABLED The command identified by <paramref name="nCmdID" /> is currently disabled and cannot be executed.
        /// OLECMDERR_E_NOHELP The caller has asked for help on the command identified by <paramref name="nCmdID" />, but no help is available.
        /// OLECMDERR_E_CANCELED The user canceled the execution of the command.</returns>
        public int Exec(ref Guid pguidCmdGroup, int nCmdID, int nCmdexecopt, object[] pvaIn, int pvaOut)
        {
            if((int)NativeMethods.OLECMDID.OLECMDID_SHOWSCRIPTERROR == nCmdID)
            {   // Do nothing (suppress script errors)
                return NativeMethods.S_OK;
            }

            // Indicate that command is unknown. The command will then be handled by another IOleCommandTarget.
            return NativeMethods.OLECMDERR_E_UNKNOWNGROUP;
        }
    }

    #endregion
}

~

/// <summary>
/// Native (unmanaged) methods, required for custom command handling for the WebBrowser control.
/// </summary>
public static class NativeMethods
{
    /// From docobj.h
    public const int OLECMDERR_E_UNKNOWNGROUP = -2147221244;

    /// <summary>
    /// From Microsoft.VisualStudio.OLE.Interop (Visual Studio 2010 SDK).
    /// </summary>
    public enum OLECMDID
    {
        /// <summary />
        OLECMDID_OPEN = 1,
        /// <summary />
        OLECMDID_NEW,
        /// <summary />
        OLECMDID_SAVE,
        /// <summary />
        OLECMDID_SAVEAS,
        /// <summary />
        OLECMDID_SAVECOPYAS,
        /// <summary />
        OLECMDID_PRINT,
        /// <summary />
        OLECMDID_PRINTPREVIEW,
        /// <summary />
        OLECMDID_PAGESETUP,
        /// <summary />
        OLECMDID_SPELL,
        /// <summary />
        OLECMDID_PROPERTIES,
        /// <summary />
        OLECMDID_CUT,
        /// <summary />
        OLECMDID_COPY,
        /// <summary />
        OLECMDID_PASTE,
        /// <summary />
        OLECMDID_PASTESPECIAL,
        /// <summary />
        OLECMDID_UNDO,
        /// <summary />
        OLECMDID_REDO,
        /// <summary />
        OLECMDID_SELECTALL,
        /// <summary />
        OLECMDID_CLEARSELECTION,
        /// <summary />
        OLECMDID_ZOOM,
        /// <summary />
        OLECMDID_GETZOOMRANGE,
        /// <summary />
        OLECMDID_UPDATECOMMANDS,
        /// <summary />
        OLECMDID_REFRESH,
        /// <summary />
        OLECMDID_STOP,
        /// <summary />
        OLECMDID_HIDETOOLBARS,
        /// <summary />
        OLECMDID_SETPROGRESSMAX,
        /// <summary />
        OLECMDID_SETPROGRESSPOS,
        /// <summary />
        OLECMDID_SETPROGRESSTEXT,
        /// <summary />
        OLECMDID_SETTITLE,
        /// <summary />
        OLECMDID_SETDOWNLOADSTATE,
        /// <summary />
        OLECMDID_STOPDOWNLOAD,
        /// <summary />
        OLECMDID_ONTOOLBARACTIVATED,
        /// <summary />
        OLECMDID_FIND,
        /// <summary />
        OLECMDID_DELETE,
        /// <summary />
        OLECMDID_HTTPEQUIV,
        /// <summary />
        OLECMDID_HTTPEQUIV_DONE,
        /// <summary />
        OLECMDID_ENABLE_INTERACTION,
        /// <summary />
        OLECMDID_ONUNLOAD,
        /// <summary />
        OLECMDID_PROPERTYBAG2,
        /// <summary />
        OLECMDID_PREREFRESH,
        /// <summary />
        OLECMDID_SHOWSCRIPTERROR,
        /// <summary />
        OLECMDID_SHOWMESSAGE,
        /// <summary />
        OLECMDID_SHOWFIND,
        /// <summary />
        OLECMDID_SHOWPAGESETUP,
        /// <summary />
        OLECMDID_SHOWPRINT,
        /// <summary />
        OLECMDID_CLOSE,
        /// <summary />
        OLECMDID_ALLOWUILESSSAVEAS,
        /// <summary />
        OLECMDID_DONTDOWNLOADCSS,
        /// <summary />
        OLECMDID_UPDATEPAGESTATUS,
        /// <summary />
        OLECMDID_PRINT2,
        /// <summary />
        OLECMDID_PRINTPREVIEW2,
        /// <summary />
        OLECMDID_SETPRINTTEMPLATE,
        /// <summary />
        OLECMDID_GETPRINTTEMPLATE
    }

    /// <summary>
    /// From Microsoft.VisualStudio.Shell (Visual Studio 2010 SDK).
    /// </summary>
    public const int S_OK = 0;

    /// <summary>
    /// OLE command structure.
    /// </summary>
    [StructLayout(LayoutKind.Sequential)]
    public class OLECMD
    {
        /// <summary>
        /// Command ID.
        /// </summary>
        [MarshalAs(UnmanagedType.U4)]
        public int cmdID;
        /// <summary>
        /// Flags associated with cmdID.
        /// </summary>
        [MarshalAs(UnmanagedType.U4)]
        public int cmdf;
    }

    /// <summary>
    /// Enables the dispatching of commands between objects and containers.
    /// </summary>
    [ComVisible(true), Guid("B722BCCB-4E68-101B-A2BC-00AA00404770"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    [ComImport]
    public interface IOleCommandTarget
    {
        /// <summary>Queries the object for the status of one or more commands generated by user interface events.</summary>
        /// <param name="pguidCmdGroup">The GUID of the command group.</param>
        /// <param name="cCmds">The number of commands in <paramref name="prgCmds" />.</param>
        /// <param name="prgCmds">An array of <see cref="T:Microsoft.VisualStudio.OLE.Interop.OLECMD" /> structures that indicate the commands for which the caller needs status information.</param>
        /// <param name="pCmdText">An <see cref="T:Microsoft.VisualStudio.OLE.Interop.OLECMDTEXT" /> structure in which to return name and/or status information of a single command. This parameter can be null to indicate that the caller does not need this information.</param>
        /// <returns>This method returns S_OK on success. Other possible return values include the following.
        /// E_FAIL The operation failed.
        /// E_UNEXPECTED An unexpected error has occurred.
        /// E_POINTER The <paramref name="prgCmds" /> argument is null.
        /// OLECMDERR_E_UNKNOWNGROUPThe <paramref name="pguidCmdGroup" /> parameter is not null but does not specify a recognized command group.</returns>
        [PreserveSig]
        [return: MarshalAs(UnmanagedType.I4)]
        int QueryStatus(ref Guid pguidCmdGroup, int cCmds, [In] [Out] NativeMethods.OLECMD prgCmds, [In] [Out] IntPtr pCmdText);

        /// <summary>Executes the specified command.</summary>
        /// <param name="pguidCmdGroup">The GUID of the command group.</param>
        /// <param name="nCmdID">The command ID.</param>
        /// <param name="nCmdexecopt">Specifies how the object should execute the command. Possible values are taken from the <see cref="T:Microsoft.VisualStudio.OLE.Interop.OLECMDEXECOPT" /> and <see cref="T:Microsoft.VisualStudio.OLE.Interop.OLECMDID_WINDOWSTATE_FLAG" /> enumerations.</param>
        /// <param name="pvaIn">The input arguments of the command.</param>
        /// <param name="pvaOut">The output arguments of the command.</param>
        /// <returns>This method returns S_OK on success. Other possible return values include 
        /// OLECMDERR_E_UNKNOWNGROUP The <paramref name="pguidCmdGroup" /> parameter is not null but does not specify a recognized command group.
        /// OLECMDERR_E_NOTSUPPORTED The <paramref name="nCmdID" /> parameter is not a valid command in the group identified by <paramref name="pguidCmdGroup" />.
        /// OLECMDERR_E_DISABLED The command identified by <paramref name="nCmdID" /> is currently disabled and cannot be executed.
        /// OLECMDERR_E_NOHELP The caller has asked for help on the command identified by <paramref name="nCmdID" />, but no help is available.
        /// OLECMDERR_E_CANCELED The user canceled the execution of the command.</returns>
        [PreserveSig]
        [return: MarshalAs(UnmanagedType.I4)]
        int Exec(ref Guid pguidCmdGroup, int nCmdID, int nCmdexecopt, [MarshalAs(UnmanagedType.LPArray)] [In] object[] pvaIn, int pvaOut);
    }
}

Rename all files in directory from $filename_h to $filename_half?

Another approach can be manually using batch rename option

Right click on the file -> File Custom Commands -> Batch Rename and you can replace h. with half.

This will work for linux based gui using WinSCP etc

Remove table row after clicking table row delete button

As @gaurang171 mentioned, we can use .closest() which will return the first ancestor, or the closest to our delete button, and use .remove() to remove it.

This is how we can implement it using jQuery click event instead of using JavaScript onclick.

HTML:

<table id="myTable">
<tr>
  <th width="30%" style="color:red;">ID</th>
  <th width="25%" style="color:red;">Name</th>
  <th width="25%" style="color:red;">Age</th>
  <th width="1%"></th>
</tr>

<tr>
  <td width="30%" style="color:red;">SSS-001</td>
  <td width="25%" style="color:red;">Ben</td>
  <td width="25%" style="color:red;">25</td>
  <td><button type='button' class='btnDelete'>x</button></td>
</tr>

<tr>
  <td width="30%" style="color:red;">SSS-002</td>
  <td width="25%" style="color:red;">Anderson</td>
  <td width="25%" style="color:red;">47</td>
  <td><button type='button' class='btnDelete'>x</button></td>
</tr>

<tr>
  <td width="30%" style="color:red;">SSS-003</td>
  <td width="25%" style="color:red;">Rocky</td>
  <td width="25%" style="color:red;">32</td>
  <td><button type='button' class='btnDelete'>x</button></td>
</tr>

<tr>
  <td width="30%" style="color:red;">SSS-004</td>
  <td width="25%" style="color:red;">Lee</td>
  <td width="25%" style="color:red;">15</td>
  <td><button type='button' class='btnDelete'>x</button></td>
</tr>
                            

jQuery

 $(document).ready(function(){
     $("#myTable").on('click','.btnDelete',function(){
         $(this).closest('tr').remove();
      });
  });

Try in JSFiddle: click here.

How do you make strings "XML safe"?

By either escaping those characters with htmlspecialchars, or, perhaps more appropriately, using a library for building XML documents, such as DOMDocument or XMLWriter.

Another alternative would be to use CDATA sections, but then you'd have to look out for occurrences of ]]>.

Take also into consideration that that you must respect the encoding you define for the XML document (by default UTF-8).

Dictionary with list of strings as value

Just create a new array in your dictionary

Dictionary<string, List<string>> myDic = new Dictionary<string, List<string>>();
myDic.Add(newKey, new List<string>(existingList));

print spaces with String.format()

int numberOfSpaces = 3;
String space = String.format("%"+ numberOfSpaces +"s", " ");

TypeError: not all arguments converted during string formatting python

In my case, it's because I need only a single %s, i missing values input.

Can Javascript read the source of any web page?

As a security measure, Javascript can't read files from different domains. Though there might be some strange workaround for it, I'd consider a different language for this task.

Fastest method of screen capturing on Windows

For C++ you can use: http://www.pinvoke.net/default.aspx/gdi32/BitBlt.html
This may hower not work on all types of 3D applications/video apps. Then this link may be more useful as it describes 3 different methods you can use.

Old answer (C#):
You can use System.Drawing.Graphics.Copy, but it is not very fast.

A sample project I wrote doing exactly this: http://blog.tedd.no/index.php/2010/08/16/c-image-analysis-auto-gaming-with-source/

I'm planning to update this sample using a faster method like Direct3D: http://spazzarama.com/2009/02/07/screencapture-with-direct3d/

And here is a link for capturing to video: How to capture screen to be video using C# .Net?

How to change permissions for a folder and its subfolders/files in one step?

chmod 755 -R /opt/lampp/htdocs will recursively set the permissions. There's no way to set the permissions for files automatically in only this directory that are created after you set the permissions, but you could change your system-wide default file permissions with by setting umask 022.

MVC 4 Edit modal form using Bootstrap

You should use partial views. I use the following approach:

Use a view model so you're not passing your domain models to your views:

public class EditPersonViewModel
{
    public int Id { get; set; }   // this is only used to retrieve record from Db
    public string Name { get; set; }
    public string Age { get; set; }
}

In your PersonController:

[HttpGet] // this action result returns the partial containing the modal
public ActionResult EditPerson(int id)
{  
    var viewModel = new EditPersonViewModel();
    viewModel.Id = id;
    return PartialView("_EditPersonPartial", viewModel);
}

[HttpPost] // this action takes the viewModel from the modal
public ActionResult EditPerson(EditPersonViewModel viewModel)
{
    if (ModelState.IsValid)
    {
        var toUpdate = personRepo.Find(viewModel.Id);
        toUpdate.Name = viewModel.Name;
        toUpdate.Age = viewModel.Age;
        personRepo.InsertOrUpdate(toUpdate);
        personRepo.Save();
        return View("Index");
    }
}

Next create a partial view called _EditPersonPartial. This contains the modal header, body and footer. It also contains the Ajax form. It's strongly typed and takes in our view model.

@model Namespace.ViewModels.EditPersonViewModel
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
    <h3 id="myModalLabel">Edit group member</h3>
</div>
<div>
@using (Ajax.BeginForm("EditPerson", "Person", FormMethod.Post,
                    new AjaxOptions
                    {
                        InsertionMode = InsertionMode.Replace,
                        HttpMethod = "POST",
                        UpdateTargetId = "list-of-people"
                    }))
{
    @Html.ValidationSummary()
    @Html.AntiForgeryToken()
    <div class="modal-body">
        @Html.Bootstrap().ControlGroup().TextBoxFor(x => x.Name)
        @Html.Bootstrap().ControlGroup().TextBoxFor(x => x.Age)
    </div>
    <div class="modal-footer">
        <button class="btn btn-inverse" type="submit">Save</button>
    </div>
}

Now somewhere in your application, say another partial _peoplePartial.cshtml etc:

<div>
   @foreach(var person in Model.People)
    {
        <button class="btn btn-primary edit-person" data-id="@person.PersonId">Edit</button>
    }
</div>
// this is the modal definition
<div class="modal hide fade in" id="edit-person">
    <div id="edit-person-container"></div>
</div>

    <script type="text/javascript">
    $(document).ready(function () {
        $('.edit-person').click(function () {
            var url = "/Person/EditPerson"; // the url to the controller
            var id = $(this).attr('data-id'); // the id that's given to each button in the list
            $.get(url + '/' + id, function (data) {
                $('#edit-person-container').html(data);
                $('#edit-person').modal('show');
            });
        });
     });
   </script>

How to detect the currently pressed key?

If you need to listen to keys in any generic class what are pressed when a 'Form' Window, this is your code. It doesnt listen to global windows key events, so it cannot be used to see keys when the window is not active.

Form.cs

public partial class Form1 : Form
{
    public Form1()
    {
        // Some other Code
        // Register all Keys pressed
        this.KeyPreview = true;
        KeyHandler.Instance.Init();
        this.KeyDown += Form1_KeyDown;
        this.KeyUp += Form1_KeyUp;
        // Some other Code in the constructor
    }

    private void Form1_KeyUp(object sender, KeyEventArgs e)
    {
        // Fire event when a key is released
        KeyHandler.Instance.FireKeyUp(sender, e);
    }

    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        // Fire event when a key is pressed
        KeyHandler.Instance.FireKeyDown(sender, e);
    }
}

KeyHandler.cs KeyHandler is a Singleton Class and can be accessed in any other Object through Handler.Instance... Easy right.

public class KeyHandler
{
    #region Singleton
    private static KeyHandler instance;
    private KeyHandler()
    {
        currentlyPressedKeys = new List<Keys>();
    }

    public static KeyHandler Instance
    {
        get
        {
            if (instance is null)
            {
                instance = new KeyHandler();
            }
            return instance;
        }
    }
    #endregion Singleton

    private List<Keys> currentlyPressedKeys;
    public List<Keys> GetCurrentlyPressedKeys { get { return currentlyPressedKeys; } }

    public void FireKeyDown(object sender, KeyEventArgs e)
    {
        if (!currentlyPressedKeys.Contains(e.KeyCode))
        {
            currentlyPressedKeys.Add(e.KeyCode);
            KeyEventKeyPressed(sender, e);
        }
    }

    public void FireKeyUp(object sender, KeyEventArgs e)
    {
        currentlyPressedKeys.Remove(e.KeyCode);
        KeyEventKeyReleased(sender, e);
    }

    public event EventHandler<KeyEventArgs> KeyPressed;
    protected virtual void KeyEventKeyPressed(object sender, KeyEventArgs e)
    {
        EventHandler<KeyEventArgs> handler = KeyPressed;
        handler?.Invoke(sender, e);
    }

    public event EventHandler<KeyEventArgs> KeyReleased;
    protected virtual void KeyEventKeyReleased(object sender, KeyEventArgs e)
    {
        EventHandler<KeyEventArgs> handler = KeyReleased;
        handler?.Invoke(sender, e);
    }

    public void Init()
    {
        // Nothing to initialize yet
    }
}

// In any other Class/Object its now possible to receive KeyEvents that are fired when the 'Form' is active. So its possible to listen to key events in any Control object or anything else. Its possible to see if e.g. multiple keys are pressed like Shift+Ctrl+Q or something like that.

public class SomeClass
{
    public SomeClass()
    {
        KeyHandler.instance.KeyPressed += Instance_KeyPressed
        KeyHandler.Instance.KeyReleased += Instance_KeyReleased;
    }

    public void SomeMethod()
    {
        if (KeyHandler.Instance.GetCurrentlyPressedKeys.Contains(Keys.ShiftKey))
        {
            // Do Stuff when the method has a key (e.g. Shift/Control...) pressed
        }
    }

    private void Instance_KeyPressed(object sender, KeyEventArgs e)
    {
        // Any Key was pressed, do Stuff then
    }

    private void Instance_KeyReleased(object sender, KeyEventArgs e)
    {
        // Do Stuff when a Key was Released
    }
}

Android emulator failed to allocate memory 8

This following solution worked for me. In the following configuration file:

C:\Users\<user>\.android\avd\<avd-profile-name>.avd\config.ini

Replace

hw.ramSize=1024

by

hw.ramSize=1024MB

Excel VBA, How to select rows based on data in a column?

Yes using Option Explicit is a good habit. Using .Select however is not :) it reduces the speed of the code. Also fully justify sheet names else the code will always run for the Activesheet which might not be what you actually wanted.

Is this what you are trying?

Option Explicit

Sub Sample()
    Dim lastRow As Long, i As Long
    Dim CopyRange As Range

    '~~> Change Sheet1 to relevant sheet name
    With Sheets("Sheet1")
        lastRow = .Range("A" & .Rows.Count).End(xlUp).Row

        For i = 2 To lastRow
            If Len(Trim(.Range("A" & i).Value)) <> 0 Then
                If CopyRange Is Nothing Then
                    Set CopyRange = .Rows(i)
                Else
                    Set CopyRange = Union(CopyRange, .Rows(i))
                End If
            Else
                Exit For
            End If
        Next

        If Not CopyRange Is Nothing Then
            '~~> Change Sheet2 to relevant sheet name
            CopyRange.Copy Sheets("Sheet2").Rows(1)
        End If
    End With
End Sub

NOTE

If if you have data from Row 2 till Row 10 and row 11 is blank and then you have data again from Row 12 then the above code will only copy data from Row 2 till Row 10

If you want to copy all rows which have data then use this code.

Option Explicit

Sub Sample()
    Dim lastRow As Long, i As Long
    Dim CopyRange As Range

    '~~> Change Sheet1 to relevant sheet name
    With Sheets("Sheet1")
        lastRow = .Range("A" & .Rows.Count).End(xlUp).Row

        For i = 2 To lastRow
            If Len(Trim(.Range("A" & i).Value)) <> 0 Then
                If CopyRange Is Nothing Then
                    Set CopyRange = .Rows(i)
                Else
                    Set CopyRange = Union(CopyRange, .Rows(i))
                End If
            End If
        Next

        If Not CopyRange Is Nothing Then
            '~~> Change Sheet2 to relevant sheet name
            CopyRange.Copy Sheets("Sheet2").Rows(1)
        End If
    End With
End Sub

Hope this is what you wanted?

Sid

How to pretty print XML from the command line?

This simple(st) solution doesn't provide indentation, but it is nevertheless much easier on the human eye. Also it allows the xml to be handled more easily by simple tools like grep, head, awk, etc.

Use sed to replace '<' with itself preceeded with a newline.

And as mentioned by Gilles, it's probably not a good idea to use this in production.

# check you are getting more than one line out
sed 's/</\n</g' sample.xml | wc -l

# check the output looks generally ok
sed 's/</\n</g' sample.xml | head

# capture the pretty xml in a different file
sed 's/</\n</g' sample.xml > prettySample.xml

Explicitly set column value to null SQL Developer

If you want to use the GUI... click/double-click the table and select the Data tab. Click in the column value you want to set to (null). Select the value and delete it. Hit the commit button (green check-mark button). It should now be null.

enter image description here

More info here:

How to use the SQL Worksheet in SQL Developer to Insert, Update and Delete Data

Why are elementwise additions much faster in separate loops than in a combined loop?

Upon further analysis of this, I believe this is (at least partially) caused by the data alignment of the four-pointers. This will cause some level of cache bank/way conflicts.

If I've guessed correctly on how you are allocating your arrays, they are likely to be aligned to the page line.

This means that all your accesses in each loop will fall on the same cache way. However, Intel processors have had 8-way L1 cache associativity for a while. But in reality, the performance isn't completely uniform. Accessing 4-ways is still slower than say 2-ways.

EDIT: It does in fact look like you are allocating all the arrays separately. Usually when such large allocations are requested, the allocator will request fresh pages from the OS. Therefore, there is a high chance that large allocations will appear at the same offset from a page-boundary.

Here's the test code:

int main(){
    const int n = 100000;

#ifdef ALLOCATE_SEPERATE
    double *a1 = (double*)malloc(n * sizeof(double));
    double *b1 = (double*)malloc(n * sizeof(double));
    double *c1 = (double*)malloc(n * sizeof(double));
    double *d1 = (double*)malloc(n * sizeof(double));
#else
    double *a1 = (double*)malloc(n * sizeof(double) * 4);
    double *b1 = a1 + n;
    double *c1 = b1 + n;
    double *d1 = c1 + n;
#endif

    //  Zero the data to prevent any chance of denormals.
    memset(a1,0,n * sizeof(double));
    memset(b1,0,n * sizeof(double));
    memset(c1,0,n * sizeof(double));
    memset(d1,0,n * sizeof(double));

    //  Print the addresses
    cout << a1 << endl;
    cout << b1 << endl;
    cout << c1 << endl;
    cout << d1 << endl;

    clock_t start = clock();

    int c = 0;
    while (c++ < 10000){

#if ONE_LOOP
        for(int j=0;j<n;j++){
            a1[j] += b1[j];
            c1[j] += d1[j];
        }
#else
        for(int j=0;j<n;j++){
            a1[j] += b1[j];
        }
        for(int j=0;j<n;j++){
            c1[j] += d1[j];
        }
#endif

    }

    clock_t end = clock();
    cout << "seconds = " << (double)(end - start) / CLOCKS_PER_SEC << endl;

    system("pause");
    return 0;
}

Benchmark Results:

EDIT: Results on an actual Core 2 architecture machine:

2 x Intel Xeon X5482 Harpertown @ 3.2 GHz:

#define ALLOCATE_SEPERATE
#define ONE_LOOP
00600020
006D0020
007A0020
00870020
seconds = 6.206

#define ALLOCATE_SEPERATE
//#define ONE_LOOP
005E0020
006B0020
00780020
00850020
seconds = 2.116

//#define ALLOCATE_SEPERATE
#define ONE_LOOP
00570020
00633520
006F6A20
007B9F20
seconds = 1.894

//#define ALLOCATE_SEPERATE
//#define ONE_LOOP
008C0020
00983520
00A46A20
00B09F20
seconds = 1.993

Observations:

  • 6.206 seconds with one loop and 2.116 seconds with two loops. This reproduces the OP's results exactly.

  • In the first two tests, the arrays are allocated separately. You'll notice that they all have the same alignment relative to the page.

  • In the second two tests, the arrays are packed together to break that alignment. Here you'll notice both loops are faster. Furthermore, the second (double) loop is now the slower one as you would normally expect.

As @Stephen Cannon points out in the comments, there is a very likely possibility that this alignment causes false aliasing in the load/store units or the cache. I Googled around for this and found that Intel actually has a hardware counter for partial address aliasing stalls:

http://software.intel.com/sites/products/documentation/doclib/stdxe/2013/~amplifierxe/pmw_dp/events/partial_address_alias.html


5 Regions - Explanations

Region 1:

This one is easy. The dataset is so small that the performance is dominated by overhead like looping and branching.

Region 2:

Here, as the data sizes increase, the amount of relative overhead goes down and the performance "saturates". Here two loops is slower because it has twice as much loop and branching overhead.

I'm not sure exactly what's going on here... Alignment could still play an effect as Agner Fog mentions cache bank conflicts. (That link is about Sandy Bridge, but the idea should still be applicable to Core 2.)

Region 3:

At this point, the data no longer fits in the L1 cache. So performance is capped by the L1 <-> L2 cache bandwidth.

Region 4:

The performance drop in the single-loop is what we are observing. And as mentioned, this is due to the alignment which (most likely) causes false aliasing stalls in the processor load/store units.

However, in order for false aliasing to occur, there must be a large enough stride between the datasets. This is why you don't see this in region 3.

Region 5:

At this point, nothing fits in the cache. So you're bound by memory bandwidth.


2 x Intel X5482 Harpertown @ 3.2 GHz Intel Core i7 870 @ 2.8 GHz Intel Core i7 2600K @ 4.4 GHz

How to send an email with Gmail as provider using Python?

    import smtplib

    fromadd='[email protected]'
    toadd='[email protected]'

    msg='''hi,how r u'''
    username='[email protected]'
    passwd='password'

    try:
        server = smtplib.SMTP('smtp.gmail.com:587')
        server.ehlo()
        server.starttls()
        server.login(username,passwd)

        server.sendmail(fromadd,toadd,msg)
        print("Mail Send Successfully")
        server.quit()

   except:
        print("Error:unable to send mail")

   NOTE:https://www.google.com/settings/security/lesssecureapps that                                                         should be enabled

"Parameter" vs "Argument"

A parameter is the variable which is part of the method’s signature (method declaration). An argument is an expression used when calling the method.

Consider the following code:

void Foo(int i, float f)
{
    // Do things
}

void Bar()
{
    int anInt = 1;
    Foo(anInt, 2.0);
}

Here i and f are the parameters, and anInt and 2.0 are the arguments.

iOS: Compare two dates

I don't know exactly if you have asked this but if you only want to compare the date component of a NSDate you have to use NSCalendar and NSDateComponents to remove the time component.

Something like this should work as a category for NSDate:

- (NSComparisonResult)compareDateOnly:(NSDate *)otherDate {
    NSUInteger dateFlags = NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit;
    NSCalendar *gregorianCalendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
    NSDateComponents *selfComponents = [gregorianCalendar components:dateFlags fromDate:self];
    NSDate *selfDateOnly = [gregorianCalendar dateFromComponents:selfComponents];

    NSDateComponents *otherCompents = [gregorianCalendar components:dateFlags fromDate:otherDate];
    NSDate *otherDateOnly = [gregorianCalendar dateFromComponents:otherCompents];
    return [selfDateOnly compare:otherDateOnly];
}

How do I replace a double-quote with an escape-char double-quote in a string using JavaScript?

The other answers will work for most strings, but you can end up unescaping an already escaped double quote, which is probably not what you want.

To work correctly, you are going to need to escape all backslashes and then escape all double quotes, like this:

var test_str = '"first \\" middle \\" last "';
var result = test_str.replace(/\\/g, '\\\\').replace(/\"/g, '\\"');

depending on how you need to use the string, and the other escaped charaters involved, this may still have some issues, but I think it will probably work in most cases.

How to add custom validation to an AngularJS form?

Here's a cool way to do custom wildcard expression validations in a form (from: Advanced form validation with AngularJS and filters):

<form novalidate="">  
   <input type="text" id="name" name="name" ng-model="newPerson.name"
      ensure-expression="(persons | filter:{name: newPerson.name}:true).length !== 1">
   <!-- or in your case:-->
   <input type="text" id="fruitName" name="fruitName" ng-model="data.fruitName"
      ensure-expression="(blacklist | filter:{fruitName: data.fruitName}:true).length !== 1">
</form>
app.directive('ensureExpression', ['$http', '$parse', function($http, $parse) {
    return {
        require: 'ngModel',
        link: function(scope, ele, attrs, ngModelController) {
            scope.$watch(attrs.ngModel, function(value) {
                var booleanResult = $parse(attrs.ensureExpression)(scope);
                ngModelController.$setValidity('expression', booleanResult);
            });
        }
    };
}]);

jsFiddle demo (supports expression naming and multiple expressions)

It's similar to ui-validate, but you don't need a scope specific validation function (this works generically) and ofcourse you don't need ui.utils this way.

How to save a plot as image on the disk?

Like this

png('filename.png')
# make plot
dev.off()

or this

# sometimes plots do better in vector graphics
svg('filename.svg')
# make plot
dev.off()

or this

pdf('filename.pdf')
# make plot
dev.off()

And probably others too. They're all listed together in the help pages.

Installing tensorflow with anaconda in windows

1) Update conda

Run the anaconda prompt as administrator

conda update -n base -c defaults conda

2) Create an environment for python new version say, 3.6

conda create --name py36 python=3.6

3) Activate the new environment

conda activate py36

4) Upgrade pip

pip install --upgrade pip

5) Install tensorflow

pip install https://testpypi.python.org/packages/db/d2/876b5eedda1f81d5b5734277a155fa0894d394a7f55efa9946a818ad1190/tensorflow-0.12.1-cp36-cp36m-win_amd64.whl

If it doesn't work

If you have problem with wheel at the environment location, or pywrap_tensorflow problem,

 pip install tensorflow --upgrade --force-reinstall

Swift add icon/image in UITextField

Swift 3.1

extension UITextField
{
    enum Direction
    {
        case Left
        case Right
    }

    func AddImage(direction:Direction,imageName:String,Frame:CGRect,backgroundColor:UIColor)
    {
        let View = UIView(frame: Frame)
        View.backgroundColor = backgroundColor

        let imageView = UIImageView(frame: Frame)
        imageView.image = UIImage(named: imageName)

        View.addSubview(imageView)

        if Direction.Left == direction
        {
            self.leftViewMode = .always
            self.leftView = View
        }
        else
        {
            self.rightViewMode = .always
            self.rightView = View
        }
    }

}

Android: How to rotate a bitmap on a center point

I hope the following sequence of code will help you:

Bitmap targetBitmap = Bitmap.createBitmap(targetWidth, targetHeight, config);
Canvas canvas = new Canvas(targetBitmap);
Matrix matrix = new Matrix();
matrix.setRotate(mRotation,source.getWidth()/2,source.getHeight()/2);
canvas.drawBitmap(source, matrix, new Paint());

If you check the following method from ~frameworks\base\graphics\java\android\graphics\Bitmap.java

public static Bitmap createBitmap(Bitmap source, int x, int y, int width, int height,
        Matrix m, boolean filter)

this would explain what it does with rotation and translate.

Return Index of an Element in an Array Excel VBA

'To return the position of an element within any-dimension array  
'Returns 0 if the element is not in the array, and -1 if there is an error  
Public Function posInArray(ByVal itemSearched As Variant, ByVal aArray As Variant) As Long  
Dim pos As Long, item As Variant  

posInArray = -1  
If IsArray(aArray) Then  
    If not IsEmpty(aArray) Then  
        pos = 1  
        For Each item In aArray  
            If itemSearched = item Then  
                posInArray = pos  
                Exit Function  
            End If  
            pos = pos + 1  
        Next item  
        posInArray = 0  
    End If  
End If

End Function

How can I open a website in my web browser using Python?

import webbrowser

webbrowser.open("http://www.google.com")

The link will be opened in default web browser unless specified

How do I raise the same Exception with a custom message in Python?

It seems all the answers are adding info to e.args[0], thereby altering the existing error message. Is there a downside to extending the args tuple instead? I think the possible upside is, you can leave the original error message alone for cases where parsing that string is needed; and you could add multiple elements to the tuple if your custom error handling produced several messages or error codes, for cases where the traceback would be parsed programmatically (like via a system monitoring tool).

## Approach #1, if the exception may not be derived from Exception and well-behaved:

def to_int(x):
    try:
        return int(x)
    except Exception as e:
        e.args = (e.args if e.args else tuple()) + ('Custom message',)
        raise

>>> to_int('12')
12

>>> to_int('12 monkeys')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in to_int
ValueError: ("invalid literal for int() with base 10: '12 monkeys'", 'Custom message')

or

## Approach #2, if the exception is always derived from Exception and well-behaved:

def to_int(x):
    try:
        return int(x)
    except Exception as e:
        e.args += ('Custom message',)
        raise

>>> to_int('12')
12

>>> to_int('12 monkeys')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in to_int
ValueError: ("invalid literal for int() with base 10: '12 monkeys'", 'Custom message')

Can you see a downside to this approach?

Get root password for Google Cloud Engine VM

I had the same problem. Even after updating the password using sudo passwd it was not working. I had to give "multiple" roles for my user through IAM & Admin Refer Screen Shot on IAM & Admin screen of google cloud

After that i restarted the VM. Then again changed the password and then it worked.

user1@sap-hanaexpress-public-1-vm:~> sudo passwd
New password: 
Retype new password: 
passwd: password updated successfully
user1@sap-hanaexpress-public-1-vm:~> su
Password: 
sap-hanaexpress-public-1-vm:/home/user1 # whoami
root
sap-hanaexpress-public-1-vm:/home/user1 #

Error : Program type already present: android.support.design.widget.CoordinatorLayout$Behavior

Adding this to project's gradle.properties fixed it for us:

android.enableJetifier=true
android.useAndroidX=true

[] and {} vs list() and dict(), which is better?

IMHO, using list() and dict() makes your Python look like C. Ugh.

Why is HttpContext.Current null?

In IIS7 with integrated mode, Current is not available in Application_Start. There is a similar thread here.

Multiple separate IF conditions in SQL Server

To avoid syntax errors, be sure to always put BEGIN and END after an IF clause, eg:

IF (@A!= @SA)
   BEGIN
   --do stuff
   END
IF (@C!= @SC)
   BEGIN
   --do stuff
   END

... and so on. This should work as expected. Imagine BEGIN and END keyword as the opening and closing bracket, respectively.

AttributeError: 'datetime' module has no attribute 'strptime'

Use the correct call: strptime is a classmethod of the datetime.datetime class, it's not a function in the datetime module.

self.date = datetime.datetime.strptime(self.d, "%Y-%m-%d")

As mentioned by Jon Clements in the comments, some people do from datetime import datetime, which would bind the datetime name to the datetime class, and make your initial code work.

To identify which case you're facing (in the future), look at your import statements

  • import datetime: that's the module (that's what you have right now).
  • from datetime import datetime: that's the class.

How do I get the current time zone of MySQL?

To get Current timezone of the mysql you can do following things:

 SELECT @@system_time_zone;   # from this you can get the system timezone 
 SELECT IF(@@session.time_zone = 'SYSTEM', @@system_time_zone, @@session.time_zone) # This will give you time zone if system timezone is different from global timezone

Now if you want to change the mysql timezone then:

 SET GLOBAL time_zone = '+00:00';   # this will set mysql timezone in UTC
 SET @@session.time_zone = "+00:00";  # by this you can chnage the timezone only for your particular session 

How to upload a file in Django?

I also had the similar requirement. Most of the examples on net are asking to create models and create forms which I did not wanna use. Here is my final code.

if request.method == 'POST':
    file1 = request.FILES['file']
    contentOfFile = file1.read()
    if file1:
        return render(request, 'blogapp/Statistics.html', {'file': file1, 'contentOfFile': contentOfFile})

And in HTML to upload I wrote:

{% block content %}
    <h1>File content</h1>
    <form action="{% url 'blogapp:uploadComplete'%}" method="post" enctype="multipart/form-data">
         {% csrf_token %}
        <input id="uploadbutton" type="file" value="Browse" name="file" accept="text/csv" />
        <input type="submit" value="Upload" />
    </form>
    {% endblock %}

Following is the HTML which displays content of file:

{% block content %}
    <h3>File uploaded successfully</h3>
    {{file.name}}
    </br>content = {{contentOfFile}}
{% endblock %}

What is this: [Ljava.lang.Object;?

If you are here because of the Liquibase error saying:

Caused By: Precondition Error
...
Can't detect type of array [Ljava.lang.Short

and you are using

not {
  indexExists()
}

precondition multiple times, then you are facing an old bug: https://liquibase.jira.com/browse/CORE-1342

We can try to execute an above check using bare sqlCheck(Postgres):

SELECT COUNT(i.relname)
FROM
    pg_class t,
    pg_class i,
    pg_index ix
WHERE
    t.oid = ix.indrelid
    and i.oid = ix.indexrelid
    and t.relkind = 'r'
    and t.relname = 'tableName'
    and i.relname = 'indexName';

where tableName - is an index table name and indexName - is an index name

Should I test private methods or only public ones?

You can also make your method package-private i.e. default and you should be able to unit test it unless it is required to be private.

Correct way to handle conditional styling in React

Another way, using inline style and the spread operator

style={{
  ...completed ? { textDecoration: completed } : {}
}}

That way be useful in some situations where you want to add a bunch of properties at the same time base on the condition.

Adding headers to requests module

From http://docs.python-requests.org/en/latest/user/quickstart/

url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
headers = {'content-type': 'application/json'}

r = requests.post(url, data=json.dumps(payload), headers=headers)

You just need to create a dict with your headers (key: value pairs where the key is the name of the header and the value is, well, the value of the pair) and pass that dict to the headers parameter on the .get or .post method.

So more specific to your question:

headers = {'foobar': 'raboof'}
requests.get('http://himom.com', headers=headers)

Non-conformable arrays error in code

The problem is that omega in your case is matrix of dimensions 1 * 1. You should convert it to a vector if you wish to multiply t(X) %*% X by a scalar (that is omega)

In particular, you'll have to replace this line:

omega   = rgamma(1,a0,1) / L0

with:

omega   = as.vector(rgamma(1,a0,1) / L0)

everywhere in your code. It happens in two places (once inside the loop and once outside). You can substitute as.vector(.) or c(t(.)). Both are equivalent.

Here's the modified code that should work:

gibbs = function(data, m01 = 0, m02 = 0, k01 = 0.1, k02 = 0.1, 
                     a0 = 0.1, L0 = 0.1, nburn = 0, ndraw = 5000) {
    m0      = c(m01, m02) 
    C0      = matrix(nrow = 2, ncol = 2) 
    C0[1,1] = 1 / k01 
    C0[1,2] = 0 
    C0[2,1] = 0 
    C0[2,2] = 1 / k02 
    beta    = mvrnorm(1,m0,C0) 
    omega   = as.vector(rgamma(1,a0,1) / L0)
    draws   = matrix(ncol = 3,nrow = ndraw) 
    it      = -nburn 

    while (it < ndraw) {
        it    = it + 1 
        C1    = solve(solve(C0) + omega * t(X) %*% X) 
        m1    = C1 %*% (solve(C0) %*% m0 + omega * t(X) %*% y)
        beta  = mvrnorm(1, m1, C1) 
        a1    = a0 + n / 2 
        L1    = L0 + t(y - X %*% beta) %*% (y - X %*% beta) / 2 
        omega = as.vector(rgamma(1, a1, 1) / L1)
        if (it > 0) { 
            draws[it,1] = beta[1]
            draws[it,2] = beta[2]
            draws[it,3] = omega
        }
    }
    return(draws)
}

How to unload a package without restarting R

When you are going back and forth between scripts it may only sometimes be necessary to unload a package. Here's a simple IF statement that will prevent warnings that would appear if you tried to unload a package that was not currently loaded.

if("package:vegan" %in% search()) detach("package:vegan", unload=TRUE) 

Including this at the top of a script might be helpful.

I hope that makes your day!

ASP.NET MVC Ajax Error handling

Unfortunately, neither of answers are good for me. Surprisingly the solution is much simpler. Return from controller:

return new HttpStatusCodeResult(HttpStatusCode.BadRequest, e.Response.ReasonPhrase);

And handle it as standard HTTP error on client as you like.

JQUERY ajax passing value from MVC View to Controller

Try using the data option of the $.ajax function. More info here.

$('#btnSaveComments').click(function () {
    var comments = $('#txtComments').val();
    var selectedId = $('#hdnSelectedId').val();

    $.ajax({
        url: '<%: Url.Action("SaveComments")%>',
        data: { 'id' : selectedId, 'comments' : comments },
        type: "post",
        cache: false,
        success: function (savingStatus) {
            $("#hdnOrigComments").val($('#txtComments').val());
            $('#lblCommentsNotification').text(savingStatus);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            $('#lblCommentsNotification').text("Error encountered while saving the comments.");
        }
    });
});

Logical operators ("and", "or") in DOS batch

The following examples show how to make an AND statement (used for setting variables or including parameters for a command).

To start Notepad and close the CMD window:

start notepad.exe & exit

To set variables x, y, and z to values if the variable 'a' equals blah.

IF "%a%"=="blah" (set x=1) & (set y=2) & (set z=3)

Hope that helps!

Ternary operator in AngularJS templates

Update: Angular 1.1.5 added a ternary operator, this answer is correct only to versions preceding 1.1.5. For 1.1.5 and later, see the currently accepted answer.

Before Angular 1.1.5:

The form of a ternary in angularjs is:

((condition) && (answer if true) || (answer if false))

An example would be:

<ul class="nav">
    <li>
        <a   href="#/page1" style="{{$location.path()=='/page2' && 'color:#fff;' || 'color:#000;'}}">Goals</a>
    </li>
    <li>
        <a   href="#/page2" style="{{$location.path()=='/page2' && 'color:#fff;' || 'color:#000;'}}">Groups</a>
    </li>
</ul>

or:

 <li  ng-disabled="currentPage == 0" ng-click="currentPage=0"  class="{{(currentPage == 0) && 'disabled' || ''}}"><a> << </a></li>

What tool to use to draw file tree diagram

The advice to use Graphviz is good: you can generate the dot file and it will do the hard work of measuring strings, doing the layout, etc. Plus it can output the graphs in lot of formats, including vector ones.

I found a Perl program doing precisely that, in a mailing list, but I just can't find it back! I copied the sample dot file and studied it, since I don't know much of this declarative syntax and I wanted to learn a bit more.

Problem: with latest Graphviz, I have errors (or rather, warnings, as the final diagram is generated), both in the original graph and the one I wrote (by hand). Some searches shown this error was found in old versions and disappeared in more recent versions. Looks like it is back.

I still give the file, maybe it can be a starting point for somebody, or maybe it is enough for your needs (of course, you still have to generate it).

digraph tree
{
  rankdir=LR;

  DirTree [label="Directory Tree" shape=box]

  a_Foo_txt [shape=point]
  f_Foo_txt [label="Foo.txt", shape=none]
  a_Foo_txt -> f_Foo_txt

  a_Foo_Bar_html [shape=point]
  f_Foo_Bar_html [label="Foo Bar.html", shape=none]
  a_Foo_Bar_html -> f_Foo_Bar_html

  a_Bar_png [shape=point]
  f_Bar_png [label="Bar.png", shape=none]
  a_Bar_png -> f_Bar_png

  a_Some_Dir [shape=point]
  d_Some_Dir [label="Some Dir", shape=ellipse]
  a_Some_Dir -> d_Some_Dir

  a_VBE_C_reg [shape=point]
  f_VBE_C_reg [label="VBE_C.reg", shape=none]
  a_VBE_C_reg -> f_VBE_C_reg

  a_P_Folder [shape=point]
  d_P_Folder [label="P Folder", shape=ellipse]
  a_P_Folder -> d_P_Folder

  a_Processing_20081117_7z [shape=point]
  f_Processing_20081117_7z [label="Processing-20081117.7z", shape=none]
  a_Processing_20081117_7z -> f_Processing_20081117_7z

  a_UsefulBits_lua [shape=point]
  f_UsefulBits_lua [label="UsefulBits.lua", shape=none]
  a_UsefulBits_lua -> f_UsefulBits_lua

  a_Graphviz [shape=point]
  d_Graphviz [label="Graphviz", shape=ellipse]
  a_Graphviz -> d_Graphviz

  a_Tree_dot [shape=point]
  f_Tree_dot [label="Tree.dot", shape=none]
  a_Tree_dot -> f_Tree_dot

  {
    rank=same;
    DirTree -> a_Foo_txt -> a_Foo_Bar_html -> a_Bar_png -> a_Some_Dir -> a_Graphviz [arrowhead=none]
  }
  {
    rank=same;
    d_Some_Dir -> a_VBE_C_reg -> a_P_Folder -> a_UsefulBits_lua [arrowhead=none]
  }
  {
    rank=same;
    d_P_Folder -> a_Processing_20081117_7z [arrowhead=none]
  }
  {
    rank=same;
    d_Graphviz -> a_Tree_dot [arrowhead=none]
  }
}

> dot -Tpng Tree.dot -o Tree.png
Error: lost DirTree a_Foo_txt edge
Error: lost a_Foo_txt a_Foo_Bar_html edge
Error: lost a_Foo_Bar_html a_Bar_png edge
Error: lost a_Bar_png a_Some_Dir edge
Error: lost a_Some_Dir a_Graphviz edge
Error: lost d_Some_Dir a_VBE_C_reg edge
Error: lost a_VBE_C_reg a_P_Folder edge
Error: lost a_P_Folder a_UsefulBits_lua edge
Error: lost d_P_Folder a_Processing_20081117_7z edge
Error: lost d_Graphviz a_Tree_dot edge

I will try another direction, using Cairo, which is also able to export a number of formats. It is more work (computing positions/offsets) but the structure is simple, shouldn't be too hard.

Remove a child with a specific attribute, in SimpleXML for PHP

Since I encountered the same fatal error as Gerry and I'm not familiar with DOM, I decided to do it like this:

$item = $xml->xpath("//seg[@id='A12']");
$page = $xml->xpath("/data");
$id = "A12";

if (  count($item)  &&  count($page) ) {
    $item = $item[0];
    $page = $page[0];

     // find the numerical index within ->children().
    $ch = $page->children();
    $ch_as_array = (array) $ch;

    if (  count($ch_as_array)  &&  isset($ch_as_array['seg'])  ) {
        $ch_as_array = $ch_as_array['seg'];
        $index_in_array = array_search($item, $ch_as_array);
        if (  ($index_in_array !== false)
          &&  ($index_in_array !== null)
          &&  isset($ch[$index_in_array])
          &&  ($ch[$index_in_array]['id'] == $id)  ) {

             // delete it!
            unset($ch[$index_in_array]);

            echo "<pre>"; var_dump($xml); echo "</pre>";
        }
    }  // end of ( if xml object successfully converted to array )
}  // end of ( valid item  AND  section )

Indirectly referenced from required .class file

I was getting this error:

The type com.ibm.portal.state.exceptions.StateException cannot be resolved. It is indirectly referenced from required .class files

Doing the following fixed it for me:

Properties -> Java build path -> Libraries -> Server Library[wps.base.v61]unbound -> Websphere Portal v6.1 on WAS 7 -> Finish -> OK

How can I switch my signed in user in Visual Studio 2013?

Execute VSWinExpress /resetuserdata, located in C:\Program Files (x86)\Microsoft Visual Studio 12.0, to reset the user credentials for Visual Studio 2013 Express.

Eslint: How to disable "unexpected console statement" in Node.js?

The following works with ESLint in VSCode if you want to disable the rule for just one line.

To disable the next line:

// eslint-disable-next-line no-console
console.log('hello world');

To disable the current line:

console.log('hello world'); // eslint-disable-line no-console

Sorting a DropDownList? - C#, ASP.NET

        List<ListItem> li = new List<ListItem>();
        foreach (ListItem list in DropDownList1.Items)
        {
            li.Add(list);
        }
        li.Sort((x, y) => string.Compare(x.Text, y.Text));
        DropDownList1.Items.Clear();
        DropDownList1.DataSource = li;
        DropDownList1.DataTextField = "Text";
        DropDownList1.DataValueField = "Value";
        DropDownList1.DataBind();

Display an image into windows forms

private void Form1_Load(object sender, EventArgs e)
    {
        PictureBox pb = new PictureBox();
        pb.Location = new Point(0, 0);
        pb.Size = new Size(150, 150);
        pb.Image = Image.FromFile("E:\\Wallpaper (204).jpg");
        pb.Visible = true;
        this.Controls.Add(pb);
    }

What does random.sample() method in python do?

According to documentation:

random.sample(population, k)

Return a k length list of unique elements chosen from the population sequence. Used for random sampling without replacement.

Basically, it picks k unique random elements, a sample, from a sequence:

>>> import random
>>> c = list(range(0, 15))
>>> c
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
>>> random.sample(c, 5)
[9, 2, 3, 14, 11]

random.sample works also directly from a range:

>>> c = range(0, 15)
>>> c
range(0, 15)
>>> random.sample(c, 5)
[12, 3, 6, 14, 10]

In addition to sequences, random.sample works with sets too:

>>> c = {1, 2, 4}
>>> random.sample(c, 2)
[4, 1]

However, random.sample doesn't work with arbitrary iterators:

>>> c = [1, 3]
>>> random.sample(iter(c), 5)
TypeError: Population must be a sequence or set.  For dicts, use list(d).

Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state

Solution with JavaScript debugging enabled

From the Chrome browser, go to: Settings>Advanced>System and disable "Continue running background apps when Google Chrome is closed".

IMPORTANT! The option above must be set for the correct Chrome User Profile!
Visual Studio has its own Chrome User Profile, preferences you set when using your "normal" Chrome browser wont have any affect on the Chrome browser launched from VS (with JS debugging enabled).

  1. Run your project from VS with "Enable JavaScript debugging..." enabled. The Chrome browser should open and you'll get the error in VS.
  2. Go back to the same instance of Chrome that VS started and disable "Continue running background apps when Google Chrome is closed" as explained above.
    If you don't have "Enable JavaScript debugging..." enabled/checked, the Chrome instance would use your Default User Profile and the error would persist.
  3. Stop and rerun your project, Chrome should load the project as expected without any errors and with JS debugging enabled.

Whenever you stop debugging, you must close the Chrome instance initiated by VS or the error will return the next time you run the project. If there are other Chrome instances, you can leave these open.

To make sure Chrome is using the correct User Profile, go to chrome://version/ by typing it in the url bar, then look at the value for Profile Path. On Windows, the correct value should look something like this:
"C:\Users\[UserName]\AppData\Local\Microsoft\VisualStudio\15.*\WebTools\ChromeUserData_*\Default"

If Chrome is using the browser default or if you're logged in to Chrome with an account, it will look something like this:
"C:\Users\[UserName]\AppData\Local\Google\Chrome\User Data\[ProfileName] OR Default"

Bonus note. If you use Chrome Extensions when debugging, these has to be installed when the VS Profile is active.

Mysql select distinct

You can use DISTINCT like that

mysql_query("SELECT DISTINCT(ticket_id), column1, column2, column3 
FROM temp_tickets 
ORDER BY ticket_id");

Get all inherited classes of an abstract class

typeof(AbstractDataExport).Assembly tells you an assembly your types are located in (assuming all are in the same).

assembly.GetTypes() gives you all types in that assembly or assembly.GetExportedTypes() gives you types that are public.

Iterating through the types and using type.IsAssignableFrom() gives you whether the type is derived.

How to replace all spaces in a string

VERY EASY:

just use this to replace all white spaces with -:

myString.replace(/ /g,"-")

Critical t values in R

The code you posted gives the critical value for a one-sided test (Hence the answer to you question is simply:

abs(qt(0.25, 40)) # 75% confidence, 1 sided (same as qt(0.75, 40))
abs(qt(0.01, 40)) # 99% confidence, 1 sided (same as qt(0.99, 40))

Note that the t-distribution is symmetric. For a 2-sided test (say with 99% confidence) you can use the critical value

abs(qt(0.01/2, 40)) # 99% confidence, 2 sided

What are the most common naming conventions in C?

You should also think about the order of the words to make the auto name completion easier.

A good practice: library name + module name + action + subject

If a part is not relevant just skip it, but at least a module name and an action always should be presented.

Examples:

  • function name: os_task_set_prio, list_get_size, avg_get
  • define (here usually no action part): OS_TASK_PRIO_MAX

Bootstrap how to get text to vertical align in a div container

HTML:

First, we will need to add a class to your text container so that we can access and style it accordingly.

<div class="col-xs-5 textContainer">
     <h3 class="text-left">Link up with other gamers all over the world who share the same tastes in games.</h3>
</div>

CSS:

Next, we will apply the following styles to align it vertically, according to the size of the image div next to it.

.textContainer { 
    height: 345px; 
    line-height: 340px;
}

.textContainer h3 {
    vertical-align: middle;
    display: inline-block;
}

All Done! Adjust the line-height and height on the styles above if you believe that it is still slightly out of align.

WORKING EXAMPLE

Catching "Maximum request length exceeded"

You can solve this by increasing the maximum request length and execution time out in your web.config:

-Please Clarify the maximum execution time out grater then 1200

<?xml version="1.0" encoding="utf-8"?> <configuration> <system.web> <httpRuntime maxRequestLength="102400" executionTimeout="1200" /> </system.web> </configuration>

What do the makefile symbols $@ and $< mean?

The $@ and $< are called automatic variables. The variable $@ represents the name of the target and $< represents the first prerequisite required to create the output file.
For example:

hello.o: hello.c hello.h
         gcc -c $< -o $@

Here, hello.o is the output file. This is what $@ expands to. The first dependency is hello.c. That's what $< expands to.

The -c flag generates the .o file; see man gcc for a more detailed explanation. The -o specifies the output file to create.

For further details, you can read this article about Linux Makefiles.

Also, you can check the GNU make manuals. It will make it easier to make Makefiles and to debug them.

If you run this command, it will output the makefile database:

make -p 

Slide div left/right using jQuery

The easiest way to do so is using jQuery and animate.css animation library.

Javascript

/* --- Show DIV --- */
$( '.example' ).removeClass( 'fadeOutRight' ).show().addClass( 'fadeInRight' );

/* --- Hide DIV --- */
$( '.example' ).removeClass( 'fadeInRight' ).addClass( 'fadeOutRight' );


HTML

<div class="example">Some text over here.</div>


Easy enough to implement. Just don't forget to include the animate.css file in the header :)

Generate a range of dates using SQL

A week from 6 months back

SELECT (date'2015-08-03' + (LEVEL-1)) AS DATES
 FROM DUAL 
 where ROWNUM < 8
 connect by level <= (sysdate-date'2015-08-03'); 

if you omit ROWNUM you get 50 rows only, independent of the value.

Block Comments in a Shell Script

You can use:

if [ 1 -eq 0 ]; then
  echo "The code that you want commented out goes here."
  echo "This echo statement will not be called."
fi

how to remove "," from a string in javascript

If you need a number greater than 999,999.00 you will have a problem.
These are only good for numbers less than 1 million, 1,000,000.
They only remove 1 or 2 commas.

Here the script that can remove up to 12 commas:

function uncomma(x) {
  var string1 = x;
  for (y = 0; y < 12; y++) {
    string1 = string1.replace(/\,/g, '');
  }
  return string1;
}

Modify that for loop if you need bigger numbers.

What is the correct format to use for Date/Time in an XML file

EDIT: This is bad advice. Use "o", as above. "s" does the wrong thing.

I always use this:

dateTime.ToUniversalTime().ToString("s");

This is correct if your schema looks like this:

<xs:element name="startdate" type="xs:dateTime"/>

Which would result in:

<startdate>2002-05-30T09:00:00</startdate>

You can get more information here: http://www.w3schools.com/xml/schema_dtypes_date.asp

Java getting the Enum name given the Enum Value

Here is the below code, it will return the Enum name from Enum value.

public enum Test {

    PLUS("Plus One"), MINUS("MinusTwo"), TIMES("MultiplyByFour"), DIVIDE(
            "DivideByZero");
    private String operationName;

    private Test(final String operationName) {
        setOperationName(operationName);
    }

    public String getOperationName() {
        return operationName;
    }

    public void setOperationName(final String operationName) {
        this.operationName = operationName;
    }

    public static Test getOperationName(final String operationName) {

        for (Test oprname : Test.values()) {
            if (operationName.equals(oprname.toString())) {
                return oprname;
            }
        }
        return null;
    }

    @Override
    public String toString() {
        return operationName;
    }
}

public class Main {
    public static void main(String[] args) {

        Test test = Test.getOperationName("Plus One");
        switch (test) {
        case PLUS:
            System.out.println("Plus.....");
            break;
        case MINUS:
            System.out.println("Minus.....");
            break;

        default:
            System.out.println("Nothing..");
            break;
        }
    }
}

I can't delete a remote master branch on git

To answer the question literally (since GitHub is not in the question title), also be aware of this post over on superuser. EDIT: Answer copied here in relevant part, slightly modified for clarity in square brackets:

You're getting rejected because you're trying to delete the branch that your origin has currently "checked out".

If you have direct access to the repo, you can just open up a shell [in the bare repo] directory and use good old git branch to see what branch origin is currently on. To change it to another branch, you have to use git symbolic-ref HEAD refs/heads/another-branch.

How to link to specific line number on github

Many editors (but also see the Commands section below) support linking to a file's line number or range on GitHub or BitBucket (or others). Here's a short list:

Atom

Open on GitHub

Emacs

git-link

Sublime Text

GitLink

Vim

gitlink-vim


Commands

  • git-link - Git subcommand for getting a repo-browser link to a git object
  • ghwd - Open the github URL that matches your shell's current branch and working directory

Android Reading from an Input stream efficiently

The problem in your code is that it's creating lots of heavy String objects, copying their contents and performing operations on them. Instead, you should use StringBuilder to avoid creating new String objects on each append and to avoid copying the char arrays. The implementation for your case would be something like this:

BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder total = new StringBuilder();
for (String line; (line = r.readLine()) != null; ) {
    total.append(line).append('\n');
}

You can now use total without converting it to String, but if you need the result as a String, simply add:

String result = total.toString();

I'll try to explain it better...

  • a += b (or a = a + b), where a and b are Strings, copies the contents of both a and b to a new object (note that you are also copying a, which contains the accumulated String), and you are doing those copies on each iteration.
  • a.append(b), where a is a StringBuilder, directly appends b contents to a, so you don't copy the accumulated string at each iteration.

How to use AND in IF Statement

I think you should append .value in IF statement:

If Cells(i, "A").Value <> "Miami" And Cells(i, "D").Value <> "Florida" Then
    Cells(i, "C").Value = "BA"
End IF

Convert a string to datetime in PowerShell

$invoice = "Jul-16"
[datetime]$newInvoice = "01-" + $invoice

$newInvoice.ToString("yyyy-MM-dd")

There you go, use a type accelerator, but also into a new var, if you want to use it elsewhere, use it like so: $newInvoice.ToString("yyyy-MM-dd")as $newInvoice will always be in the datetime format, unless you cast it as a string afterwards, but will lose the ability to perform datetime functions - adding days etc...

Find first element in a sequence that matches a predicate

To find first element in a sequence seq that matches a predicate:

next(x for x in seq if predicate(x))

Or (itertools.ifilter on Python 2):

next(filter(predicate, seq))

It raises StopIteration if there is none.


To return None if there is no such element:

next((x for x in seq if predicate(x)), None)

Or:

next(filter(predicate, seq), None)

Double border with different color

You can use the border and box-shadow properties along with CSS pseudo elements to achieve a triple-border sort of effect. See the example below for an idea of how to create three borders at the bottom of a div:

_x000D_
_x000D_
.triple-border:after {_x000D_
    content: " ";_x000D_
    display: block;_x000D_
    width: 100%;_x000D_
    background: #FFE962;_x000D_
    height: 9px;_x000D_
    padding-bottom: 8px;_x000D_
    border-bottom: 9px solid #A3C662;_x000D_
    box-shadow: -2px 11px 0 -1px #34b6af;_x000D_
}
_x000D_
<div class="triple-border">Triple border bottom with multiple colours</div>
_x000D_
_x000D_
_x000D_

You'll have to play around with the values to get the alignment correct. However, you can also achieve more flexibility, e.g. 4 borders if you put some of the attributes in the proper element rather than the pseudo selector.

Structs data type in php?

It seems that the struct datatype is commonly used in SOAP:

var_dump($client->__getTypes());

array(52) {
  [0] =>
  string(43) "struct Bank {\n string Code;\n string Name;\n}"
}

This is not a native PHP datatype!

It seems that the properties of the struct type referred to in SOAP can be accessed as a simple PHP stdClass object:

$some_struct = $client->SomeMethod();
echo 'Name: ' . $some_struct->Name;

Correct way to pass multiple values for same parameter name in GET request

I am describing a simple method which worked very smoothly in Python (Django Framework).

1. While sending the request, send the request like this

http://server/action?id=a,b

2. Now in my backend, I split the value received with a split function which always creates a list.

id_filter = id.split(',')

Example: So if I send two values in the request,

http://server/action?id=a,b

then the filter on the data is

id_filter = ['a', 'b']

If I send only one value in the request,

http://server/action?id=a

then the filter outcome is

id_filter = ['a']

3. To actually filter the data, I simply use the 'in' function

queryset = queryset.filter(model_id__in=id_filter)

which roughly speaking performs the SQL equivalent of

WHERE model_id IN ('a', 'b')

with the first request and,

WHERE model_id IN ('a')

with the second request.

This would work with more than 2 parameter values in the request as well !

JPA Hibernate One-to-One relationship

This should be working too using JPA 2.0 @MapsId annotation instead of Hibernate's GenericGenerator:

@Entity
public class Person {

    @Id
    @GeneratedValue
    public int id;

    @OneToOne
    @PrimaryKeyJoinColumn
    public OtherInfo otherInfo;

    rest of attributes ...
}

@Entity
public class OtherInfo {

    @Id
    public int id;

    @MapsId
    @OneToOne
    @JoinColumn(name="id")
    public Person person;

    rest of attributes ...
}

More details on this in Hibernate 4.1 documentation under section 5.1.2.2.7.

How can I use jQuery in Greasemonkey?

There's absolutely nothing wrong with including the entirety of jQuery within your Greasemonkey script. Just take the source, and place it at the top of your user script. No need to make a script tag, since you're already executing JavaScript!

The user only downloads the script once anyways, so size of script is not a big concern. In addition, if you ever want your Greasemonkey script to work in non-GM environments (such as Opera's GM-esque user scripts, or Greasekit on Safari), it'll help not to use GM-unique constructs such as @require.

Is there a GUI design app for the Tkinter / grid geometry?

Apart from the options already given in other answers, there's a current more active, recent and open-source project called pygubu.

This is the first description by the author taken from the github repository:

Pygubu is a RAD tool to enable quick & easy development of user interfaces for the python tkinter module.

The user interfaces designed are saved as XML, and by using the pygubu builder these can be loaded by applications dynamically as needed. Pygubu is inspired by Glade.


Pygubu hello world program is an introductory video explaining how to create a first project using Pygubu.

The following in an image of interface of the last version of pygubu designer on a OS X Yosemite 10.10.2:

enter image description here

I would definitely give it a try, and contribute to its development.

Python UTC datetime object's ISO format doesn't include Z (Zulu or Zero offset)

Pass a UTC timezone object to datetime.now() instead of using datetime.utcnow():

from datetime import datetime, timezone

datetime.now(timezone.utc)
>>> datetime.datetime(2020, 1, 8, 6, 6, 24, 260810, tzinfo=datetime.timezone.utc)

datetime.now(timezone.utc).isoformat()
>>> '2020-01-08T06:07:04.492045+00:00'

That looks good, so let's see what Django and dateutil think:

from django.utils.timezone import is_aware

is_aware(datetime.now(timezone.utc))
>>> True

from dateutil.parser import isoparse

is_aware(isoparse(datetime.now(timezone.utc).isoformat()))
>>> True

Note that you need to use isoparse() because the Python documentation for datetime.fromisoformat() says it "does not support parsing arbitrary ISO 8601 strings".

Okay, the Python datetime object and the ISO 8601 string are both UTC "aware". Now let's look at what JavaScript thinks of the datetime string. Borrowing from this answer we get:

let date= '2020-01-08T06:07:04.492045+00:00';
const dateParsed = new Date(Date.parse(date))

document.write(dateParsed);
document.write("\n");
// Tue Jan 07 2020 22:07:04 GMT-0800 (Pacific Standard Time)

document.write(dateParsed.toISOString());
document.write("\n");
// 2020-01-08T06:07:04.492Z

document.write(dateParsed.toUTCString());
document.write("\n");
// Wed, 08 Jan 2020 06:07:04 GMT

Notes:

I approached this problem with a few goals:

  • generate a UTC "aware" datetime string in ISO 8601 format
  • use only Python Standard Library functions for datetime object and string creation
  • validate the datetime object and string with the Django timezone utility function and the dateutil parser
  • use JavaScript functions to validate that the ISO 8601 datetime string is UTC aware

Note that this approach does not include a Z suffix and does not use utcnow(). But it's based on the recommendation in the Python documentation and it passes muster with both Django and JavaScript.

See also:

How do I push a new local branch to a remote Git repository and track it too?

You can do it in 2 steeps:

1. Use the checkout for create the local branch:

git checkout -b yourBranchName

Work with your Branch as you want.

2. Use the push command to autocreate the branch and send the code to the remote repository:

git push -u origin yourBanchName

There are mutiple ways to do this but I think that this way is really simple.

Accessing the web page's HTTP Headers in JavaScript

To get the headers as an object which is handier (improvement of Raja's answer):

var req = new XMLHttpRequest();
req.open('GET', document.location, false);
req.send(null);
var headers = req.getAllResponseHeaders().toLowerCase();
headers = headers.split(/\n|\r|\r\n/g).reduce(function(a, b) {
    if (b.length) {
        var [ key, value ] = b.split(': ');
        a[key] = value;
    }
    return a;
}, {});
console.log(headers);

Python RuntimeWarning: overflow encountered in long scalars

An easy way to overcome this problem is to use 64 bit type

list = numpy.array(list, dtype=numpy.float64)

CodeIgniter: How To Do a Select (Distinct Fieldname) MySQL Query

$record = '123';

$this->db->distinct();

$this->db->select('accessid');

$this->db->where('record', $record); 

$query = $this->db->get('accesslog');

then

$query->num_rows();

should go a long way towards it.

Excel: VLOOKUP that returns true or false?

You can use:

=IF(ISERROR(VLOOKUP(lookup value,table array,column no,FALSE)),"FALSE","TRUE")

how can I Update top 100 records in sql server

Note, the parentheses are required for UPDATE statements:

update top (100) table1 set field1 = 1

Git ignore file for Xcode projects

A Structure of a standerd .gitignore file for Xcode project >

.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
Icon?
ehthumbs.db
Thumbs.db
build/
*.pbxuser
!default.pbxuser
*.mode1v3
!default.mode1v3
*.mode2v3
!default.mode2v3
*.perspectivev3
!default.perspectivev3
!default.xcworkspace
xcuserdata
profile
*.moved-aside
DerivedData
.idea/

Replace spaces with dashes and make all letters lower-case

@CMS's answer is just fine, but I want to note that you can use this package: https://github.com/sindresorhus/slugify, which does it for you and covers many edge cases (i.e., German umlauts, Vietnamese, Arabic, Russian, Romanian, Turkish, etc.).

Heap vs Binary Search Tree (BST)

Insert all n elements from an array to BST takes O(n logn). n elemnts in an array can be inserted to a heap in O(n) time. Which gives heap a definite advantage

Print new output on same line

Lets take an example where you want to print numbers from 0 to n in the same line. You can do this with the help of following code.

n=int(raw_input())
i=0
while(i<n):
    print i,
    i = i+1

At input, n = 5

Output : 0 1 2 3 4 

How to round up integer division and have int result in Java?

long numberOfPages = new BigDecimal(resultsSize).divide(new BigDecimal(pageSize), RoundingMode.UP).longValue();

Sorting a Python list by two fields

employees.sort(key = lambda x:x[1])
employees.sort(key = lambda x:x[0])

We can also use .sort with lambda 2 times because python sort is in place and stable. This will first sort the list according to the second element, x[1]. Then, it will sort the first element, x[0] (highest priority).

employees[0] = Employee's Name
employees[1] = Employee's Salary

This is equivalent to doing the following: employees.sort(key = lambda x:(x[0], x[1]))

Unable to load AWS credentials from the /AwsCredentials.properties file on the classpath

Try this for the file format:

[default]
aws_access_key_id=<your access key>
aws_secret_access_key=<your secret access key>

I saved this file as ~/.aws/credentials with ProfileCredentialsProvider().

How can I use/create dynamic template to compile dynamic Component with Angular 2.0?

I must have arrived at the party late, none of the solutions here seemed helpful to me - too messy and felt like too much of a workaround.

What I ended up doing is using Angular 4.0.0-beta.6's ngComponentOutlet.

This gave me the shortest, simplest solution all written in the dynamic component's file.

  • Here is a simple example which just receives text and places it in a template, but obviously you can change according to your need:
import {
  Component, OnInit, Input, NgModule, NgModuleFactory, Compiler
} from '@angular/core';

@Component({
  selector: 'my-component',
  template: `<ng-container *ngComponentOutlet="dynamicComponent;
                            ngModuleFactory: dynamicModule;"></ng-container>`,
  styleUrls: ['my.component.css']
})
export class MyComponent implements OnInit {
  dynamicComponent;
  dynamicModule: NgModuleFactory<any>;

  @Input()
  text: string;

  constructor(private compiler: Compiler) {
  }

  ngOnInit() {
    this.dynamicComponent = this.createNewComponent(this.text);
    this.dynamicModule = this.compiler.compileModuleSync(this.createComponentModule(this.dynamicComponent));
  }

  protected createComponentModule (componentType: any) {
    @NgModule({
      imports: [],
      declarations: [
        componentType
      ],
      entryComponents: [componentType]
    })
    class RuntimeComponentModule
    {
    }
    // a module for just this Type
    return RuntimeComponentModule;
  }

  protected createNewComponent (text:string) {
    let template = `dynamically created template with text: ${text}`;

    @Component({
      selector: 'dynamic-component',
      template: template
    })
    class DynamicComponent implements OnInit{
       text: any;

       ngOnInit() {
       this.text = text;
       }
    }
    return DynamicComponent;
  }
}
  • Short explanation:
    1. my-component - the component in which a dynamic component is rendering
    2. DynamicComponent - the component to be dynamically built and it is rendering inside my-component

Don't forget to upgrade all the angular libraries to ^Angular 4.0.0

Hope this helps, good luck!

UPDATE

Also works for angular 5.

How to restrict UITextField to take only numbers in Swift?

While most of these solutions will work, be aware that in some localisations a decimals are separated with a "," and not a "."

The cleaner way to do this would be

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    let decimalCharacter = NSNumberFormatter().decimalSeparator
    let characterSet = NSMutableCharacterSet.decimalDigitCharacterSet()
    characterSet.addCharactersInString(decimalCharacter)

    return replacementString.rangeOfCharacterFromSet(characterSet.invertedSet) == nil
}

jQuery count child elements

var length = $('#selected ul').children('li').length
// or the same:
var length = $('#selected ul > li').length

You probably could also omit li in the children's selector.

See .length.

How to do a Postgresql subquery in select clause with join in from clause like SQL Server?

I am just answering here with the formatted version of the final sql I needed based on Bob Jarvis answer as posted in my comment above:

select n1.name, n1.author_id, cast(count_1 as numeric)/total_count
  from (select id, name, author_id, count(1) as count_1
          from names
          group by id, name, author_id) n1
inner join (select author_id, count(1) as total_count
              from names
              group by author_id) n2
  on (n2.author_id = n1.author_id)

Capitalize first letter. MySQL

Vincents excellent answer for Uppercase First Letter works great for the first letter only capitalization of an entire column string..

BUT what if you want to Uppercase the First Letter of EVERY word in the strings of a table column?

eg: "Abbeville High School"

I hadn't found an answer to this in Stackoverflow. I had to cobble together a few answers I found in Google to provide a solid solution to the above example. Its not a native function but a user created function which MySQL version 5+ allows.

If you have Super/Admin user status on MySQL or have a local mysql installation on your own computer you can create a FUNCTION (like a stored procedure) which sits in your database and can be used in all future SQL query on any part of the db.

The function I created allows me to use this new function I called "UC_Words" just like the built in native functions of MySQL so that I can update a complete column like this:

UPDATE Table_name
SET column_name = UC_Words(column_name) 

To insert the function code, I changed the MySQL standard delimiter(;) whilst creating the function, and then reset it back to normal after the function creation script. I also personally wanted the output to be in UTF8 CHARSET too.

Function creation =

DELIMITER ||  

CREATE FUNCTION `UC_Words`( str VARCHAR(255) ) RETURNS VARCHAR(255) CHARSET utf8 DETERMINISTIC  
BEGIN  
  DECLARE c CHAR(1);  
  DECLARE s VARCHAR(255);  
  DECLARE i INT DEFAULT 1;  
  DECLARE bool INT DEFAULT 1;  
  DECLARE punct CHAR(17) DEFAULT ' ()[]{},.-_!@;:?/';  
  SET s = LCASE( str );  
  WHILE i < LENGTH( str ) DO  
     BEGIN  
       SET c = SUBSTRING( s, i, 1 );  
       IF LOCATE( c, punct ) > 0 THEN  
        SET bool = 1;  
      ELSEIF bool=1 THEN  
        BEGIN  
          IF c >= 'a' AND c <= 'z' THEN  
             BEGIN  
               SET s = CONCAT(LEFT(s,i-1),UCASE(c),SUBSTRING(s,i+1));  
               SET bool = 0;  
             END;  
           ELSEIF c >= '0' AND c <= '9' THEN  
            SET bool = 0;  
          END IF;  
        END;  
      END IF;  
      SET i = i+1;  
    END;  
  END WHILE;  
  RETURN s;  
END ||  

DELIMITER ; 

This works a treat outputting Uppercase first letters on multiple words within a string.

Assuming your MySQL login username has sufficient privileges - if not, and you cant set up a temporary DB on your personal machine to convert your tables, then ask your shared hosting provider if they will set this function for you.

getting JRE system library unbound error in build path

This is like user3076252's answer, but you'll be choosing a different set of options:

  • Project > Properties > Java Build Path
  • Select Libraries tab > Alternate JRE > Installed JREs...
  • Click "Search." Unless you know the exact folder name, you should choose a drive to search.

It should find your unbound JRE, but this time with all the numbers in it's name (rather than unbound), and you can select it. It will take a while to search the drive, but you can stop it at any time, and it will save the results, if any.

Plotting dates on the x-axis with Python's matplotlib

As @KyssTao has been saying, help(dates.num2date) says that the x has to be a float giving the number of days since 0001-01-01 plus one. Hence, 19910102 is not 2/Jan/1991, because if you counted 19910101 days from 0001-01-01 you'd get something in the year 54513 or similar (divide by 365.25, number of days in a year).

Use datestr2num instead (see help(dates.datestr2num)):

new_x = dates.datestr2num(date) # where date is '01/02/1991'

How to group pandas DataFrame entries by date in a non-unique column

ecatmur's solution will work fine. This will be better performance on large datasets, though:

data.groupby(data['date'].map(lambda x: x.year))

Standard way to embed version into python package?

Also worth noting is that as well as __version__ being a semi-std. in python so is __version_info__ which is a tuple, in the simple cases you can just do something like:

__version__ = '1.2.3'
__version_info__ = tuple([ int(num) for num in __version__.split('.')])

...and you can get the __version__ string from a file, or whatever.

Is it possible to return empty in react render function?

Slightly off-topic but if you ever needed a class-based component that never renders anything and you are happy to use some yet-to-be-standardised ES syntax, you might want to go:

render = () => null

This is basically an arrow method that currently requires the transform-class-properties Babel plugin. React will not let you define a component without the render function and this is the most concise form satisfying this requirement that I can think of.

I'm currently using this trick in a variant of ScrollToTop borrowed from the react-router documentation. In my case, there's only a single instance of the component and it doesn't render anything, so a short form of "render null" fits nice in there.

How to parse a JSON file in swift?

I just wrote a class called JSON, which makes JSON handling in Swift as easy as JSON object in ES5.

Turn your swift object to JSON like so:

let obj:[String:AnyObject] = [
    "array": [JSON.null, false, 0, "",[],[:]],
    "object":[
        "null":   JSON.null,
        "bool":   true,
        "int":    42,
        "double": 3.141592653589793,
        "string": "a a\t?\n",
        "array":  [],
        "object": [:]
    ],
    "url":"http://blog.livedoor.com/dankogai/"
]

let json = JSON(obj)
json.toString()

...or string...

let json = JSON.parse("{\"array\":[...}")

...or URL.

let json = JSON.fromURL("http://api.dan.co.jp/jsonenv")
Tree Traversal

Just traverse elements via subscript:

json["object"]["null"].asNull       // NSNull()
// ...
json["object"]["string"].asString   // "a a\t?\n"
json["array"][0].asNull             // NSNull()
json["array"][1].asBool             // false
// ...

Just like SwiftyJSON you don't worry if the subscripted entry does not exist.

if let b = json["noexistent"][1234567890]["entry"].asBool {
    // ....
} else {
    let e = json["noexistent"][1234567890]["entry"].asError
    println(e)
}

If you are tired of subscripts, add your scheme like so:

//// schema by subclassing
class MyJSON : JSON {
    init(_ obj:AnyObject){ super.init(obj) }
    init(_ json:JSON)  { super.init(json) }
    var null  :NSNull? { return self["null"].asNull }
    var bool  :Bool?   { return self["bool"].asBool }
    var int   :Int?    { return self["int"].asInt }
    var double:Double? { return self["double"].asDouble }
    var string:String? { return self["string"].asString }
}

And you go:

let myjson = MyJSON(obj)
myjson.object.null
myjson.object.bool
myjson.object.int
myjson.object.double
myjson.object.string
// ...

Hope you like it.

With the new xCode 7.3+ its important to add your domain to the exception list (How can I add NSAppTransportSecurity to my info.plist file?), refer to this posting for instructions, otherwise you will get a transport authority error.

Automatically get loop index in foreach loop in Perl

Well, there is this way:

use List::Rubyish;

$list = List::Rubyish->new( [ qw<a b c> ] );
$list->each_index( sub { say "\$_=$_" } );

See List::Rubyish.

How do I bind a List<CustomObject> to a WPF DataGrid?

You dont need to give column names manually in xaml. Just set AutoGenerateColumns property to true and your list will be automatically binded to DataGrid. refer code. XAML Code:

<Grid>
    <DataGrid x:Name="MyDatagrid" AutoGenerateColumns="True" Height="447" HorizontalAlignment="Left" Margin="20,85,0,0" VerticalAlignment="Top" Width="799"  ItemsSource="{Binding Path=ListTest, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"  CanUserAddRows="False"> </Grid>

C#

Public Class Test 
{
    public string m_field1_Test{get;set;}
    public string m_field2_Test { get; set; }
    public Test()
    {
        m_field1_Test = "field1";
        m_field2_Test = "field2";
    }
    public MainWindow()
    {

        listTest = new List<Test>();

        for (int i = 0; i < 10; i++)
        {
            obj = new Test();
            listTest.Add(obj);

        }

        this.MyDatagrid.ItemsSource = ListTest;

        InitializeComponent();

    }

Python Anaconda - How to Safely Uninstall

For windows

  • Install anaconda-clean module using

    conda install anaconda-clean
    

    then, run the following command to delete files step by step:

    anaconda-clean
    

    Or, just run following command to delete them all-

    anaconda-clean --yes
    
  • After this Open Control Panel> Programs> Uninstall Program, here uninstall that python for which publisher is Anaconda.

  • Now, you can remove anaconda/scripts and /anaconda/ from PATH variable.

Hope, it helps.

JSON parse error: Can not construct instance of java.time.LocalDate: no String-argument constructor/factory method to deserialize from String value

Well, what I do on every project is a mix of the options above.

First, add the jsr310 dependency:

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
</dependency>

Important detail: put this dependency on the top of your depedencies list. I already see a project where the Localdate error persists even with this dependency on the pom.xml. But changing the order of the depedency the error was gone.

On your /src/main/resources/application.yml file, setup the write-dates-as-timestamps property:

spring:
  jackson:
    serialization:
      write-dates-as-timestamps: false

And create a ObjectMapper bean as this:

@Configuration
public class WebConfigurer {

    @Bean
    @Primary
    public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.build();
        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        return objectMapper;
    }

}

Following this configuration, the conversion always work on Spring Boot 1.5.x without any error.

Bonus: Spring AMQP Queue configuration

Working with Spring AMQP, pay attention if you have a new instance of Jackson2JsonMessageConverter (common thing when creating a SimpleRabbitListenerContainerFactory). You need to pass the ObjectMapper bean to it, like:

Jackson2JsonMessageConverter converter = new Jackson2JsonMessageConverter(objectMapper);

Otherwise, you will receive the same error.

Printing long int value in C

To take input " long int " and output " long int " in C is :

long int n;
scanf("%ld", &n);
printf("%ld", n);

To take input " long long int " and output " long long int " in C is :

long long int n;
scanf("%lld", &n);
printf("%lld", n);

Hope you've cleared..

How to disable Hyper-V in command line?

Open command prompt as admin and write :

bcdedit /set hypervisorlaunchtype off

(Deep) copying an array using jQuery

Everything in JavaScript is pass by reference, so if you want a true deep copy of the objects in the array, the best method I can think of is to serialize the entire array to JSON and then de-serialize it back.

How to close the command line window after running a batch file?

Your code is absolutely fine. It just needs "exit 0" for a cleaner exit.

 tncserver.exe C:\Work -p4 -b57600 -r -cFE -tTNC426B
 exit 0

Joining two lists together

See this link

public class ProductA
{ 
public string Name { get; set; }
public int Code { get; set; }
}

public class ProductComparer : IEqualityComparer<ProductA>
{

public bool Equals(ProductA x, ProductA y)
{
    //Check whether the objects are the same object. 
    if (Object.ReferenceEquals(x, y)) return true;

    //Check whether the products' properties are equal. 
    return x != null && y != null && x.Code.Equals(y.Code) && x.Name.Equals(y.Name);
    }

public int GetHashCode(ProductA obj)
{
    //Get hash code for the Name field if it is not null. 
    int hashProductName = obj.Name == null ? 0 : obj.Name.GetHashCode();

    //Get hash code for the Code field. 
    int hashProductCode = obj.Code.GetHashCode();

    //Calculate the hash code for the product. 
    return hashProductName ^ hashProductCode;
}
}


    ProductA[] store1 = { new ProductA { Name = "apple", Code = 9 }, 
                   new ProductA { Name = "orange", Code = 4 } };

    ProductA[] store2 = { new ProductA { Name = "apple", Code = 9 }, 
                   new ProductA { Name = "lemon", Code = 12 } };

//Get the products from the both arrays //excluding duplicates.

IEnumerable<ProductA> union =
  store1.Union(store2);

foreach (var product in union)
    Console.WriteLine(product.Name + " " + product.Code);

/*
    This code produces the following output:

    apple 9
    orange 4
    lemon 12
*/

Php multiple delimiters in explode

Try about using:

$output = preg_split('/ (@|vs) /', $input);

error::make_unique is not a member of ‘std’

If you have latest compiler, you can change the following in your build settings:

 C++ Language Dialect    C++14[-std=c++14]

This works for me.

PostgreSQL: How to make "case-insensitive" query

The most common approach is to either lowercase or uppercase the search string and the data. But there are two problems with that.

  1. It works in English, but not in all languages. (Maybe not even in most languages.) Not every lowercase letter has a corresponding uppercase letter; not every uppercase letter has a corresponding lowercase letter.
  2. Using functions like lower() and upper() will give you a sequential scan. It can't use indexes. On my test system, using lower() takes about 2000 times longer than a query that can use an index. (Test data has a little over 100k rows.)

There are at least three less frequently used solutions that might be more effective.

  1. Use the citext module, which mostly mimics the behavior of a case-insensitive data type. Having loaded that module, you can create a case-insensitive index by CREATE INDEX ON groups (name::citext);. (But see below.)
  2. Use a case-insensitive collation. This is set when you initialize a database. Using a case-insensitive collation means you can accept just about any format from client code, and you'll still return useful results. (It also means you can't do case-sensitive queries. Duh.)
  3. Create a functional index. Create a lowercase index by using CREATE INDEX ON groups (LOWER(name));. Having done that, you can take advantage of the index with queries like SELECT id FROM groups WHERE LOWER(name) = LOWER('ADMINISTRATOR');, or SELECT id FROM groups WHERE LOWER(name) = 'administrator'; You have to remember to use LOWER(), though.

The citext module doesn't provide a true case-insensitive data type. Instead, it behaves as if each string were lowercased. That is, it behaves as if you had called lower() on each string, as in number 3 above. The advantage is that programmers don't have to remember to lowercase strings. But you need to read the sections "String Comparison Behavior" and "Limitations" in the docs before you decide to use citext.

How to execute a program or call a system command from Python

As an example (in Linux):

import subprocess
subprocess.run('mkdir test.dir', shell=True)

This creates test.dir in the current directory. Note that this also works:

import subprocess
subprocess.call('mkdir test.dir', shell=True)

The equivalent code using os.system is:

import os
os.system('mkdir test.dir')

Best practice would be to use subprocess instead of os, with .run favored over .call. All you need to know about subprocess is here. Also, note that all Python documentation is available for download from here. I downloaded the PDF packed as .zip. I mention this because there's a nice overview of the os module in tutorial.pdf (page 81). Besides, it's an authoritative resource for Python coders.

Matrix multiplication using arrays

import java.util.*; public class Mult {

public static int[][] C;

public static void main(String[] args) {

    Scanner s = new Scanner(System.in);

    System.out.println("Enter Row of Matrix A");
    int Rowa = s.nextInt();

    System.out.println("Enter Column of Matrix A");
    int Cola = s.nextInt();

    System.out.println("Enter Row of Matrix B");
    int Rowb = s.nextInt();

    System.out.println("Enter Column of Matrix B");
    int Colb = s.nextInt();

    int[][] A = new int[Rowa][Cola];
    int[][] B = new int[Rowb][Colb];

    C= new int[Rowa][Colb];
    //int[][] C = new int;
    System.out.println("Enter Values of Matrix A");

    for(int i =0 ; i< A.length ; i++) {
        for(int j = 0 ; j<A.length;j++) {
            A[i][j] = s.nextInt();
        }

    }

    System.out.println("Enter Values of Matrix B");

    for(int i =0 ; i< B.length ; i++) {
        for(int j = 0 ; j<B.length;j++) {
            B[i][j] = s.nextInt();
        }
    }




    if(Cola==Rowb) {
        for(int i = 0;i < A.length;i++){
              for(int j = 0;j < A.length;j++){
                 C[i][j]=0;
                 for(int k = 0;k < B.length;k++){
                    C[i][j] += A[i][k] * B[k][j];
                 }
              }
           }
    }
    else {
        System.out.println("Cannot multiply");
    }









    // Printing matrix A
    /*
    for(int i =0 ; i< A.length ; i++) {
        for(int j = 0 ; j<A.length;j++) {
        System.out.print(A[i][j]+ "\t");
        }
        System.out.println();
    }
    */

    for(int i =0 ; i< A.length ; i++) {
        for(int j = 0 ; j<A.length;j++) {
        System.out.print(C[i][j]+ "\t");
        }
        System.out.println();
    }

}

}

Best way to check for nullable bool in a condition expression (if ...)

Another way is to use constant pattern matching:

if (nullableBool is true) {}
if (nullableBool is false) {}
if (nullableBool is null) {}

Unlike the operator ==, when reading the code, this will distinguish the nullable type check from ordinary "code with a smell".

Unmount the directory which is mounted by sshfs in Mac

If you have a problems with fusermount command you can kill the process :

ps -ax | grep "sshfs"

Installation of VB6 on Windows 7 / 8 / 10

VB6 Installs just fine on Windows 7 (and Windows 8 / Windows 10) with a few caveats.

Here is how to install it:

  • Before proceeding with the installation process below, create a zero-byte file in C:\Windows called MSJAVA.DLL. The setup process will look for this file, and if it doesn't find it, will force an installation of old, old Java, and require a reboot. By creating the zero-byte file, the installation of moldy Java is bypassed, and no reboot will be required.
  • Turn off UAC.
  • Insert Visual Studio 6 CD.
  • Exit from the Autorun setup.
  • Browse to the root folder of the VS6 CD.
  • Right-click SETUP.EXE, select Run As Administrator.
  • On this and other Program Compatibility Assistant warnings, click Run Program.
  • Click Next.
  • Click "I accept agreement", then Next.
  • Enter name and company information, click Next.
  • Select Custom Setup, click Next.
  • Click Continue, then Ok.
  • Setup will "think to itself" for about 2 minutes. Processing can be verified by starting Task Manager, and checking the CPU usage of ACMSETUP.EXE.
  • On the options list, select the following:
    • Microsoft Visual Basic 6.0
    • ActiveX
    • Data Access
    • Graphics
    • All other options should be unchecked.
  • Click Continue, setup will continue.
  • Finally, a successful completion dialog will appear, at which click Ok. At this point, Visual Basic 6 is installed.
  • If you do not have the MSDN CD, clear the checkbox on the next dialog, and click next. You'll be warned of the lack of MSDN, but just click Yes to accept.
  • Click Next to skip the installation of Installshield. This is a really old version you don't want anyway.
  • Click Next again to skip the installation of BackOffice, VSS, and SNA Server. Not needed!
  • On the next dialog, clear the checkbox for "Register Now", and click Finish.
  • The wizard will exit, and you're done. You can find VB6 under Start, All Programs, Microsoft Visual Studio 6. Enjoy!
  • Turn On UAC again

  • You might notice after successfully installing VB6 on Windows 7 that working in the IDE is a bit, well, sluggish. For example, resizing objects on a form is a real pain.
  • After installing VB6, you'll want to change the compatibility settings for the IDE executable.
  • Using Windows Explorer, browse the location where you installed VB6. By default, the path is C:\Program Files\Microsoft Visual Studio\VB98\
  • Right click the VB6.exe program file, and select properties from the context menu.
  • Click on the Compatibility tab.
  • Place a check in each of these checkboxes:
  • Run this program in compatibility mode for Windows XP (Service Pack 3)
    • Disable Visual Themes
    • Disable Desktop Composition
    • Disable display scaling on high DPI settings
    • If you have UAC turned on, it is probably advisable to check the 'Run this program as an Administrator' box

After changing these settings, fire up the IDE, and things should be back to normal, and the IDE is no longer sluggish.

Edit: Updated dead link to point to a different page with the same instructions

Edit: Updated the answer with the actual instructions in the post as the link kept dying

MySql with JAVA error. The last packet sent successfully to the server was 0 milliseconds ago

Try the following suggestions:

  1. Your machine may have a static IP; map this IP to the hosts file as localhost.
  2. Try to log in from your computer or within the network via mysql command; if login is successful, it means that MySQL runs fine.

Which data structures and algorithms book should I buy?

Introduction to Algorithms by Cormen et. al. is a standard introductory algorithms book, and is used by many universities, including my own. It has pretty good coverage and is very approachable.

And anything by Robert Sedgewick is good too.

Reset select value to default

One nice clean way is to add a data-default attribute to the select

<select id="my_select" data-default="b">
...
</select>

An then the code is really simple:

$("#reset").on("click", function () {
    var $select = $('#my_select');
    $select.val($select.data('default'));
});

Live example: http://jsfiddle.net/T8sCf/7/

Is there a function to round a float in C or do I need to write my own?

To print a rounded value, @Matt J well answers the question.

float x = 45.592346543;
printf("%0.1f\n", x);  // 45.6

As most floating point (FP) is binary based, exact rounding to one decimal place is not possible when the mathematically correct answer is x.1, x.2, ....

To convert the FP number to the nearest 0.1 is another matter.

Overflow: Approaches that first scale by 10 (or 100, 1000, etc) may overflow for large x.

float round_tenth1(float x) {
  x = x * 10.0f;
  ...
}

Double rounding: Adding 0.5f and then using floorf(x*10.0f + 0.5f)/10.0 returns the wrong result when the intermediate sum x*10.0f + 0.5f rounds up to a new integer.

// Fails to round 838860.4375 correctly, comes up with 838860.5 
// 0.4499999880790710449 fails as it rounds to 0.5
float round_tenth2(float x) {
  if (x < 0.0) {
    return ceilf(x*10.0f + 0.5f)/10.0f;
  }
  return floorf(x*10.0f + 0.5f)/10.0f;
}

Casting to int has the obvious problem when float x is much greater than INT_MAX.


Using roundf() and family, available in <math.h> is the best approach.

float round_tenthA(float x) {
  double x10 = 10.0 * x;
  return (float) (round(x10)/10.0);
}

To avoid using double, simply test if the number needs rounding.

float round_tenthB(float x) {
  const float limit = 1.0/FLT_EPSILON;
  if (fabsf(x) < limit) {
    return roundf(x*10.0f)/10.0f;
  }
  return x;
}

How do I execute a program from Python? os.system fails due to spaces in path

import win32api # if active state python is installed or install pywin32 package seperately

try: win32api.WinExec('NOTEPAD.exe') # Works seamlessly
except: pass

Error You must specify a region when running command aws ecs list-container-instances

I think you need to use for example:

aws ecs list-container-instances --cluster default --region us-east-1

This depends of your region of course.

Convert string to float?

String s = "3.14";
float f = Float.parseFloat(s);

Apache POI Excel - how to configure columns to be expanded?

For Excel POI:

sheetName.autoSizeColumn(cellnum); 

How can I get the request URL from a Java Filter?

Is this what you're looking for?

if (request instanceof HttpServletRequest) {
 String url = ((HttpServletRequest)request).getRequestURL().toString();
 String queryString = ((HttpServletRequest)request).getQueryString();
}

To Reconstruct:

System.out.println(url + "?" + queryString);

Info on HttpServletRequest.getRequestURL() and HttpServletRequest.getQueryString().