Programs & Examples On #32bit 64bit

Issues related to the use of a 64bit vs a 32bit architecture

How do I use a 32-bit ODBC driver on 64-bit Server 2008 when the installer doesn't create a standard DSN?

Open IIS manager, select Application Pools, select the application pool you are using, click on Advanced Settings in the right-hand menu. Under General, set "Enable 32-Bit Applications" to "True".

How to find out if an installed Eclipse is 32 or 64 bit version?

Open eclipse.ini in the installation directory, and observe the line with text:

plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.0.200.v20090519 then it is 64 bit.

If it would be plugins/org.eclipse.equinox.launcher.win32.win32.x86_32_1.0.200.v20090519 then it is 32 bit.

How to determine whether a given Linux is 32 bit or 64 bit?

If you have a 64-bit OS, instead of i686, you have x86_64 or ia64 in the output of uname -a. In that you do not have any of these two strings; you have a 32-bit OS (note that this does not mean that your CPU is not 64-bit).

Is it possible to install both 32bit and 64bit Java on Windows 7?

To install 32-bit Java on Windows 7 (64-bit OS + Machine). You can do:

1) Download JDK: http://javadl.sun.com/webapps/download/AutoDL?BundleId=58124
2) Download JRE: http://www.java.com/en/download/installed.jsp?jre_version=1.6.0_22&vendor=Sun+Microsystems+Inc.&os=Linux&os_version=2.6.41.4-1.fc15.i686

3) System variable create: C:\program files (x86)\java\jre6\bin\

4) Anywhere you type java -version

it use 32-bit on (64-bit). I have to use this because lots of third party libraries do not work with 64-bit. Java wake up from the hell, give us peach :P. Go-language is killer.

Range of values in C Int and Long 32 - 64 bits

Take a look at limits.h. You can find the specific values for your compiler. INT_MIN and INT_MAX will be of interest.

Why do 64-bit DLLs go to System32 and 32-bit DLLs to SysWoW64 on 64-bit Windows?

I should add: You should not be putting your dll's into \system32\ anyway! Modify your code, modify your installer... find a home for your bits that is NOT anywhere under c:\windows\

For example, your installer puts your dlls into:

\program files\<your app dir>\

or

\program files\common files\<your app name>\

(Note: The way you actually do this is to use the environment var: %ProgramFiles% or %ProgramFiles(x86)% to find where Program Files is.... you do not assume it is c:\program files\ ....)

and then sets a registry tag :

HKLM\software\<your app name>
-- dllLocation

The code that uses your dlls reads the registry, then dynamically links to the dlls in that location.

The above is the smart way to go.

You do not ever install your dlls, or third party dlls into \system32\ or \syswow64. If you have to statically load, you put your dlls in your exe dir (where they will be found). If you cannot predict the exe dir (e.g. some other exe is going to call your dll), you may have to put your dll dir into the search path (avoid this if at all poss!)

system32 and syswow64 are for Windows provided files... not for anyone elses files. The only reason folks got into the bad habit of putting stuff there is because it is always in the search path, and many apps/modules use static linking. (So, if you really get down to it, the real sin is static linking -- this is a sin in native code and managed code -- always always always dynamically link!)

CentOS 64 bit bad ELF interpreter

In general, when you get an error like this, just do

yum provides ld-linux.so.2

then you'll see something like:

glibc-2.20-5.fc21.i686 : The GNU libc libraries
Repo        : fedora
Matched from:
Provides    : ld-linux.so.2

and then you just run the following like BRPocock wrote (in case you were wondering what the logic was...):

yum install glibc.i686

Determining 32 vs 64 bit in C++

Try this:
#ifdef _WIN64
// 64 bit code
#elif _WIN32
// 32 bit code
#else
   if(sizeof(void*)==4)

       // 32 bit code
   else 

       // 64 bit code   
#endif

MS Access DB Engine (32-bit) with Office 64-bit

I hate to answer my own questions, but I did finally find a solution that actually works (using socket communication between services may fix the problem, but it creates even more problems). Since our database is legacy, it merely required Microsoft.ACE.OLEDB.12.0 in the connection string. It turns out that this was also included in Office 2007 (and MSDE 2007), where there is only a 32-bit version available. So, instead of installing MSDE 2010 32-bit, we install MSDE 2007, and it works just fine. Other applications can then install 64-bit MSDE 2010 (or 64-bit Office 2010), and it does not conflict with our application.

Thus far, it appears this is an acceptable solution for all Windows OS environments.

Can't start Eclipse - Java was started but returned exit code=13

In "Path" variable removed "C:\ProgramData\Oracle\Java\javapath" and replaced it with "C:\Program Files\Java\jdk1.8.0_212\bin"

It worked for me.

how much memory can be accessed by a 32 bit machine?

basically 32bit architecture can address 4GB as you expected. There are some techniques which allows processor to address more data like AWE or PAE.

Retrieving the COM class factory for component with CLSID {XXXX} failed due to the following error: 80040154

My problem was that I had the wrong MS Sync FrameWork version (1.0) in my project References. After update to the version 2.1, the error was gone and life is good again.

How can I test a Windows DLL file to determine if it is 32 bit or 64 bit?

A crude way would be to call dumpbin with the headers option from the Visual Studio tools on each DLL and look for the appropriate output:

dumpbin /headers my32bit.dll

PE signature found

File Type: DLL

FILE HEADER VALUES
             14C machine (x86)
               1 number of sections
        45499E0A time date stamp Thu Nov 02 03:28:10 2006
               0 file pointer to symbol table
               0 number of symbols
              E0 size of optional header
            2102 characteristics
                   Executable
                   32 bit word machine
                   DLL

OPTIONAL HEADER VALUES
             10B magic # (PE32)

You can see a couple clues in that output that it is a 32 bit DLL, including the 14C value that Paul mentions. Should be easy to look for in a script.

Should I use Python 32bit or Python 64bit

You do not need to use 64bit since windows will emulate 32bit programs using wow64. But using the native version (64bit) will give you more performance.

Detect whether Office is 32bit or 64bit via the registry

Search the registry for the install path of the office component you are interested in, e.g. for Excel 2010 look in SOFTWARE(Wow6432Node)\Microsoft\Office\14.0\Excel\InstallRoot. It will only be either in the 32-bit registry or the 64-bit registry not both.

Microsoft.Jet.OLEDB.4.0' provider is not registered on the local machine

I have the same problem

Microsoft.Jet.OLEDB.4.0' provider is not registered on the local machine

I applied the answer by neo but it did not work until I change the provider to “Provider=Microsoft.ACE.OLEDB.12.0;” in connection string.

Hope this will help if some one face the same issue.

Missing include "bits/c++config.h" when cross compiling 64 bit program on 32 bit in Ubuntu

While compiling in RHEL 6.2 (x86_64), I installed both 32bit and 64bit libstdc++-dev packages, but I had the "c++config.h no such file or directory" problem.

Resolution:

The directory /usr/include/c++/4.4.6/x86_64-redhat-linux was missing.

I did the following:

cd /usr/include/c++/4.4.6/
mkdir x86_64-redhat-linux
cd x86_64-redhat-linux
ln -s ../i686-redhat-linux 32

I'm now able to compile 32bit binaries on a 64bit OS.

Running vbscript from batch file

This is the command for the batch file and it can run the vbscript.

C:\Windows\SysWOW64\cmd.exe /c cscript C:\Windows\SysWOW64\...\necdaily.vbs

Passing javascript variable to html textbox

You could also use to localStorage feature of HTML5 to store your test value and then access it at any other point in your website by using the localStorage.getItem() method. To see how this works you should look at the w3schools explanation or the explanation from the Opera Developer website. Hope this helps.

HTML 5 Favicon - Support?

The answers provided (at the time of this post) are link only answers so I thought I would summarize the links into an answer and what I will be using.

When working to create Cross Browser Favicons (including touch icons) there are several things to consider.

The first (of course) is Internet Explorer. IE does not support PNG favicons until version 11. So our first line is a conditional comment for favicons in IE 9 and below:

<!--[if IE]><link rel="shortcut icon" href="path/to/favicon.ico"><![endif]-->

To cover the uses of the icon create it at 32x32 pixels. Notice the rel="shortcut icon" for IE to recognize the icon it needs the word shortcut which is not standard. Also we wrap the .ico favicon in a IE conditional comment because Chrome and Safari will use the .ico file if it is present, despite other options available, not what we would like.

The above covers IE up to IE 9. IE 11 accepts PNG favicons, however, IE 10 does not. Also IE 10 does not read conditional comments thus IE 10 won't show a favicon. With IE 11 and Edge available I don't see IE 10 in widespread use, so I ignore this browser.

For the rest of the browsers we are going to use the standard way to cite a favicon:

<link rel="icon" href="path/to/favicon.png">

This icon should be 196x196 pixels in size to cover all devices that may use this icon.

To cover touch icons on mobile devices we are going to use Apple's proprietary way to cite a touch icon:

<link rel="apple-touch-icon-precomposed" href="apple-touch-icon-precomposed.png">

Using rel="apple-touch-icon-precomposed" will not apply the reflective shine when bookmarked on iOS. To have iOS apply the shine use rel="apple-touch-icon". This icon should be sized to 180x180 pixels as that is the current size recommend by Apple for the latest iPhones and iPads. I have read Blackberry will also use rel="apple-touch-icon-precomposed".

As a note: Chrome for Android states:

The apple-touch-* are deprecated, and will be supported only for a short time. (Written as of beta for m31 of Chrome).

Custom Tiles for IE 11+ on Windows 8.1+

IE 11+ on Windows 8.1+ does offer a way to create pinned tiles for your site.

Microsoft recommends creating a few tiles at the following size:

Small: 128 x 128

Medium: 270 x 270

Wide: 558 x 270

Large: 558 x 558

These should be transparent images as we will define a color background next.

Once these images are created you should create an xml file called browserconfig.xml with the following code:

<?xml version="1.0" encoding="utf-8"?>
<browserconfig>
  <msapplication>
    <tile>
      <square70x70logo src="images/smalltile.png"/>
      <square150x150logo src="images/mediumtile.png"/>
      <wide310x150logo src="images/widetile.png"/>
      <square310x310logo src="images/largetile.png"/>
      <TileColor>#009900</TileColor>
    </tile>
  </msapplication>
</browserconfig>

Save this xml file in the root of your site. When a site is pinned IE will look for this file. If you want to name the xml file something different or have it in a different location add this meta tag to the head:

<meta name="msapplication-config" content="path-to-browserconfig/custom-name.xml" />

For additional information on IE 11+ custom tiles and using the XML file visit Microsoft's website.

Putting it all together:

To put it all together the above code would look like this:

<!-- For IE 9 and below. ICO should be 32x32 pixels in size -->
<!--[if IE]><link rel="shortcut icon" href="path/to/favicon.ico"><![endif]-->

<!-- Touch Icons - iOS and Android 2.1+ 180x180 pixels in size. --> 
<link rel="apple-touch-icon-precomposed" href="apple-touch-icon-precomposed.png">

<!-- Firefox, Chrome, Safari, IE 11+ and Opera. 196x196 pixels in size. -->
<link rel="icon" href="path/to/favicon.png">

Windows Phone Live Tiles

If a user is using a Windows Phone they can pin a website to the start screen of their phone. Unfortunately, when they do this it displays a screenshot of your phone, not a favicon (not even the MS specific code referenced above). To make a "Live Tile" for Windows Phone Users for your website one must use the following code:

Here are detailed instructions from Microsoft but here is a synopsis:

Step 1

Create a square image for your website, to support hi-res screens create it at 768x768 pixels in size.

Step 2

Add a hidden overlay of this image. Here is example code from Microsoft:

<div id="TileOverlay" onclick="ToggleTileOverlay()" style='background-color: Highlight; height: 100%; width: 100%; top: 0px; left: 0px; position: fixed; color: black; visibility: hidden'>
  <img src="customtile.png" width="320" height="320" />
  <div style='margin-top: 40px'>
     Add text/graphic asking user to pin to start using the menu...
  </div>
</div>

Step 3

You then can add thew following line to add a pin to start link:

<a href="javascript:ToggleTileOverlay()">Pin this site to your start screen</a>

Microsoft recommends that you detect windows phone and only show that link to those users since it won't work for other users.

Step 4

Next you add some JS to toggle the overlay visibility

<script>
function ToggleTileOverlay() {
 var newVisibility =     (document.getElementById('TileOverlay').style.visibility == 'visible') ? 'hidden' : 'visible';
 document.getElementById('TileOverlay').style.visibility =    newVisibility;
}
</script>

Note on Sizes

I am using one size as every browser will scale down the image as necessary. I could add more HTML to specify multiple sizes if desired for those with a lower bandwidth but I am already compressing the PNG files heavily using TinyPNG and I find this unnecessary for my purposes. Also, according to philippe_b's answer Chrome and Firefox have bugs that cause the browser to load all sizes of icons. Using one large icon may be better than multiple smaller ones because of this.

Further Reading

For those who would like more details see the links below:

Convert Difference between 2 times into Milliseconds?

var firstTime = DateTime.Now;
var secondTime = DateTime.Now.AddMilliseconds(600);
var diff = secondTime.Subtract(firstTime).Milliseconds;


// var diff = DateTime.Now.AddMilliseconds(600).Subtract(DateTime.Now).Milliseconds;

Convert between UIImage and Base64 string

See my class -  AppExtension.swift


// MARK: - UIImage (Base64 Encoding)

public enum ImageFormat {
    case PNG
    case JPEG(CGFloat)
}

extension UIImage {

    public func base64(format: ImageFormat) -> String {
        var imageData: NSData
        switch format {
        case .PNG: imageData = UIImagePNGRepresentation(self)
        case .JPEG(let compression): imageData = UIImageJPEGRepresentation(self, compression)
        }
        return imageData.base64EncodedStringWithOptions(.allZeros)
    }
}

How do I seed a random class to avoid getting duplicate random values

public static Random rand = new Random(); // this happens once, and will be great at preventing duplicates

Note, this is not to be used for cryptographic purposes.

Bootstrap 3 Glyphicons are not working

I had this problem and it was caused by the variables.less file. Overriding it to set the icon-font-path value solved the problem.

The file structured looks like this:

\Content
        \Bootstrap
        \Fonts
 styles.less
 variables.less

Adding my own variables.less file in the root of Content and referencing this in styles.less resolved the 404 error.

Variables.less contains:

@icon-font-path:          "fonts/";

Why is the gets function so dangerous that it should not be used?

You can't remove API functions without breaking the API. If you would, many applications would no longer compile or run at all.

This is the reason that one reference gives:

Reading a line that overflows the array pointed to by s results in undefined behavior. The use of fgets() is recommended.

Difference between Role and GrantedAuthority in Spring Security

AFAIK GrantedAuthority and roles are same in spring security. GrantedAuthority's getAuthority() string is the role (as per default implementation SimpleGrantedAuthority).

For your case may be you can use Hierarchical Roles

<bean id="roleVoter" class="org.springframework.security.access.vote.RoleHierarchyVoter">
    <constructor-arg ref="roleHierarchy" />
</bean>
<bean id="roleHierarchy"
        class="org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl">
    <property name="hierarchy">
        <value>
            ROLE_ADMIN > ROLE_createSubUsers
            ROLE_ADMIN > ROLE_deleteAccounts 
            ROLE_USER > ROLE_viewAccounts
        </value>
    </property>
</bean>

Not the exact sol you looking for, but hope it helps

Edit: Reply to your comment

Role is like a permission in spring-security. using intercept-url with hasRole provides a very fine grained control of what operation is allowed for which role/permission.

The way we handle in our application is, we define permission (i.e. role) for each operation (or rest url) for e.g. view_account, delete_account, add_account etc. Then we create logical profiles for each user like admin, guest_user, normal_user. The profiles are just logical grouping of permissions, independent of spring-security. When a new user is added, a profile is assigned to it (having all permissible permissions). Now when ever user try to perform some action, permission/role for that action is checked against user grantedAuthorities.

Also the defaultn RoleVoter uses prefix ROLE_, so any authority starting with ROLE_ is considered as role, you can change this default behavior by using a custom RolePrefix in role voter and using it in spring security.

Input and output numpy arrays to h5py

A cleaner way to handle file open/close and avoid memory leaks:

Prep:

import numpy as np
import h5py

data_to_write = np.random.random(size=(100,20)) # or some such

Write:

with h5py.File('name-of-file.h5', 'w') as hf:
    hf.create_dataset("name-of-dataset",  data=data_to_write)

Read:

with h5py.File('name-of-file.h5', 'r') as hf:
    data = hf['name-of-dataset'][:]

How To: Best way to draw table in console app (C#)

This is an improvement to a previous answer. It adds support for values with varying lengths and rows with a varying number of cells. For example:

+------------------------------------------------------------------------------+
¦Identifier¦     Type¦               Description¦  CPU Credit Use¦Hours¦Balance¦
+----------+---------+--------------------------+----------------+-----+-------+
¦ i-1234154¦ t2.small¦       This is an example.¦         3263.75¦  360¦
+----------+---------+--------------------------+----------------+-----+
¦ i-1231412¦ t2.small¦  This is another example.¦         3089.93¦
+----------------------------------------------------------------+

Here is the code:

public class ArrayPrinter
{
    const string TOP_LEFT_JOINT = "+";
    const string TOP_RIGHT_JOINT = "+";
    const string BOTTOM_LEFT_JOINT = "+";
    const string BOTTOM_RIGHT_JOINT = "+";
    const string TOP_JOINT = "-";
    const string BOTTOM_JOINT = "-";
    const string LEFT_JOINT = "+";
    const string JOINT = "+";
    const string RIGHT_JOINT = "¦";
    const char HORIZONTAL_LINE = '-';
    const char PADDING = ' ';
    const string VERTICAL_LINE = "¦";

    private static int[] GetMaxCellWidths(List<string[]> table)
    {
        int maximumCells = 0;
        foreach (Array row in table)
        {
            if (row.Length > maximumCells)
                maximumCells = row.Length;
        }

        int[] maximumCellWidths = new int[maximumCells];
        for (int i = 0; i < maximumCellWidths.Length; i++)
            maximumCellWidths[i] = 0;

        foreach (Array row in table)
        {
            for (int i = 0; i < row.Length; i++)
            {
                if (row.GetValue(i).ToString().Length > maximumCellWidths[i])
                    maximumCellWidths[i] = row.GetValue(i).ToString().Length;
            }
        }

        return maximumCellWidths;
    }

    public static string GetDataInTableFormat(List<string[]> table)
    {
        StringBuilder formattedTable = new StringBuilder();
        Array nextRow = table.FirstOrDefault();
        Array previousRow = table.FirstOrDefault();

        if (table == null || nextRow == null)
            return String.Empty;

        // FIRST LINE:
        int[] maximumCellWidths = GetMaxCellWidths(table);
        for (int i = 0; i < nextRow.Length; i++)
        {
            if (i == 0 && i == nextRow.Length - 1)
                formattedTable.Append(String.Format("{0}{1}{2}", TOP_LEFT_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE), TOP_RIGHT_JOINT));
            else if (i == 0)
                formattedTable.Append(String.Format("{0}{1}", TOP_LEFT_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE)));
            else if (i == nextRow.Length - 1)
                formattedTable.AppendLine(String.Format("{0}{1}{2}", TOP_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE), TOP_RIGHT_JOINT));
            else
                formattedTable.Append(String.Format("{0}{1}", TOP_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE)));
        }

        int rowIndex = 0;
        int lastRowIndex = table.Count - 1;
        foreach (Array thisRow in table)
        {
            // LINE WITH VALUES:
            int cellIndex = 0;
            int lastCellIndex = thisRow.Length - 1;
            foreach (object thisCell in thisRow)
            {
                string thisValue = thisCell.ToString().PadLeft(maximumCellWidths[cellIndex], PADDING);

                if (cellIndex == 0 && cellIndex == lastCellIndex)
                    formattedTable.AppendLine(String.Format("{0}{1}{2}", VERTICAL_LINE, thisValue, VERTICAL_LINE));
                else if (cellIndex == 0)
                    formattedTable.Append(String.Format("{0}{1}", VERTICAL_LINE, thisValue));
                else if (cellIndex == lastCellIndex)
                    formattedTable.AppendLine(String.Format("{0}{1}{2}", VERTICAL_LINE, thisValue, VERTICAL_LINE));
                else
                    formattedTable.Append(String.Format("{0}{1}", VERTICAL_LINE, thisValue));

                cellIndex++;
            }

            previousRow = thisRow;

            // SEPARATING LINE:
            if (rowIndex != lastRowIndex)
            {
                nextRow = table[rowIndex + 1];

                int maximumCells = Math.Max(previousRow.Length, nextRow.Length);
                for (int i = 0; i < maximumCells; i++)
                {
                    if (i == 0 && i == maximumCells - 1)
                    {
                        formattedTable.Append(String.Format("{0}{1}{2}", LEFT_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE), RIGHT_JOINT));
                    }
                    else if (i == 0)
                    {
                        formattedTable.Append(String.Format("{0}{1}", LEFT_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE)));
                    }
                    else if (i == maximumCells - 1)
                    {
                        if (i > previousRow.Length)
                            formattedTable.AppendLine(String.Format("{0}{1}{2}", TOP_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE), TOP_RIGHT_JOINT));
                        else if (i > nextRow.Length)
                            formattedTable.AppendLine(String.Format("{0}{1}{2}", BOTTOM_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE), BOTTOM_RIGHT_JOINT));
                        else if (i > previousRow.Length - 1)
                            formattedTable.AppendLine(String.Format("{0}{1}{2}", JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE), TOP_RIGHT_JOINT));
                        else if (i > nextRow.Length - 1)
                            formattedTable.AppendLine(String.Format("{0}{1}{2}", JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE), BOTTOM_RIGHT_JOINT));
                        else
                            formattedTable.AppendLine(String.Format("{0}{1}{2}", JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE), RIGHT_JOINT));
                    }
                    else
                    {
                        if (i > previousRow.Length)
                            formattedTable.Append(String.Format("{0}{1}", TOP_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE)));
                        else if (i > nextRow.Length)
                            formattedTable.Append(String.Format("{0}{1}", BOTTOM_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE)));
                        else
                            formattedTable.Append(String.Format("{0}{1}", JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE)));
                    }
                }
            }

            rowIndex++;
        }

        // LAST LINE:
        for (int i = 0; i < previousRow.Length; i++)
        {
            if (i == 0)
                formattedTable.Append(String.Format("{0}{1}", BOTTOM_LEFT_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE)));
            else if (i == previousRow.Length - 1)
                formattedTable.AppendLine(String.Format("{0}{1}{2}", BOTTOM_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE), BOTTOM_RIGHT_JOINT));
            else
                formattedTable.Append(String.Format("{0}{1}", BOTTOM_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE)));
        }

        return formattedTable.ToString();
    }
}

git pull keeping local changes

If you have a file in your repo that it is supposed to be customized by most pullers, then rename the file to something like config.php.template and add config.php to your .gitignore.

Likelihood of collision using most significant bits of a UUID in Java

You are better off just generating a random long value, then all the bits are random. In Java 6, new Random() uses the System.nanoTime() plus a counter as a seed.

There are different levels of uniqueness.

If you need uniqueness across many machines, you could have a central database table for allocating unique ids, or even batches of unique ids.

If you just need to have uniqueness in one app you can just have a counter (or a counter which starts from the currentTimeMillis()*1000 or nanoTime() depending on your requirements)

Laravel Request getting current path with query string

Get the flag parameter from the URL string http://cube.wisercapital.com/hf/create?flag=1

public function create(Request $request)
{
$flag = $request->input('flag');
return view('hf.create', compact('page_title', 'page_description', 'flag'));
}

How to convert dataframe into time series?

Input. We will start with the text of the input shown in the question since the question did not provide the csv input:

Lines <- "Dates   Bajaj_close Hero_close
3/14/2013   1854.8  1669.1
3/15/2013   1850.3  1684.45
3/18/2013   1812.1  1690.5
3/19/2013   1835.9  1645.6
3/20/2013   1840    1651.15
3/21/2013   1755.3  1623.3
3/22/2013   1820.65 1659.6
3/25/2013   1802.5  1617.7
3/26/2013   1801.25 1571.85
3/28/2013   1799.55 1542"

zoo. "ts" class series normally do not represent date indexes but we can create a zoo series that does (see zoo package):

library(zoo)
z <- read.zoo(text = Lines, header = TRUE, format = "%m/%d/%Y")

Alternately, if you have already read this into a data frame DF then it could be converted to zoo as shown on the second line below:

DF <- read.table(text = Lines, header = TRUE)
z <- read.zoo(DF, format = "%m/%d/%Y")

In either case above z ia a zoo series with a "Date" class time index. One could also create the zoo series, zz, which uses 1, 2, 3, ... as the time index:

zz <- z
time(zz) <- seq_along(time(zz))

ts. Either of these could be converted to a "ts" class series:

as.ts(z)
as.ts(zz)

The first has a time index which is the number of days since the Epoch (January 1, 1970) and will have NAs for missing days and the second will have 1, 2, 3, ... as the time index and no NAs.

Monthly series. Typically "ts" series are used for monthly, quarterly or yearly series. Thus if we were to aggregate the input into months we could reasonably represent it as a "ts" series:

z.m <- as.zooreg(aggregate(z, as.yearmon, mean), freq = 12)
as.ts(z.m)

ascending/descending in LINQ - can one change the order via parameter?

What about ordering desc by the desired property,

   blah = blah.OrderByDescending(x => x.Property);

And then doing something like

  if (!descending)
  {
       blah = blah.Reverse()
  }
  else
  {
      // Already sorted desc ;)
  }

Is it Reverse() too slow?

Uninstalling Android ADT

If running on windows vista or later,
remember to run eclipse under a user with proper file permissions.
try to use the 'Run as Administrator' option.

Query to list number of records in each table in a database

I think that the shortest, fastest and simplest way would be:

SELECT
    object_name(object_id) AS [Table],
    SUM(row_count) AS [Count]
FROM
    sys.dm_db_partition_stats
WHERE
    --object_schema_name(object_id) = 'dbo' AND 
    index_id < 2
GROUP BY
    object_id

Why am I getting a "401 Unauthorized" error in Maven?

If you were like me, running maven compile deploy from eclipse's maven run configuration, the issue could be related to eclipse's own embedded maven as described in https://bugs.eclipse.org/bugs/show_bug.cgi?id=562847

The workaround is to run mvn compile deploy from CLI such as bash, or to NOT use embedded maven in the eclipse's maven run configuration, and add an external maven (mine is in /usr/share/mvn), and voila, it'll say BUILD SUCCESS.

jQuery date/time picker

I researched this just recently and have yet to find a decent date picker that also includes a decent time picker. What I ended up using was eyecon's awesome DatePicker, with two simple dropdowns for time. I was tempted to use Timepickr.js though, looks like a really nice approach.

How to use glOrtho() in OpenGL?

Minimal runnable example

glOrtho: 2D games, objects close and far appear the same size:

enter image description here

glFrustrum: more real-life like 3D, identical objects further away appear smaller:

enter image description here

main.c

#include <stdlib.h>

#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>

static int ortho = 0;

static void display(void) {
    glClear(GL_COLOR_BUFFER_BIT);
    glLoadIdentity();
    if (ortho) {
    } else {
        /* This only rotates and translates the world around to look like the camera moved. */
        gluLookAt(0.0, 0.0, -3.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
    }
    glColor3f(1.0f, 1.0f, 1.0f);
    glutWireCube(2);
    glFlush();
}

static void reshape(int w, int h) {
    glViewport(0, 0, w, h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    if (ortho) {
        glOrtho(-2.0, 2.0, -2.0, 2.0, -1.5, 1.5);
    } else {
        glFrustum(-1.0, 1.0, -1.0, 1.0, 1.5, 20.0);
    }
    glMatrixMode(GL_MODELVIEW);
}

int main(int argc, char** argv) {
    glutInit(&argc, argv);
    if (argc > 1) {
        ortho = 1;
    }
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
    glutInitWindowSize(500, 500);
    glutInitWindowPosition(100, 100);
    glutCreateWindow(argv[0]);
    glClearColor(0.0, 0.0, 0.0, 0.0);
    glShadeModel(GL_FLAT);
    glutDisplayFunc(display);
    glutReshapeFunc(reshape);
    glutMainLoop();
    return EXIT_SUCCESS;
}

GitHub upstream.

Compile:

gcc -ggdb3 -O0 -o main -std=c99 -Wall -Wextra -pedantic main.c -lGL -lGLU -lglut

Run with glOrtho:

./main 1

Run with glFrustrum:

./main

Tested on Ubuntu 18.10.

Schema

Ortho: camera is a plane, visible volume a rectangle:

enter image description here

Frustrum: camera is a point,visible volume a slice of a pyramid:

enter image description here

Image source.

Parameters

We are always looking from +z to -z with +y upwards:

glOrtho(left, right, bottom, top, near, far)
  • left: minimum x we see
  • right: maximum x we see
  • bottom: minimum y we see
  • top: maximum y we see
  • -near: minimum z we see. Yes, this is -1 times near. So a negative input means positive z.
  • -far: maximum z we see. Also negative.

Schema:

Image source.

How it works under the hood

In the end, OpenGL always "uses":

glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0);

If we use neither glOrtho nor glFrustrum, that is what we get.

glOrtho and glFrustrum are just linear transformations (AKA matrix multiplication) such that:

  • glOrtho: takes a given 3D rectangle into the default cube
  • glFrustrum: takes a given pyramid section into the default cube

This transformation is then applied to all vertexes. This is what I mean in 2D:

Image source.

The final step after transformation is simple:

  • remove any points outside of the cube (culling): just ensure that x, y and z are in [-1, +1]
  • ignore the z component and take only x and y, which now can be put into a 2D screen

With glOrtho, z is ignored, so you might as well always use 0.

One reason you might want to use z != 0 is to make sprites hide the background with the depth buffer.

Deprecation

glOrtho is deprecated as of OpenGL 4.5: the compatibility profile 12.1. "FIXED-FUNCTION VERTEX TRANSFORMATIONS" is in red.

So don't use it for production. In any case, understanding it is a good way to get some OpenGL insight.

Modern OpenGL 4 programs calculate the transformation matrix (which is small) on the CPU, and then give the matrix and all points to be transformed to OpenGL, which can do the thousands of matrix multiplications for different points really fast in parallel.

Manually written vertex shaders then do the multiplication explicitly, usually with the convenient vector data types of the OpenGL Shading Language.

Since you write the shader explicitly, this allows you to tweak the algorithm to your needs. Such flexibility is a major feature of more modern GPUs, which unlike the old ones that did a fixed algorithm with some input parameters, can now do arbitrary computations. See also: https://stackoverflow.com/a/36211337/895245

With an explicit GLfloat transform[] it would look something like this:

glfw_transform.c

#include <math.h>
#include <stdio.h>
#include <stdlib.h>

#define GLEW_STATIC
#include <GL/glew.h>

#include <GLFW/glfw3.h>

static const GLuint WIDTH = 800;
static const GLuint HEIGHT = 600;
/* ourColor is passed on to the fragment shader. */
static const GLchar* vertex_shader_source =
    "#version 330 core\n"
    "layout (location = 0) in vec3 position;\n"
    "layout (location = 1) in vec3 color;\n"
    "out vec3 ourColor;\n"
    "uniform mat4 transform;\n"
    "void main() {\n"
    "    gl_Position = transform * vec4(position, 1.0f);\n"
    "    ourColor = color;\n"
    "}\n";
static const GLchar* fragment_shader_source =
    "#version 330 core\n"
    "in vec3 ourColor;\n"
    "out vec4 color;\n"
    "void main() {\n"
    "    color = vec4(ourColor, 1.0f);\n"
    "}\n";
static GLfloat vertices[] = {
/*   Positions          Colors */
     0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f,
    -0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f,
     0.0f,  0.5f, 0.0f, 0.0f, 0.0f, 1.0f
};

/* Build and compile shader program, return its ID. */
GLuint common_get_shader_program(
    const char *vertex_shader_source,
    const char *fragment_shader_source
) {
    GLchar *log = NULL;
    GLint log_length, success;
    GLuint fragment_shader, program, vertex_shader;

    /* Vertex shader */
    vertex_shader = glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(vertex_shader, 1, &vertex_shader_source, NULL);
    glCompileShader(vertex_shader);
    glGetShaderiv(vertex_shader, GL_COMPILE_STATUS, &success);
    glGetShaderiv(vertex_shader, GL_INFO_LOG_LENGTH, &log_length);
    log = malloc(log_length);
    if (log_length > 0) {
        glGetShaderInfoLog(vertex_shader, log_length, NULL, log);
        printf("vertex shader log:\n\n%s\n", log);
    }
    if (!success) {
        printf("vertex shader compile error\n");
        exit(EXIT_FAILURE);
    }

    /* Fragment shader */
    fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fragment_shader, 1, &fragment_shader_source, NULL);
    glCompileShader(fragment_shader);
    glGetShaderiv(fragment_shader, GL_COMPILE_STATUS, &success);
    glGetShaderiv(fragment_shader, GL_INFO_LOG_LENGTH, &log_length);
    if (log_length > 0) {
        log = realloc(log, log_length);
        glGetShaderInfoLog(fragment_shader, log_length, NULL, log);
        printf("fragment shader log:\n\n%s\n", log);
    }
    if (!success) {
        printf("fragment shader compile error\n");
        exit(EXIT_FAILURE);
    }

    /* Link shaders */
    program = glCreateProgram();
    glAttachShader(program, vertex_shader);
    glAttachShader(program, fragment_shader);
    glLinkProgram(program);
    glGetProgramiv(program, GL_LINK_STATUS, &success);
    glGetProgramiv(program, GL_INFO_LOG_LENGTH, &log_length);
    if (log_length > 0) {
        log = realloc(log, log_length);
        glGetProgramInfoLog(program, log_length, NULL, log);
        printf("shader link log:\n\n%s\n", log);
    }
    if (!success) {
        printf("shader link error");
        exit(EXIT_FAILURE);
    }

    /* Cleanup. */
    free(log);
    glDeleteShader(vertex_shader);
    glDeleteShader(fragment_shader);
    return program;
}

int main(void) {
    GLint shader_program;
    GLint transform_location;
    GLuint vbo;
    GLuint vao;
    GLFWwindow* window;
    double time;

    glfwInit();
    window = glfwCreateWindow(WIDTH, HEIGHT, __FILE__, NULL, NULL);
    glfwMakeContextCurrent(window);
    glewExperimental = GL_TRUE;
    glewInit();
    glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
    glViewport(0, 0, WIDTH, HEIGHT);

    shader_program = common_get_shader_program(vertex_shader_source, fragment_shader_source);

    glGenVertexArrays(1, &vao);
    glGenBuffers(1, &vbo);
    glBindVertexArray(vao);
    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
    /* Position attribute */
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)0);
    glEnableVertexAttribArray(0);
    /* Color attribute */
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
    glEnableVertexAttribArray(1);
    glBindVertexArray(0);

    while (!glfwWindowShouldClose(window)) {
        glfwPollEvents();
        glClear(GL_COLOR_BUFFER_BIT);

        glUseProgram(shader_program);
        transform_location = glGetUniformLocation(shader_program, "transform");
        /* THIS is just a dummy transform. */
        GLfloat transform[] = {
            0.0f, 0.0f, 0.0f, 0.0f,
            0.0f, 0.0f, 0.0f, 0.0f,
            0.0f, 0.0f, 1.0f, 0.0f,
            0.0f, 0.0f, 0.0f, 1.0f,
        };
        time = glfwGetTime();
        transform[0] = 2.0f * sin(time);
        transform[5] = 2.0f * cos(time);
        glUniformMatrix4fv(transform_location, 1, GL_FALSE, transform);

        glBindVertexArray(vao);
        glDrawArrays(GL_TRIANGLES, 0, 3);
        glBindVertexArray(0);
        glfwSwapBuffers(window);
    }
    glDeleteVertexArrays(1, &vao);
    glDeleteBuffers(1, &vbo);
    glfwTerminate();
    return EXIT_SUCCESS;
}

GitHub upstream.

Compile and run:

gcc -ggdb3 -O0 -o glfw_transform.out -std=c99 -Wall -Wextra -pedantic glfw_transform.c -lGL -lGLU -lglut -lGLEW -lglfw -lm
./glfw_transform.out

Output:

enter image description here

The matrix for glOrtho is really simple, composed only of scaling and translation:

scalex, 0,      0,      translatex,
0,      scaley, 0,      translatey,
0,      0,      scalez, translatez,
0,      0,      0,      1

as mentioned in the OpenGL 2 docs.

The glFrustum matrix is not too hard to calculate by hand either, but starts getting annoying. Note how frustum cannot be made up with only scaling and translations like glOrtho, more info at: https://gamedev.stackexchange.com/a/118848/25171

The GLM OpenGL C++ math library is a popular choice for calculating such matrices. http://glm.g-truc.net/0.9.2/api/a00245.html documents both an ortho and frustum operations.

xpath find if node exists

I work in Ruby and using Nokogiri I fetch the element and look to see if the result is nil.

require 'nokogiri'

url = "http://somthing.com/resource"

resp = Nokogiri::XML(open(url))

first_name = resp.xpath("/movies/actors/actor[1]/first-name")

puts "first-name not found" if first_name.nil?

Session 'app' error while installing APK

You just need to restart your adb. Instruction for that is given in this Link

Using cut command to remove multiple columns

You are able to cut all odd/even columns by using seq:

This would print all odd columns

echo 1,2,3,4,5,6,7,8,9,10 | cut -d, -f$(seq -s, 1 2 10)

To print all even columns you could use

echo 1,2,3,4,5,6,7,8,9,10 | cut -d, -f$(seq -s, 2 2 10)

By changing the second number of seq you can specify which columns to be printed.

If the specification which columns to print is more complex you could also use a "one-liner-if-clause" like

echo 1,2,3,4,5,6,7,8,9,10 | cut -d, -f$(for i in $(seq 1 10); do if [[ $i -lt 10 && $i -lt 5 ]];then echo -n $i,; else echo -n $i;fi;done)

This would print all columns from 1 to 5 - you can simply modify the conditions to create more complex conditions to specify weather a column shall be printed.

How to update TypeScript to latest version with npm?

If you are on Windows and have Visual Studio installed you might have something in your PATH that is pointing to an old version of TypeScript. I found that removing the folder "C:\Program Files (x86)\Microsoft SDKs\TypeScript\1.0\" from my PATH (or deleting/renaming this folder) will allow the more recent npm globally installed TypeScript version of tsc to work.

Editor does not contain a main type in Eclipse

Right click on Sample.java file and delete it. Now go to File -> New -> Class , enter name of program (i.e. hello) , click on finish . It will create file hello.java. Enter source code of program and finallly press ctrl + F11

click here to see screenshot1

click here to see screenshot2

How do you copy and paste into Git Bash

It's not really a function of git, msys, or bash; every windows console program is stuck using the same cumbersome copy/paste mechanism for historical reasons. Turning on QuickEdit mode can help -- or you can install a nice alternative console like this one, and change your git bash shortcut to use it instead.

How to generate a random number in C++?

The most fundamental problem of your test application is that you call srand once and then call rand one time and exit.

The whole point of srand function is to initialize the sequence of pseudo-random numbers with a random seed.

It means that if you pass the same value to srand in two different applications (with the same srand/rand implementation) then you will get exactly the same sequence of rand() values read after that in both applications.

However in your example application pseudo-random sequence consists only of one element - the first element of a pseudo-random sequence generated from seed equal to current time of 1 sec precision. What do you expect to see on output then?

Obviously when you happen to run application on the same second - you use the same seed value - thus your result is the same of course (as Martin York already mentioned in a comment to the question).

Actually you should call srand(seed) one time and then call rand() many times and analyze that sequence - it should look random.

EDIT:

Oh I get it. Apparently verbal description is not enough (maybe language barrier or something... :) ).

OK. Old-fashioned C code example based on the same srand()/rand()/time() functions that was used in the question:

#include <stdlib.h>
#include <time.h>
#include <stdio.h>

int main(void)
{
    unsigned long j;
    srand( (unsigned)time(NULL) );

    for( j = 0; j < 100500; ++j )
    {
        int n;

        /* skip rand() readings that would make n%6 non-uniformly distributed
          (assuming rand() itself is uniformly distributed from 0 to RAND_MAX) */
        while( ( n = rand() ) > RAND_MAX - (RAND_MAX-5)%6 )
        { /* bad value retrieved so get next one */ }

        printf( "%d,\t%d\n", n, n % 6 + 1 );
    }

    return 0;
}

^^^ THAT sequence from a single run of the program is supposed to look random.

Please NOTE that I don't recommend to use rand/srand functions in production for the reasons explained below and I absolutely don't recommend to use function time as a random seed for the reasons that IMO already should be quite obvious. Those are fine for educational purposes and to illustrate the point sometimes but for any serious use they are mostly useless.

EDIT2:

When using C or C++ standard library it is important to understand that as of now there is not a single standard function or class producing actually random data definitively (guaranteed by the standard). The only standard tool that approaches this problem is std::random_device that unfortunately still does not provide guarantees of actual randomness.

Depending on the nature of application you should first decide if you really need truly random (unpredictable) data. Notable case when you do most certainly need true randomness is information security - e.g. generating symmetric keys, asymmetric private keys, salt values, security tokens, etc.

However security-grade random numbers is a separate industry worth a separate article.

In most cases Pseudo-Random Number Generator is sufficient - e.g. for scientific simulations or games. In some cases consistently defined pseudo-random sequence is even required - e.g. in games you may choose to generate exactly same maps in runtime to avoid storing lots of data.

The original question and reoccurring multitude of identical/similar questions (and even many misguided "answers" to them) indicate that first and foremost it is important to distinguish random numbers from pseudo-random numbers AND to understand what is pseudo-random number sequence in the first place AND to realize that pseudo-random number generators are NOT used the same way you could use true random number generators.

Intuitively when you request random number - the result returned shouldn't depend on previously returned values and shouldn't depend if anyone requested anything before and shouldn't depend in what moment and by what process and on what computer and from what generator and in what galaxy it was requested. That is what word "random" means after all - being unpredictable and independent of anything - otherwise it is not random anymore, right? With this intuition it is only natural to search the web for some magic spells to cast to get such random number in any possible context.

^^^ THAT kind of intuitive expectations IS VERY WRONG and harmful in all cases involving Pseudo-Random Number Generators - despite being reasonable for true random numbers.

While the meaningful notion of "random number" exists (kind of) - there is no such thing as "pseudo-random number". A Pseudo-Random Number Generator actually produces pseudo-random number sequence.

Pseudo-random sequence is in fact always deterministic (predetermined by its algorithm and initial parameters) i.e. there is actually nothing random about it.

When experts talk about quality of PRNG they actually talk about statistical properties of the generated sequence (and its notable sub-sequences). For example if you combine two high quality PRNGs by using them both in turns - you may produce bad resulting sequence - despite them generating good sequences each separately (those two good sequences may simply correlate to each other and thus combine badly).

Specifically rand()/srand(s) pair of functions provide a singular per-process non-thread-safe(!) pseudo-random number sequence generated with implementation-defined algorithm. Function rand() produces values in range [0, RAND_MAX].

Quote from C11 standard (ISO/IEC 9899:2011):

The srand function uses the argument as a seed for a new sequence of pseudo-random numbers to be returned by subsequent calls to rand. If srand is then called with the same seed value, the sequence of pseudo-random numbers shall be repeated. If rand is called before any calls to srand have been made, the same sequence shall be generated as when srand is first called with a seed value of 1.

Many people reasonably expect that rand() would produce a sequence of semi-independent uniformly distributed numbers in range 0 to RAND_MAX. Well it most certainly should (otherwise it's useless) but unfortunately not only standard doesn't require that - there is even explicit disclaimer that states "there is no guarantees as to the quality of the random sequence produced". In some historical cases rand/srand implementation was of very bad quality indeed. Even though in modern implementations it is most likely good enough - but the trust is broken and not easy to recover. Besides its non-thread-safe nature makes its safe usage in multi-threaded applications tricky and limited (still possible - you may just use them from one dedicated thread).

New class template std::mersenne_twister_engine<> (and its convenience typedefs - std::mt19937/std::mt19937_64 with good template parameters combination) provides per-object pseudo-random number generator defined in C++11 standard. With the same template parameters and the same initialization parameters different objects will generate exactly the same per-object output sequence on any computer in any application built with C++11 compliant standard library. The advantage of this class is its predictably high quality output sequence and full consistency across implementations.

Also there are more PRNG engines defined in C++11 standard - std::linear_congruential_engine<> (historically used as fair quality srand/rand algorithm in some C standard library implementations) and std::subtract_with_carry_engine<>. They also generate fully defined parameter-dependent per-object output sequences.

Modern day C++11 example replacement for the obsolete C code above:

#include <iostream>
#include <chrono>
#include <random>

int main()
{
    std::random_device rd;
    // seed value is designed specifically to make initialization
    // parameters of std::mt19937 (instance of std::mersenne_twister_engine<>)
    // different across executions of application
    std::mt19937::result_type seed = rd() ^ (
            (std::mt19937::result_type)
            std::chrono::duration_cast<std::chrono::seconds>(
                std::chrono::system_clock::now().time_since_epoch()
                ).count() +
            (std::mt19937::result_type)
            std::chrono::duration_cast<std::chrono::microseconds>(
                std::chrono::high_resolution_clock::now().time_since_epoch()
                ).count() );

    std::mt19937 gen(seed);

    for( unsigned long j = 0; j < 100500; ++j )
    /* ^^^Yes. Generating single pseudo-random number makes no sense
       even if you use std::mersenne_twister_engine instead of rand()
       and even when your seed quality is much better than time(NULL) */    
    {
        std::mt19937::result_type n;
        // reject readings that would make n%6 non-uniformly distributed
        while( ( n = gen() ) > std::mt19937::max() -
                                    ( std::mt19937::max() - 5 )%6 )
        { /* bad value retrieved so get next one */ }

        std::cout << n << '\t' << n % 6 + 1 << '\n';
    }

    return 0;
}

The version of previous code that uses std::uniform_int_distribution<>

#include <iostream>
#include <chrono>
#include <random>

int main()
{
    std::random_device rd;
    std::mt19937::result_type seed = rd() ^ (
            (std::mt19937::result_type)
            std::chrono::duration_cast<std::chrono::seconds>(
                std::chrono::system_clock::now().time_since_epoch()
                ).count() +
            (std::mt19937::result_type)
            std::chrono::duration_cast<std::chrono::microseconds>(
                std::chrono::high_resolution_clock::now().time_since_epoch()
                ).count() );

    std::mt19937 gen(seed);
    std::uniform_int_distribution<unsigned> distrib(1, 6);

    for( unsigned long j = 0; j < 100500; ++j )
    {
        std::cout << distrib(gen) << ' ';
    }

    std::cout << '\n';
    return 0;
}

AngularJS app.run() documentation?

Specifically...

How and where is app.run() used? After module definition or after app.config(), after app.controller()?

Where:

In your package.js E.g. /packages/dashboard/public/controllers/dashboard.js

How:

Make it look like this

var app = angular.module('mean.dashboard', ['ui.bootstrap']);

app.controller('DashboardController', ['$scope', 'Global', 'Dashboard',
    function($scope, Global, Dashboard) {
        $scope.global = Global;
        $scope.package = {
            name: 'dashboard'
        };
        // ...
    }
]);

app.run(function(editableOptions) {
    editableOptions.theme = 'bs3'; // bootstrap3 theme. Can be also 'bs2', 'default'
});

PHP + curl, HTTP POST sample code?

curlPost('google.com', [
    'username' => 'admin',
    'password' => '12345',
]);


function curlPost($url, $data) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    $response = curl_exec($ch);
    $error = curl_error($ch);
    curl_close($ch);
    if ($error !== '') {
        throw new \Exception($error);
    }

    return $response;
}

Bundling data files with PyInstaller (--onefile)

If you are still trying to put files relative to your executable instead of in the temp directory, you need to copy it yourself. This is how I ended up getting it done.

https://stackoverflow.com/a/59415662/999943

You add a step in the spec file that does a filesystem copy to the DISTPATH variable.

Hope that helps.

What is the printf format specifier for bool?

ANSI C99/C11 don't include an extra printf conversion specifier for bool.

But the GNU C library provides an API for adding custom specifiers.

An example:

#include <stdio.h>
#include <printf.h>
#include <stdbool.h>

static int bool_arginfo(const struct printf_info *info, size_t n,
    int *argtypes, int *size)
{
  if (n) {
    argtypes[0] = PA_INT;
    *size = sizeof(bool);
  }
  return 1;
}
static int bool_printf(FILE *stream, const struct printf_info *info,
    const void *const *args)
{
  bool b =  *(const bool*)(args[0]);
  int r = fputs(b ? "true" : "false", stream);
  return r == EOF ? -1 : (b ? 4 : 5);
}
static int setup_bool_specifier()
{
  int r = register_printf_specifier('B', bool_printf, bool_arginfo);
  return r;
}
int main(int argc, char **argv)
{
  int r = setup_bool_specifier();
  if (r) return 1;
  bool b = argc > 1;
  r = printf("The result is: %B\n", b);
  printf("(written %d characters)\n", r);
  return 0;
}

Since it is a glibc extensions the GCC warns about that custom specifier:

$ gcc -Wall -g    main.c   -o main
main.c: In function ‘main’:
main.c:34:3: warning: unknown conversion type character ‘B’ in format [-Wformat=]
   r = printf("The result is: %B\n", b);
   ^
main.c:34:3: warning: too many arguments for format [-Wformat-extra-args]

Output:

$ ./main
The result is: false
(written 21 characters)
$ ./main 1
The result is: true
(written 20 characters)

HTTP Error 500.19 and error code : 0x80070021

I got this error while trying to host a WCF service in an empty ASP.NET application. The whole solution was using .NET 4.5 platform, on IIS 8.5 running on Windows 8.1. The gotcha was to

  1. Open up "Turn Windows Features on or off"

  2. Go to WCF section under ASP.NET 4.5 advanced services

  3. Check HTTP Activation.

  4. You'll be asked to restart the system.

    Screen Shot

This should Fix the HTTP 500.19!

EDIT 11-FEB-2016 Just got an issue on Windows 10 Pro, IIS 10, This time, it was an HTTP 404.0. The fix is still the same, turn on "HTTP Activation" under Windows Features -> .NET Framework 4.6 Advanced Services -> WCF Services -> HTTP Activation

Update with two tables?

The answers didn't work for me with postgresql 9.1+

This is what I had to do (you can check more in the manual here)

UPDATE schema.TableA as A
SET "columnA" = "B"."columnB"
FROM schema.TableB as B
WHERE A.id = B.id;

You can omit the schema, if you are using the default schema for both tables.

R color scatter plot points based on values

Also it'd work to just specify ifelse() twice:

plot(pos,cn, col= ifelse(cn >= 3, "red", ifelse(cn <= 1,"blue", "black")), ylim = c(0, 10))

How to get a tab character?

Posting another alternative to be more complete. When I tried the "pre" based answers, they added extra vertical line breaks as well.

Each tab can be converted to a sequence non-breaking spaces which require no wrapping.

"&nbsp;&nbsp;&nbsp;&nbsp;" 

This is not recommended for repeated/extensive use within a page. A div margin/padding approach would appear much cleaner.

Error : getaddrinfo ENOTFOUND registry.npmjs.org registry.npmjs.org:443

If Ubuntu try opening All Settings > Network > Network proxy set the method to automatic and save.

How to create an HTTPS server in Node.js?

To enable your app to listen for both http and https on ports 80 and 443 respectively, do the following

Create an express app:

var express = require('express');
var app = express();

The app returned by express() is a JavaScript function. It can be be passed to Node’s HTTP servers as a callback to handle requests. This makes it easy to provide both HTTP and HTTPS versions of your app using the same code base.

You can do so as follows:

var express = require('express');
var https = require('https');
var http = require('http');
var fs = require('fs');
var app = express();

var options = {
  key: fs.readFileSync('/path/to/key.pem'),
  cert: fs.readFileSync('/path/to/cert.pem')
};

http.createServer(app).listen(80);
https.createServer(options, app).listen(443);

For complete detail see the doc

Python - How do you run a .py file?

Since you seem to be on windows you can do this so python <filename.py>. Check that python's bin folder is in your PATH, or you can do c:\python23\bin\python <filename.py>. Python is an interpretive language and so you need the interpretor to run your file, much like you need java runtime to run a jar file.

syntax error when using command line in python

In order to run scripts, you should write the "python test.py" command in the command prompt, and not within the python shell. also, the test.py file should be at the path you run from in the cli.

How to resolve the "ADB server didn't ACK" error?

Try the following:

  • Close Eclipse.
  • Restart your phone.
  • End adb.exe process in Task Manager (Windows). In Mac, force close in Activity Monitor.
  • Issue kill and start command in \platform-tools\
    • C:\sdk\platform-tools>adb kill-server
    • C:\sdk\platform-tools>adb start-server
  • If it says something like 'started successfully', you are good.

Removing numbers from string

And, just to throw it in the mix, is the oft-forgotten str.translate which will work a lot faster than looping/regular expressions:

For Python 2:

from string import digits

s = 'abc123def456ghi789zero0'
res = s.translate(None, digits)
# 'abcdefghizero'

For Python 3:

from string import digits

s = 'abc123def456ghi789zero0'
remove_digits = str.maketrans('', '', digits)
res = s.translate(remove_digits)
# 'abcdefghizero'

Best Practice: Access form elements by HTML id or name attribute?

I prefer This One

document.forms['idOfTheForm'].nameOfTheInputFiled.value;

jQuery ajax success callback function definition

You don't need to declare the variable. Ajax success function automatically takes up to 3 parameters: Function( Object data, String textStatus, jqXHR jqXHR )

How to convert milliseconds into a readable date?

Using the library Datejs you can accomplish this quite elegantly, with its toString format specifiers: http://jsfiddle.net/TeRnM/1/.

var date = new Date(1324339200000);

date.toString("MMM dd"); // "Dec 20"

remove white space from the end of line in linux

Try using

cat kb.txt | sed -e 's/\s$//g'

How do I get the AM/PM value from a DateTime?

its pretty simple

  Date someDate = new DateTime();
  string timeOfDay = someDate.ToString("hh:mm tt"); 
  // hh - shows hour and mm - shows minute - tt - shows AM or PM

Boxplot show the value of mean

First, you can calculate the group means with aggregate:

means <- aggregate(weight ~  group, PlantGrowth, mean)

This dataset can be used with geom_text:

library(ggplot2)
ggplot(data=PlantGrowth, aes(x=group, y=weight, fill=group)) + geom_boxplot() +
  stat_summary(fun.y=mean, colour="darkred", geom="point", 
               shape=18, size=3,show_guide = FALSE) + 
  geom_text(data = means, aes(label = weight, y = weight + 0.08))

Here, + 0.08 is used to place the label above the point representing the mean.

enter image description here


An alternative version without ggplot2:

means <- aggregate(weight ~  group, PlantGrowth, mean)

boxplot(weight ~ group, PlantGrowth)
points(1:3, means$weight, col = "red")
text(1:3, means$weight + 0.08, labels = means$weight)

enter image description here

SQLite in Android How to update a specific row

//Here is some simple sample code for update

//First declare this

private DatabaseAppHelper dbhelper;
private SQLiteDatabase db;

//initialize the following

dbhelper=new DatabaseAppHelper(this);
        db=dbhelper.getWritableDatabase();

//updation code

 ContentValues values= new ContentValues();
                values.put(DatabaseAppHelper.KEY_PEDNAME, ped_name);
                values.put(DatabaseAppHelper.KEY_PEDPHONE, ped_phone);
                values.put(DatabaseAppHelper.KEY_PEDLOCATION, ped_location);
                values.put(DatabaseAppHelper.KEY_PEDEMAIL, ped_emailid);
                db.update(DatabaseAppHelper.TABLE_NAME, values,  DatabaseAppHelper.KEY_ID + "=" + ?, null);

//put ur id instead of the 'question mark' is a function in my shared preference.

how to get GET and POST variables with JQuery?

Or you can use this one http://plugins.jquery.com/project/parseQuery, it's smaller than most (minified 449 bytes), returns an object representing name-value pairs.

node.js string.replace doesn't work?

Isn't string.replace returning a value, rather than modifying the source string?

So if you wanted to modify variableABC, you'd need to do this:

var variableABC = "A B C";

variableABC = variableABC.replace('B', 'D') //output: 'A D C'

Could not autowire field in spring. why?

I had exactly the same problem try to put the two classes in the same package and add line in the pom.xml

<dependency> 
            <groupId> org.springframework.boot </groupId> 
            <artifactId> spring-boot-starter-web </artifactId> 
            <version> 1.2.0.RELEASE </version> 
</dependency>

How to generate an MD5 file hash in JavaScript?

As a contemporary alternative, there is a standard now for client side cryptography. This has the advantage of being optimised by the browser itself.

Taken from the example in the documentation:

async function sha256(message) {

    // encode as UTF-8
    const msgBuffer = new TextEncoder('utf-8').encode(message);

    // hash the message
    const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);

    // convert ArrayBuffer to Array
    const hashArray = Array.from(new Uint8Array(hashBuffer));

    // convert bytes to hex string
    const hashHex = hashArray.map(b => ('00' + b.toString(16)).slice(-2)).join('');
    return hashHex;
}

sha256('abc').then(hash => console.log(hash));

(async function() {
    const hash = await sha256('abc');
}());

MD5 is likely unsupported, however the likes of SHA-256, SHA-384, and SHA-512 are.

And those will likely be able to be calculated server side also.

Here's some documentation on usage: https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest

And cross browser compatibility: https://caniuse.com/#feat=cryptography

1052: Column 'id' in field list is ambiguous

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

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

How can I delay a method call for 1 second?

You can also:

[UIView animateWithDuration:1.0
                 animations:^{ self.view.alpha = 1.1; /* Some fake chages */ }
                 completion:^(BOOL finished)
{
    NSLog(@"A second lapsed.");
}];

This case you have to fake some changes to some view to get the animation work. It is hacky indeed, but I love the block based stuff. Or wrap up @mcfedr answer below.


waitFor(1.0, ^
{
    NSLog(@"A second lapsed");
});

typedef void (^WaitCompletionBlock)();
void waitFor(NSTimeInterval duration, WaitCompletionBlock completion)
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, duration * NSEC_PER_SEC),
                   dispatch_get_main_queue(), ^
    { completion(); });
}

jQuery Date Picker - disable past dates

you can simply use

startDate: 'today'

it working fine for me.

How to assign pointer address manually in C programming language?

int *p=(int *)0x1234 = 10; //0x1234 is the memory address and value 10 is assigned in that address


unsigned int *ptr=(unsigned int *)0x903jf = 20;//0x903j is memory address and value 20 is assigned 

Basically in Embedded platform we are using directly addresses instead of names

XML shape drawable not rendering desired color

In drawable I use this xml code to define the border and background:

<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
  <stroke android:width="4dp" android:color="#D8FDFB" /> 
  <padding android:left="7dp" android:top="7dp" 
    android:right="7dp" android:bottom="7dp" /> 
  <corners android:radius="4dp" /> 
  <solid android:color="#f0600000"/> 
</shape> 

How to add (vertical) divider to a horizontal LinearLayout?

use this for horizontal divider

<View
    android:layout_width="1dp"
    android:layout_height="match_parent"
    android:background="@color/honeycombish_blue" />

and this for vertical divider

<View
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:background="@color/honeycombish_blue" />

OR if you can use the LinearLayout divider, for horizontal divider

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
    <size android:height="1dp"/>
    <solid android:color="#f6f6f6"/>
</shape>

and in LinearLayout

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:divider="@drawable/divider"
    android:orientation="vertical"
    android:showDividers="middle" >

If you want to user vertical divider then in place of android:height="1dp" in shape use android:width="1dp"

Tip: Don't forget the android:showDividers item.

PHP Regex to get youtube video ID?

The following will work for all youtube links

<?php
    // Here is a sample of the URLs this regex matches: (there can be more content after the given URL that will be ignored)
    // http://youtu.be/dQw4w9WgXcQ
    // http://www.youtube.com/embed/dQw4w9WgXcQ
    // http://www.youtube.com/watch?v=dQw4w9WgXcQ
    // http://www.youtube.com/?v=dQw4w9WgXcQ
    // http://www.youtube.com/v/dQw4w9WgXcQ
    // http://www.youtube.com/e/dQw4w9WgXcQ
    // http://www.youtube.com/user/username#p/u/11/dQw4w9WgXcQ
    // http://www.youtube.com/sandalsResorts#p/c/54B8C800269D7C1B/0/dQw4w9WgXcQ
    // http://www.youtube.com/watch?feature=player_embedded&v=dQw4w9WgXcQ
    // http://www.youtube.com/?feature=player_embedded&v=dQw4w9WgXcQ
    // It also works on the youtube-nocookie.com URL with the same above options.
    // It will also pull the ID from the URL in an embed code (both iframe and object tags)

$url = "https://www.youtube.com/watch?v=v2_MLFVdlQM";

    preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $url, $match);

    $youtube_id = $match[1];

echo $youtube_id;
    ?>

How to pass a type as a method parameter in Java

You should pass a Class...

private void foo(Class<?> t){
    if(t == String.class){ ... }
    else if(t == int.class){ ... }
}

private void bar()
{
   foo(String.class);
}

How to add a footer to the UITableView?

If you don't prefer the sticky bottom effect i would put it in viewDidLoad() https://stackoverflow.com/a/38176479/4127670

Using multiple arguments for string formatting in Python (e.g., '%s ... %s')

For python2 you can also do this

'%(author)s in %(publication)s'%{'author':unicode(self.author),
                                  'publication':unicode(self.publication)}

which is handy if you have a lot of arguments to substitute (particularly if you are doing internationalisation)

Python2.6 onwards supports .format()

'{author} in {publication}'.format(author=self.author,
                                   publication=self.publication)

What is the difference between screenX/Y, clientX/Y and pageX/Y?

The difference between those will depend largely on what browser you are currently referring to. Each one implements these properties differently, or not at all. Quirksmode has great documentation regarding browser differences in regards to W3C standards like the DOM and JavaScript Events.

Firefox Add-on RESTclient - How to input POST parameters?

If you want to submit a POST request

  1. You have to set the “request header” section of the Firefox plugin to have a “name” = “Content-Type” and “value” = “application/x-www-form-urlencoded
  2. Now, you are able to submit parameter like “name=mynamehere&title=TA” in the “request body” text area field

Should C# or C++ be chosen for learning Games Programming (consoles)?

Hey, if BASIC is good enough for Gorillas, it's good enough for me.

How do I get the calling method name and type using reflection?

It's actually something that can be done using a combination of the current stack-trace data, and reflection.

public void MyMethod()
{
     StackTrace stackTrace = new System.Diagnostics.StackTrace();
     StackFrame frame = stackTrace.GetFrames()[1];
     MethodInfo method = frame.GetMethod();
     string methodName = method.Name;
     Type methodsClass = method.DeclaringType;
}

The 1 index on the StackFrame array will give you the method which called MyMethod

How to add background image for input type="button"?

.button{
    background-image:url('/image/btn.png');
    background-repeat:no-repeat;
}

How a thread should close itself in Java?

If you want to terminate the thread, then just returning is fine. You do NOT need to call Thread.currentThread().interrupt() (it will not do anything bad though. It's just that you don't need to.) This is because interrupt() is basically used to notify the owner of the thread (well, not 100% accurate, but sort of). Because you are the owner of the thread, and you decided to terminate the thread, there is no one to notify, so you don't need to call it.

By the way, why in the first case we need to use currentThread? Is Thread does not refer to the current thread?

Yes, it doesn't. I guess it can be confusing because e.g. Thread.sleep() affects the current thread, but Thread.sleep() is a static method.

If you are NOT the owner of the thread (e.g. if you have not extended Thread and coded a Runnable etc.) you should do

Thread.currentThread().interrupt();
return;

This way, whatever code that called your runnable will know the thread is interrupted = (normally) should stop whatever it is doing and terminate. As I said earlier, it is just a mechanism of communication though. The owner might simply ignore the interrupted status and do nothing.. but if you do set the interrupted status, somebody might thank you for that in the future.

For the same reason, you should never do

Catch(InterruptedException ie){
     //ignore
}

Because if you do, you are stopping the message there. Instead one should do

Catch(InterruptedException ie){
    Thread.currentThread().interrupt();//preserve the message
    return;//Stop doing whatever I am doing and terminate
}

What is an NP-complete in computer science?

The definitions for NP complete problems above is correct, but I thought I might wax lyrical about their philosophical importance as nobody has addressed that issue yet.

Almost all complex problems you'll come up against will be NP Complete. There's something very fundamental about this class, and which just seems to be computationally different from easily solvable problems. They sort of have their own flavour, and it's not so hard to recognise them. This basically means that any moderately complex algorithm is impossible for you to solve exactly -- scheduling, optimising, packing, covering etc.

But not all is lost if a problem you'll encounter is NP Complete. There is a vast and very technical field where people study approximation algorithms, which will give you guarantees for being close to the solution of an NP complete problem. Some of these are incredibly strong guarantees -- for example, for 3sat, you can get a 7/8 guarantee through a really obvious algorithm. Even better, in reality, there are some very strong heuristics, which excel at giving great answers (but no guarantees!) for these problems.

Note that two very famous problems -- graph isomorphism and factoring -- are not known to be P or NP.

get current date and time in groovy?

Date has the time as well, just add HH:mm:ss to the date format:

import java.text.SimpleDateFormat
def date = new Date()
def sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss")
println sdf.format(date)

In case you are using JRE 8 you can use LoaclDateTime:

import java.time.*

LocalDateTime t = LocalDateTime.now();
return t as String

Oracle SQL Developer: Unable to find a JVM

The solution that worked for me: If you have Sqldeveloper with java incorporated, you can use the \sqldeveloper\bin\sqldeveloper.bat to launch sqldeveloper as told here.

How can I create a simple index.html file which lists all files/directories?

You can either: Write a server-side script page like PHP, JSP, ASP.net etc to generate this HTML dynamically

or

Setup the web-server that you are using (e.g. Apache) to do exactly that automatically for directories that doesn't contain welcome-page (e.g. index.html)

Specifically in apache read more here: Edit the httpd.conf: http://justlinux.com/forum/showthread.php?s=&postid=502789#post502789 (updated link: https://forums.justlinux.com/showthread.php?94230-Make-apache-list-directory-contents&highlight=502789)

or add the autoindex mod: http://httpd.apache.org/docs/current/mod/mod_autoindex.html

Can a main() method of class be invoked from another class in java

if I got your question correct...

main() method is defined in the class below...

public class ToBeCalledClass{

   public static void main (String args[ ]) {
      System.out.println("I am being called");
   }
}

you want to call this main method in another class.

public class CallClass{

    public void call(){
       ToBeCalledClass.main(null);
    }
}

Reference requirements.txt for the install_requires kwarg in setuptools setup.py file

I did this:

import re

def requirements(filename):
    with open(filename) as f:
        ll = f.read().splitlines()
    d = {}
    for l in ll:
        k, v = re.split(r'==|>=', l)
        d[k] = v
    return d

def packageInfo():
    try:
        from pip._internal.operations import freeze
    except ImportError:
        from pip.operations import freeze

    d = {}
    for kv in freeze.freeze():
        k, v = re.split(r'==|>=', kv)
        d[k] = v
    return d

req = getpackver('requirements.txt')
pkginfo = packageInfo()

for k, v in req.items():
    print(f'{k:<16}: {v:<6} -> {pkginfo[k]}')

Ansible: Store command's stdout in new variable?

I'm a newbie in Ansible, but I would suggest next solution:

playbook.yml

...
vars:
  command_output_full:
    stdout: will be overriden below
  command_output: {{ command_output_full.stdout }}
...
...
...
tasks:
  - name: Create variable from command
    command: "echo Hello"
    register: command_output_full
  - debug: msg="{{ command_output }}"

It should work (and works for me) because Ansible uses lazy evaluation. But it seems it checks validity before the launch, so I have to define command_output_full.stdout in vars.

And, of course, if it is too many such vars in vars section, it will look ugly.

How can I move all the files from one folder to another using the command line?

Be sure to use quotes if there are spaces in the file path:

move "C:\Users\MyName\My Old Folder\*" "C:\Users\MyName\My New Folder"

That will move the contents of C:\Users\MyName\My Old Folder\ to C:\Users\MyName\My New Folder

How to format number of decimal places in wpf using style/template?

The accepted answer does not show 0 in integer place on giving input like 0.299. It shows .3 in WPF UI. So my suggestion to use following string format

<TextBox Text="{Binding Value,  StringFormat={}{0:#,0.0}}" 

Search for all occurrences of a string in a mysql database

I was looking for the same but couldn't find it, so I make a small script in PHP, you can find it at: http://tequilaphp.wordpress.com/2010/07/05/searching-strings-in-a-database-and-files/

Good luck! (I remove some private code, let me know if I didn't break it in the process :D)

Angular 2: Can't bind to 'ngModel' since it isn't a known property of 'input'

Step to follow

1. Open your app.module.ts file.

.

2. Add import { FormsModule } from '@angular/forms';

.

3. Add FormsModule to imports asimports: [ BrowserModule, FormsModule ],

.

Final result will look like this

.....
import { FormsModule } from '@angular/forms';
.....
@NgModule({
.....
  imports: [   
     BrowserModule, FormsModule 
  ],
.....
})

Installing specific laravel version with composer create-project

From the composer help create-project command

The create-project command creates a new project from a given
package into a new directory. If executed without params and in a directory with a composer.json file it installs the packages for the current project.
You can use this command to bootstrap new projects or setup a clean
version-controlled installation for developers of your project.

[version]
You can also specify the version with the package name using = or : as separator.

To install unstable packages, either specify the version you want, or use the --stability=dev (where dev can be one of RC, beta, alpha or dev).

This command works:

composer create-project laravel/laravel=4.1.27 your-project-name --prefer-dist

This works with the * notation.

What is an opaque response, and what purpose does it serve?

Consider the case in which a service worker acts as an agnostic cache. Your only goal is serve the same resources that you would get from the network, but faster. Of course you can't ensure all the resources will be part of your origin (consider libraries served from CDNs, for instance). As the service worker has the potential of altering network responses, you need to guarantee you are not interested in the contents of the response, nor on its headers, nor even on the result. You're only interested on the response as a black box to possibly cache it and serve it faster.

This is what { mode: 'no-cors' } was made for.

Reading large text files with streams in C#

Have a look at the following code snippet. You have mentioned Most files will be 30-40 MB. This claims to read 180 MB in 1.4 seconds on an Intel Quad Core:

private int _bufferSize = 16384;

private void ReadFile(string filename)
{
    StringBuilder stringBuilder = new StringBuilder();
    FileStream fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read);

    using (StreamReader streamReader = new StreamReader(fileStream))
    {
        char[] fileContents = new char[_bufferSize];
        int charsRead = streamReader.Read(fileContents, 0, _bufferSize);

        // Can't do much with 0 bytes
        if (charsRead == 0)
            throw new Exception("File is 0 bytes");

        while (charsRead > 0)
        {
            stringBuilder.Append(fileContents);
            charsRead = streamReader.Read(fileContents, 0, _bufferSize);
        }
    }
}

Original Article

SQL Server - Adding a string to a text column (concat equivalent)

hmm, try doing CAST(' ' AS TEXT) + [myText]

Although, i am not completely sure how this will pan out.

I also suggest against using the Text datatype, use varchar instead.

If that doesn't work, try ' ' + CAST ([myText] AS VARCHAR(255))

Using set_facts and with_items together in Ansible

Updated 2018-06-08: My previous answer was a bit of hack so I have come back and looked at this again. This is a cleaner Jinja2 approach.

- name: Set fact 4
  set_fact:
    foo: "{% for i in foo_result.results %}{% do foo.append(i) %}{% endfor %}{{ foo }}"

I am adding this answer as current best answer for Ansible 2.2+ does not completely cover the original question. Thanks to Russ Huguley for your answer this got me headed in the right direction but it left me with a concatenated string not a list. This solution gets a list but becomes even more hacky. I hope this gets resolved in a cleaner manner.

- name: build foo_string
  set_fact:
    foo_string: "{% for i in foo_result.results %}{{ i.ansible_facts.foo_item }}{% if not loop.last %},{% endif %}{%endfor%}"

- name: set fact foo
  set_fact:
    foo: "{{ foo_string.split(',') }}"

get launchable activity name of package from adb

Since Android 7.0 you can use adb shell cmd package resolve-activity command to get the default activity of an installed app like this:

adb shell "cmd package resolve-activity --brief com.google.android.calculator | tail -n 1"
com.google.android.calculator/com.android.calculator2.Calculator

Access Control Origin Header error using Axios in React Web throwing error in Chrome

I had a similar problem when I tried to create the React Axios instance.

I resolved it using the below approach.

const instance = axios.create({
  baseURL: "https://jsonplaceholder.typicode.com/",
  withCredentials: false,
  headers: {
    'Access-Control-Allow-Origin' : '*',
    'Access-Control-Allow-Methods':'GET,PUT,POST,DELETE,PATCH,OPTIONS',
    }
});

What's the whole point of "localhost", hosts and ports at all?

I heard a good description (parable) which illustrates ports as different delivery points for a large building, e.g. Post office for letters and small parcels, Goods In for large deliveries / pallets, Doors for people.

MySQL LEFT JOIN Multiple Conditions

SELECT * FROM a WHERE a.group_id IN 
(SELECT group_id FROM b WHERE b.user_id!=$_SESSION{'[user_id']} AND b.group_id = a.group_id)
WHERE a.keyword LIKE '%".$keyword."%';

How can I return camelCase JSON serialized by JSON.NET from ASP.NET MVC controller methods?

If you are returning ActionResult in .net core web api, or IHttpAction result then you can just wrap up your model in an Ok() method which will match the case on your front end and serialise it for you. No need to use JsonConvert. :)

Unloading classes in java?

If you're live watching if unloading class worked in JConsole or something, try also adding java.lang.System.gc() at the end of your class unloading logic. It explicitly triggers Garbage Collector.

How to install XCODE in windows 7 platform?

X-code is primarily made for OS-X or iPhone development on Mac systems. Versions for Windows are not available. However this might help!

There is no way to get Xcode on Windows; however you can use a different SDK like Corona instead although it will not use Objective-C (I believe it uses Lua). I have however heard that it is horrible to use.

Source: classroomm.com

AngularJS: Uncaught Error: [$injector:modulerr] Failed to instantiate module?

For people having the same error with a similar code:

$(function(){
    var app = angular.module("myApp", []); 
    app.controller('myController', function(){

    });
});

Removing the $(function(){ ... }); solved the error.

Find all special characters in a column in SQL Server 2008

select count(*) from dbo.tablename where address_line_1 LIKE '%[\'']%' {eSCAPE'\'}

Regex - how to match everything except a particular pattern

(B)|(A)

then use what group 2 captures...

SQL set values of one column equal to values of another column in the same table

Here is sample code that might help you coping Column A to Column B:

UPDATE YourTable
SET ColumnB = ColumnA
WHERE
ColumnB IS NULL
AND ColumnA IS NOT NULL;

App can't be opened because it is from an unidentified developer

Try looking into Gatekeeper. I am not sure of too much Mac stuff, but I heard that you can enable it in there.

Asynchronous Requests with Python requests

DISCLAMER: Following code creates different threads for each function.

This might be useful for some of the cases as it is simpler to use. But know that it is not async but gives illusion of async using multiple threads, even though decorator suggests that.

You can use the following decorator to give a callback once the execution of function is completed, the callback must handle the processing of data returned by the function.

Please note that after the function is decorated it will return a Future object.

import asyncio

## Decorator implementation of async runner !!
def run_async(callback, loop=None):
    if loop is None:
        loop = asyncio.get_event_loop()

    def inner(func):
        def wrapper(*args, **kwargs):
            def __exec():
                out = func(*args, **kwargs)
                callback(out)
                return out

            return loop.run_in_executor(None, __exec)

        return wrapper

    return inner

Example of implementation:

urls = ["https://google.com", "https://facebook.com", "https://apple.com", "https://netflix.com"]
loaded_urls = []  # OPTIONAL, used for showing realtime, which urls are loaded !!


def _callback(resp):
    print(resp.url)
    print(resp)
    loaded_urls.append((resp.url, resp))  # OPTIONAL, used for showing realtime, which urls are loaded !!


# Must provide a callback function, callback func will be executed after the func completes execution
# Callback function will accept the value returned by the function.
@run_async(_callback)
def get(url):
    return requests.get(url)


for url in urls:
    get(url)

If you wish to see which url are loaded in real-time then, you can add the following code at the end as well:

while True:
    print(loaded_urls)
    if len(loaded_urls) == len(urls):
        break

how to print a string to console in c++

"Visual Studio does not support std::cout as debug tool for non-console applications"
- from Marius Amado-Alves' answer to "How can I see cout output in a non-console application?"

Which means if you use it, Visual Studio shows nothing in the "output" window (in my case VS2008)

crop text too long inside div

You can use:

overflow:hidden;

to hide the text outside the zone.

Note that it may cut the last letter (so a part of the last letter will still be displayed). A nicer way is to display an ellipsis at the end. You can do it by using text-overflow:

overflow: hidden;
white-space: nowrap; /* Don't forget this one */
text-overflow: ellipsis;

Bootstrap 4 File Input

Solution based on @Elnoor answer, but working with multiple file upload form input and without the "fakepath hack":

HTML:

<div class="custom-file">
    <input id="logo" type="file" class="custom-file-input" multiple>
    <label for="logo" class="custom-file-label text-truncate">Choose file...</label>
</div>

JS:

$('input[type="file"]').on('change', function () {
    let filenames = [];
    let files = document.getElementById('health_claim_file_form_files').files;

    for (let i in files) {
        if (files.hasOwnProperty(i)) {
            filenames.push(files[i].name);
        }
    }

    $(this).next('.custom-file-label').addClass("selected").html(filenames.join(',    '));
});

JavaScript OR (||) variable assignment explanation

This is made to assign a default value, in this case the value of y, if the x variable is falsy.

The boolean operators in JavaScript can return an operand, and not always a boolean result as in other languages.

The Logical OR operator (||) returns the value of its second operand, if the first one is falsy, otherwise the value of the first operand is returned.

For example:

"foo" || "bar"; // returns "foo"
false || "bar"; // returns "bar"

Falsy values are those who coerce to false when used in boolean context, and they are 0, null, undefined, an empty string, NaN and of course false.

How to Set Active Tab in jQuery Ui

If you want to set the active tab by ID instead of index, you can also use the following:

$('#tabs').tabs({ active: $('#tabs ul').index($('#tab-101')) });

How to export SQL Server 2005 query to CSV

In Sql Server 2012 - Management Studio:

Solution 1:

Execute the query

Right click the Results Window

Select Save Results As from the menu

Select CSV

Solution 2:

Right click on database

Select Tasks, Export Data

Select Source DB

Select Destination: Flat File Destination

Pick a file name

Select Format - Delimited

Choose a table or write a query

Pick a Column delimiter

Note: You can pick a Text qualifier that will delimit your text fields, such as quotes.

If you have a field with commas, don't use you use comma as a delimiter, because it does not escape commas. You can pick a column delimiter such as Vertical Bar: | instead of comma, or a tab character. Otherwise, write a query that escapes your commas or delimits your varchar field.

The escape character or text qualifier you need to use depends on your requirements.

Positioning the colorbar

using padding pad

In order to move the colorbar relative to the subplot, one may use the pad argument to fig.colorbar.

import matplotlib.pyplot as plt
import numpy as np; np.random.seed(1)

fig, ax = plt.subplots(figsize=(4,4))
im = ax.imshow(np.random.rand(11,16))
ax.set_xlabel("x label")

fig.colorbar(im, orientation="horizontal", pad=0.2)
plt.show()

enter image description here

using an axes divider

One can use an instance of make_axes_locatable to divide the axes and create a new axes which is perfectly aligned to the image plot. Again, the pad argument would allow to set the space between the two axes.

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np; np.random.seed(1)

fig, ax = plt.subplots(figsize=(4,4))
im = ax.imshow(np.random.rand(11,16))
ax.set_xlabel("x label")

divider = make_axes_locatable(ax)
cax = divider.new_vertical(size="5%", pad=0.7, pack_start=True)
fig.add_axes(cax)
fig.colorbar(im, cax=cax, orientation="horizontal")

plt.show()

enter image description here

using subplots

One can directly create two rows of subplots, one for the image and one for the colorbar. Then, setting the height_ratios as gridspec_kw={"height_ratios":[1, 0.05]} in the figure creation, makes one of the subplots much smaller in height than the other and this small subplot can host the colorbar.

import matplotlib.pyplot as plt
import numpy as np; np.random.seed(1)

fig, (ax, cax) = plt.subplots(nrows=2,figsize=(4,4), 
                  gridspec_kw={"height_ratios":[1, 0.05]})
im = ax.imshow(np.random.rand(11,16))
ax.set_xlabel("x label")

fig.colorbar(im, cax=cax, orientation="horizontal")

plt.show()

enter image description here

Why do I get a C malloc assertion failure?

We got this error because we forgot to multiply by sizeof(int). Note the argument to malloc(..) is a number of bytes, not number of machine words or whatever.

Reliable way to convert a file to a byte[]

looks good enough as a generic version. You can modify it to meet your needs, if they're specific enough.

also test for exceptions and error conditions, such as file doesn't exist or can't be read, etc.

you can also do the following to save some space:

 byte[] bytes = System.IO.File.ReadAllBytes(filename);

Pressed <button> selector

Should we include a little JS? Because CSS was not basically created for this job. CSS was just a style sheet to add styles to the HTML, but its pseudo classes can do something that the basic CSS can't do. For example button:active active is pseudo.

Reference:

http://css-tricks.com/pseudo-class-selectors/ You can learn more about pseudo here!

Your code:

The code that you're having the basic but helpfull. And yes :active will only occur once the click event is triggered.

button {
font-size: 18px;
border: 2px solid gray;
border-radius: 100px;
width: 100px;
height: 100px;
}

button:active {
font-size: 18px;
border: 2px solid red;
border-radius: 100px;
width: 100px;
height: 100px;
}

This is what CSS would do, what rlemon suggested is good, but that would as he suggested would require a tag.

How to use CSS:

You can use :focus too. :focus would work once the click is made and would stay untill you click somewhere else, this was the CSS, you were trying to use CSS, so use :focus to make the buttons change.

What JS would do:

The JavaScript's jQuery library is going to help us for this code. Here is the example:

$('button').click(function () {
  $(this).css('border', '1px solid red');
}

This will make sure that the button stays red even if the click gets out. To change the focus type (to change the color of red to other) you can use this:

$('button').click(function () {
  $(this).css('border', '1px solid red');
  // find any other button with a specific id, and change it back to white like
  $('button#red').css('border', '1px solid white');
}

This way, you will create a navigation menu. Which will automatically change the color of the tabs as you click on them. :)

Hope you get the answer. Good luck! Cheers.

In SQL, how can you "group by" in ranges?

Try

SELECT (str(range) + "-" + str(range + 9) ) AS [Score range], COUNT(score) AS [number of occurances]
FROM (SELECT  score,  int(score / 10 ) * 10  AS range  FROM scoredata )  
GROUP BY range;

How do I get a class instance of generic type T?

I had this problem in an abstract generic class. In this particular case, the solution is simpler:

abstract class Foo<T> {
    abstract Class<T> getTClass();
    //...
}

and later on the derived class:

class Bar extends Foo<Whatever> {
    @Override
    Class<T> getTClass() {
        return Whatever.class;
    }
}

Why does adb return offline after the device string?

On my Galaxy Nexus with Android 4.2.2, I had the same problem initially, 'adb devices' was showing the device but with offline status (USB debugging was initially active on my device).

These are the steps I took to remedy the situation :

  1. Disable USB debugging (Device not connected to PC)
  2. Re enable USB debugging
  3. Now connect to your PC, now a pop up on the device (not on PC) will ask you for authenticating the PC, Thats it...

adb devices now lists both device id and no offline.

Auto start node.js server on boot

This isn't something to configure in node.js at all, this is purely OS responsibility (Windows in your case). The most reliable way to achieve this is through a Windows Service.

There's this super easy module that installs a node script as a windows service, it's called node-windows (npm, github, documentation). I've used before and worked like a charm.

var Service = require('node-windows').Service;

// Create a new service object
var svc = new Service({
  name:'Hello World',
  description: 'The nodejs.org example web server.',
  script: 'C:\\path\\to\\helloworld.js'
});

// Listen for the "install" event, which indicates the
// process is available as a service.
svc.on('install',function(){
  svc.start();
});

svc.install();

p.s.

I found the thing so useful that I built an even easier to use wrapper around it (npm, github).

Installing it:

npm install -g qckwinsvc

Installing your service:

> qckwinsvc
prompt: Service name: [name for your service]
prompt: Service description: [description for it]
prompt: Node script path: [path of your node script]
Service installed

Uninstalling your service:

> qckwinsvc --uninstall
prompt: Service name: [name of your service]
prompt: Node script path: [path of your node script]
Service stopped
Service uninstalled

How do I get Bin Path?

var assemblyPath = Assembly.GetExecutingAssembly().CodeBase;

RecyclerView - Get view at particular position

You can use below

mRecyclerview.getChildAt(pos);

android image button

You can use the button :

1 - make the text empty

2 - set the background for it

+3 - you can use the selector to more useful and nice button


About the imagebutton you can set the image source and the background the same picture and it must be (*.png) when you do it you can make any design for the button

and for more beauty button use the selector //just Google it ;)

Event detect when css property changed using Jquery

You can't. CSS does not support "events". Dare I ask what you need it for? Check out this post here on SO. I can't think of a reason why you would want to hook up an event to a style change. I'm assuming here that the style change is triggered somwhere else by a piece of javascript. Why not add extra logic there?

How to uninstall Apache with command line

sc delete Apache2.4

Remove service in windows

In Python, what does dict.pop(a,b) mean?

def func(*args): 
    pass

When you define a function this way, *args will be array of arguments passed to the function. This allows your function to work without knowing ahead of time how many arguments are going to be passed to it.

You do this with keyword arguments too, using **kwargs:

def func2(**kwargs): 
    pass

See: Arbitrary argument lists


In your case, you've defined a class which is acting like a dictionary. The dict.pop method is defined as pop(key[, default]).

Your method doesn't use the default parameter. But, by defining your method with *args and passing *args to dict.pop(), you are allowing the caller to use the default parameter.

In other words, you should be able to use your class's pop method like dict.pop:

my_a = a()
value1 = my_a.pop('key1')       # throw an exception if key1 isn't in the dict
value2 = my_a.pop('key2', None) # return None if key2 isn't in the dict

C# : changing listbox row color?

How about

      MyLB is a listbox

        Label ll = new Label();
        ll.Width = MyLB.Width;
        ll.Content = ss;
        if(///<some condition>///)
            ll.Background = Brushes.LightGreen;
        else
            ll.Background = Brushes.LightPink;
        MyLB.Items.Add(ll);

java.lang.NoClassDefFoundError: com/fasterxml/jackson/core/JsonFactory

If you are using springboot then jackson is added by default,

So the version of jackson you are adding manualy is probably conflicting with the one spring boot adds,

Try to delete the jackson dependencies from your pom,

If you need to override the version spring boots add, then you need to exclude it first and then add your own

How to export JavaScript array info to csv (on client side)?

Download CSV File

  let csvContent = "data:text/csv;charset=utf-8,";
  rows.forEach(function (rowArray) {
    for (var i = 0, len = rowArray.length; i < len; i++) {
      if (typeof (rowArray[i]) == 'string')
        rowArray[i] = rowArray[i].replace(/<(?:.|\n)*?>/gm, '');
      rowArray[i] = rowArray[i].replace(/,/g, '');
    }

    let row = rowArray.join(",");
    csvContent += row + "\r\n"; // add carriage return
  });
  var encodedUri = encodeURI(csvContent);
  var link = document.createElement("a");
  link.setAttribute("href", encodedUri);
  link.setAttribute("download", "fileName.csv");
  document.body.appendChild(link);
  link.click();

CSS '>' selector; what is it?

It declares parent reference, look at this page for definition:

http://www.w3.org/TR/CSS2/selector.html#child-selectors

RegEx: Grabbing values between quotation marks

From Greg H. I was able to create this regex to suit my needs.

I needed to match a specific value that was qualified by being inside quotes. It must be a full match, no partial matching could should trigger a hit

e.g. "test" could not match for "test2".

reg = r"""(['"])(%s)\1"""
if re.search(reg%(needle), haystack, re.IGNORECASE):
    print "winning..."

Hunter

Dataset - Vehicle make/model/year (free)

Apparently there is not much out there. And a lot of doubt that someone would be willing to provide such a repository. So I solved the problem myself, and am sharing my dataset with anyone else who finds themselves facing the same problem.

https://github.com/n8barr/automotive-model-year-data

Good way to encapsulate Integer.parseInt()

You shouldn't use Exceptions to validate your values.

For single character there is a simple solution:

Character.isDigit()

For longer values it's better to use some utils. NumberUtils provided by Apache would work perfectly here:

NumberUtils.isNumber()

Please check https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/math/NumberUtils.html

ORA-01653: unable to extend table by in tablespace ORA-06512

Just add a new datafile for the existing tablespace

ALTER TABLESPACE LEGAL_DATA ADD DATAFILE '/u01/oradata/userdata03.dbf' SIZE 200M;

To find out the location and size of your data files:

SELECT FILE_NAME, BYTES FROM DBA_DATA_FILES WHERE TABLESPACE_NAME = 'LEGAL_DATA';

How can one grab a stack trace in C?

For Windows check the StackWalk64() API (also on 32bit Windows). For UNIX you should use the OS' native way to do it, or fallback to glibc's backtrace(), if availabe.

Note however that taking a Stacktrace in native code is rarely a good idea - not because it is not possible, but because you're usally trying to achieve the wrong thing.

Most of the time people try to get a stacktrace in, say, an exceptional circumstance, like when an exception is caught, an assert fails or - worst and most wrong of them all - when you get a fatal "exception" or signal like a segmentation violation.

Considering the last issue, most of the APIs will require you to explicitly allocate memory or may do it internally. Doing so in the fragile state in which your program may be currently in, may acutally make things even worse. For example, the crash report (or coredump) will not reflect the actual cause of the problem, but your failed attempt to handle it).

I assume you're trying to achive that fatal-error-handling thing, as most people seem to try that when it comes to getting a stacktrace. If so, I would rely on the debugger (during development) and letting the process coredump in production (or mini-dump on windows). Together with proper symbol-management, you should have no trouble figuring the causing instruction post-mortem.

How to terminate a thread when main program ends?

Try with enabling the sub-thread as daemon-thread.

For Instance:

Recommended:

from threading import Thread

t = Thread(target=<your-method>)
t.daemon = True  # This thread dies when main thread (only non-daemon thread) exits.
t.start()

Inline:

t = Thread(target=<your-method>, daemon=True).start()

Old API:

t.setDaemon(True)
t.start()

When your main thread terminates ("i.e. when I press Ctrl+C"), other threads will also be killed by the instructions above.

Convert blob URL to normal URL

another way to create a data url from blob url may be using canvas.

var canvas = document.createElement("canvas")
var context = canvas.getContext("2d")
context.drawImage(img, 0, 0) // i assume that img.src is your blob url
var dataurl = canvas.toDataURL("your prefer type", your prefer quality)

as what i saw in mdn, canvas.toDataURL is supported well by browsers. (except ie<9, always ie<9)

Code signing is required for product type Unit Test Bundle in SDK iOS 8.0

The other advice here didn't help me, but I fixed this error by going to Product > Scheme > Edit Scheme. Then I clicked Build on the left hand side and deselected any checkboxes next to AppNameTests. I'm using XCode 6.3

enter image description here

Copy a file from one folder to another using vbscripting

For copying the single file, here is the code:

Function CopyFiles(FiletoCopy,DestinationFolder)
   Dim fso
                Dim Filepath,WarFileLocation
                Set fso = CreateObject("Scripting.FileSystemObject")
                If  Right(DestinationFolder,1) <>"\"Then
                    DestinationFolder=DestinationFolder&"\"
                End If
    fso.CopyFile FiletoCopy,DestinationFolder,True
                FiletoCopy = Split(FiletoCopy,"\")

End Function

How to enable scrolling on website that disabled scrolling?

Try this:

window.onmousewheel = document.onmousewheel = null
window.ontouchmove = null 
window.onwheel = null 

How do I add a foreign key to an existing SQLite table?

Create a foreign key to the existing SQLLite table:

There is no direct way to do that for SQL LITE. Run the below query to recreate STUDENTS table with foreign keys. Run the query after creating initial STUDENTS table and inserting data into the table.

CREATE TABLE    STUDENTS    (       
    STUDENT_ID  INT NOT NULL,   
    FIRST_NAME  VARCHAR(50) NOT NULL,   
    LAST_NAME   VARCHAR(50) NOT NULL,   
    CITY    VARCHAR(50) DEFAULT NULL,   
    BADGE_NO    INT DEFAULT NULL
    PRIMARY KEY(STUDENT_ID) 
);

Insert data into STUDENTS table.

Then Add FOREIGN KEY : making BADGE_NO as the foreign key of same STUDENTS table

BEGIN;
CREATE TABLE STUDENTS_new (
    STUDENT_ID  INT NOT NULL,   
    FIRST_NAME  VARCHAR(50) NOT NULL,   
    LAST_NAME   VARCHAR(50) NOT NULL,   
    CITY    VARCHAR(50) DEFAULT NULL,   
    BADGE_NO    INT DEFAULT NULL,
    PRIMARY KEY(STUDENT_ID) ,
    FOREIGN KEY(BADGE_NO) REFERENCES STUDENTS(STUDENT_ID)   
);
INSERT INTO STUDENTS_new SELECT * FROM STUDENTS;
DROP TABLE STUDENTS;
ALTER TABLE STUDENTS_new RENAME TO STUDENTS;
COMMIT;

we can add the foreign key from any other table as well.

PersistentObjectException: detached entity passed to persist thrown by JPA and Hibernate

In my case I was committing transaction when persist method was used. On changing persist to save method , it got resolved.

How can I change property names when serializing with Json.net?

There is still another way to do it, which is using a particular NamingStrategy, which can be applied to a class or a property by decorating them with [JSonObject] or [JsonProperty].

There are predefined naming strategies like CamelCaseNamingStrategy, but you can implement your own ones.

The implementation of different naming strategies can be found here: https://github.com/JamesNK/Newtonsoft.Json/tree/master/Src/Newtonsoft.Json/Serialization

Java/Groovy - simple date reformatting

Your DateFormat pattern does not match you input date String. You could use

new SimpleDateFormat("dd-MMM-yyyy")

How can JavaScript save to a local file?

Based on http://html5-demos.appspot.com/static/a.download.html:

var fileContent = "My epic novel that I don't want to lose.";
var bb = new Blob([fileContent ], { type: 'text/plain' });
var a = document.createElement('a');
a.download = 'download.txt';
a.href = window.URL.createObjectURL(bb);
a.click();

Modified the original fiddle: http://jsfiddle.net/9av2mfjx/

Responsive web design is working on desktop but not on mobile device

You are probably missing the viewport meta tag in the html head:

 <meta name="viewport" content="width=device-width, initial-scale=1">

Without it the device assumes and sets the viewport to full size.

More info here.

Remove #N/A in vlookup result

To avoid errors in any excel function, use the Error Handling functions that start with IS* in Excel. Embed your function with these error handing functions and avoid the undesirable text in your results. More info in OfficeTricks Page

Angular 2 Cannot find control with unspecified name attribute on formArrays

Only WinMerge made me find it (by comparison with a version that works). I had a case problem on formGroupName. Brackets around this word can lead to the same problem.

Element count of an array in C++

Use the Microsoft "_countof(array)" Macro. This link to the Microsoft Developer Network explains it and offers an example that demonstrates the difference between "sizeof(array)" and the "_countof(array)" macro.

Microsoft and the "_countof(array)" Macro

Save a subplot in matplotlib

While @Eli is quite correct that there usually isn't much of a need to do it, it is possible. savefig takes a bbox_inches argument that can be used to selectively save only a portion of a figure to an image.

Here's a quick example:

import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np

# Make an example plot with two subplots...
fig = plt.figure()
ax1 = fig.add_subplot(2,1,1)
ax1.plot(range(10), 'b-')

ax2 = fig.add_subplot(2,1,2)
ax2.plot(range(20), 'r^')

# Save the full figure...
fig.savefig('full_figure.png')

# Save just the portion _inside_ the second axis's boundaries
extent = ax2.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
fig.savefig('ax2_figure.png', bbox_inches=extent)

# Pad the saved area by 10% in the x-direction and 20% in the y-direction
fig.savefig('ax2_figure_expanded.png', bbox_inches=extent.expanded(1.1, 1.2))

The full figure: Full Example Figure


Area inside the second subplot: Inside second subplot


Area around the second subplot padded by 10% in the x-direction and 20% in the y-direction: Full second subplot

Can't find the 'libpq-fe.h header when trying to install pg gem

Step 1) Make sure postgress is installed in your system ( If it's already installed and you can run postgress server on your machine move to step (2)

apt-get install postgresql postgresql-contrib (sol - fatal error: libpq-fe.h: No such file or directory)
sudo apt-get install ruby-dev (required to install postgress below)
sudo gem install pg
sudo service postgresql restart

Step 2) Some of the c++ files are trying to access libpq-fe.h directly and cant find. So we need to manually search every such file and replace libpq-fe.h with postgresql/libpq-fe.h

Command for searching all occurrences of libpq-fe.h in all dir and subdir is grep -rnw ./ -e 'libpq-fe.h'

3) Go to All the file listed by command run in step 2 and manually change libpq-fe.h with postgresql/libpq-fe.h.

Java - Convert String to valid URI object

Android has always had the Uri class as part of the SDK: http://developer.android.com/reference/android/net/Uri.html

You can simply do something like:

String requestURL = String.format("http://www.example.com/?a=%s&b=%s", Uri.encode("foo bar"), Uri.encode("100% fubar'd"));

What's the difference between next() and nextLine() methods from Scanner class?

A scanner breaks its input into tokens using a delimiter pattern, which is by default known the Whitespaces.

Next() uses to read a single word and when it gets a white space,it stops reading and the cursor back to its original position. NextLine() while this one reads a whole word even when it meets a whitespace.the cursor stops when it finished reading and cursor backs to the end of the line. so u don't need to use a delimeter when you want to read a full word as a sentence.you just need to use NextLine().

 public static void main(String[] args) {
            // TODO code application logic here
           String str;
            Scanner input = new Scanner( System.in );
            str=input.nextLine();
            System.out.println(str);
       }

How can jQuery deferred be used?

1) Use it to ensure an ordered execution of callbacks:

var step1 = new Deferred();
var step2 = new Deferred().done(function() { return step1 });
var step3 = new Deferred().done(function() { return step2 });

step1.done(function() { alert("Step 1") });
step2.done(function() { alert("Step 2") });
step3.done(function() { alert("All done") });
//now the 3 alerts will also be fired in order of 1,2,3
//no matter which Deferred gets resolved first.

step2.resolve();
step3.resolve();
step1.resolve();

2) Use it to verify the status of the app:

var loggedIn = logUserInNow(); //deferred
var databaseReady = openDatabaseNow(); //deferred

jQuery.when(loggedIn, databaseReady).then(function() {
  //do something
});

How can I convert an Integer to localized month name in Java?

tl;dr

Month                             // Enum class, predefining and naming a dozen objects, one for each month of the year. 
.of( 12 )                         // Retrieving one of the enum objects by number, 1-12. 
.getDisplayName(
    TextStyle.FULL_STANDALONE , 
    Locale.CANADA_FRENCH          // Locale determines the human language and cultural norms used in localizing. 
)

java.time

Since Java 1.8 (or 1.7 & 1.6 with the ThreeTen-Backport) you can use this:

Month.of(integerMonth).getDisplayName(TextStyle.FULL_STANDALONE, locale);

Note that integerMonth is 1-based, i.e. 1 is for January. Range is always from 1 to 12 for January-December (i.e. Gregorian calendar only).

Java generating non-repeating random numbers

A simple algorithm that gives you random numbers without duplicates can be found in the book Programming Pearls p. 127.

Attention: The resulting array contains the numbers in order! If you want them in random order, you have to shuffle the array, either with Fisher–Yates shuffle or by using a List and call Collections.shuffle().

The benefit of this algorithm is that you do not need to create an array with all the possible numbers and the runtime complexity is still linear O(n).

public static int[] sampleRandomNumbersWithoutRepetition(int start, int end, int count) {
    Random rng = new Random();

    int[] result = new int[count];
    int cur = 0;
    int remaining = end - start;
    for (int i = start; i < end && count > 0; i++) {
        double probability = rng.nextDouble();
        if (probability < ((double) count) / (double) remaining) {
            count--;
            result[cur++] = i;
        }
        remaining--;
    }
    return result;
}

How do I display a ratio in Excel in the format A:B?

Try this formula:

=SUBSTITUTE(TEXT(A1/B1,"?/?"),"/",":")

Result:

A   B   C
33  11  3:1
25  5   5:1
6   4   3:2

Explanation:

  • TEXT(A1/B1,"?/?") turns A/B into an improper fraction
  • SUBSTITUTE(...) replaces the "/" in the fraction with a colon

This doesn't require any special toolkits or macros. The only downside might be that the result is considered text--not a number--so you can easily use it for further calculations.


Note: as @Robin Day suggested, increase the number of question marks (?) as desired to reduce rounding (thanks Robin!).

Apply CSS style attribute dynamically in Angular JS

I would say that you should put styles that won't change into a regular style attribute, and conditional/scope styles into an ng-style attribute. Also, string keys are not necessary. For hyphen-delimited CSS keys, use camelcase.

<div ng-style="{backgroundColor: data.backgroundCol}" style="width:20px; height:20px; margin-top:10px; border:solid 1px black;"></div>

How to change date format (MM/DD/YY) to (YYYY-MM-DD) in date picker

This is what worked for me in every datePicker version, firstly converting date into internal datePicker date format, and then converting it back to desired one

var date = "2017-11-07";   
date = $.datepicker.formatDate("dd.mm.yy", $.datepicker.parseDate('yy-mm-dd', date));
// 07.11.2017

How can I listen for a click-and-hold in jQuery?

Try this:

var thumbnailHold;

    $(".image_thumb").mousedown(function() {
        thumbnailHold = setTimeout(function(){
             checkboxOn(); // Your action Here

         } , 1000);
     return false;
});

$(".image_thumb").mouseup(function() {
    clearTimeout(thumbnailHold);
});

Install a Nuget package in Visual Studio Code

If you're working with .net core, you can use the dotnet CLI, for instance

dotnet add package <package name>

Changing route doesn't scroll to top in the new page

Setting autoScroll to true did not the trick for me, so I did choose another solution. I built a service that hooks in every time the route changes and that uses the built-in $anchorScroll service to scroll to top. Works for me :-).

Service:

 (function() {
    "use strict";

    angular
        .module("mymodule")
        .factory("pageSwitch", pageSwitch);

    pageSwitch.$inject = ["$rootScope", "$anchorScroll"];

    function pageSwitch($rootScope, $anchorScroll) {
        var registerListener = _.once(function() {
            $rootScope.$on("$locationChangeSuccess", scrollToTop);
        });

        return {
            registerListener: registerListener
        };

        function scrollToTop() {
            $anchorScroll();
        }
    }
}());

Registration:

angular.module("mymodule").run(["pageSwitch", function (pageSwitch) {
    pageSwitch.registerListener();
}]);

How to apply a low-pass or high-pass filter to an array in Matlab?

You can design a lowpass Butterworth filter in runtime, using butter() function, and then apply that to the signal.

fc = 300; % Cut off frequency
fs = 1000; % Sampling rate

[b,a] = butter(6,fc/(fs/2)); % Butterworth filter of order 6
x = filter(b,a,signal); % Will be the filtered signal

Highpass and bandpass filters are also possible with this method. See https://www.mathworks.com/help/signal/ref/butter.html

How do I enable the column selection mode in Eclipse?

On Windows and Linux, it's AltShiftA, as RichieHindle pointed out. On OSX it's OptionCommandA (??A). It's also worth noting that the two modes can have different font preferences, so if you've changed the default text font, it can be jarring to toggle block selection modes and see the font change.

Finally, the "search commands" (Ctrl3 or Command3) pop-up will find it for you if you type block. This is useful if you use the feature just frequently enough to forget the hotkey.

Getting XML Node text value with Java DOM

I use a very old java. Jdk 1.4.08 and I had the same issue. The Node class for me did not had the getTextContent() method. I had to use Node.getFirstChild().getNodeValue() instead of Node.getNodeValue() to get the value of the node. This fixed for me.

How do you count the lines of code in a Visual Studio solution?

Obviously tools are easier, but I feel cool doing this in powershell:)

This script finds all the .csproj references in the .sln file, and then within each csproj file it locates files included for compilation. For each file that is included for compilation it creates an object with properties: Solution, Project, File, Lines. It stores all these objects in a list, and then groups and projects the data as needed.

#path to the solution file e.g. "D:\Code\Test.sln"
$slnFile = "D:\Code\Test.sln"


#results
$results = @()

#iterate through .csproj references in solution file
foreach($projLines in get-item $slnFile | Get-Content | Select-String '".*csproj')
{
    $projFile = [System.IO.Path]::Combine([System.IO.Path]::GetDirectoryName($slnFile), [regex]::Match($projLines,'[^"]*csproj').Value)
    $projFolder = [System.IO.Path]::GetDirectoryName($projFile)

    #from csproj file: get lines for files to compile <Compile Include="..."/>
    $includeLines = get-item $projFile | Get-Content | Select-String '<Compile Include'


    #count of all files lines in project
    $linesInProject = 0;
    foreach($fileLine in $includeLines)
    {
        $includedFilePath = [System.IO.Path]::Combine($projFolder, [Regex]::Match($fileLine, '"(?<file>.*)"').Groups["file"].Value)
        $lineCountInFile = (Get-Content $includedFilePath).Count      
        $results+=New-Object PSObject -Property @{ Solution=$slnFile ;Project=$projFile; File=$includedFilePath; Lines=$lineCountInFile }
    }
}

#filter out any files we dont need
$results = $results | ?{!($_.File -match "Designer")}


#print out:

"---------------lines per solution--------------"
$results | group Solution | %{$_.Name + ": " + ($_.Group | Measure-Object Lines -Sum).Sum}
"---------------lines per peoject--------------"
$results | group Project | %{$_.Name + ": " + ($_.Group | Measure-Object Lines -Sum).Sum}

An error has occured. Please see log file - eclipse juno

For me the problem was that I installed Java sdk 1.9 before installing eclipse. deleting it and installing Java sdk 1.8 instead fixed it. Also, if you are using mac, try

export JAVA_HOME=$(/usr/libexec/java_home)

and then

echo $JAVA_HOME

your should get something like

/Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home

what is the use of annotations @Id and @GeneratedValue(strategy = GenerationType.IDENTITY)? Why the generationtype is identity?

In a Object Relational Mapping context, every object needs to have a unique identifier. You use the @Id annotation to specify the primary key of an entity.

The @GeneratedValue annotation is used to specify how the primary key should be generated. In your example you are using an Identity strategy which

Indicates that the persistence provider must assign primary keys for the entity using a database identity column.

There are other strategies, you can see more here.

How to merge multiple lists into one list in python?

a = ['it']
b = ['was']
c = ['annoying']

a.extend(b)
a.extend(c)

# a now equals ['it', 'was', 'annoying']

How do I point Crystal Reports at a new database

Use the Database menu and "Set Datasource Location" menu option to change the name or location of each table in a report.

This works for changing the location of a database, changing to a new database, and changing the location or name of an individual table being used in your report.

To change the datasource connection, go the Database menu and click Set Datasource Location.

  1. Change the Datasource Connection:
    1. From the Current Data Source list (the top box), click once on the datasource connection that you want to change.
    2. In the Replace with list (the bottom box), click once on the new datasource connection.
    3. Click Update.
  2. Change Individual Tables:
    1. From the Current Data Source list (the top box), expand the datasource connection that you want to change.
    2. Find the table for which you want to update the location or name.
    3. In the Replace with list (the bottom box), expand the new datasource connection.
    4. Find the new table you want to update to point to.
    5. Click Update.
    6. Note that if the table name has changed, the old table name will still appear in the Field Explorer even though it is now using the new table. (You can confirm this be looking at the Table Name of the table's properties in Current Data Source in Set Datasource Location. Screenshot http://i.imgur.com/gzGYVTZ.png) It's possible to rename the old table name to the new name from the context menu in Database Expert -> Selected Tables.
  3. Change Subreports:
    1. Repeat each of the above steps for any subreports you might have embedded in your report.
    2. Close the Set Datasource Location window.
  4. Any Commands or SQL Expressions:
    1. Go to the Database menu and click Database Expert.
    2. If the report designer used "Add Command" to write custom SQL it will be shown in the Selected Tables box on the right.
    3. Right click that command and choose "Edit Command".
    4. Check if that SQL is specifying a specific database. If so you might need to change it.
    5. Close the Database Expert window.
    6. In the Field Explorer pane on the right, right click any SQL Expressions.
    7. Check if the SQL Expressions are specifying a specific database. If so you might need to change it also.
    8. Save and close your Formula Editor window when you're done editing.

And try running the report again.

The key is to change the datasource connection first, then any tables you need to update, then the other stuff. The connection won't automatically change the tables underneath. Those tables are like goslings that've imprinted on the first large goose-like animal they see. They'll continue to bypass all reason and logic and go to where they've always gone unless you specifically manually change them.

To make it more convenient, here's a tip: You can "Show SQL Query" in the Database menu, and you'll see table names qualified with the database (like "Sales"."dbo"."Customers") for any tables that go straight to a specific database. That might make the hunting easier if you have a lot of stuff going on. When I tackled this problem I had to change each and every table to point to the new table in the new database.

Simple UDP example to send and receive data from same socket

(I presume you are aware that using UDP(User Datagram Protocol) does not guarantee delivery, checks for duplicates and congestion control and will just answer your question).

In your server this line:

var data = udpServer.Receive(ref groupEP);

re-assigns groupEP from what you had to a the address you receive something on.

This line:

udpServer.Send(new byte[] { 1 }, 1); 

Will not work since you have not specified who to send the data to. (It works on your client because you called connect which means send will always be sent to the end point you connected to, of course we don't want that on the server as we could have many clients). I would:

UdpClient udpServer = new UdpClient(UDP_LISTEN_PORT);

while (true)
{
    var remoteEP = new IPEndPoint(IPAddress.Any, 11000);
    var data = udpServer.Receive(ref remoteEP);
    udpServer.Send(new byte[] { 1 }, 1, remoteEP); // if data is received reply letting the client know that we got his data          
}

Also if you have server and client on the same machine you should have them on different ports.

How to build a Horizontal ListView with RecyclerView?

There is a RecyclerView subclass named HorizontalGridView you can use it to have horizontal direction. VerticalGridView for vertical direction

How can I set the background color of <option> in a <select> element?

Just like normal background-color: #f0f

You just need a way to target it, eg: <option id="myPinkOption">blah</option>

String concatenation in MySQL

Use concat() function instead of + like this:

select concat(firstname, lastname) as "Name" from test.student

JavaScript editor within Eclipse

Didn't use eclipse for a while, but there are ATF and Aptana.

How should I import data from CSV into a Postgres table using pgAdmin 3?

assuming you have a SQL table called mydata - you can load data from a csv file as follows:

COPY MYDATA FROM '<PATH>/MYDATA.CSV' CSV HEADER;

For more details refer to: http://www.postgresql.org/docs/9.2/static/sql-copy.html

Pipe output and capture exit status in Bash

(command | tee out.txt; exit ${PIPESTATUS[0]})

Unlike @cODAR's answer this returns the original exit code of the first command and not only 0 for success and 127 for failure. But as @Chaoran pointed out you can just call ${PIPESTATUS[0]}. It is important however that all is put into brackets.

Which Eclipse version should I use for an Android app?

I would recommend at least Eclipse Indigo (v 3.7) for Android Development because even though a minimum of Helios (v 3.6) is required for ADT 22.0.1 as explained here...

http://developer.android.com/tools/sdk/eclipse-adt.html

... Indigo is required for Android NDK development using CDT, as explained here:

http://tools.android.com/recent/usingthendkplugin

Adjust list style image position?

Another option you can do, is the following:

li:before{
    content:'';
    padding: 0 0 0 25px;
    background:url(../includes/images/layouts/featured-list-arrow.png) no-repeat 0 3px;
}

Use (0 3px) to position the list image.

Works in IE8+, Chrome, Firefox, and Opera.

I use this option because you can swap out list-style easily and a good chance you may not even have to use an image at all. (fiddle below)

http://jsfiddle.net/flashminddesign/cYAzV/1/

UPDATE:

This will account for text / content going into the second line:

ul{ 
    list-style-type:none;
}

li{
    position:relative;
}

ul li:before{
    content:'>';
    padding:0 10px 0 0;
    position:absolute;
    top:0; left:-10px;
}

Add padding-left: to the li if you want more space between the bullet and content.

http://jsfiddle.net/McLeodWebDev/wfzwm0zy/

How to fetch the row count for all tables in a SQL SERVER database

    SELECT
          SUM(sdmvPTNS.row_count) AS [DBRows]
    FROM
          sys.objects AS sOBJ
          INNER JOIN sys.dm_db_partition_stats AS sdmvPTNS
                ON sOBJ.object_id = sdmvPTNS.object_id
    WHERE 
          sOBJ.type = 'U'
          AND sOBJ.is_ms_shipped = 0
          AND sdmvPTNS.index_id < 2
    GO

Lambda function in list comprehensions

The first one

f = lambda x: x*x
[f(x) for x in range(10)]

runs f() for each value in the range so it does f(x) for each value

the second one

[lambda x: x*x for x in range(10)]

runs the lambda for each value in the list, so it generates all of those functions.

What is the OAuth 2.0 Bearer Token exactly?

Please read the example in rfc6749 sec 7.1 first.

The bearer token is a type of access token, which does NOT require PoP(proof-of-possession) mechanism.

PoP means kind of multi-factor authentication to make access token more secure. ref

Proof-of-Possession refers to Cryptographic methods that mitigate the risk of Security Tokens being stolen and used by an attacker. In contrast to 'Bearer Tokens', where mere possession of the Security Token allows the attacker to use it, a PoP Security Token cannot be so easily used - the attacker MUST have both the token itself and access to some key associated with the token (which is why they are sometimes referred to 'Holder-of-Key' (HoK) tokens).

Maybe it's not the case, but I would say,

  • access token = payment methods
  • bearer token = cash
  • access token with PoP mechanism = credit card (signature or password will be verified, sometimes need to show your ID to match the name on the card)

BTW, there's a draft of "OAuth 2.0 Proof-of-Possession (PoP) Security Architecture" now.

How to secure database passwords in PHP?

Several people misread this as a question about how to store passwords in a database. That is wrong. It is about how to store the password that lets you get to the database.

The usual solution is to move the password out of source-code into a configuration file. Then leave administration and securing that configuration file up to your system administrators. That way developers do not need to know anything about the production passwords, and there is no record of the password in your source-control.

"Thinking in AngularJS" if I have a jQuery background?

jQuery

jQuery makes ridiculously long JavaScript commands like getElementByHerpDerp shorter and cross-browser.

AngularJS

AngularJS allows you to make your own HTML tags/attributes that do things which work well with dynamic web applications (since HTML was designed for static pages).

Edit:

Saying "I have a jQuery background how do I think in AngularJS?" is like saying "I have an HTML background how do I think in JavaScript?" The fact that you're asking the question shows you most likely don't understand the fundamental purposes of these two resources. This is why I chose to answer the question by simply pointing out the fundamental difference rather than going through the list saying "AngularJS makes use of directives whereas jQuery uses CSS selectors to make a jQuery object which does this and that etc....". This question does not require a lengthy answer.

jQuery is a way to make programming JavaScript in the browser easier. Shorter, cross-browser commands, etc.

AngularJS extends HTML, so you don't have to put <div> all over the place just to make an application. It makes HTML actually work for applications rather than what it was designed for, which is static, educational web pages. It accomplishes this in a roundabout way using JavaScript, but fundamentally it is an extension of HTML, not JavaScript.

Check if two unordered lists are equal

What about getting the string representation of the lists and comparing them ?

>>> l1 = ['one', 'two', 'three']
>>> l2 = ['one', 'two', 'three']
>>> l3 = ['one', 'three', 'two']
>>> print str(l1) == str(l2)
True
>>> print str(l1) == str(l3)
False

Good MapReduce examples

One set of familiar operations that you can do in MapReduce is the set of normal SQL operations: SELECT, SELECT WHERE, GROUP BY, ect.

Another good example is matrix multiply, where you pass one row of M and the entire vector x and compute one element of M * x.

How to install mcrypt extension in xampp

The recent versions of XAMPP for Windows runs PHP 7.x which are NOT compatible with mbcrypt. If you have a package like Laravel that requires mbcrypt, you will need to install an older version of XAMPP. OR, you can run XAMPP with multiple versions of PHP by downloading a PHP package from Windows.PHP.net, installing it in your XAMPP folder, and configuring php.ini and httpd.conf to use the correct version of PHP for your site.

Call a Class From another class

First create an object of class2 in class1 and then use that object to call any function of class2 for example write this in class1

class2 obj= new class2();
obj.thefunctioname(args);

Subprocess changing directory

I guess these days you would do:

import subprocess

subprocess.run(["pwd"], cwd="sub-dir")

grep exclude multiple strings

egrep -v "Nopaging the limit is|keyword to remove is"

contenteditable change events

A simple answer in JQuery, I just created this code and thought it will be helpful for others too

    var cont;

    $("div [contenteditable=true]").focus(function() {
        cont=$(this).html();
    });

    $("div [contenteditable=true]").blur(function() {
        if ($(this).html()!=cont) {
           //Here you can write the code to run when the content change
        }           
    });

Expanding tuples into arguments

This is the functional programming method. It lifts the tuple expansion feature out of syntax sugar:

apply_tuple = lambda f, t: f(*t)

Redefine apply_tuple via curry to save a lot of partial calls in the long run:

from toolz import curry
apply_tuple = curry(apply_tuple)

Example usage:

from operator import add, eq
from toolz import thread_last

thread_last(
    [(1,2), (3,4)],
    (map, apply_tuple(add)),
    list,
    (eq, [3, 7])
)
# Prints 'True'

Check if a string is a palindrome

String extension method, easy to use:

    public static bool IsPalindrome(this string str)
    {
        str = new Regex("[^a-zA-Z]").Replace(str, "").ToLower();
        return !str.Where((t, i) => t != str[str.Length - i - 1]).Any();
    }

Java Embedded Databases Comparison

neo4j is:

an embedded, disk-based, fully transactional Java persistence engine that stores data structured in graphs rather than in tables

I haven't had a chance to try it yet - but it looks very promising. Note this is not an SQL database - your object graph is persisted for you - so it might not be appropriate for your existing app.

CSS disable hover effect

  .buttonDisabled{
     background-color: unset !important;
    color: unset !important;
}

Android Intent Cannot resolve constructor

Use

Intent myIntent = new Intent(v.getContext(), MyClass.class);

or

 Intent myIntent = new Intent(MyFragment.this.getActivity(), MyClass.class);

to start a new Activity. This is because you will need to pass Application or component context as a first parameter to the Intent Constructor when you are creating an Intent for a specific component of your application.

Join/Where with LINQ and Lambda

Posting because when I started LINQ + EntityFramework, I stared at these examples for a day.

If you are using EntityFramework, and you have a navigation property named Meta on your Post model object set up, this is dirt easy. If you're using entity and don't have that navigation property, what are you waiting for?

database
  .Posts
  .Where(post => post.ID == id)
  .Select(post => new { post, post.Meta });

If you're doing code first, you'd set up the property thusly:

class Post {
  [Key]
  public int ID {get; set}
  public int MetaID { get; set; }
  public virtual Meta Meta {get; set;}
}

Showing an image from console in Python

You can also using the Python module Ipython, which in addition to displaying an image in the Spyder console can embed images in Jupyter notebook. In Spyder, the image will be displayed in full size, not scaled to fit the console.

from IPython.display import Image, display
display(Image(filename="mypic.png"))

@ViewChild in *ngIf

The answers above did not work for me because in my project, the ngIf is on an input element. I needed access to the nativeElement attribute in order to focus on the input when ngIf is true. There seems to be no nativeElement attribute on ViewContainerRef. Here is what I did (following @ViewChild documentation):

<button (click)='showAsset()'>Add Asset</button>
<div *ngIf='showAssetInput'>
    <input #assetInput />
</div>

...

private assetInputElRef:ElementRef;
@ViewChild('assetInput') set assetInput(elRef: ElementRef) {
    this.assetInputElRef = elRef;
}

...

showAsset() {
    this.showAssetInput = true;
    setTimeout(() => { this.assetInputElRef.nativeElement.focus(); });
}

I used setTimeout before focusing because the ViewChild takes a sec to be assigned. Otherwise it would be undefined.

VSCode cannot find module '@angular/core' or any other modules

Do run

npm install 

it will work most of the cases

PHP: trying to create a new line with "\n"

if your text has newlines, use nl2br php function:

<?php
$string = "foo"."\n"."bar";
echo nl2br($string);
?>

This should look good in browser

How to set custom header in Volley Request

It looks like you override public Map<String, String> getHeaders(), defined in Request, to return your desired HTTP headers.

MySQL LIKE IN()?

A REGEXP might be more efficient, but you'd have to benchmark it to be sure, e.g.

SELECT * from fiberbox where field REGEXP '1740|1938|1940'; 

Using OpenSSL what does "unable to write 'random state'" mean?

One other issue on the Windows platform, make sure you are running your command prompt as an Administrative User!

I don't know how many times this has bitten me...

Excel "External table is not in the expected format."

(I have too low reputation to comment, but this is comment on JoshCaba's entry, using the Ace-engine instead of Jet for Excel 2007)

If you don't have Ace installed/registered on your machine, you can get it at: https://www.microsoft.com/en-US/download/details.aspx?id=13255

It applies for Excel 2010 as well.

Why use sys.path.append(path) instead of sys.path.insert(1, path)?

If you have multiple versions of a package / module, you need to be using virtualenv (emphasis mine):

virtualenv is a tool to create isolated Python environments.

The basic problem being addressed is one of dependencies and versions, and indirectly permissions. Imagine you have an application that needs version 1 of LibFoo, but another application requires version 2. How can you use both these applications? If you install everything into /usr/lib/python2.7/site-packages (or whatever your platform’s standard location is), it’s easy to end up in a situation where you unintentionally upgrade an application that shouldn’t be upgraded.

Or more generally, what if you want to install an application and leave it be? If an application works, any change in its libraries or the versions of those libraries can break the application.

Also, what if you can’t install packages into the global site-packages directory? For instance, on a shared host.

In all these cases, virtualenv can help you. It creates an environment that has its own installation directories, that doesn’t share libraries with other virtualenv environments (and optionally doesn’t access the globally installed libraries either).

That's why people consider insert(0, to be wrong -- it's an incomplete, stopgap solution to the problem of managing multiple environments.