Programs & Examples On #Video encoding

This tag should be used for questions related with programmatically handling of video encoding in any format. For questions related to trimming and modifying videos use [video-editing], and [video-processing] for questions related to processing videos with filtering video frames.

What is the difference between H.264 video and MPEG-4 video?

They are names for the same standard from two different industries with different naming methods, the guys who make & sell movies and the guys who transfer the movies over the internet. Since 2003: "MPEG 4 Part 10" = "H.264" = "AVC". Before that the relationship was a little looser in that they are not equal but an "MPEG 4 Part 2" decoder can render a stream that's "H.263". The Next standard is "MPEG H Part 2" = "H.265" = "HEVC"

Using ffmpeg to encode a high quality video

Make sure the PNGs are fully opaque before creating the video

e.g. with imagemagick, give them a black background:

convert 0.png -background black -flatten +matte 0_opaque.png

From my tests, no bitrate or codec is sufficient to make the video look good if you feed ffmpeg PNGs with transparency

Make a number a percentage

var percent = Math.floor(100 * number1 / number2 - 100) + ' %';

How to align the text middle of BUTTON

I think you can use Padding like: Hope this one can help you.

.loginButton {
    background:url(images/loginBtn-center.jpg) repeat-x;
    width:175px;
    height:65px;
    margin:20px auto;
    border-radius:10px;
    -webkit-border-radius:10px;
    box-shadow:0 1px 2px #5e5d5b;
    <!--Using padding to align text in box or image-->
    padding: 3px 2px;
}

Is it better to return null or empty collection?

Returning an empty collection is better in most cases.

The reason for that is convenience of implementation of the caller, consistent contract, and easier implementation.

If a method returns null to indicate empty result, the caller must implement a null checking adapter in addition to enumeration. This code is then duplicated in various callers, so why not to put this adapter inside the method so it could be reused.

A valid usage of null for IEnumerable might be an indication of absent result, or an operation failure, but in this case other techniques should be considered, such as throwing an exception.

using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;

namespace StackOverflow.EmptyCollectionUsageTests.Tests
{
    /// <summary>
    /// Demonstrates different approaches for empty collection results.
    /// </summary>
    class Container
    {
        /// <summary>
        /// Elements list.
        /// Not initialized to an empty collection here for the purpose of demonstration of usage along with <see cref="Populate"/> method.
        /// </summary>
        private List<Element> elements;

        /// <summary>
        /// Gets elements if any
        /// </summary>
        /// <returns>Returns elements or empty collection.</returns>
        public IEnumerable<Element> GetElements()
        {
            return elements ?? Enumerable.Empty<Element>();
        }

        /// <summary>
        /// Initializes the container with some results, if any.
        /// </summary>
        public void Populate()
        {
            elements = new List<Element>();
        }

        /// <summary>
        /// Gets elements. Throws <see cref="InvalidOperationException"/> if not populated.
        /// </summary>
        /// <returns>Returns <see cref="IEnumerable{T}"/> of <see cref="Element"/>.</returns>
        public IEnumerable<Element> GetElementsStrict()
        {
            if (elements == null)
            {
                throw new InvalidOperationException("You must call Populate before calling this method.");
            }

            return elements;
        }

        /// <summary>
        /// Gets elements, empty collection or nothing.
        /// </summary>
        /// <returns>Returns <see cref="IEnumerable{T}"/> of <see cref="Element"/>, with zero or more elements, or null in some cases.</returns>
        public IEnumerable<Element> GetElementsInconvenientCareless()
        {
            return elements;
        }

        /// <summary>
        /// Gets elements or nothing.
        /// </summary>
        /// <returns>Returns <see cref="IEnumerable{T}"/> of <see cref="Element"/>, with elements, or null in case of empty collection.</returns>
        /// <remarks>We are lucky that elements is a List, otherwise enumeration would be needed.</remarks>
        public IEnumerable<Element> GetElementsInconvenientCarefull()
        {
            if (elements == null || elements.Count == 0)
            {
                return null;
            }
            return elements;
        }
    }

    class Element
    {
    }

    /// <summary>
    /// http://stackoverflow.com/questions/1969993/is-it-better-to-return-null-or-empty-collection/
    /// </summary>
    class EmptyCollectionTests
    {
        private Container container;

        [SetUp]
        public void SetUp()
        {
            container = new Container();
        }

        /// <summary>
        /// Forgiving contract - caller does not have to implement null check in addition to enumeration.
        /// </summary>
        [Test]
        public void UseGetElements()
        {
            Assert.AreEqual(0, container.GetElements().Count());
        }

        /// <summary>
        /// Forget to <see cref="Container.Populate"/> and use strict method.
        /// </summary>
        [Test]
        [ExpectedException(typeof(InvalidOperationException))]
        public void WrongUseOfStrictContract()
        {
            container.GetElementsStrict().Count();
        }

        /// <summary>
        /// Call <see cref="Container.Populate"/> and use strict method.
        /// </summary>
        [Test]
        public void CorrectUsaOfStrictContract()
        {
            container.Populate();
            Assert.AreEqual(0, container.GetElementsStrict().Count());
        }

        /// <summary>
        /// Inconvenient contract - needs a local variable.
        /// </summary>
        [Test]
        public void CarefulUseOfCarelessMethod()
        {
            var elements = container.GetElementsInconvenientCareless();
            Assert.AreEqual(0, elements == null ? 0 : elements.Count());
        }

        /// <summary>
        /// Inconvenient contract - duplicate call in order to use in context of an single expression.
        /// </summary>
        [Test]
        public void LameCarefulUseOfCarelessMethod()
        {
            Assert.AreEqual(0, container.GetElementsInconvenientCareless() == null ? 0 : container.GetElementsInconvenientCareless().Count());
        }

        [Test]
        public void LuckyCarelessUseOfCarelessMethod()
        {
            // INIT
            var praySomeoneCalledPopulateBefore = (Action)(()=>container.Populate());
            praySomeoneCalledPopulateBefore();

            // ACT //ASSERT
            Assert.AreEqual(0, container.GetElementsInconvenientCareless().Count());
        }

        /// <summary>
        /// Excercise <see cref="ArgumentNullException"/> because of null passed to <see cref="Enumerable.Count{TSource}(System.Collections.Generic.IEnumerable{TSource})"/>
        /// </summary>
        [Test]
        [ExpectedException(typeof(ArgumentNullException))]
        public void UnfortunateCarelessUseOfCarelessMethod()
        {
            Assert.AreEqual(0, container.GetElementsInconvenientCareless().Count());
        }

        /// <summary>
        /// Demonstrates the client code flow relying on returning null for empty collection.
        /// Exception is due to <see cref="Enumerable.First{TSource}(System.Collections.Generic.IEnumerable{TSource})"/> on an empty collection.
        /// </summary>
        [Test]
        [ExpectedException(typeof(InvalidOperationException))]
        public void UnfortunateEducatedUseOfCarelessMethod()
        {
            container.Populate();
            var elements = container.GetElementsInconvenientCareless();
            if (elements == null)
            {
                Assert.Inconclusive();
            }
            Assert.IsNotNull(elements.First());
        }

        /// <summary>
        /// Demonstrates the client code is bloated a bit, to compensate for implementation 'cleverness'.
        /// We can throw away the nullness result, because we don't know if the operation succeeded or not anyway.
        /// We are unfortunate to create a new instance of an empty collection.
        /// We might have already had one inside the implementation,
        /// but it have been discarded then in an effort to return null for empty collection.
        /// </summary>
        [Test]
        public void EducatedUseOfCarefullMethod()
        {
            Assert.AreEqual(0, (container.GetElementsInconvenientCarefull() ?? Enumerable.Empty<Element>()).Count());
        }
    }
}

Opening a CHM file produces: "navigation to the webpage was canceled"

other way is to use different third party software. This link shows more third party software to view chm files...

I tried with SumatraPDF and it work fine.

Instantiating a generic type

You cannot do new T() due to type erasure. The default constructor can only be

public Navigation() {     this("", "", null); } 

​ You can create other constructors to provide default values for trigger and description. You need an concrete object of T.

automatically execute an Excel macro on a cell change

I prefer this way, not using a cell but a range

    Dim cell_to_test As Range, cells_changed As Range

    Set cells_changed = Target(1, 1)
    Set cell_to_test = Range( RANGE_OF_CELLS_TO_DETECT )

    If Not Intersect(cells_changed, cell_to_test) Is Nothing Then 
       Macro
    End If

How to scroll the page when a modal dialog is longer than the screen?

simple way you can do this by adding this css So, you just added this to CSS:

.modal-body {
position: relative;
padding: 20px;
height: 200px;
overflow-y: scroll;
}

and it's working!

Timestamp Difference In Hours for PostgreSQL

You can use the "extract" or "date_part" functions on intervals as well as timestamps, but I don't think that does what you want. For example, it gives 3 for an interval of '2 days, 3 hours'. However, you can convert an interval to a number of seconds by specifying 'epoch' as the time element you want: extract(epoch from '2 days, 3 hours'::interval) returns 183600 (which you then divide by 3600 to convert seconds to hours).

So, putting this all together, you get basically Michael's answer: extract(epoch from timestamp1 - timestamp2)/3600. Since you don't seem to care about which timestamp precedes which, you probably want to wrap that in abs:

SELECT abs(extract(epoch from timestamp1 - timestamp2)/3600)

Magento: Set LIMIT on collection

The way to do was looking at the code in code/core/Mage/Catalog/Model/Resource/Category/Flat/Collection.php at line 380 in Magento 1.7.2 on the function setPage($pageNum, $pageSize)

 $collection = Mage::getModel('model')
     ->getCollection()
     ->setCurPage(2) // 2nd page
     ->setPageSize(10); // 10 elements per pages

I hope this will help someone.

Test if registry value exists

$regkeypath= "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" 
$value1 = (Get-ItemProperty $regkeypath -ErrorAction SilentlyContinue).Zoiper -eq $null 
If ($value1 -eq $False) {
Write-Host "Value Exist"
} Else {
Write-Host "The value does not exist"
}

How to use absolute path in twig functions

You probably want to use the assets_base_urls configuration.

framework:
    templating:
        assets_base_urls:
            http:   [http://www.website.com]
            ssl:   [https://www.website.com]

http://symfony.com/doc/current/reference/configuration/framework.html#assets


Note that the configuration is different since Symfony 2.7:

framework:
    # ...
    assets:
        base_urls:
            - 'http://cdn.example.com/'

Tools: replace not replacing in Android manifest

You can replace those in your Manifest application tag:

<application
    tools:replace="android:icon, android:label, android:theme, android:name,android:allowBackup"
android:allowBackup="false"...>

and will work for you.

How to send redirect to JSP page in Servlet

Look at the HttpServletResponse#sendRedirect(String location) method.

Use it as:

response.sendRedirect(request.getContextPath() + "/welcome.jsp")

Alternatively, look at HttpServletResponse#setHeader(String name, String value) method.

The redirection is set by adding the location header:

response.setHeader("Location", request.getContextPath() + "/welcome.jsp");

How do I import a .bak file into Microsoft SQL Server 2012?

Not sure why they removed the option to just right click on the database and restore like you could in SQL Server Management Studio 2008 and earlier, but as mentioned above you can restore from a .BAK file with:

RESTORE DATABASE YourDB FROM DISK = 'D:BackUpYourBaackUpFile.bak' WITH REPLACE

But you will want WITH REPLACE instead of WITH RESTORE if your moving it from one server to another.

Https Connection Android

Any of this answers didn't work for me so here is code which trust any certificates.

import java.io.IOException;

    import java.net.Socket;
    import java.security.KeyManagementException;
    import java.security.KeyStoreException;
    import java.security.NoSuchAlgorithmException;
    import java.security.UnrecoverableKeyException;
    import java.security.cert.CertificateException;
    import java.security.cert.X509Certificate;

    import javax.net.ssl.SSLContext;
    import javax.net.ssl.TrustManager;
    import javax.net.ssl.X509TrustManager;

    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.conn.scheme.PlainSocketFactory;
    import org.apache.http.conn.scheme.Scheme;
    import org.apache.http.conn.scheme.SchemeRegistry;
    import org.apache.http.conn.ssl.SSLSocketFactory;
    import org.apache.http.conn.ssl.X509HostnameVerifier;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
    import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

    public class HttpsClientBuilder {
        public static DefaultHttpClient getBelieverHttpsClient() {

            DefaultHttpClient client = null;

            SchemeRegistry Current_Scheme = new SchemeRegistry();
            Current_Scheme.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
            try {
                Current_Scheme.register(new Scheme("https", new Naive_SSLSocketFactory(), 8443));
            } catch (KeyManagementException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (UnrecoverableKeyException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (KeyStoreException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            HttpParams Current_Params = new BasicHttpParams();
            int timeoutConnection = 8000;
            HttpConnectionParams.setConnectionTimeout(Current_Params, timeoutConnection);
            int timeoutSocket = 10000;
            HttpConnectionParams.setSoTimeout(Current_Params, timeoutSocket);
            ThreadSafeClientConnManager Current_Manager = new ThreadSafeClientConnManager(Current_Params, Current_Scheme);
            client = new DefaultHttpClient(Current_Manager, Current_Params);
            //HttpPost httpPost = new HttpPost(url);
            //client.execute(httpPost);

         return client;
         }

    public static class Naive_SSLSocketFactory extends SSLSocketFactory
    {
        protected SSLContext Cur_SSL_Context = SSLContext.getInstance("TLS");

        public Naive_SSLSocketFactory ()
                throws NoSuchAlgorithmException, KeyManagementException,
                KeyStoreException, UnrecoverableKeyException
        {
            super(null, null, null, null, null, (X509HostnameVerifier)null);
            Cur_SSL_Context.init(null, new TrustManager[] { new X509_Trust_Manager() }, null);
        }

        @Override
        public Socket createSocket(Socket socket, String host, int port,
                boolean autoClose) throws IOException
        {
            return Cur_SSL_Context.getSocketFactory().createSocket(socket, host, port, autoClose);
        }

        @Override
        public Socket createSocket() throws IOException
        {
            return Cur_SSL_Context.getSocketFactory().createSocket();
        }
    }

    private static class X509_Trust_Manager implements X509TrustManager
    {

        public void checkClientTrusted(X509Certificate[] chain, String authType)
                throws CertificateException {
            // TODO Auto-generated method stub

        }

        public void checkServerTrusted(X509Certificate[] chain, String authType)
                throws CertificateException {
            // TODO Auto-generated method stub

        }

        public X509Certificate[] getAcceptedIssuers() {
            // TODO Auto-generated method stub
            return null;
        }

    };
}

How to display all elements in an arraylist?

Arraylist uses Iterator interface to traverse the elements Use this

public void display(ArrayList<Integer> v) {
        Iterator vEnum = v.iterator();
        System.out.println("\nElements in vector:");
        while (vEnum.hasNext()) {
            System.out.print(vEnum.next() + " ");
        }
    }

How to represent a DateTime in Excel

Excel can display a Date type in a similar manner to a DateTime. Right click on the affected cell, select Format Cells, then under Category select Date and under Type select the type that looks something like this:

3/14/01 1:30 PM

That should do what you requested. I tested sorting on some sample data with this format and it seemed to work fine.

Create SQL identity as primary key?

Simple change to syntax is all that is needed:

 create table ImagenesUsuario (
   idImagen int not null identity(1,1) primary key
 )

By explicitly using the "constraint" keyword, you can give the primary key constraint a particular name rather than depending on SQL Server to auto-assign a name:

 create table ImagenesUsuario (
   idImagen int not null identity(1,1) constraint pk_ImagenesUsario primary key
 )

Add the "CLUSTERED" keyword if that makes the most sense based on your use of the table (i.e., the balance of searches for a particular idImagen and amount of writing outweighs the benefits of clustering the table by some other index).

Is there any WinSCP equivalent for linux?

  1. gFTP
  2. Konqueror's fish kio-slave (just write as file path: ssh://user@server/path

How to manually set an authenticated user in Spring Security / SpringMVC

Ultimately figured out the root of the problem.

When I create the security context manually no session object is created. Only when the request finishes processing does the Spring Security mechanism realize that the session object is null (when it tries to store the security context to the session after the request has been processed).

At the end of the request Spring Security creates a new session object and session ID. However this new session ID never makes it to the browser because it occurs at the end of the request, after the response to the browser has been made. This causes the new session ID (and hence the Security context containing my manually logged on user) to be lost when the next request contains the previous session ID.

Use of min and max functions in C++

By the way, in cstdlib there are __min and __max you can use.

For more: http://msdn.microsoft.com/zh-cn/library/btkhtd8d.aspx

Angular2 - Http POST request parameters

angular: 
    MethodName(stringValue: any): Observable<any> {
    let params = new HttpParams();
    params = params.append('categoryName', stringValue);

    return this.http.post('yoururl', '', {
      headers: new HttpHeaders({
        'Content-Type': 'application/json'
      }),
      params: params,
      responseType: "json"
    })
  }

api:   
  [HttpPost("[action]")]
  public object Method(string categoryName)

Iterate all files in a directory using a 'for' loop

I use the xcopy command with the /L option to get the file names. So if you want to get either a directory or all the files in the subdirectory you could do something like this:

for /f "delims=" %%a IN ('xcopy "D:\*.pdf" c:\ /l') do echo %%a

I just use the c:\ as the destination because it always exists on windows systems and it is not copying so it does not matter. if you want the subdirectories too just use /s option on the end. You can also use the other switches of xcopy if you need them for other reasons.

Angular + Material - How to refresh a data source (mat-table)

import { Subject } from 'rxjs/Subject';
import { Observable } from 'rxjs/Observable';

export class LanguageComponent implemnts OnInit {
  displayedColumns = ['name', 'native', 'code', 'leavel'];
  user: any;
  private update = new Subject<void>();
  update$ = this.update.asObservable();

  constructor(private authService: AuthService, private dialog: MatDialog) {}

   ngOnInit() {
     this.update$.subscribe(() => { this.refresh()});
   }

   setUpdate() {
     this.update.next();
   }

   add() {
     this.dialog.open(LanguageAddComponent, {
     data: { user: this.user },
   }).afterClosed().subscribe(result => {
     this.setUpdate();
   });
 }

 refresh() {
   this.authService.getAuthenticatedUser().subscribe((res) => {
     this.user = res;
     this.teachDS = new LanguageDataSource(this.user.profile.languages.teach);   
    });
  }
}

Errors in pom.xml with dependencies (Missing artifact...)

I know it is an old question. But I hope my answer will help somebody. I had the same issue and I think the problem is that it cannot find those .jar files in your local repository. So what I did is I added the following code to my pom.xml and it worked.

<repositories>
  <repository>
      <id>spring-milestones</id>
      <name>Spring Milestones</name>
      <url>https://repo.spring.io/libs-milestone</url>
      <snapshots>
          <enabled>false</enabled>
      </snapshots>
  </repository>
</repositories>

Error Importing SSL certificate : Not an X.509 Certificate

Many CAs will provide a cert in PKCS7 format.

According to Oracle documentation, the keytool commmand can handle PKCS#7 but sometimes it fails

The keytool command can import X.509 v1, v2, and v3 certificates, and PKCS#7 formatted certificate chains consisting of certificates of that type. The data to be imported must be provided either in binary encoding format or in printable encoding format (also known as Base64 encoding) as defined by the Internet RFC 1421 standard. In the latter case, the encoding must be bounded at the beginning by a string that starts with -----BEGIN, and bounded at the end by a string that starts with -----END.

If the PKCS7 file can't be imported try to transform it from PKCS7 to X.509:

openssl pkcs7 -print_certs -in certificate.p7b -out certificate.cer

Remove Datepicker Function dynamically

Well I had the same issue and tried "destroy" but that not worked for me. Then I found following work around My HTML was:

<input placeholder="Select Date" id="MyControlId" class="form-control datepicker" type="text" />

Jquery That work for me:

$('#MyControlId').data('datepicker').remove();

How to detect if URL has changed after hash in JavaScript

I wanted to be able to add locationchange event listeners. After the modification below, we'll be able to do it, like this

window.addEventListener('locationchange', function(){
    console.log('location changed!');
})

In contrast, window.addEventListener('hashchange',()=>{}) would only fire if the part after a hashtag in a url changes, and window.addEventListener('popstate',()=>{}) doesn't always work.

This modification, similar to Christian's answer, modifies the history object to add some functionality.

By default, before these modifications, there's a popstate event, but there are no events for pushstate, and replacestate.

This modifies these three functions so that all fire a custom locationchange event for you to use, and also pushstate and replacestate events if you want to use those.

These are the modifications:

history.pushState = ( f => function pushState(){
    var ret = f.apply(this, arguments);
    window.dispatchEvent(new Event('pushstate'));
    window.dispatchEvent(new Event('locationchange'));
    return ret;
})(history.pushState);

history.replaceState = ( f => function replaceState(){
    var ret = f.apply(this, arguments);
    window.dispatchEvent(new Event('replacestate'));
    window.dispatchEvent(new Event('locationchange'));
    return ret;
})(history.replaceState);

window.addEventListener('popstate',()=>{
    window.dispatchEvent(new Event('locationchange'))
});

Note:

We're creating a closure, old = (f=>function new(){f();...})(old) replaces old with a new function that contains the previous old saved within it (old is not run at this moment, but it will be run inside of new)

Compiling LaTex bib source

I am using texmaker as the editor. you have to compile it in terminal as following:

  1. pdflatex filename (with or without extensions)
  2. bibtex filename (without extensions)
  3. pdflatex filename (with or without extensions)
  4. pdflatex filename (with or without extensions)

but sometimes, when you use \citep{}, the names of the references don't show up. In this case, I had to open the references.bib file , so that texmaker could capture the references from the references.bib file. After every edition of the bib file, I had to close and reopen it!! So that texmaker could capture the content of new .bbl file each time. But remember, you have to also run your code in texmaker too.

Sending a JSON to server and retrieving a JSON in return, without JQuery

Sending and receiving data in JSON format using POST method

// Sending and receiving data in JSON format using POST method
//
var xhr = new XMLHttpRequest();
var url = "url";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
        var json = JSON.parse(xhr.responseText);
        console.log(json.email + ", " + json.password);
    }
};
var data = JSON.stringify({"email": "[email protected]", "password": "101010"});
xhr.send(data);

Sending and receiving data in JSON format using GET method

// Sending a receiving data in JSON format using GET method
//      
var xhr = new XMLHttpRequest();
var url = "url?data=" + encodeURIComponent(JSON.stringify({"email": "[email protected]", "password": "101010"}));
xhr.open("GET", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
        var json = JSON.parse(xhr.responseText);
        console.log(json.email + ", " + json.password);
    }
};
xhr.send();

Handling data in JSON format on the server-side using PHP

<?php
// Handling data in JSON format on the server-side using PHP
//
header("Content-Type: application/json");
// build a PHP variable from JSON sent using POST method
$v = json_decode(stripslashes(file_get_contents("php://input")));
// build a PHP variable from JSON sent using GET method
$v = json_decode(stripslashes($_GET["data"]));
// encode the PHP variable to JSON and send it back on client-side
echo json_encode($v);
?>

The limit of the length of an HTTP Get request is dependent on both the server and the client (browser) used, from 2kB - 8kB. The server should return 414 (Request-URI Too Long) status if an URI is longer than the server can handle.

Note Someone said that I could use state names instead of state values; in other words I could use xhr.readyState === xhr.DONE instead of xhr.readyState === 4 The problem is that Internet Explorer uses different state names so it's better to use state values.

Facebook Open Graph Error - Inferred Property

It might help some people who are struggling to get Facebook to read Open Graph nicely...

Have a look at the source code that is generated by browser using Firefox, Chrome or another desktop browser (many mobiles won't do view source) and make sure there is no blank lines before the doctype line or head tag... If there is Facebook will have a complete tantrum and throw it's toys out of the pram! (Best description!) Remove Blank Line - happy Facebook... took me about 1.5 - 2 hours to spot this!

Ignoring a class property in Entity Framework 4.1 Code First

You can use the NotMapped attribute data annotation to instruct Code-First to exclude a particular property

public class Customer
{
    public int CustomerID { set; get; }
    public string FirstName { set; get; } 
    public string LastName{ set; get; } 
    [NotMapped]
    public int Age { set; get; }
}

[NotMapped] attribute is included in the System.ComponentModel.DataAnnotations namespace.

You can alternatively do this with Fluent API overriding OnModelCreating function in your DBContext class:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
   modelBuilder.Entity<Customer>().Ignore(t => t.LastName);
   base.OnModelCreating(modelBuilder);
}

http://msdn.microsoft.com/en-us/library/hh295847(v=vs.103).aspx

The version I checked is EF 4.3, which is the latest stable version available when you use NuGet.


Edit : SEP 2017

Asp.NET Core(2.0)

Data annotation

If you are using asp.net core (2.0 at the time of this writing), The [NotMapped] attribute can be used on the property level.

public class Customer
{
    public int Id { set; get; }
    public string FirstName { set; get; } 
    public string LastName { set; get; } 
    [NotMapped]
    public int FullName { set; get; }
}

Fluent API

public class SchoolContext : DbContext
{
    public SchoolContext(DbContextOptions<SchoolContext> options) : base(options)
    {
    }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Customer>().Ignore(t => t.FullName);
        base.OnModelCreating(modelBuilder);
    }
    public DbSet<Customer> Customers { get; set; }
}

Moving average or running mean

With @Aikude's variables, I wrote one-liner.

import numpy as np

mylist = [1, 2, 3, 4, 5, 6, 7]
N = 3

mean = [np.mean(mylist[x:x+N]) for x in range(len(mylist)-N+1)]
print(mean)

>>> [2.0, 3.0, 4.0, 5.0, 6.0]

Git push requires username and password

As many users has said, you just have to change your Git repository URL from HTTPS to SSH.

If you haven't generated a SSH key in your machine, then your are going to have to do it.

Just as an additional information, after doing this change I still was getting the same error:

Permission Denied.

In my case, the problem was that I was using the Windows Shell to execute the ngh command; since this command should open a prompt to request the SSH phrase and the Windows Shell doesn't open these kinds of prompts, the authentication just failed.

So, I just had to open the Git shell and execute the ngh command there, put the SSH phrase in the prompt every time it asked for it and "voilà"... It just worked fine!

String Pattern Matching In Java

You can do it using string.indexOf("{item}"). If the result is greater than -1 {item} is in the string

Why should text files end with a newline?

Basically there are many programs which will not process files correctly if they don't get the final EOL EOF.

GCC warns you about this because it's expected as part of the C standard. (section 5.1.1.2 apparently)

"No newline at end of file" compiler warning

Declaring a custom android UI element using XML

It seems that Google has updated its developer page and added various trainings there.

One of them deals with the creation of custom views and can be found here

How to get current formatted date dd/mm/yyyy in Javascript and append it to an input

I honestly suggest that you use moment.js. Just download moment.min.js and then use this snippet to get your date in whatever format you want:

<script>
$(document).ready(function() {

     // set an element
     $("#date").val( moment().format('MMM D, YYYY') );

     // set a variable
     var today = moment().format('D MMM, YYYY');

});
</script>

Use following chart for date formats:

enter image description here

How to get first character of a string in SQL?

If you search the first char of string in Sql string

SELECT CHARINDEX('char', 'my char')

=> return 4

How to check if spark dataframe is empty?

If you do df.count > 0. It takes the counts of all partitions across all executors and add them up at Driver. This take a while when you are dealing with millions of rows.

The best way to do this is to perform df.take(1) and check if its null. This will return java.util.NoSuchElementException so better to put a try around df.take(1).

The dataframe return an error when take(1) is done instead of an empty row. I have highlighted the specific code lines where it throws the error.

enter image description here

Javascript Equivalent to PHP Explode()

var str = "helloword~this~is~me";
var exploded = str.splice(~);

the exploded variable will return array and you can access elements of the array be accessing it true exploded[nth] where nth is the index of the value you want to get

Linear regression with matplotlib / numpy

from pylab import * 

import numpy as np
x1 = arange(data) #for example this is a list
y1 = arange(data) #for example this is a list 
x=np.array(x) #this will convert a list in to an array
y=np.array(y)
m,b = polyfit(x, y, 1) 

plot(x, y, 'yo', x, m*x+b, '--k') 
show()

Node.js Port 3000 already in use but it actually isn't?

This started happening to me today on Windows. I have restarted my computer and checked that nothing is on the port 3000 and it isn't.

I tried using 3001, 3005 with the same result.

In the end I moved to 8881 and it works now.

The only thing that changed for me was installing windows updates and updating source-map-explorer. As this also occurs in other apps its either something with Web Storm or windows. My guess is the ports may be locked down but the ones in the 88XX range are not.

How to know function return type and argument types?

This is how dynamic languages work. It is not always a good thing though, especially if the documentation is poor - anyone tried to use a poorly documented python framework? Sometimes you have to revert to reading the source.

Here are some strategies to avoid problems with duck typing:

  • create a language for your problem domain
  • this will help you to name stuff properly
  • use types to represent concepts in your domain language
  • name function parameters using the domain language vocabulary

Also, one of the most important points:

  • keep data as local as possible!

There should only be a few well-defined and documented types being passed around. Anything else should be obvious by looking at the code: Don't have weird parameter types coming from far away that you can't figure out by looking in the vicinity of the code...

Related, (and also related to docstrings), there is a technique in python called doctests. Use that to document how your methods are expected to be used - and have nice unit test coverage at the same time!

getting the error: expected identifier or ‘(’ before ‘{’ token

{
int main(void);

should be

int main(void)
{

Then I let you fix the next compilation errors of your program...

How can I find which tables reference a given table in Oracle SQL Developer?

This has been in the product for years - although it wasn't in the product in 2011.

But, simply click on the Model page.

Make sure you are on at least version 4.0 (released in 2013) to access this feature.

enter image description here

Fastest way to check if string contains only digits

Try this code:

bool isDigitsOnly(string str)
{
   try
   {
      int number = Convert.ToInt32(str);
      return true;
   }
   catch (Exception)
   {
      return false;
   }
}

C++ multiline string literal

You can just do this:

const char *text = "This is my string it is "
     "very long";

Visually managing MongoDB documents and collections

I use MongoVUE, it's good for viewing data, but there is almost no editing abilities.

Call to getLayoutInflater() in places not in activity

or

View.inflate(context, layout, parent)

What is the difference between vmalloc and kmalloc?

Short answer: download Linux Device Drivers and read the chapter on memory management.

Seriously, there are a lot of subtle issues related to kernel memory management that you need to understand - I spend a lot of my time debugging problems with it.

vmalloc() is very rarely used, because the kernel rarely uses virtual memory. kmalloc() is what is typically used, but you have to know what the consequences of the different flags are and you need a strategy for dealing with what happens when it fails - particularly if you're in an interrupt handler, like you suggested.

Array.push() if does not exist?

a is the array of objects you have

a.findIndex(x => x.property=="WhateverPropertyYouWantToMatch") <0 ? 
a.push(objectYouWantToPush) : console.log("response if object exists");

Descending order by date filter in AngularJs

And a code example:

<div ng-app>
    <div ng-controller="FooController">
        <ul ng-repeat="item in items | orderBy:'num':true">
            <li>{{item.num}} :: {{item.desc}}</li>
        </ul>
    </div>
</div>

And the JavaScript:

function FooController($scope) {
    $scope.items = [
        {desc: 'a', num: 1},
        {desc: 'b', num: 2},
        {desc: 'c', num: 3},
    ];
}

Will give you:

3 :: c
2 :: b
1 :: a

On JSFiddle: http://jsfiddle.net/agjqN/

How to put text over images in html?

The <img> element is empty — it doesn't have an end tag.

If the image is a background image, use CSS. If it is a content image, then set position: relative on a container, then absolutely position the image and/or text within it.

how to get value of selected item in autocomplete

To answer the question more generally, the answer is:

select: function( event , ui ) {
    alert( "You selected: " + ui.item.label );
}

Complete example :

_x000D_
_x000D_
$('#test').each(function(i, el) {_x000D_
    var that = $(el);_x000D_
    that.autocomplete({_x000D_
        source: ['apple','banana','orange'],_x000D_
        select: function( event , ui ) {_x000D_
            alert( "You selected: " + ui.item.label );_x000D_
        }_x000D_
    });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css" />_x000D_
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script>_x000D_
_x000D_
Type a fruit here: <input type="text" id="test" />
_x000D_
_x000D_
_x000D_

How to use goto statement correctly

Java does not support goto, it is reserved as a keyword in case they wanted to add it to a later version

C++ Redefinition Header Files (winsock2.h)

You should use header guard.

put those line at the top of the header file

#ifndef PATH_FILENAME_H
#define PATH_FILENAME_H

and at the bottom

#endif

Spring RestTemplate timeout

This question is the first link for a Spring Boot search, therefore, would be great to put here the solution recommended in the official documentation. Spring Boot has its own convenience bean RestTemplateBuilder:

@Bean
public RestTemplate restTemplate(
        RestTemplateBuilder restTemplateBuilder) {

    return restTemplateBuilder
            .setConnectTimeout(Duration.ofSeconds(500))
            .setReadTimeout(Duration.ofSeconds(500))
            .build();
}

Manual creation of RestTemplate instances is a potentially troublesome approach because other auto-configured beans are not being injected in manually created instances.

How to install PyQt4 in anaconda?

It looks like the latest version of anaconda forces install of pyqt5.6 over any pyqt build, which will be fatal for your applications. In a terminal, Try:

conda install -c anaconda pyqt=4.11.4

It will prompt to downgrade conda client. After that, it should be good.

UPDATE: If you want to know what pyqt versions are available for install, try:

conda search pyqt

UPDATE: The most recent version of conda installs anaconda-navigator. This depends on qt5, and should first be removed:

conda uninstall anaconda-navigator

Then install "newest" qt4:

conda install qt=4

Convert datetime object to a String of date only in Python

Another option:

import datetime
now=datetime.datetime.now()
now.isoformat()
# ouptut --> '2016-03-09T08:18:20.860968'

Ctrl+click doesn't work in Eclipse Juno

I faced this issue several times. As described by Ashutosh Jindal, if the Hyperlinking is already enabled and still the ctrl+click doesn't work then you need to:

  1. Navigate to Java -> Editor -> Mark Occurrences in Preferences
  2. Uncheck "Mark occurrences of the selected element in the current file" if its already checked.
  3. Now, check on the above mentioned option and then check on all the items under it. Click Apply.

This should now enabled the ctrl+click functionality.

Seeing the underlying SQL in the Spring JdbcTemplate?

This works for me with org.springframework.jdbc-3.0.6.RELEASE.jar. I could not find this anywhere in the Spring docs (maybe I'm just lazy) but I found (trial and error) that the TRACE level did the magic.

I'm using log4j-1.2.15 along with slf4j (1.6.4) and properties file to configure the log4j:

log4j.logger.org.springframework.jdbc.core = TRACE

This displays both the SQL statement and bound parameters like this:

Executing prepared SQL statement [select HEADLINE_TEXT, NEWS_DATE_TIME from MY_TABLE where PRODUCT_KEY = ? and NEWS_DATE_TIME between ? and ? order by NEWS_DATE_TIME]
Setting SQL statement parameter value: column index 1, parameter value [aaa], value class [java.lang.String], SQL type unknown
Setting SQL statement parameter value: column index 2, parameter value [Thu Oct 11 08:00:00 CEST 2012], value class [java.util.Date], SQL type unknown
Setting SQL statement parameter value: column index 3, parameter value [Thu Oct 11 08:00:10 CEST 2012], value class [java.util.Date], SQL type unknown

Not sure about the SQL type unknown but I guess we can ignore it here

For just an SQL (i.e. if you're not interested in bound parameter values) DEBUG should be enough.

Transpose list of lists

Maybe not the most elegant solution, but here's a solution using nested while loops:

def transpose(lst):
    newlist = []
    i = 0
    while i < len(lst):
        j = 0
        colvec = []
        while j < len(lst):
            colvec.append(lst[j][i])
            j = j + 1
        newlist.append(colvec)
        i = i + 1
    return newlist

Are PHP short tags acceptable to use?

  • Short tags are not turned on by default in some webservers (shared hosts, etc.), so code portability becomes an issue if you need to move to one of these.

  • Readability may be an issue for some. Many developers may find that <?php catches the eye as a more obvious marker of the beginning of a code block than <? when you scan a file, particularly if you're stuck with a code base with HTML and PHP tightly inter-woven.

How to style a select tag's option element?

I have a workaround using jquery... although we cannot style a particular option, we can style the select itself - and use javascript to change the class of the select based on what is selected. It works sufficiently for simple cases.

_x000D_
_x000D_
$('select.potentially_red').on('change', function() {_x000D_
 if ($(this).val()=='red') {_x000D_
  $(this).addClass('option_red');_x000D_
 } else {_x000D_
  $(this).removeClass('option_red');_x000D_
 }_x000D_
});_x000D_
$('select.potentially_red').each( function() {_x000D_
 if ($(this).val()=='red') {_x000D_
  $(this).addClass('option_red');_x000D_
 } else {_x000D_
  $(this).removeClass('option_red');_x000D_
 }_x000D_
});
_x000D_
.option_red {_x000D_
    background-color: #cc0000; _x000D_
    font-weight: bold; _x000D_
    font-size: 12px; _x000D_
    color: white;_x000D_
}
_x000D_
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>_x000D_
<!-- The js will affect all selects which have the class 'potentially_red' -->_x000D_
<select name="color" class="potentially_red">_x000D_
    <option value="red">Red</option>_x000D_
    <option value="white">White</option>_x000D_
    <option value="blue">Blue</option>_x000D_
    <option value="green">Green</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Note that the js is in two parts, the each part for initializing everything on the page correctly, the .on('change', ... part for responding to change. I was unable to mangle the js into a function to DRY it up, it breaks it for some reason

How do I post button value to PHP?

Change the type to submit and give it a name (and remove the useless onclick and flat out the 90's style uppercased tags/attributes).

<input type="submit" name="foo" value="A" />
<input type="submit" name="foo" value="B" />
...

The value will be available by $_POST['foo'] (if the parent <form> has a method="post").

Send Outlook Email Via Python?

For a solution that uses outlook see TheoretiCAL's answer below.

Otherwise, use the smtplib that comes with python. Note that this will require your email account allows smtp, which is not necessarily enabled by default.

SERVER = "smtp.example.com"
FROM = "[email protected]"
TO = ["listOfEmails"] # must be a list

SUBJECT = "Subject"
TEXT = "Your Text"

# Prepare actual message
message = """From: %s\r\nTo: %s\r\nSubject: %s\r\n\

%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)

# Send the mail
import smtplib
server = smtplib.SMTP(SERVER)
server.sendmail(FROM, TO, message)
server.quit()

EDIT: this example uses reserved domains like described in RFC2606

SERVER = "smtp.example.com"
FROM = "[email protected]"
TO = ["[email protected]"] # must be a list

SUBJECT = "Hello!"
TEXT = "This is a test of emailing through smtp of example.com."

# Prepare actual message
message = """From: %s\r\nTo: %s\r\nSubject: %s\r\n\

%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)

# Send the mail
import smtplib
server = smtplib.SMTP(SERVER)
server.login("MrDoe", "PASSWORD")
server.sendmail(FROM, TO, message)
server.quit()

For it to actually work with gmail, Mr. Doe will need to go to the options tab in gmail and set it to allow smtp connections.

Note the addition of the login line to authenticate to the remote server. The original version does not include this, an oversight on my part.

How to configure PHP to send e-mail?

This will not work on a local host, but uploaded on a server, this code should do the trick. Just make sure to enter your own email address for the $to line.

<?php
if (isset($_POST['name']) && isset($_POST['email'])) {
    $name = $_POST['name'];
    $email = $_POST['email'];
    $to = '[email protected]';
    $subject = "New Message on YourWebsite.com";
    $body = '<html>
                <body>
                    <h2>Title</h2>
                    <br>
                    <p>Name:<br>'.$name.'</p>
                    <p>Email:<br>'.$email.'</p>

                </body>
            </html>';

//headers
$headers = "From: ".$name." <".$email.">\r\n";
$headers = "Reply-To: ".$email."\r\n";
$headers = "MIME-Version: 1.0\r\n";
$headers = "Content-type: text/html; charset=utf-8";

//send
$send = mail($to, $subject, $body, $headers);
if ($send) {
    echo '<br>';
    echo "Success. Thanks for Your Message.";
} else {
    echo 'Error.';
}
}
?>

<html>
    <head>
        <meta charset="utf-8">
    </head>
    <body>
        <form action="" method="post">
            <input type="text" name="name" placeholder="Your Name"><br>
            <input type="text" name="email" placeholder="Your Email"><br>
            <button type="submit">Subscribe</button>
        </form>
    </body>
</html>

PHP namespaces and "use"

The use operator is for giving aliases to names of classes, interfaces or other namespaces. Most use statements refer to a namespace or class that you'd like to shorten:

use My\Full\Namespace;

is equivalent to:

use My\Full\Namespace as Namespace;
// Namespace\Foo is now shorthand for My\Full\Namespace\Foo

If the use operator is used with a class or interface name, it has the following uses:

// after this, "new DifferentName();" would instantiate a My\Full\Classname
use My\Full\Classname as DifferentName;

// global class - making "new ArrayObject()" and "new \ArrayObject()" equivalent
use ArrayObject;

The use operator is not to be confused with autoloading. A class is autoloaded (negating the need for include) by registering an autoloader (e.g. with spl_autoload_register). You might want to read PSR-4 to see a suitable autoloader implementation.

Checking character length in ruby

I think you could just use the String#length method...

http://ruby-doc.org/core-1.9.3/String.html#method-i-length

Example:

text = 'The quick brown fox jumps over the lazy dog.'
puts text.length > 25 ? 'Too many characters' : 'Accepted'

User Get-ADUser to list all properties and export to .csv

This can be simplified by completely skipping the where object and the $users declaration. All you need is:

Code

get-content c:\scripts\users.txt | get-aduser -properties * | select displayname, office | export-csv c:\path\to\your.csv

Replace part of a string in Python?

>>> stuff = "Big and small"
>>> stuff.replace(" and ","/")
'Big/small'

JNZ & CMP Assembly Instructions

You can read JNE/Z as *

Jump if the status is "Not set" on Equal/Zero flag

"Not set" is a status when "equal/zero flag" in the CPU is set to 0 which only happens when the condition is met or equally matched.

CSS height 100% percent not working

You aren't specifying the "height" of your html. When you're assigning a percentage in an element (i.e. divs) the css compiler needs to know the size of the parent element. If you don't assign that, you should see divs without height.

The most common solution is to set the following property in css:

html{
    height: 100%;
    margin: 0;
    padding: 0;
}

You are saying to the html tag (html is the parent of all the html elements) "Take all the height in the HTML document"

I hope I helped you. Cheers

Maven plugin in Eclipse - Settings.xml file is missing

The settings file is never created automatically, you must create it yourself, whether you use embedded or "real" maven.

Create it at the following location <your home folder>/.m2/settings.xml e.g. C:\Users\YourUserName\.m2\settings.xml on Windows or /home/YourUserName/.m2/settings.xml on Linux

Here's an empty skeleton you can use:

<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                      http://maven.apache.org/xsd/settings-1.0.0.xsd">
  <localRepository/>
  <interactiveMode/>
  <usePluginRegistry/>
  <offline/>
  <pluginGroups/>
  <servers/>
  <mirrors/>
  <proxies/>
  <profiles/>
  <activeProfiles/>
</settings>

If you use Eclipse to edit it, it will give you auto-completion when editing it.

And here's the Maven settings.xml Reference page

How to center an iframe horizontally?

If you can't access the iFrame class then add below css to wrapper div.

<div style="display: flex; justify-content: center;">
    <iframe></iframe>
</div>

How to access session variables from any class in ASP.NET?

The answers presented before mine provide apt solutions to the problem, however, I feel that it is important to understand why this error results:

The Session property of the Page returns an instance of type HttpSessionState relative to that particular request. Page.Session is actually equivalent to calling Page.Context.Session.

MSDN explains how this is possible:

Because ASP.NET pages contain a default reference to the System.Web namespace (which contains the HttpContext class), you can reference the members of HttpContext on an .aspx page without the fully qualified class reference to HttpContext.

However, When you try to access this property within a class in App_Code, the property will not be available to you unless your class derives from the Page Class.

My solution to this oft-encountered scenario is that I never pass page objects to classes. I would rather extract the required objects from the page Session and pass them to the Class in the form of a name-value collection / Array / List, depending on the case.

How does the stack work in assembly language?

I think that main answer you are looking for has already been hinted at.

When an x86 computer boots up, the stack is not setup. The programmer must explicitly set it up at boot time. However, if you are already in an operating system, this has been taken care of. Below is a code sample from a simple bootstrap program.

First the data and stack segment registers are set, and then the stack pointer is set 0x4000 beyond that.


    movw    $BOOT_SEGMENT, %ax
    movw    %ax, %ds
    movw    %ax, %ss
    movw    $0x4000, %ax
    movw    %ax, %sp

After this code the stack may be used. Now I am sure it can be done in a number of different ways, but I think this should illustrate the idea.

Python element-wise tuple operations like sum

simple solution without class definition that returns tuple

import operator
tuple(map(operator.add,a,b))

How to prevent background scrolling when Bootstrap 3 modal open on mobile browsers?

No scripts needed.

BS 3 sets a .modal-open class on body that you can use to set the position and overflow values (made with LESS).

body {
    font-family:'Open Sans';
    margin:0;

    &.modal-open {
        position:fixed;
        overflow:hidden;

        .modal { 
            overflow: scroll;

            @media only screen and (min-resolution:150dpi) and (max-width: @screen-sm),
            only screen and (-webkit-min-device-pixel-ratio:1.5) {
                overflow: scroll; 
                -webkit-overflow-scrolling: touch; 
            }
        }
    }   
}

Icons missing in jQuery UI

I found icons were not displaying due to a difference in the casing (ie upper case vs lower case). The CSS file was using "FFFFFF" while the actual file was using "ffffff". Icons displayed for me once I changed the case to match.

npm not working - "read ECONNRESET"

In case this helps anyone who was in my situation: I recently installed Fiddler, which (unbeknownst to me) added a network proxy through 127.0.0.1:8866. I went into my Ubuntu network settings, clicked into the "Network Proxy" settings, and disabled it, and then all was back to normal.

So in general, check to make sure you haven't got a network proxy set up due to a side-effect of something else you were doing.

Error occurred during initialization of VM (java/lang/NoClassDefFoundError: java/lang/Object)

Not able to run Appium {“message”:”A new session could not be created. (Original error: ‘java -version’ failed

I used Jdk 1.8 and JRE 1.8, Classpath is also set properly but I observed that Java command gives Error to initialization of VM (java/lang/NoClassDefFoundError: java/lang/Object)

Solution:
Uninstalled JRE and JDK completely 
Installed JRE 1.8 then
Installed JDK 1.8 
Set Classpath
check Java command works or not and its working 
also able to execute the Appium program thru Eclipse Kepler Service Release 2 with JDK1.8 support

Importing text file into excel sheet

There are many ways you can import Text file to the current sheet. Here are three (including the method that you are using above)

  1. Using a QueryTable
  2. Open the text file in memory and then write to the current sheet and finally applying Text To Columns if required.
  3. If you want to use the method that you are currently using then after you open the text file in a new workbook, simply copy it over to the current sheet using Cells.Copy

Using a QueryTable

Here is a simple macro that I recorded. Please amend it to suit your needs.

Sub Sample()
    With ActiveSheet.QueryTables.Add(Connection:= _
        "TEXT;C:\Sample.txt", Destination:=Range("$A$1") _
        )
        .Name = "Sample"
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .TextFilePromptOnRefresh = False
        .TextFilePlatform = 437
        .TextFileStartRow = 1
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierDoubleQuote
        .TextFileConsecutiveDelimiter = False
        .TextFileTabDelimiter = True
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = True
        .TextFileSpaceDelimiter = False
        .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
    End With
End Sub

Open the text file in memory

Sub Sample()
    Dim MyData As String, strData() As String

    Open "C:\Sample.txt" For Binary As #1
    MyData = Space$(LOF(1))
    Get #1, , MyData
    Close #1
    strData() = Split(MyData, vbCrLf)
End Sub

Once you have the data in the array you can export it to the current sheet.

Using the method that you are already using

Sub Sample()
    Dim wbI As Workbook, wbO As Workbook
    Dim wsI As Worksheet

    Set wbI = ThisWorkbook
    Set wsI = wbI.Sheets("Sheet1") '<~~ Sheet where you want to import

    Set wbO = Workbooks.Open("C:\Sample.txt")

    wbO.Sheets(1).Cells.Copy wsI.Cells

    wbO.Close SaveChanges:=False
End Sub

FOLLOWUP

You can use the Application.GetOpenFilename to choose the relevant file. For example...

Sub Sample()
    Dim Ret

    Ret = Application.GetOpenFilename("Prn Files (*.prn), *.prn")

    If Ret <> False Then
        With ActiveSheet.QueryTables.Add(Connection:= _
        "TEXT;" & Ret, Destination:=Range("$A$1"))

            '~~> Rest of the code

        End With
    End If
End Sub

How to debug Angular JavaScript Code

Try ng-inspector. Download the add-on for Firefox from the website http://ng-inspector.org/. It is not available on the Firefox add on menu.

http://ng-inspector.org/ - website

http://ng-inspector.org/ng-inspector.xpi - Firefox Add-on?

How to add a touch event to a UIView?

Why don't you guys try SSEventListener?

You don't need to create any gesture recognizer and separate your logic apart to another method. SSEventListener supports setting listener blocks on a view to listen for single tap gesture, double tap gesture and N-tap gesture if you like, and long press gesture. Setting a single tap gesture listener becomes this way:

[view ss_addTapViewEventListener:^(UITapGestureRecognizer *recognizer) { ... } numberOfTapsRequired:1];

How do I reference the input of an HTML <textarea> control in codebehind?

You need to use runat="server" like this:

<textarea id="TextArea1" cols="20" rows="2" runat="server"></textarea>

You can use the runat=server attribute with any standard HTML element, and later use it from codebehind.

How to properly add include directories with CMake

I had the same problem.

My project directory was like this:

    --project
    ---Classes
    ----Application
    -----.h and .c files
    ----OtherFolders
    --main.cpp

And what I used to include the files in all those folders:

    file(GLOB source_files
            "*.h"
            "*.cpp"
            "Classes/*/*.cpp"
            "Classes/*/*.h"
    )

    add_executable(Server ${source_files})

And it totally worked.

Handling MySQL datetimes and timestamps in Java

BalusC gave a good description about the problem but it lacks a good end to end code that users can pick and test it for themselves.

Best practice is to always store date-time in UTC timezone in DB. Sql timestamp type does not have timezone info.

When writing datetime value to sql db

    //Convert the time into UTC and build Timestamp object.
    Timestamp ts = Timestamp.valueOf(LocalDateTime.now(ZoneId.of("UTC")));
    //use setTimestamp on preparedstatement
    preparedStatement.setTimestamp(1, ts);

When reading the value back from DB into java,

  1. Read it as it is in java.sql.Timestamp type.
  2. Decorate the DateTime value as time in UTC timezone using atZone method in LocalDateTime class.
  3. Then, change it to your desired timezone. Here I am changing it to Toronto timezone.

    ResultSet resultSet = preparedStatement.executeQuery();
    resultSet.next();
    Timestamp timestamp = resultSet.getTimestamp(1);
    ZonedDateTime timeInUTC = timestamp.toLocalDateTime().atZone(ZoneId.of("UTC"));
    LocalDateTime timeInToronto = LocalDateTime.ofInstant(timeInUTC.toInstant(), ZoneId.of("America/Toronto"));
    

OperationalError, no such column. Django

This error can happen if you instantiate a class that relies on that table, for example in views.py.

How do I load the contents of a text file into a javascript variable?

here is how I did it in jquery:

jQuery.get('http://localhost/foo.txt', function(data) {
    alert(data);
});

Android 6.0 multiple permissions

This is what I have done in my activity. Hoping will be helpful. I am asking for camera and microphone permissions.

public class ActiveCallActivity extends AppCompatActivity {
    .....

    private static final String cameraPermissionKey = "cameraPermission";
    private static final String microphonePermissionkey = "microphonePermission";

    private static ArrayList<String> permissionsQueue = new ArrayList<String>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        .....
        // in ValidationCheckersAndValidators simply checking if have permission or not.
        if(ValidationCheckersAndValidators.haveCameraPermission(this)) performHaveCameraPermissionLayout(); else performHaveNoCameraPermissionLayout();
        if(ValidationCheckersAndValidators.haveMicrophonePermission(this)) performHaveMicrophonePermissionLayout(); else performHaveNoMicrophonePermissionLayout();

    }

    private void performHaveNoCameraPermissionLayout() {
        .....
        permissionsQueue.add(cameraPermissionKey);
    }

    private void performHaveNoMicrophonePermissionLayout() {
        .....
        permissionsQueue.add(microphonePermissionkey);
    }

    @Override
    protected void onResume() {
        super.onResume();

        .....
        passThroughPermissionsQueue();
    }

    private void passThroughPermissionsQueue() {
        if(!permissionsQueue.isEmpty()) {
            String permissionKey = permissionsQueue.remove(0);
            switch (permissionKey) {
                case cameraPermissionKey: {
                    ValidationCheckersAndValidators.requestForCameraPermission(this);
                    return;
                }
                case microphonePermissionkey: {
                    ValidationCheckersAndValidators.requestForMicrophonePermission(this);
                    return;
                }
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch(requestCode) {
            case cameraPermissionRequestCode: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    performHaveCameraPermissionLayout();
                }
                break;
            }
            case microphonePermissionRequestCode: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    performHaveMicrophonePermissionLayout();
                }
                break;
            }
        }
        passThroughPermissionsQueue();
    }
}

How to submit an HTML form without redirection

If you control the back end, then use something like response.redirect instead of response.send.

You can create custom HTML pages for this or just redirect to something you already have.

In Express.js:

const handler = (req, res) => {
  const { body } = req
  handleResponse(body)
  .then(data => {
    console.log(data)
    res.redirect('https://yoursite.com/ok.html')
  })
  .catch(err => {
    console.log(err)
    res.redirect('https://yoursite.com/err.html')
  })
}
...
app.post('/endpoint', handler)

Find duplicate characters in a String and count the number of occurances using Java

Use google guava Multiset<String>.

Multiset<String> wordsMultiset = HashMultiset.create();
wordsMultiset.addAll(words);
for(Multiset.Entry<E> entry:wordsMultiset.entrySet()){
     System.out.println(entry.getElement()+" - "+entry.getCount());
}

How to remove the arrow from a select element in Firefox

While not a complete solution I've found that…

-moz-appearance: window;

…works to some extent. You can't change the background (-color or -image) but the element can be rendered invisible with color: transparent. Not perfect but it's a start and you don't need to replace the system level element with a js one.

How to add white spaces in HTML paragraph

If you really need then you can use i.e. &nbsp; entity to do that, but remember that fonts used to render your page are usually proportional, so "aligning" with spaces does not really work and looks ugly.

How to install SignTool.exe for Windows 10

As per the comments in the question... On Windows 10 Signtool.exe and other SDK tools have been moved into "%programfiles(x86)%\Windows Kits\".

Typical path to signtool on Windows 10.

  • 32 bit = "c:\Program Files (x86)\Windows Kits\10\bin\x86\signtool.exe"
  • 64 bit = "c:\Program Files (x86)\Windows Kits\10\bin\x64\signtool.exe"

Tools for SDK 8.0 and 8.1 also reside in the "Windows Kits" folder.

Can we instantiate an abstract class?

No, you can't instantite an abstract class.We instantiate only anonymous class.In abstract class we declare abstract methods and define concrete methods only.

How to switch to new window in Selenium for Python?

On top of the answers already given, to open a new tab the javascript command window.open() can be used.

For example:

# Opens a new tab
self.driver.execute_script("window.open()")

# Switch to the newly opened tab
self.driver.switch_to.window(self.driver.window_handles[1])

# Navigate to new URL in new tab
self.driver.get("https://google.com")
# Run other commands in the new tab here

You're then able to close the original tab as follows

# Switch to original tab
self.driver.switch_to.window(self.driver.window_handles[0])

# Close original tab
self.driver.close()

# Switch back to newly opened tab, which is now in position 0
self.driver.switch_to.window(self.driver.window_handles[0])

Or close the newly opened tab

# Close current tab
self.driver.close()

# Switch back to original tab
self.driver.switch_to.window(self.driver.window_handles[0])

Hope this helps.

How to upload a file using Java HttpClient library working with PHP

Ok, the Java code I used was wrong, here comes the right Java class:

import java.io.File;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.EntityUtils;


public class PostFile {
  public static void main(String[] args) throws Exception {
    HttpClient httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

    HttpPost httppost = new HttpPost("http://localhost:9001/upload.php");
    File file = new File("c:/TRASH/zaba_1.jpg");

    MultipartEntity mpEntity = new MultipartEntity();
    ContentBody cbFile = new FileBody(file, "image/jpeg");
    mpEntity.addPart("userfile", cbFile);


    httppost.setEntity(mpEntity);
    System.out.println("executing request " + httppost.getRequestLine());
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity resEntity = response.getEntity();

    System.out.println(response.getStatusLine());
    if (resEntity != null) {
      System.out.println(EntityUtils.toString(resEntity));
    }
    if (resEntity != null) {
      resEntity.consumeContent();
    }

    httpclient.getConnectionManager().shutdown();
  }
}

note using MultipartEntity.

Mutex lock threads

Below, code snippet, will help you in understanding the mutex-lock-unlock concept. Attempt dry-run on the code. (further by varying the wait-time and process-time, you can build you understanding).

Code for your reference:

#include <stdio.h>
#include <pthread.h>

void in_progress_feedback(int);

int global = 0;
pthread_mutex_t mutex;
void *compute(void *arg) {

    pthread_t ptid = pthread_self();
    printf("ptid : %08x \n", (int)ptid);    

    int i;
    int lock_ret = 1;   
    do{

        lock_ret = pthread_mutex_trylock(&mutex);
        if(lock_ret){
            printf("lock failed(%08x :: %d)..attempt again after 2secs..\n", (int)ptid,  lock_ret);
            sleep(2);  //wait time here..
        }else{  //ret =0 is successful lock
            printf("lock success(%08x :: %d)..\n", (int)ptid, lock_ret);
            break;
        }

    } while(lock_ret);

        for (i = 0; i < 10*10 ; i++) 
        global++;

    //do some stuff here
    in_progress_feedback(10);  //processing-time here..

    lock_ret = pthread_mutex_unlock(&mutex);
    printf("unlocked(%08x :: %d)..!\n", (int)ptid, lock_ret);

     return NULL;
}

void in_progress_feedback(int prog_delay){

    int i=0;
    for(;i<prog_delay;i++){
    printf(". ");
    sleep(1);
    fflush(stdout);
    }

    printf("\n");
    fflush(stdout);
}

int main(void)
{
    pthread_t tid0,tid1;
    pthread_mutex_init(&mutex, NULL);
    pthread_create(&tid0, NULL, compute, NULL);
    pthread_create(&tid1, NULL, compute, NULL);
    pthread_join(tid0, NULL);
    pthread_join(tid1, NULL);
    printf("global = %d\n", global);
    pthread_mutex_destroy(&mutex);
          return 0;
}

Add leading zeroes to number in Java?

In case of your jdk version less than 1.5, following option can be used.

    int iTest = 2;
    StringBuffer sTest = new StringBuffer("000000"); //if the string size is 6
    sTest.append(String.valueOf(iTest));
    System.out.println(sTest.substring(sTest.length()-6, sTest.length()));

How to import an excel file in to a MySQL database

If you are using Toad for MySQL steps to import a file is as follows:

  1. create a table in MySQL with the same columns that of the file to be imported.
  2. now the table is created, goto > Tools > Import > Import Wizard
  3. now in the import wizard dialogue box, click Next.
  4. click Add File, browse and select the file to be imported.
  5. choose the correct dilimination.("," seperated for .csv file)
  6. click Next, check if the mapping is done properly.
  7. click Next, select the "A single existing table" radio button also select the table that to be mapped from the dropdown menu of Tables.
  8. Click next and finish the process.

How to do this using jQuery - document.getElementById("selectlist").value

It can be done by three different ways,though all them are nearly the same

Javascript way

document.getElementById('test').value

Jquery way

$("#test").val()          

$("#test")[0].value             

$("#test").get(0).value

Sending websocket ping/pong frame from browser

There is no Javascript API to send ping frames or receive pong frames. This is either supported by your browser, or not. There is also no API to enable, configure or detect whether the browser supports and is using ping/pong frames. There was discussion about creating a Javascript ping/pong API for this. There is a possibility that pings may be configurable/detectable in the future, but it is unlikely that Javascript will be able to directly send and receive ping/pong frames.

However, if you control both the client and server code, then you can easily add ping/pong support at a higher level. You will need some sort of message type header/metadata in your message if you don't have that already, but that's pretty simple. Unless you are planning on sending pings hundreds of times per second or have thousands of simultaneous clients, the overhead is going to be pretty minimal to do it yourself.

Aligning a button to the center

You should use something like this:

<div style="text-align:center">  
    <input type="submit" />  
</div>  

Or you could use something like this. By giving the element a width and specifying auto for the left and right margins the element will center itself in its parent.

<input type="submit" style="width: 300px; margin: 0 auto;" />

window.print() not working in IE

I am also facing this problem.

Problem in IE is newWin.document.write(divToPrint.innerHTML);

when we remove this line print function in IE is working. but again problem still exist about the content of page.

You can open the page using window.open, and write the content in that page. then print function will work in IE.This is alternate solution.

Best luck.

@Pratik

Python list directory, subdirectory, and files

A bit simpler one-liner:

import os
from itertools import product, chain

chain.from_iterable([[os.sep.join(w) for w in product([i[0]], i[2])] for i in os.walk(dir)])

Does Typescript support the ?. operator? (And, what's it called?)

Update: Yes its supported now!

It just got released with TypeScript 3.7 : https://devblogs.microsoft.com/typescript/announcing-typescript-3-7/

It is called optional chaining : https://devblogs.microsoft.com/typescript/announcing-typescript-3-7/#optional-chaining

With it the following:

let x = foo?.bar.baz(); 

is equivalent to:

let x = (foo === null || foo === undefined) ?
    undefined :
    foo.bar.baz();

Old answer

There is an open feature request for this on github where you can voice your opinion / desire : https://github.com/Microsoft/TypeScript/issues/16

How can I create an utility class?

For a completely stateless utility class in Java, I suggest the class be declared public and final, and have a private constructor to prevent instantiation. The final keyword prevents sub-classing and can improve efficiency at runtime.

The class should contain all static methods and should not be declared abstract (as that would imply the class is not concrete and has to be implemented in some way).

The class should be given a name that corresponds to its set of provided utilities (or "Util" if the class is to provide a wide range of uncategorized utilities).

The class should not contain a nested class unless the nested class is to be a utility class as well (though this practice is potentially complex and hurts readability).

Methods in the class should have appropriate names.

Methods only used by the class itself should be private.

The class should not have any non-final/non-static class fields.

The class can also be statically imported by other classes to improve code readability (this depends on the complexity of the project however).

Example:

public final class ExampleUtilities {
    // Example Utility method
    public static int foo(int i, int j) {
        int val;

        //Do stuff

        return val;
    }

    // Example Utility method overloaded
    public static float foo(float i, float j) {
        float val;

        //Do stuff

        return val;
    }

    // Example Utility method calling private method
    public static long bar(int p) {
        return hid(p) * hid(p);
    }

    // Example private method
    private static long hid(int i) {
        return i * 2 + 1;
    }
}

Perhaps most importantly of all, the documentation for each method should be precise and descriptive. Chances are methods from this class will be used very often and its good to have high quality documentation to complement the code.

LINK : fatal error LNK1561: entry point must be defined ERROR IN VC++

change it to Console (/SUBSYSTEM:CONSOLE) it will work

Close all infowindows in Google Maps API v3

You should have to click your map - $('#map-selector').click();

How often does python flush to a file?

You can also force flush the buffer to a file programmatically with the flush() method.

with open('out.log', 'w+') as f:
    f.write('output is ')
    # some work
    s = 'OK.'
    f.write(s)
    f.write('\n')
    f.flush()
    # some other work
    f.write('done\n')
    f.flush()

I have found this useful when tailing an output file with tail -f.

Access PHP variable in JavaScript

I'm not sure how necessary this is, and it adds a call to getElementById, but if you're really keen on getting inline JavaScript out of your code, you can pass it as an HTML attribute, namely:

<span class="metadata" id="metadata-size-of-widget" title="<?php echo json_encode($size_of_widget) ?>"></span>

And then in your JavaScript:

var size_of_widget = document.getElementById("metadata-size-of-widget").title;

What are the rules for JavaScript's automatic semicolon insertion (ASI)?

Just to add,

const foo = function(){ return "foo" } //this doesn't add a semicolon here.
(function (){
    console.log("aa");
})()

see this, using immediately invoked function expression(IIFE)

How do you overcome the svn 'out of date' error?

I sometimes get this with TortoiseSVN on windows. The solution for me is to svn update the directory, even though there are no revisions to download or update. It does something to the metadata, which magically fixes it.

Command not found error in Bash variable assignment

When you define any variable then you do not have to put in any extra spaces.

E.g.

name = "Stack Overflow"  
// it is not valid, you will get an error saying- "Command not found"

So remove spaces:

name="Stack Overflow" 

and it will work fine.

How should I declare default values for instance variables in Python?

You can also declare class variables as None which will prevent propagation. This is useful when you need a well defined class and want to prevent AttributeErrors. For example:

>>> class TestClass(object):
...     t = None
... 
>>> test = TestClass()
>>> test.t
>>> test2 = TestClass()
>>> test.t = 'test'
>>> test.t
'test'
>>> test2.t
>>>

Also if you need defaults:

>>> class TestClassDefaults(object):
...    t = None
...    def __init__(self, t=None):
...       self.t = t
... 
>>> test = TestClassDefaults()
>>> test.t
>>> test2 = TestClassDefaults([])
>>> test2.t
[]
>>> test.t
>>>

Of course still follow the info in the other answers about using mutable vs immutable types as the default in __init__.

How do I save a stream to a file in C#?

private void SaveFileStream(String path, Stream stream)
{
    var fileStream = new FileStream(path, FileMode.Create, FileAccess.Write);
    stream.CopyTo(fileStream);
    fileStream.Dispose();
}

C++ Cout & Cin & System "Ambiguous"

This kind of thing doesn't just magically happen on its own; you changed something! In industry we use version control to make regular savepoints, so when something goes wrong we can trace back the specific changes we made that resulted in that problem.

Since you haven't done that here, we can only really guess. In Visual Studio, Intellisense (the technology that gives you auto-complete dropdowns and those squiggly red lines) works separately from the actual C++ compiler under the bonnet, and sometimes gets things a bit wrong.

In this case I'd ask why you're including both cstdlib and stdlib.h; you should only use one of them, and I recommend the former. They are basically the same header, a C header, but cstdlib puts them in the namespace std in order to "C++-ise" them. In theory, including both wouldn't conflict but, well, this is Microsoft we're talking about. Their C++ toolchain sometimes leaves something to be desired. Any time the Intellisense disagrees with the compiler has to be considered a bug, whichever way you look at it!

Anyway, your use of using namespace std (which I would recommend against, in future) means that std::system from cstdlib now conflicts with system from stdlib.h. I can't explain what's going on with std::cout and std::cin.

Try removing #include <stdlib.h> and see what happens.

If your program is building successfully then you don't need to worry too much about this, but I can imagine the false positives being annoying when you're working in your IDE.

Excel - Combine multiple columns into one column

Not sure if this completely helps, but I had an issue where I needed a "smart" merge. I had two columns, A & B. I wanted to move B over only if A was blank. See below. It is based on a selection Range, which you could use to offset the first row, perhaps.

Private Sub MergeProjectNameColumns()
    Dim rngRowCount As Integer
    Dim i As Integer

    'Loop through column C and simply copy the text over to B if it is not blank
    rngRowCount = Range(dataRange).Rows.Count
    ActiveCell.Offset(0, 0).Select
    ActiveCell.Offset(0, 2).Select
    For i = 1 To rngRowCount
        If (Len(RTrim(ActiveCell.Value)) > 0) Then
            Dim currentValue As String
            currentValue = ActiveCell.Value
            ActiveCell.Offset(0, -1) = currentValue
        End If
        ActiveCell.Offset(1, 0).Select
    Next i

    'Now delete the unused column
    Columns("C").Select

    selection.Delete Shift:=xlToLeft
End Sub

How to SHUTDOWN Tomcat in Ubuntu?

I had a similar problem and found the following command to work:

sudo systemctl stop tomcat

After running this command you can type the following to verify that it is "disabled":

systemctl list-units

output for systemctl list-units

Excel - Using COUNTIF/COUNTIFS across multiple sheets/same column

This could be solved without VBA by the following technique.

In this example I am counting all the threes (3) in the range A:A of the sheets Page M904, Page M905 and Page M906.

List all the sheet names in a single continuous range like in the following example. Here listed in the range D3:D5.

enter image description here

Then by having the lookup value in cell B2, the result can be found in cell B4 by using the following formula:

=SUMPRODUCT(COUNTIF(INDIRECT("'"&D3:D5&"'!A:A"), B2))

How many threads can a Java VM support?

At least on Mac OS X 10.6 32bit, there is a limit (2560) by the operating system. Check this stackoverflow thread.

Checking version of angular-cli that's installed?

ng version or ng --version or ng v OR ng -v

You can use this 4 commands to check the which version of angular-cli installed in your machine.

time.sleep -- sleeps thread or process?

Only the thread unless your process has a single thread.

Referring to a Column Alias in a WHERE Clause

The most effective way to do it without repeating your code is use of HAVING instead of WHERE

SELECT logcount, logUserID, maxlogtm
   , DATEDIFF(day, maxlogtm, GETDATE()) AS daysdiff
FROM statslogsummary
HAVING daysdiff > 120

Integer value comparison

You can also use equals:

 Integer a = 0;

 if (a.equals(0)) {
     // a == 0
 }

which is equivalent to:

 if (a.intValue() == 0) {
     // a == 0
 }

and also:

 if (a == 0) {

 }

(the Java compiler automatically adds intValue())

Note that autoboxing/autounboxing can introduce a significant overhead (especially inside loops).

Does Android keep the .apk files? if so where?

If you are rooted, download the app Root Explorer. Best File manager for rooted users. Anyways, System/app has all the default apks that came with the phone, and data/apk has all the apks of the apps you have installed. Just long press on the apk you want (while in Root Explorer), get to your /sdcard folder and just paste.

How to host google web fonts on my own server?

You can download source fonts from https://github.com/google/fonts

After that use font-ranger tool to split your large Unicode font into multiple subsets (e.g. latin, cyrillic). You should do the following with the tool:

  • Generate subsets for each language you support
  • Use unicode-range subsetting for saving bandwidth
  • Remove bloat from your fonts and optimize them for web
  • Convert your fonts to a compressed woff2 format
  • Provide .woff fallback for older browsers
  • Customize font loading and rendering
  • Generate CSS file with @font-face rules
  • Self-host web fonts or use them locally

Font-Ranger: https://www.npmjs.com/package/font-ranger

P.S. You can also automate this using Node.js API

How to remove all duplicate items from a list

Just make a new list to populate, if the item for your list is not yet in the new list input it, else just move on to the next item in your original list.

for i in mylist:
  if i not in newlist:
    newlist.append(i)

I think this is the correct syntax, but my python is a bit shaky, I hope you at least get the idea.

Get size of folder or file

If you want to use Java 8 NIO API, the following program will print the size, in bytes, of the directory it is located in.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class PathSize {

    public static void main(String[] args) {
        Path path = Paths.get(".");
        long size = calculateSize(path);
        System.out.println(size);
    }

    /**
     * Returns the size, in bytes, of the specified <tt>path</tt>. If the given
     * path is a regular file, trivially its size is returned. Else the path is
     * a directory and its contents are recursively explored, returning the
     * total sum of all files within the directory.
     * <p>
     * If an I/O exception occurs, it is suppressed within this method and
     * <tt>0</tt> is returned as the size of the specified <tt>path</tt>.
     * 
     * @param path path whose size is to be returned
     * @return size of the specified path
     */
    public static long calculateSize(Path path) {
        try {
            if (Files.isRegularFile(path)) {
                return Files.size(path);
            }

            return Files.list(path).mapToLong(PathSize::calculateSize).sum();
        } catch (IOException e) {
            return 0L;
        }
    }

}

The calculateSize method is universal for Path objects, so it also works for files. Note that if a file or directory is inaccessible, in this case the returned size of the path object will be 0.

Twitter bootstrap collapse: change display of toggle button

You do like this. the function return the old text.

$('button').click(function(){ 
        $(this).text(function(i,old){
            return old=='Read More' ?  'Read Less' : 'Read More';
        });
    });

What does the "$" sign mean in jQuery or JavaScript?

In jQuery, the $ sign is just an alias to jQuery(), then an alias to a function.

This page reports:

Basic syntax is: $(selector).action()

  • A dollar sign to define jQuery
  • A (selector) to "query (or find)" HTML elements
  • A jQuery action() to be performed on the element(s)

Select rows where column is null

I'm not sure if this answers your question, but using the IS NULL construct, you can test whether any given scalar expression is NULL:

SELECT * FROM customers WHERE first_name IS NULL

On MS SQL Server, the ISNULL() function returns the first argument if it's not NULL, otherwise it returns the second. You can effectively use this to make sure a query always yields a value instead of NULL, e.g.:

SELECT ISNULL(column1, 'No value found') FROM mytable WHERE column2 = 23

Other DBMSes have similar functionality available.

If you want to know whether a column can be null (i.e., is defined to be nullable), without querying for actual data, you should look into information_schema.

Converting xml to string using C#

As Chris suggests, you can do it like this:

public string GetXMLAsString(XmlDocument myxml)
{
    return myxml.OuterXml;
}

Or like this:

public string GetXMLAsString(XmlDocument myxml)
    {

        StringWriter sw = new StringWriter();
        XmlTextWriter tx = new XmlTextWriter(sw);
        myxml.WriteTo(tx);

        string str = sw.ToString();// 
        return str;
    }

and if you really want to create a new XmlDocument then do this

XmlDocument newxmlDoc= myxml

How to set an button align-right with Bootstrap?

UPDATE: For Bootstrap 5

The class name is now "float-end" instead of "pull-right"

<div class="alert alert-info clearfix">
    <a href="#" class="alert-link">
      Summary:Its some description.......testtesttest
    </a> 
    <button type="button" class="btn btn-primary btn-lg float-end">
      Large button
    </button>
</div>

For Bootstrap 4 and under

Just add a simple pull-right class to the button, and make sure the container div is clearfixed:

<div class="alert alert-info clearfix">
    <a href="#" class="alert-link">
      Summary:Its some description.......testtesttest
    </a> 
    <button type="button" class="btn btn-primary btn-lg pull-right">
      Large button
    </button>
</div>

Get program path in VB.NET?

If the path is a drive, a slash will also appear in the path, and this time the use will cause problems. To unify, the best solution is the following command.

        Dim FileName As String = "MyFileName"
    Dim MyPath1 As String = Application.StartupPath().TrimEnd("\") & "\" & FileName
    Dim MyPath2 As String = My.Application.Info.DirectoryPath.TrimEnd("\") & "\" & FileName

Yarn install command error No such file or directory: 'install'

With kudos to all the answers that correctly suggest removing the Ubuntu yarn package and installing Yarn through NPM, here is a detailed answer with explanation (and, be warned, opinions):

The reason for the No such file or directory error from yarn install is that you are not using the "correct" Yarn: the software you get when you install yarn using the Ubuntu software sources is the "yarn" scenario testing tool from the cmdtest blackbox testing suite. This is likely not what you meant as Yarn is also a popular development lifecycle tool for Javascript application (similar to Make, Maven and friends).

The Javascript Yarn tool is not available from Ubuntu software sources but can be installed by NPM (which is another development lifecycle tool that Yarn aims to replace - so that's awkward...).

To make Yarn available in Ubuntu, start by removing cmdtest and its tools:

$ sudo apt purge cmdtest

Then make sure NPM is installed:

$ sudo apt install npm

Then use NPM to install Yarn:

$ npm install -g yarn

Note: using npm install -g will install a Javascript package for your current user account, which should be fine for most purposes. If you want to install Yarn for all users, you can use sudo for the NPM command, but that is not recommended: NPM packages are rarely audited for security in the context of a multi-user operating system and installing some packages might even break when installing them as "root". NPM used to warn against running it with sudo and the main reason it is not doing so today is that it annoys people that use sandboxed "root-like" environments (such as Docker) for building and deploying Javascript applications for single-user servers.

How to get HTTP Response Code using Selenium WebDriver

For those people using Python, you might consider Selenium Wire, a library for inspecting requests made by the browser during a test.

You get access to requests via the driver.requests attribute:

from seleniumwire import webdriver  # Import from seleniumwire

# Create a new instance of the Firefox driver
driver = webdriver.Firefox()

# Go to the Google home page
driver.get('https://www.google.com')

# Access requests via the `requests` attribute
for request in driver.requests:
    if request.response:
        print(
            request.url,
            request.response.status_code,
            request.response.headers['Content-Type']
        )

Prints:

https://www.google.com/ 200 text/html; charset=UTF-8
https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png 200 image/png
https://consent.google.com/status?continue=https://www.google.com&pc=s&timestamp=1531511954&gl=GB 204 text/html; charset=utf-8
https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png 200 image/png
https://ssl.gstatic.com/gb/images/i2_2ec824b0.png 200 image/png
https://www.google.com/gen_204?s=webaft&t=aft&atyp=csi&ei=kgRJW7DBONKTlwTK77wQ&rt=wsrt.366,aft.58,prt.58 204 text/html; charset=UTF-8
...

The library gives you the ability to access headers, status code, body content, as well as the ability to modify headers and rewrite URLs.

Can I save input from form to .txt in HTML, using JAVASCRIPT/jQuery, and then use it?

Answer is YES

<html>
<head>
</head>
<body>
<script language="javascript">
function WriteToFile()
{
var fso = new ActiveXObject("Scripting.FileSystemObject");
var s = fso.CreateTextFile("C:\\NewFile.txt", true);
var text=document.getElementById("TextArea1").innerText;
s.WriteLine(text);
s.WriteLine('***********************');
s.Close();
}
</script>

<form name="abc">
<textarea name="text">FIFA</textarea>
<button onclick="WriteToFile()">Click to save</Button>  
</form> 

</body>
</html>

Creating a script for a Telnet session?

I've used various methods for scripting telnet sessions under unix, but the simplest one is probably a sequence of echo and sleep commands, with their output piped into telnet. Piping the output into another command is also a possibility.

Silly example

(echo password; echo "show ip route"; sleep 1; echo "quit" ) | telnet myrouter

This (basicallly) retrieves the routing table of a Cisco router.

How to set a Timer in Java?

[Android] if someone looking to implement timer on android using java.

you need use UI thread like this to perform operations.

Timer timer = new Timer();
timer.schedule(new TimerTask() {
           @Override
            public void run() {
                ActivityName.this.runOnUiThread(new Runnable(){
                    @Override
                      public void run() {
                       // do something
                      }        
                });
            }
        }, 2000));

How to read/write a boolean when implementing the Parcelable interface?

out.writeInt(mBool ? 1 : 0); //Write
this.mBool =in.readInt()==1; //Read

Using C++ base class constructors?

Prefer initialization:

class C : public A
{
public:
    C(const string &val) : A(anInt) {}
};

In C++11, you can use inheriting constructors (which has the syntax seen in your example D).

Update: Inheriting Constructors have been available in GCC since version 4.8.


If you don't find initialization appealing (e.g. due to the number of possibilities in your actual case), then you might favor this approach for some TMP constructs:

class A
{
public: 
    A() {}
    virtual ~A() {}
    void init(int) { std::cout << "A\n"; }
};

class B : public A
{
public:
    B() : A() {}
    void init(int) { std::cout << "B\n"; }
};

class C : public A
{
public:
    C() : A() {}
    void init(int) { std::cout << "C\n"; }
};

class D : public A
{
public:
    D() : A() {}
    using A::init;
    void init(const std::string& s) { std::cout << "D -> " << s << "\n"; }
};

int main()
{
    B b; b.init(10);
    C c; c.init(10);
    D d; d.init(10); d.init("a");

    return 0;
}

How to create duplicate table with new name in SQL Server 2008

I have used this query it is created new table with existing data.

Query : select * into [newtablename] from [existingtable]

Here is the link Microsoft instructions. https://docs.microsoft.com/en-us/sql/relational-databases/tables/duplicate-tables?view=sql-server-2017

jquery Ajax call - data parameters are not being passed to MVC Controller action

If you have trouble with caching ajax you can turn it off:

$.ajaxSetup({cache: false});

Apache Spark: The number of cores vs. the number of executors

To hopefully make all of this a little more concrete, here’s a worked example of configuring a Spark app to use as much of the cluster as possible: Imagine a cluster with six nodes running NodeManagers, each equipped with 16 cores and 64GB of memory. The NodeManager capacities, yarn.nodemanager.resource.memory-mb and yarn.nodemanager.resource.cpu-vcores, should probably be set to 63 * 1024 = 64512 (megabytes) and 15 respectively. We avoid allocating 100% of the resources to YARN containers because the node needs some resources to run the OS and Hadoop daemons. In this case, we leave a gigabyte and a core for these system processes. Cloudera Manager helps by accounting for these and configuring these YARN properties automatically.

The likely first impulse would be to use --num-executors 6 --executor-cores 15 --executor-memory 63G. However, this is the wrong approach because:

63GB + the executor memory overhead won’t fit within the 63GB capacity of the NodeManagers. The application master will take up a core on one of the nodes, meaning that there won’t be room for a 15-core executor on that node. 15 cores per executor can lead to bad HDFS I/O throughput.

A better option would be to use --num-executors 17 --executor-cores 5 --executor-memory 19G. Why?

This config results in three executors on all nodes except for the one with the AM, which will have two executors. --executor-memory was derived as (63/3 executors per node) = 21. 21 * 0.07 = 1.47. 21 – 1.47 ~ 19.

The explanation was given in an article in Cloudera's blog, How-to: Tune Your Apache Spark Jobs (Part 2).

How does += (plus equal) work?

+= in JavaScript (as well as in many other languages) adds the right hand side to the variable on the left hand side, storing the result in that variable. Your example of 1 +=2 therefore does not make sense. Here is an example:

var x = 5;
x += 4; // x now equals 9, same as writing x = x + 4;
x -= 3; // x now equals 6, same as writing x = x - 3;
x *= 2; // x now equals 12, same as writing x = x * 2;
x /= 3; // x now equals 4, same as writing x = x / 3;

In your specific example the loop is summing the numbers in the array data.

When running UPDATE ... datetime = NOW(); will all rows updated have the same date/time?

They should have the same time, the update is supposed to be atomic, meaning that whatever how long it takes to perform, the action is supposed to occurs as if all was done at the same time.

If you're experiencing a different behaviour, it's time to change for another DBMS.

Calling jQuery method from onClick attribute in HTML

Don't do this!

Stay away from putting the events inline with the elements! If you don't, you're missing the point of JQuery (or one of the biggest ones at least).

The reason why it's easy to define click() handlers one way and not the other is that the other way is simply not desirable. Since you're just learning JQuery, stick to the convention. Now is not the time in your learning curve for JQuery to decide that everyone else is doing it wrong and you have a better way!

Simple way to count character occurrences in a string

Not optimal, but simple way to count occurrences:

String s = "...";
int counter = s.split("\\$", -1).length - 1;

Note:

  • Dollar sign is a special Regular Expression symbol, so it must be escaped with a backslash.
  • A backslash is a special symbol for escape characters such as newlines, so it must be escaped with a backslash.
  • The second argument of split prevents empty trailing strings from being removed.

How to set the max value and min value of <input> in html5 by javascript or jquery?

jQuery makes it easy to set any attributes for an element - just use the .attr() method:

$(document).ready(function() {
    $("input").attr({
       "max" : 10,        // substitute your own
       "min" : 2          // values (or variables) here
    });
});

The document ready handler is not required if your script block appears after the element(s) you want to manipulate.

Using a selector of "input" will set the attributes for all inputs though, so really you should have some way to identify the input in question. If you gave it an id you could say:

$("#idHere").attr(...

...or with a class:

$(".classHere").attr(...

Match everything except for specified strings

I had the same question, the solutions proposed were almost working but they had some issue. In the end the regex I used is:

^(?!red|green|blue).*

I tested it in Javascript and .NET.

.* should't be placed inside the negative lookahead like this: ^(?!.*red|green|blue) or it would make the first element behave different from the rest (i.e. "anotherred" wouldn't be matched while "anothergreen" would)

How to get correct timestamp in C#

Your mistake is using new DateTime(), which returns January 1, 0001 at 00:00:00.000 instead of current date and time. The correct syntax to get current date and time is DateTime.Now, so change this:

String timeStamp = GetTimestamp(new DateTime());

to this:

String timeStamp = GetTimestamp(DateTime.Now);

Javascript - sort array based on another array

  const result = sortingArr.map((i) => {
    const pos = itemsArray.findIndex(j => j[1] === i);
    const item = itemsArray[pos];
    itemsArray.splice(pos, 1);
    return item;
  });

How to use ConfigurationManager

Okay, it took me a while to see this, but there's no way this compiles:

return String.(ConfigurationManager.AppSettings[paramName]);

You're not even calling a method on the String type. Just do this:

return ConfigurationManager.AppSettings[paramName];

The AppSettings KeyValuePair already returns a string. If the name doesn't exist, it will return null.


Based on your edit you have not yet added a Reference to the System.Configuration assembly for the project you're working in.

Merge unequal dataframes and replace missing rows with 0

"all" option does not work anymore, The new parameter is;

x = pd.merge(df1, df2, how="outer")

How can I return the current action in an ASP.NET MVC view?

In the RC you can also extract route data like the action method name like this

ViewContext.Controller.ValueProvider["action"].RawValue
ViewContext.Controller.ValueProvider["controller"].RawValue
ViewContext.Controller.ValueProvider["id"].RawValue

Update for MVC 3

ViewContext.Controller.ValueProvider.GetValue("action").RawValue
ViewContext.Controller.ValueProvider.GetValue("controller").RawValue
ViewContext.Controller.ValueProvider.GetValue("id").RawValue

Update for MVC 4

ViewContext.Controller.RouteData.Values["action"]
ViewContext.Controller.RouteData.Values["controller"]
ViewContext.Controller.RouteData.Values["id"]

Update for MVC 4.5

ViewContext.RouteData.Values["action"]
ViewContext.RouteData.Values["controller"]
ViewContext.RouteData.Values["id"]

How do I use CMake?

Regarding CMake 3.13.3, platform Windows, and IDE Visual Studio 2017, I suggest this guide. In brief I suggest:
1. Download cmake > unzip it > execute it.
2. As example download GLFW > unzip it > create inside folder Build.
3. In cmake Browse "Source" > Browse "Build" > Configure and Generate.
4. In Visual Studio 2017 Build your Solution.
5. Get the binaries.
Regards.

Django - Reverse for '' not found. '' is not a valid view function or pattern name

Add store name to template like {% url 'app_name:url_name' %}

App_name = store

In urls.py, path('search', views.searched, name="searched"),

<form action="{% url 'store:searched' %}" method="POST">

Separating class code into a header and cpp file

A2DD.h

class A2DD
{
  private:
  int gx;
  int gy;

  public:
  A2DD(int x,int y);

  int getSum();
};

A2DD.cpp

  A2DD::A2DD(int x,int y)
  {
    gx = x;
    gy = y;
  }

  int A2DD::getSum()
  {
    return gx + gy;
  }

The idea is to keep all function signatures and members in the header file.
This will allow other project files to see how the class looks like without having to know the implementation.

And besides that, you can then include other header files in the implementation instead of the header. This is important because whichever headers are included in your header file will be included (inherited) in any other file that includes your header file.

Oracle Trigger ORA-04098: trigger is invalid and failed re-validation

Cause: A trigger was attempted to be retrieved for execution and was found to be invalid. This also means that compilation/authorization failed for the trigger.

Action: Options are to resolve the compilation/authorization errors, disable the trigger, or drop the trigger.

Syntax

ALTER TRIGGER trigger Name DISABLE;

ALTER TRIGGER trigger_Name ENABLE;

plain count up timer in javascript

Timer for jQuery - smaller, working, tested.

_x000D_
_x000D_
    var sec = 0;_x000D_
    function pad ( val ) { return val > 9 ? val : "0" + val; }_x000D_
    setInterval( function(){_x000D_
        $("#seconds").html(pad(++sec%60));_x000D_
        $("#minutes").html(pad(parseInt(sec/60,10)));_x000D_
    }, 1000);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<span id="minutes"></span>:<span id="seconds"></span>
_x000D_
_x000D_
_x000D_

Pure JavaScript:

_x000D_
_x000D_
    var sec = 0;_x000D_
    function pad ( val ) { return val > 9 ? val : "0" + val; }_x000D_
    setInterval( function(){_x000D_
        document.getElementById("seconds").innerHTML=pad(++sec%60);_x000D_
        document.getElementById("minutes").innerHTML=pad(parseInt(sec/60,10));_x000D_
    }, 1000);
_x000D_
<span id="minutes"></span>:<span id="seconds"></span>
_x000D_
_x000D_
_x000D_

Update:

This answer shows how to pad.

Stopping setInterval MDN is achieved with clearInterval MDN

var timer = setInterval ( function(){...}, 1000 );
...
clearInterval ( timer );

Fiddle

Getting the name of the currently executing method

To get the name of the method that called the current method you can use:

new Exception("is not thrown").getStackTrace()[1].getMethodName()

This works on my MacBook as well as on my Android phone

I also tried:

Thread.currentThread().getStackTrace()[1]

but Android will return "getStackTrace" I could fix this for Android with

Thread.currentThread().getStackTrace()[2]

but then I get the wrong answer on my MacBook

What is the meaning of git reset --hard origin/master?

In newer version of git (2.23+) you can use:

git switch -C master origin/master

-C is same as --force-create. Related Reference Docs

Check if input value is empty and display an alert

Also you can try this, if you want to focus on same text after error.

If you wants to show this error message in a paragraph then you can use this one:

 $(document).ready(function () {
    $("#submit").click(function () {
        if($('#selBooks').val() === '') {
            $("#Paragraph_id").text("Please select a book and then proceed.").show();
            $('#selBooks').focus();
            return false;
        }
    });
 });

How do I run .sh or .bat files from Terminal?

I had this problem for *.sh files in Yosemite and couldn't figure out what the correct path is for a folder on my Desktop...after some gnashing of teeth, dragged the file itself into the Terminal window; hey presto!!

MySQL error 1449: The user specified as a definer does not exist

Your view, "view_quotes" may have been copied from a different database where "web2vi" is a valid user into a database where "web2vi" is not a valid user.
Either add the "web2vi" user to the database or alter the view (normally removing the DEFINER='web2vi'@'%' part and executing the script will do the trick)

AJAX cross domain call

I faced the same problem during 2 days and I found the solution, and it's elegant after googling a lot. I needed xss Ajax for some widget clients which pull datastream from tiers websites to my Rails app. here's how I did.

Java Multiple Inheritance

Problem not solved. To sufficiently model this out and to prevent code replication you'd either need multiple inheritance or mixins. Interfaces with default functions are not sufficient because you cannot hold members in interfaces. Interface modeling leads to code replication in subclasses or statics, which is both evil.

All you can do is to use a custom construction and split it up in more components and compose it all together...

toy language

Java 8: merge lists with stream API

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

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

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

preferredStatusBarStyle isn't called

Note that when using the self.navigationController.navigationBar.barStyle = UIBarStyleBlack; solution

be sure to go to your plist and set "View controller-based status bar appearance" to YES. If its NO it will not work.

Adding one day to a date

Since you already have an answer to what's wrong with your code, I can bring another perspective on how you can play with datetimes generally, and solve your problem specifically.

Oftentimes you find yourself posing a problem in terms of solution. This is just one of the reasons you end up with an imperative code. It's great if it works though; there are just other, arguably more maintainable alternatives. One of them is a declarative code. The point is asking what you need, instead of how to get there.

In your particular case, this can look like the following. First, you need to find out what is it that you're looking for, that is, discover abstractions. In your case, it looks like you need a date. Not just any date, but the one having some standard representation. Say, ISO8601 date. There are at least two implementations: the first one is a date parsed from an ISO8601-formatted string (or a string in any other format actually), and the second is some future date which is a day later. Thus, the whole code could look like that:

(new Future(
    new DateTimeParsedFromISO8601('2009-09-30 20:24:00'),
    new OneDay()
))
    ->value();

For more examples with datetime juggling check out this one.

Deserializing JSON data to C# using JSON.NET

Building off of bbant's answer, this is my complete solution for deserializing JSON from a remote URL.

using Newtonsoft.Json;
using System.Net.Http;

namespace Base
{
    public class ApiConsumer<T>
    {
        public T data;
        private string url;

        public CalendarApiConsumer(string url)
        {
            this.url = url;
            this.data = getItems();
        }

        private T getItems()
        {
            T result = default(T);
            HttpClient client = new HttpClient();

            // This allows for debugging possible JSON issues
            var settings = new JsonSerializerSettings
            {
                Error = (sender, args) =>
                {
                    if (System.Diagnostics.Debugger.IsAttached)
                    {
                        System.Diagnostics.Debugger.Break();
                    }
                }
            };

            using (HttpResponseMessage response = client.GetAsync(this.url).Result)
            {
                if (response.IsSuccessStatusCode)
                {
                    result = JsonConvert.DeserializeObject<T>(response.Content.ReadAsStringAsync().Result, settings);
                }
            }
            return result;
        }
    }
}

Usage would be like:

ApiConsumer<FeedResult> feed = new ApiConsumer<FeedResult>("http://example.info/feeds/feeds.aspx?alt=json-in-script");

Where FeedResult is the class generated using the Xamasoft JSON Class Generator

Here is a screenshot of the settings I used, allowing for weird property names which the web version could not account for.

Xamasoft JSON Class Generator

Best way to store time (hh:mm) in a database

Are you sure you will only ever need the hours and minutes? If you want to do anything meaningful with it (like for example compute time spans between two such data points) not having information about time zones and DST may give incorrect results. Time zones do maybe not apply in your case, but DST most certainly will.

SQL Server PRINT SELECT (Print a select query result)?

Try this query

DECLARE @PrintVarchar nvarchar(max) = (Select Sum(Amount) From Expense)
PRINT 'Varchar format =' + @PrintVarchar

DECLARE @PrintInt int = (Select Sum(Amount) From Expense)
PRINT @PrintInt

Convert HTML to NSAttributedString in iOS

Helpful Extensions

Inspired by this thread, a pod, and Erica Sadun's ObjC example in iOS Gourmet Cookbook p.80, I wrote an extension on String and on NSAttributedString to go back and forth between HTML plain-strings and NSAttributedStrings and vice versa -- on GitHub here, which I have found helpful.

The signatures are (again, full code in a Gist, link above):

extension NSAttributedString {
    func encodedString(ext: DocEXT) -> String?
    static func fromEncodedString(_ eString: String, ext: DocEXT) -> NSAttributedString? 
    static func fromHTML(_ html: String) -> NSAttributedString? // same as above, where ext = .html
}

extension String {
    func attributedString(ext: DocEXT) -> NSAttributedString?
}

enum DocEXT: String { case rtfd, rtf, htm, html, txt }

How do we change the URL of a working GitLab install?

Do not forget to clear the cache after updating the external_url param in /etc/gitlab/gitlab.rb, otherwise your existing project clone URLs will still be showing your old host name.

A simple 3 step process to change the hostname is as follows

  • update the external_url param in /etc/gitlab/gitlab.rb
  • sudo gitlab-ctl reconfigure
  • sudo gitlab-ctl restart
  • sudo gitlab-rake cache:clear

Ref:

https://forum.gitlab.com/t/clone-url-wont-change/21692/6

Python - 'ascii' codec can't decode byte

If you are starting the python interpreter from a shell on Linux or similar systems (BSD, not sure about Mac), you should also check the default encoding for the shell.

Call locale charmap from the shell (not the python interpreter) and you should see

[user@host dir] $ locale charmap
UTF-8
[user@host dir] $ 

If this is not the case, and you see something else, e.g.

[user@host dir] $ locale charmap
ANSI_X3.4-1968
[user@host dir] $ 

Python will (at least in some cases such as in mine) inherit the shell's encoding and will not be able to print (some? all?) unicode characters. Python's own default encoding that you see and control via sys.getdefaultencoding() and sys.setdefaultencoding() is in this case ignored.

If you find that you have this problem, you can fix that by

[user@host dir] $ export LC_CTYPE="en_EN.UTF-8"
[user@host dir] $ locale charmap
UTF-8
[user@host dir] $ 

(Or alternatively choose whichever keymap you want instead of en_EN.) You can also edit /etc/locale.conf (or whichever file governs the locale definition in your system) to correct this.

what do <form action="#"> and <form method="post" action="#"> do?

Apparently, action was required prior to HTML5 (and # was just a stand in), but you no longer have to use it.

See The Action Attribute:

When specified with no attributes, as below, the data is sent to the same page that the form is present on:

<form>

Update all objects in a collection using LINQ

There is no built-in extension method to do this. Although defining one is fairly straight forward. At the bottom of the post is a method I defined called Iterate. It can be used like so

collection.Iterate(c => { c.PropertyToSet = value;} );

Iterate Source

public static void Iterate<T>(this IEnumerable<T> enumerable, Action<T> callback)
{
    if (enumerable == null)
    {
        throw new ArgumentNullException("enumerable");
    }

    IterateHelper(enumerable, (x, i) => callback(x));
}

public static void Iterate<T>(this IEnumerable<T> enumerable, Action<T,int> callback)
{
    if (enumerable == null)
    {
        throw new ArgumentNullException("enumerable");
    }

    IterateHelper(enumerable, callback);
}

private static void IterateHelper<T>(this IEnumerable<T> enumerable, Action<T,int> callback)
{
    int count = 0;
    foreach (var cur in enumerable)
    {
        callback(cur, count);
        count++;
    }
}

UPDATE multiple tables in MySQL using LEFT JOIN

UPDATE  t1
LEFT JOIN
        t2
ON      t2.id = t1.id
SET     t1.col1 = newvalue
WHERE   t2.id IS NULL

Note that for a SELECT it would be more efficient to use NOT IN / NOT EXISTS syntax:

SELECT  t1.*
FROM    t1
WHERE   t1.id NOT IN
        (
        SELECT  id
        FROM    t2
        )

See the article in my blog for performance details:

Unfortunately, MySQL does not allow using the target table in a subquery in an UPDATE statement, that's why you'll need to stick to less efficient LEFT JOIN syntax.

Calling Python in Java?

Several of the answers mention that you can use JNI or JNA to access cpython but I would not recommend starting from scratch because there are already open source libraries for accessing cpython from java. For example:

How to debug heap corruption errors?

I'd like to add my experience. In the last few days, I solved an instance of this error in my application. In my particular case, the errors in the code were:

  • Removing elements from an STL collection while iterating over it (I believe there are debug flags in Visual Studio to catch these things; I caught it during code review)
  • This one is more complex, I'll divide it in steps:
    • From a native C++ thread, call back into managed code
    • In managed land, call Control.Invoke and dispose a managed object which wraps the native object to which the callback belongs.
    • Since the object is still alive inside the native thread (it will remain blocked in the callback call until Control.Invoke ends). I should clarify that I use boost::thread, so I use a member function as the thread function.
    • Solution: Use Control.BeginInvoke (my GUI is made with Winforms) instead so that the native thread can end before the object is destroyed (the callback's purpose is precisely notifying that the thread ended and the object can be destroyed).

Hex transparency in colors

Color hexadecimal notation is like following: #AARRGGBB

  • A : alpha
  • R : red
  • G : green
  • B : blue

You should first look at how hexadecimal works. You can write at most FF.

How to access a dictionary key value present inside a list?

First of all don't use 'list' as variable name.

If you have simple dictionaries with unique keys then you can do the following(note that new dictionary object with all items from sub-dictionaries will be created):

res  = {}
for line in listOfDicts:
   res.update(line)
res['d']
>>> 4

Otherwise:

getValues = lambda key,inputData: [subVal[key] for subVal in inputData if key in subVal]
getValues('d', listOfDicts)
>>> [4]

Or very base:

def get_value(listOfDicts, key):
    for subVal in listOfDicts:
        if key in subVal:
            return subVal[key]

Change GitHub Account username

Yes, it's possible. But first read, "What happens when I change my username?"

To change your username, click your profile picture in the top right corner, then click Settings. On the left side, click Account. Then click Change username.

Find out which remote branch a local branch is tracking

Another simple way is to use

cat .git/config in a git repo

This will list details for local branches

Make Bootstrap 3 Tabs Responsive

Bootstrap tabs are not responsive out of the box. Responsive, IMO, is a style change, changing functions is Adaptive. There are a few plugins to turn the Bootstrap 3 tabs into a Collapse component. The best and most updated one is : https://github.com/flatlogic/bootstrap-tabcollapse.

Here's one way of implementing it:

DEMO: http://jsbin.com/zibani/1/

EDIT: http://jsbin.com/zibani/1/edit

This turns the content into a collapse component:

enter image description here

Dependencies:

  1. Bootstrap 3.2 css or higher but still in the 3 series
  2. Bootstrap 3.2 jQuery or higher but still in the 3 series
  3. Compatible version of bootstrap-tabcollapse.js

HTML -- same as question with class name addition:

       <ul class="nav nav-tabs content-tabs" id="maincontent" role="tablist">

jQuery:

$(document).ready(function() {

    // DEPENDENCY: https://github.com/flatlogic/bootstrap-tabcollapse
    $('.content-tabs').tabCollapse();

    // initialize tab function
    $('.nav-tabs a').click(function(e) {
        e.preventDefault();
        $(this).tab('show');
    });

});

CSS -- optional for fat fingers and active states:

.panel-heading {
    padding: 0
}
.panel-heading a {
    display: block;
    padding: 20px 10px;
}
.panel-heading a.collapsed {
    background: #fff
}
.panel-heading a {
    background: #f7f7f7;
    border-radius: 5px;
}
.panel-heading a:after {
    content: '-'
}
.panel-heading a.collapsed:after {
    content: '+'
}
.nav.nav-tabs li a,
.nav.nav-tabs li.active > a:hover,
.nav.nav-tabs li.active > a:active,
.nav.nav-tabs li.active > a:focus {
    border-bottom-width: 0px;
    outline: none;
}
.nav.nav-tabs li a {
    padding-top: 20px;
    padding-bottom: 20px;
}
.tab-pane {
    background: #fff;
    padding: 10px;
    border: 1px solid #ddd;
    margin-top: -1px;
}

Animate the transition between fragments

For anyone else who gets caught, ensure setCustomAnimations is called before the call to replace/add when building the transaction.

How to get last month/year in java?

you can use the Calendar class to do so:

SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd HH:mm");
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, -1);
System.out.println(format.format(cal.getTime()));

This prints : 2012.09.10 11:01 for actual date 2012.10.10 11:01

How to align an image dead center with bootstrap

You could change the CSS of the previous solution as below:

.container, .row { text-align: center; }

This should center all the elements in the parent div as well.

The first day of the current month in php using date_modify as DateTime object

I use this with a daily cron job to check if I should send an email on the first day of any given month to my affiliates. It's a few more lines than the other answers but solid as a rock.

//is this the first day of the month?
$date = date('Y-m-d');
$pieces = explode("-", $date);
$day = $pieces[2];

//if it's not the first day then stop
if($day != "01") {

     echo "error - it's not the first of the month today";
     exit;

}

The remote server returned an error: (403) Forbidden

Add the following line:

request.UseDefaultCredentials = true;

This will let the application use the credentials of the logged in user to access the site. If it's returning 403, clearly it's expecting authentication.

It's also possible that you (now?) have an authenticating proxy in between you and the remote site. In which case, try:

request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;

Hope this helps.

String Padding in C

#include<stdio.h>
#include <string.h>


void padLeft(int length, char pad, char* inStr,char* outStr) {
    int minLength = length * sizeof(char);
    if (minLength < sizeof(outStr)) {
        return;
    }

    int padLen = length - strlen(inStr);
    padLen = padLen < 0 ? 0 : padLen;

    memset(outStr, 0, sizeof(outStr));
    memset(outStr, pad,padLen);
    memcpy(outStr+padLen, inStr, minLength - padLen);
}