Programs & Examples On #Megaupload

DO NOT USE THIS TAG FOR QUESTIONS ABOUT THE MEGA API! megaupload.com was a file hosting service running bewteen 2005 and 2012, until it was famously shutdown by the United States Department of Justice.

Array of char* should end at '\0' or "\0"?

I would end it with NULL. Why? Because you can't do either of these:

array[index] == '\0'
array[index] == "\0"

The first one is comparing a char * to a char, which is not what you want. You would have to do this:

array[index][0] == '\0'

The second one doesn't even work. You're comparing a char * to a char *, yes, but this comparison is meaningless. It passes if the two pointers point to the same piece of memory. You can't use == to compare two strings, you have to use the strcmp() function, because C has no built-in support for strings outside of a few (and I mean few) syntactic niceties. Whereas the following:

array[index] == NULL

Works just fine and conveys your point.

Best way to encode text data for XML in Java?

You could use the Enterprise Security API (ESAPI) library, which provides methods like encodeForXML and encodeForXMLAttribute. Take a look at the documentation of the Encoder interface; it also contains examples of how to create an instance of DefaultEncoder.

Push item to associative array in PHP

You can use array_merge($array1, $array2) to merge the associative array. Example:

$a1=array("red","green");
$a2=array("blue","yellow");
print_r(array_merge($a1,$a2));

Output:

Array ( [0] => red [1] => green [2] => blue [3] => yellow )

How do I set environment variables from Java?

For use in scenarios where you need to set specific environment values for unit tests, you might find the following hack useful. It will change the environment variables throughout the JVM (so make sure you reset any changes after your test), but will not alter your system environment.

I found that a combination of the two dirty hacks by Edward Campbell and anonymous works best, as one of the does not work under linux, one does not work under windows 7. So to get a multiplatform evil hack I combined them:

protected static void setEnv(Map<String, String> newenv) throws Exception {
  try {
    Class<?> processEnvironmentClass = Class.forName("java.lang.ProcessEnvironment");
    Field theEnvironmentField = processEnvironmentClass.getDeclaredField("theEnvironment");
    theEnvironmentField.setAccessible(true);
    Map<String, String> env = (Map<String, String>) theEnvironmentField.get(null);
    env.putAll(newenv);
    Field theCaseInsensitiveEnvironmentField = processEnvironmentClass.getDeclaredField("theCaseInsensitiveEnvironment");
    theCaseInsensitiveEnvironmentField.setAccessible(true);
    Map<String, String> cienv = (Map<String, String>)     theCaseInsensitiveEnvironmentField.get(null);
    cienv.putAll(newenv);
  } catch (NoSuchFieldException e) {
    Class[] classes = Collections.class.getDeclaredClasses();
    Map<String, String> env = System.getenv();
    for(Class cl : classes) {
      if("java.util.Collections$UnmodifiableMap".equals(cl.getName())) {
        Field field = cl.getDeclaredField("m");
        field.setAccessible(true);
        Object obj = field.get(env);
        Map<String, String> map = (Map<String, String>) obj;
        map.clear();
        map.putAll(newenv);
      }
    }
  }
}

This Works like a charm. Full credits to the two authors of these hacks.

java.lang.ClassNotFoundException: HttpServletRequest

you should add servler-api.jar file in WEB-INF/lib folder

Python, print all floats to 2 decimal places in output

Not directly in the way you want to write that, no. One of the design tenets of Python is "Explicit is better than implicit" (see import this). This means that it's better to describe what you want rather than having the output format depend on some global formatting setting or something. You could of course format your code differently to make it look nicer:

print         '%.2f' % var1, \
      'kg =' ,'%.2f' % var2, \
      'lb =' ,'%.2f' % var3, \
      'gal =','%.2f' % var4, \
      'l'

What is the standard Python docstring format?

As apparantly no one mentioned it: you can also use the Numpy Docstring Standard. It is widely used in the scientific community.

The Napolean sphinx extension to parse Google-style docstrings (recommended in the answer of @Nathan) also supports Numpy-style docstring, and makes a short comparison of both.

And last a basic example to give an idea how it looks like:

def func(arg1, arg2):
    """Summary line.

    Extended description of function.

    Parameters
    ----------
    arg1 : int
        Description of arg1
    arg2 : str
        Description of arg2

    Returns
    -------
    bool
        Description of return value

    See Also
    --------
    otherfunc : some related other function

    Examples
    --------
    These are written in doctest format, and should illustrate how to
    use the function.

    >>> a=[1,2,3]
    >>> print [x + 3 for x in a]
    [4, 5, 6]
    """
    return True

Update query using Subquery in Sql Server

The title of this thread asks how a subquery can be used in an update. Here's an example of that:

update [dbName].[dbo].[MyTable] 
set MyColumn = 1 
where 
    (
        select count(*) 
        from [dbName].[dbo].[MyTable] mt2 
        where
            mt2.ID > [dbName].[dbo].[MyTable].ID
            and mt2.Category = [dbName].[dbo].[MyTable].Category
    ) > 0

How to embed a PDF?

Here is the code you can use for every browser:

<embed src="pdfFiles/interfaces.pdf" width="600" height="500" alt="pdf" pluginspage="http://www.adobe.com/products/acrobat/readstep2.html">

Tested on firefox and chrome

Check date between two other dates spring data jpa

Maybe you could try

List<Article> findAllByPublicationDate(Date publicationDate);

The detail could be checked in this article:

https://www.baeldung.com/spring-data-jpa-query-by-date

GDB: Listing all mapped memory regions for a crashed process

You can also use info files to list all the sections of all the binaries loaded in process binary.

How to post JSON to a server using C#?

I find this to be the friendliest and most concise way to post an read JSON data:

var url = @"http://www.myapi.com/";
var request = new Request { Greeting = "Hello world!" };
var json = JsonSerializer.Serialize<Request>(request);
using (WebClient client = new WebClient())
{
    var jsonResponse = client.UploadString(url, json);
    var response = JsonSerializer.Deserialize<Response>(jsonResponse);
}

I'm using Microsoft's System.Text.Json for serializing and deserializing JSON. See NuGet.

How to call webmethod in Asp.net C#

The problem is at [System.Web.Services.WebMethod], add [WebMethod(EnableSession = false)] and you could get rid of page life cycle, by default EnableSession is true in Page and making page to come in life though life cycle events..

Please refer below page for more details http://msdn.microsoft.com/en-us/library/system.web.configuration.pagessection.enablesessionstate.aspx

Shell script to check if file exists

The following script will help u to go to a process if that script exist in a specified variable,

cat > waitfor.csh

    #!/bin/csh

    while !( -e $1 )

    sleep 10m

    end

ctrl+D

here -e is for working with files,

$1 is a shell variable,

sleep for 10 minutes

u can execute the script by ./waitfor.csh ./temp ; echo "the file exits"

How to get a variable value if variable name is stored as string?

Based on the answer: https://unix.stackexchange.com/a/111627

###############################################################################
# Summary: Returns the value of a variable given it's name as a string.
# Required Positional Argument: 
#   variable_name - The name of the variable to return the value of
# Returns: The value if variable exists; otherwise, empty string ("").
###############################################################################
get_value_of()
{
    variable_name=$1
    variable_value=""
    if set | grep -q "^$variable_name="; then
        eval variable_value="\$$variable_name"
    fi
    echo "$variable_value"
}

test=123
get_value_of test
# 123
test="\$(echo \"something nasty\")"
get_value_of test
# $(echo "something nasty")

How should I make my VBA code compatible with 64-bit Windows?

Actually, the correct way of checking for 32 bit or 64 bit platform is to use the Win64 constant which is defined in all versions of VBA (16 bit, 32 bit, and 64 bit versions).

#If Win64 Then 
' Win64=true, Win32=true, Win16= false 
#ElseIf Win32 Then 
' Win32=true, Win16=false 
#Else 
' Win16=true 
#End If

Source: VBA help on compiler constants

Create GUI using Eclipse (Java)

Yes. Use WindowBuilder Pro (provided by Google). It supports SWT and Swing as well with multiple layouts (Group layout, MiGLayout etc.) It's integrated out of the box with Eclipse Indigo, but you can install plugin on previous versions (3.4/3.5/3.6):

enter image description here

How to add a primary key to a MySQL table?

If your table is quite big better not use the statement:

alter table goods add column `id` int(10) unsigned primary KEY AUTO_INCREMENT;

because it makes a copy of all data in a temporary table, alter table and then copies it back. Better do it manually. Rename your table:

rename table goods to goods_old;

create new table with primary key and all necessary indexes:

create table goods (
    id  int(10) unsigned not null AUTO_INCREMENT
    ... other columns ...
    primary key (id)
);

move all data from the old table into new, disabling keys and indexes to speed up copying:

-- USE THIS FOR MyISAM TABLES:

SET UNIQUE_CHECKS=0;
    ALTER TABLE goods DISABLE KEYS;
        INSERT INTO goods (... your column names ...) SELECT ... your column names FROM goods_old; 
    ALTER TABLE goods ENABLE KEYS;
SET UNIQUE_CHECKS=1;

OR

-- USE THIS FOR InnoDB TABLES:

SET AUTOCOMMIT = 0; SET UNIQUE_CHECKS=0; SET FOREIGN_KEY_CHECKS=0;
    INSERT INTO goods (... your column names ...) SELECT ... your column names FROM goods_old; 
SET FOREIGN_KEY_CHECKS=1; SET UNIQUE_CHECKS=1; COMMIT; SET AUTOCOMMIT = 1;

It takes 2 000 seconds to add PK to a table with ~200 mln rows.

Create a File object in memory from a string in Java

FileReader r = new FileReader(file);

Use a file reader load the file and then write its contents to a string buffer.

example

The link above shows you an example of how to accomplish this. As other post to this answer say to load a file into memory you do not need write access as long as you do not plan on making changes to the actual file.

How do you tell if caps lock is on using JavaScript?

Recently there was a similar question on hashcode.com, and I created a jQuery plugin to deal with it. It also supports the recognition of caps lock on numbers. (On the standard German keyboard layout caps lock has effect on numbers).

You can check the latest version here: jquery.capsChecker

Foreach Control in form, how can I do something to all the TextBoxes in my Form?

Even better, you can encapsule this to clear any type of controls you want in one method, like this:

public static void EstadoControles<T>(object control, bool estado, bool limpiar = false) where T : Control
        {
            foreach (var textEdits in ((T)control).Controls.OfType<TextEdit>()) textEdits.Enabled = estado;
            foreach (var textLookUpEdits in ((T)control).Controls.OfType<LookUpEdit>()) textLookUpEdits.Enabled = estado;

            if (!limpiar) return;
            {
                foreach (var textEdits in ((T)control).Controls.OfType<TextEdit>()) textEdits.Text = string.Empty;
                foreach (var textLookUpEdits in ((T)control).Controls.OfType<LookUpEdit>()) textLookUpEdits.EditValue = @"-1";
            }
        }

Start an activity from a fragment

You should use getActivity() to launch activities from fragments

Intent intent = new Intent(getActivity(), mFragmentFavorite.class);
startActivity(intent);

Also, you should be naming classes with caps: MFragmentActivity instead of mFragmentActivity.

How to get images in Bootstrap's card to be the same height/width?

I went with "manually" using the same breakpoints in Bootstrap 4 as media queries...

/* Equal-height card images, cf. https://stackoverflow.com/a/47698201/1375163*/
.card-img-top {
    /*height: 11vw;*/
    object-fit: cover;
}
  /* Small devices (landscape phones, 576px and up) */
  @media (min-width: 576px) {
    .card-img-top {
        height: 19vw;
    }
  }
  /* Medium devices (tablets, 768px and up) */
  @media (min-width: 768px) {
    .card-img-top {
        height: 16vw;
    }
  }
  /* Large devices (desktops, 992px and up) */
  @media (min-width: 992px) {
    .card-img-top {
        height: 11vw;
    }
  }
  /* Extra large devices (large desktops, 1200px and up) */
  @media (min-width: 992px) {
    .card-img-top {
        height: 11vw;
    }
  }

It works, though I wish there were more native responsiveness of this sort.

Partial suggestion from @sepuckett86 and I.

Setting up enviromental variables in Windows 10 to use java and javac

Here are the typical steps to set JAVA_HOME on Windows 10.

  1. Search for Advanced System Settings in your windows Search box. Click on Advanced System Settings.
  2. Click on Environment variables button: Environment Variables popup will open.
  3. Goto system variables session, and click on New button to create new variable (HOME_PATH), then New System Variables popup will open.
  4. Give Variable Name: JAVA_HOME, and Variable value : Your Java SDK home path. Ex: C:\Program Files\java\jdk1.8.0_151 Note: It should not include \bin. Then click on OK button.
  5. Now you are able to see your JAVA_HOME in system variables list. (If you are not able to, try doing it again.)
  6. Select Path (from system variables list) and click on Edit button, A new pop will opens (Edit Environment Variables). It was introduced in windows 10.
  7. Click on New button and give %JAVA_HOME%\bin at highlighted field and click Ok button.

You can find complete tutorials on my blog :

How to set JAVA_HOME in 64 bit Windows 10 OS

Android emulator shows nothing except black screen and adb devices shows "device offline"

I had the same problem on API 28, and the fix turned out to be as below;

Enabling Skia rendering for Android UI

When using images for API 27 or later, the emulator can render the Android UI with Skia, which can render more smoothly and efficiently.

To enable Skia rendering, use the following commands in adb shell:

su
setprop debug.hwui.renderer skiagl
stop
start

https://developer.android.com/studio/run/emulator-acceleration#accel-graphics

Converting dict to OrderedDict

Use dict.items(); it can be as simple as following:

ship = collections.OrderedDict(ship.items())

How do I 'svn add' all unversioned files to SVN?

Since this post is tagged Windows, I thought I would work out a solution for Windows. I wanted to automate the process, and I made a bat file. I resisted making a console.exe in C#.

I wanted to add any files or folders which are not added in my repository when I begin the commit process.

The problem with many of the answers is they will list unversioned files which should be ignored as per my ignore list in TortoiseSVN.

Here is my hook setting and batch file which does that

Tortoise Hook Script:

"start_commit_hook".
(where I checkout) working copy path = C:\Projects
command line: C:\windows\system32\cmd.exe /c C:\Tools\SVN\svnadd.bat
(X) Wait for the script to finish
(X) (Optional) Hide script while running
(X) Always execute the script

svnadd.bat

@echo off

rem Iterates each line result from the command which lists files/folders
rem     not added to source control while respecting the ignore list.
FOR /F "delims==" %%G IN ('svn status ^| findstr "^?"') DO call :DoSVNAdd "%%G"
goto end

:DoSVNAdd
set addPath=%1
rem Remove line prefix formatting from svn status command output as well as
rem    quotes from the G call (as required for long folder names). Then
rem    place quotes back around the path for the SVN add call.
set addPath="%addPath:~9,-1%"
svn add %addPath%

:end

How should I load files into my Java application?

public byte[] loadBinaryFile (String name) {
    try {

        DataInputStream dis = new DataInputStream(new FileInputStream(name));
        byte[] theBytes = new byte[dis.available()];
        dis.read(theBytes, 0, dis.available());
        dis.close();
        return theBytes;
    } catch (IOException ex) {
    }
    return null;
} // ()

CSS rotate property in IE

Just a hint... think twice before using "transform: rotate()", or even "-ms-transform :rotate()" (IE9) with mobiles!

I've been knocking hard to the wall for days. I have a 'kinetic' system going on, that slides images and, on top of it, a command area. I did "transform" on an arrow button so it simulates pointing up and down... I've reviewd the 1.000 plus code lines for ages!!! ;-)

All ok, once I removed transform:rotate from the CSS. It's a bit (not to use bad words) tricky the way IE handles it, comparing to other borwsers.

Great answer @Spudley! Thanks for writing it!

How to hide keyboard in swift on pressing return key?

When the user taps the Done button on the text keyboard, a Did End On Exit event will be generated; at that time, we need to tell the text field to give up control so that the keyboard will go away. In order to do that, we need to add an action method to our controller class. Select ViewController.swift add the following action method:

@IBAction func textFieldDoneEditing(sender: UITextField) {
sender.resignFirstResponder()}

Select Main.storyboard in the Project Navigator and bring up the connections inspector. Drag from the circle next to Did End On Exit to the yellow View Controller icon in the storyboard and let go. A small pop-up menu will appear containing the name of a single action, the one we just added. Click the textFieldDoneEditing action to select it and that's it.

After submitting a POST form open a new window showing the result

var urlAction = 'whatever.php';
var data = {param1:'value1'};

var $form = $('<form target="_blank" method="POST" action="' + urlAction + '">');
$.each(data, function(k,v){
    $form.append('<input type="hidden" name="' + k + '" value="' + v + '">');
});
$form.submit();

Submit form and stay on same page?

Use XMLHttpRequest

var xhr = new XMLHttpRequest();
xhr.open("POST", '/server', true);

//Send the proper header information along with the request
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

xhr.onreadystatechange = function() { // Call a function when the state changes.
    if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
        // Request finished. Do processing here.
    }
}
xhr.send("foo=bar&lorem=ipsum");
// xhr.send(new Int8Array()); 
// xhr.send(document);

Array versus linked-list

While many of you have touched upon major adv./dis of linked list vs array, most of the comparisons are how one is better/ worse than the other.Eg. you can do random access in array but not possible in linked list and others. However, this is assuming link lists and array are going to be applied in a similar application. However a correct answer should be how link list would be preferred over array and vice-versa in a particular application deployment. Suppose you want to implement a dictionary application, what would you use ? Array : mmm it would allow easy retrieval through binary search and other search algo .. but lets think how link list can be better..Say you want to search "Blob" in dictionary. Would it make sense to have a link list of A->B->C->D---->Z and then each list element also pointing to an array or another list of all words starting with that letter ..

A -> B -> C -> ...Z
|    |    |
|    |    [Cat, Cave]
|    [Banana, Blob]
[Adam, Apple]

Now is the above approach better or a flat array of [Adam,Apple,Banana,Blob,Cat,Cave] ? Would it even be possible with array ? So a major advantage of link list is you can have an element not just pointing to the next element but also to some other link list/array/ heap/ or any other memory location. Array is a one flat contigous memory sliced into blocks size of the element it is going to store.. Link list on the other hand is a chunks of non-contigous memory units (can be any size and can store anything) and pointing to each other the way you want. Similarly lets say you are making a USB drive. Now would you like files to be saved as any array or as a link list ? I think you get the idea what I am pointing to :)

Why do package names often begin with "com"

It's just a namespace definition to avoid collision of class names. The com.domain.package.Class is an established Java convention wherein the namespace is qualified with the company domain in reverse.

Find Facebook user (url to profile page) by known email address

The definitive answer to this is from Facebook themselves. In post today at https://developers.facebook.com/bugs/335452696581712 a Facebook dev says

The ability to pass in an e-mail address into the "user" search type was
removed on July 10, 2013. This search type only returns results that match
a user's name (including alternate name).

So, alas, the simple answer is you can no longer search for users by their email address. This sucks, but that's Facebook's new rules.

Rerender view on browser resize with React

https://github.com/renatorib/react-sizes is a HOC to do this while still maintaining good performance.

import React from 'react'
import withSizes from 'react-sizes'

@withSizes(({ width }) => ({ isMobile: width < 480 }))
class MyComponent extends Component {
  render() {
    return <div>{this.props.isMobile ? 'Is Mobile' : 'Is Not Mobile'}</div>
  }
}

export default MyComponent

How to get ID of clicked element with jQuery

@Adam Just add a function using onClick="getId()"

function getId(){console.log(this.event.target.id)}

How do I use setsockopt(SO_REUSEADDR)?

After :

sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) 
    error("ERROR opening socket");

You can add (with standard C99 compound literal support) :

if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &(int){1}, sizeof(int)) < 0)
    error("setsockopt(SO_REUSEADDR) failed");

Or :

int enable = 1;
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)) < 0)
    error("setsockopt(SO_REUSEADDR) failed");

gradle build fails on lint task

Add

android.lintOptions.abortOnError false

to your app\build.gradle

client denied by server configuration

This has happened to me several times migrating from Apache 2.2.

What I have found is that there is an Order,Deny that I missed with VIM's Search feature somehow that is the default main Vhost, line 379. Hope this helps someone. I commented out the Order Deny,Allow and Deny from All and it worked!

How to check SQL Server version

Following are possible ways to see the version:

Method 1: Connect to the instance of SQL Server, and then run the following query:

Select @@version

An example of the output of this query is as follows:

Microsoft SQL Server 2008 (SP1) - 10.0.2531.0 (X64)   Mar 29 2009 
10:11:52   Copyright (c) 1988-2008 Microsoft Corporation  Express 
Edition (64-bit) on Windows NT 6.1 <X64> (Build 7600: )

Method 2: Connect to the server by using Object Explorer in SQL Server Management Studio. After Object Explorer is connected, it will show the version information in parentheses, together with the user name that is used to connect to the specific instance of SQL Server.

Method 3: Look at the first few lines of the Errorlog file for that instance. By default, the error log is located at Program Files\Microsoft SQL Server\MSSQL.n\MSSQL\LOG\ERRORLOG and ERRORLOG.n files. The entries may resemble the following:

2011-03-27 22:31:33.50 Server      Microsoft SQL Server 2008 (SP1) - 10.0.2531.0 (X64)                 Mar 29 2009 10:11:52                 Copyright (c) 1988-2008 Microsoft Corporation                Express Edition (64-bit) on Windows NT 6.1 <X64> (Build 7600: )

As you can see, this entry gives all the necessary information about the product, such as version, product level, 64-bit versus 32-bit, the edition of SQL Server, and the OS version on which SQL Server is running.

Method 4: Connect to the instance of SQL Server, and then run the following query:

SELECT SERVERPROPERTY('productversion'), SERVERPROPERTY ('productlevel'), SERVERPROPERTY ('edition')

Note This query works with any instance of SQL Server 2000 or of a later version

Data access object (DAO) in Java

The Data Access Object is basically an object or an interface that provides access to an underlying database or any other persistence storage.

That definition from: http://en.wikipedia.org/wiki/Data_access_object

Check also the sequence diagram here: http://www.oracle.com/technetwork/java/dataaccessobject-138824.html

Maybe a simple example can help you understand the concept:

Let's say we have an entity to represent an employee:

public class Employee {

    private int id;
    private String name;


    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

}

The employee entities will be persisted into a corresponding Employee table in a database. A simple DAO interface to handle the database operation required to manipulate an employee entity will be like:

interface EmployeeDAO {

    List<Employee> findAll();
    List<Employee> findById();
    List<Employee> findByName();
    boolean insertEmployee(Employee employee);
    boolean updateEmployee(Employee employee);
    boolean deleteEmployee(Employee employee);

}

Next we have to provide a concrete implementation for that interface to deal with SQL server, and another to deal with flat files, etc.

Chrome refuses to execute an AJAX script due to wrong MIME type

For the record and Google search users, If you are a .NET Core developer, you should set the content-types manually, because their default value is null or empty:

var provider = new FileExtensionContentTypeProvider();
app.UseStaticFiles(new StaticFileOptions
{
    ContentTypeProvider = provider
});

BeanFactory not initialized or already closed - call 'refresh' before

This problem can be caused also by jvm version used to compile the project and the jvm supported by the servlet container. Try to Fix the project build path. For example if you deploy on tomcat 9, use jvm 1.8.0 or lower.

What is the difference among col-lg-*, col-md-* and col-sm-* in Bootstrap?

enter image description here

I think this image is pretty good to understand the concept better!

for more detail understanding please go though below link:

https://getbootstrap.com/docs/3.4/css/

Is it possible to "decompile" a Windows .exe? Or at least view the Assembly?

With a debugger you can step through the program assembly interactively.
With a disassembler, you can view the program assembly in more detail.
With a decompiler, you can turn a program back into partial source code, assuming you know what it was written in (which you can find out with free tools such as PEiD - if the program is packed, you'll have to unpack it first OR Detect-it-Easy if you can't find PEiD anywhere. DIE has a strong developer community on github currently).

Debuggers:

  • OllyDbg, free, a fine 32-bit debugger, for which you can find numerous user-made plugins and scripts to make it all the more useful.
  • WinDbg, free, a quite capable debugger by Microsoft. WinDbg is especially useful for looking at the Windows internals, since it knows more about the data structures than other debuggers.
  • SoftICE, SICE to friends. Commercial and development stopped in 2006. SoftICE is kind of a hardcore tool that runs beneath the operating system (and halts the whole system when invoked). SoftICE is still used by many professionals, although might be hard to obtain and might not work on some hardware (or software - namely, it will not work on Vista or NVIDIA gfx cards).

Disassemblers:

  • IDA Pro(commercial) - top of the line disassembler/debugger. Used by most professionals, like malware analysts etc. Costs quite a few bucks though (there exists free version, but it is quite quite limited)
  • W32Dasm(free) - a bit dated but gets the job done. I believe W32Dasm is abandonware these days, and there are numerous user-created hacks to add some very useful functionality. You'll have to look around to find the best version.

Decompilers:

  • Visual Basic: VB Decompiler, commercial, produces somewhat identifiable bytecode.
  • Delphi: DeDe, free, produces good quality source code.
  • C: HexRays, commercial, a plugin for IDA Pro by the same company. Produces great results but costs a big buck, and won't be sold to just anyone (or so I hear).
  • .NET(C#): dotPeek, free, decompiles .NET 1.0-4.5 assemblies to C#. Support for .dll, .exe, .zip, .vsix, .nupkg, and .winmd files.

Some related tools that might come handy in whatever it is you're doing are resource editors such as ResourceHacker (free) and a good hex editor such as Hex Workshop (commercial).

Additionally, if you are doing malware analysis (or use SICE), I wholeheartedly suggest running everything inside a virtual machine, namely VMware Workstation. In the case of SICE, it will protect your actual system from BSODs, and in the case of malware, it will protect your actual system from the target program. You can read about malware analysis with VMware here.

Personally, I roll with Olly, WinDbg & W32Dasm, and some smaller utility tools.

Also, remember that disassembling or even debugging other people's software is usually against the EULA in the very least :)

Comparing two .jar files

Use Java Decompiler to turn the jar file into source code file, and then use WinMerge to perform comparison.

You should consult the copyright holder of the source code, to see whether it is OK to do so.

How to share my Docker-Image without using the Docker-Hub?

Based on this blog, one could share a docker image without a docker registry by executing:

docker save --output latestversion-1.0.0.tar dockerregistry/latestversion:1.0.0

Once this command has been completed, one could copy the image to a server and import it as follows:

docker load --input latestversion-1.0.0.tar

Visual Studio popup: "the operation could not be completed"

Restarting Visual Studio solved my problem :)

How do I concatenate strings with variables in PowerShell?

Try the Join-Path cmdlet:

Get-ChildItem c:\code\*\bin\* -Filter *.dll | Foreach-Object {
    Join-Path -Path  $_.DirectoryName -ChildPath "$buildconfig\$($_.Name)" 
}

C#: how to get first char of a string?

Or you can do this:

MyString[0];

ImportError: DLL load failed: %1 is not a valid Win32 application

All you have to do is copy the cv2.pyd file from the x86 folder (C:\opencv\build\python\2.7\x86\ for example) to C:\Python27\Lib\site-packages\ , not from the x64 folder.

Hope that help you.

ASP.NET MVC on IIS 7.5

For me on an Azure Server 2012 R2 IIS 8.5 VM with an Asp.Net MVC 5 app (bin deployed MVC 5) I had to do the following from an elevated cmd prompt even though I had 4.5 already installed:

dism /online /enable-feature /featurename:IIS-ASPNET45

Source: http://support.microsoft.com/kb/2736284

I also brute force installed all IIS features with the following PowerShell:

import-module servermanager
add-windowsfeature web-server -includeallsubfeature

Source: http://www.iis.net/learn/install/installing-iis-85/installing-iis-85-on-windows-server-2012-r2

Now my app is working.

How can I send and receive WebSocket messages on the server side?

PHP Implementation:

function encode($message)
{
    $length = strlen($message);

    $bytesHeader = [];
    $bytesHeader[0] = 129; // 0x1 text frame (FIN + opcode)

    if ($length <= 125) {
            $bytesHeader[1] = $length;
    } else if ($length >= 126 && $length <= 65535) {
            $bytesHeader[1] = 126;
            $bytesHeader[2] = ( $length >> 8 ) & 255;
            $bytesHeader[3] = ( $length      ) & 255;
    } else {
            $bytesHeader[1] = 127;
            $bytesHeader[2] = ( $length >> 56 ) & 255;
            $bytesHeader[3] = ( $length >> 48 ) & 255;
            $bytesHeader[4] = ( $length >> 40 ) & 255;
            $bytesHeader[5] = ( $length >> 32 ) & 255;
            $bytesHeader[6] = ( $length >> 24 ) & 255;
            $bytesHeader[7] = ( $length >> 16 ) & 255;
            $bytesHeader[8] = ( $length >>  8 ) & 255;
            $bytesHeader[9] = ( $length       ) & 255;
    }

    $str = implode(array_map("chr", $bytesHeader)) . $message;

    return $str;
}

jQuery get the image src

You may find likr

$('.class').find('tag').attr('src');

Space between Column's children in Flutter

There are many ways of doing it, I'm listing a few here.

  1. Use Container and give some height:

    Column(
      children: <Widget>[
        Widget1(),
        Container(height: 10), // set height
        Widget2(),
      ],
    )
    
  2. Use Spacer

    Column(
      children: <Widget>[
        Widget1(),
        Spacer(), // use Spacer
        Widget2(),
      ],
    )
    
  3. Use Expanded

    Column(
      children: <Widget>[
        Widget1(),
        Expanded(child: SizedBox()), // use Expanded
        Widget2(),
      ],
    )
    
  4. Use mainAxisAlignment

    Column(
      mainAxisAlignment: MainAxisAlignment.spaceAround, // mainAxisAlignment
      children: <Widget>[
        Widget1(),
        Widget2(),
      ],
    )
    
  5. Use Wrap

    Wrap(
      direction: Axis.vertical, // make sure to set this
      spacing: 20, // set your spacing
      children: <Widget>[
        Widget1(),
        Widget2(),
      ],
    )
    

FCM getting MismatchSenderId

Note: I had truncated the first part of the FCM token (before :) and the error was MismatchSenderId

Fixed my script and now everything works fine.

Can I get "&&" or "-and" to work in PowerShell?

I tried this sequence of commands in PowerShell:

First Test

PS C:\> $MyVar = "C:\MyTxt.txt"
PS C:\> ($MyVar -ne $null) -and (Get-Content $MyVar)
True

($MyVar -ne $null) returned true and (Get-Content $MyVar) also returned true.

Second Test

PS C:\> $MyVar = $null
PS C:\> ($MyVar -ne $null) -and (Get-Content $MyVar)
False

($MyVar -ne $null) returned false and so far I must assume the (Get-Content $MyVar) also returned false.

The third test proved the second condition was not even analyzed.

PS C:\> ($MyVar -ne $null) -and (Get-Content "C:\MyTxt.txt")
False

($MyVar -ne $null) returned false and proved the second condition (Get-Content "C:\MyTxt.txt") never ran, by returning false on the whole command.

How to set the title of UIButton as left alignment?

Swift 5.1

self.btnPro.titleLabel?.textAlignment = .left

IntelliJ Organize Imports

In addition to Optimize Imports and Auto Import, which were pointed out by @dave-newton and @ryan-stewart in earlier answers, go to:

  • IDEA <= 13: File menu > Settings > Code Style > Java > Imports
  • IDEA >= 14: File menu > Settings > Editor > Code Style > Java > Imports (thanks to @mathias-bader for the hint!) Settings dialog

There you can fine tune the grouping and order or imports, "Class count to use import with '*'", etc.

Note:
since IDEA 13 you can configure the project default settings from the IDEA "start page": Configure > Project defaults > Settings > .... Then every new project will have those default settings: enter image description here

How to create a QR code reader in a HTML5 website?

The algorithm that drives http://www.webqr.com is a JavaScript implementation of https://github.com/LazarSoft/jsqrcode. I haven't tried how reliable it is yet, but that's certainly the easier plug-and-play solution (client- or server-side) out of the two.

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.

List<T> or IList<T>

A principle of TDD and OOP generally is programming to an interface not an implementation.

In this specific case since you're essentially talking about a language construct, not a custom one it generally won't matter, but say for example that you found List didn't support something you needed. If you had used IList in the rest of the app you could extend List with your own custom class and still be able to pass that around without refactoring.

The cost to do this is minimal, why not save yourself the headache later? It's what the interface principle is all about.

ASP.NET Web Application Message Box

Or create a method like this in your solution:

public static class MessageBox {
    public static void Show(this Page Page, String Message) {
       Page.ClientScript.RegisterStartupScript(
          Page.GetType(),
          "MessageBox",
          "<script language='javascript'>alert('" + Message + "');</script>"
       );
    }
}

Then you can use it like:

MessageBox.Show("Here is my message");

How do I check if a property exists on a dynamic anonymous type in c#?

public static bool HasProperty(dynamic obj, string name)
{
    Type objType = obj.GetType();

    if (objType == typeof(ExpandoObject))
    {
        return ((IDictionary<string, object>)obj).ContainsKey(name);
    }

    return objType.GetProperty(name) != null;
}

passing several arguments to FUN of lapply (and others *apply)

If you look up the help page, one of the arguments to lapply is the mysterious .... When we look at the Arguments section of the help page, we find the following line:

...: optional arguments to ‘FUN’.

So all you have to do is include your other argument in the lapply call as an argument, like so:

lapply(input, myfun, arg1=6)

and lapply, recognizing that arg1 is not an argument it knows what to do with, will automatically pass it on to myfun. All the other apply functions can do the same thing.

An addendum: You can use ... when you're writing your own functions, too. For example, say you write a function that calls plot at some point, and you want to be able to change the plot parameters from your function call. You could include each parameter as an argument in your function, but that's annoying. Instead you can use ... (as an argument to both your function and the call to plot within it), and have any argument that your function doesn't recognize be automatically passed on to plot.

How to capture UIView to UIImage without loss of quality on retina display

- (UIImage*)screenshotForView:(UIView *)view
{
    UIGraphicsBeginImageContext(view.bounds.size);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    // hack, helps w/ our colors when blurring
    NSData *imageData = UIImageJPEGRepresentation(image, 1); // convert to jpeg
    image = [UIImage imageWithData:imageData];

    return image;
}

How to get a file or blob from an object URL?

See Getting BLOB data from XHR request which points out that BlobBuilder doesn't work in Chrome so you need to use:

xhr.responseType = 'arraybuffer';

How to insert data to MySQL having auto incremented primary key?

Check out this post

According to it

No value was specified for the AUTO_INCREMENT column, so MySQL assigned sequence numbers automatically. You can also explicitly assign NULL or 0 to the column to generate sequence numbers.

What is HTML5 ARIA?

WAI-ARIA is a spec defining support for accessible web apps. It defines bunch of markup extensions (mostly as attributes on HTML5 elements), which can be used by the web app developer to provide additional information about the semantics of the various elements to assistive technologies like screen readers. Of course, for ARIA to work, the HTTP user agent that interprets the markup needs to support ARIA, but the spec is created in such a way, as to allow down-level user agents to ignore the ARIA-specific markup safely without affecting the web app's functionality.

Here's an example from the ARIA spec:

<ul role="menubar">

  <!-- Rule 2A: "File" label via aria-labelledby -->
  <li role="menuitem" aria-haspopup="true" aria-labelledby="fileLabel"><span id="fileLabel">File</span>
    <ul role="menu">

      <!-- Rule 2C: "New" label via Namefrom:contents -->
      <li role="menuitem" aria-haspopup="false">New</li>
      <li role="menuitem" aria-haspopup="false">Open…</li>
      ...
    </ul>
  </li>
  ...
</ul>

Note the role attribute on the outer <ul> element. This attribute does not affect in any way how the markup is rendered on the screen by the browser; however, browsers that support ARIA will add OS-specific accessibility information to the rendered UI element, so that the screen reader can interpret it as a menu and read it aloud with enough context for the end-user to understand (for example, an explicit "menu" audio hint) and is able to interact with it (for example, voice navigation).

Using a batch to copy from network drive to C: or D: drive

You are copying all files to a single file called TEST_BACKUP_FOLDER

try this:

md TEST_BACKUP_FOLDER
copy "\\My_Servers_IP\Shared Drive\FolderName\*" TEST_BACKUP_FOLDER

ArrayList - How to modify a member of an object?

I wrote you 2 classes to show you how it's done; Main and Customer. If you run the Main class you see what's going on:

import java.util.*;

public class Customer {

    private String name;
    private String email;

    public Customer(String name, String email) {
        this.name = name;
        this.email = email;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public String toString() {
        return name + " | " + email;
    }

    public static String toString(Collection<Customer> customers) {
        String s = "";
        for(Customer customer : customers) {
            s += customer + "\n";
        }
        return s;
    }

}


import java.util.*;

public class Main {

    public static void main(String[] args) {
        List<Customer> customers = new ArrayList<>();
        customers.add(new Customer("Bert", "[email protected]"));
        customers.add(new Customer("Ernie", "[email protected]"));
        System.out.println("customers before email change - start");
        System.out.println(Customer.toString(customers));
        System.out.println("end");
        customers.get(1).setEmail("[email protected]");
        System.out.println("customers after email change - start");
        System.out.println(Customer.toString(customers));
        System.out.println("end");
    }

}

to get this running, make 2 classes, Main and Customer and copy paste the contents from both classes to the correct class; then run the Main class.

java.io.IOException: Broken pipe

You may have not set the output file.

How to decorate a class?

No one has explained that you can dynamically define classes. So you can have a decorator that defines (and returns) a subclass:

def addId(cls):

    class AddId(cls):

        def __init__(self, id, *args, **kargs):
            super(AddId, self).__init__(*args, **kargs)
            self.__id = id

        def getId(self):
            return self.__id

    return AddId

Which can be used in Python 2 (the comment from Blckknght which explains why you should continue to do this in 2.6+) like this:

class Foo:
    pass

FooId = addId(Foo)

And in Python 3 like this (but be careful to use super() in your classes):

@addId
class Foo:
    pass

So you can have your cake and eat it - inheritance and decorators!

Calling onclick on a radiobutton list using javascript

To trigger the onClick event on a radio-button invoke the click() method on the DOM element:

document.getElementById("radioButton").click()

using jquery:

$("#radioButton").click()

AngularJs:

angular.element('#radioButton').trigger('click')

Get user location by IP address

Return country

static public string GetCountry()
{
    return new WebClient().DownloadString("http://api.hostip.info/country.php");
}

Usage:

Console.WriteLine(GetCountry()); // will return short code for your country

Return info

static public string GetInfo()
{
    return new WebClient().DownloadString("http://api.hostip.info/get_json.php");
}

Usage:

Console.WriteLine(GetInfo()); 
// Example:
// {
//    "country_name":"COUNTRY NAME",
//    "country_code":"COUNTRY CODE",
//    "city":"City",
//    "ip":"XX.XXX.XX.XXX"
// }

VB.NET 'If' statement with 'Or' conditional has both sides evaluated?

It's your "fault" in that that's how Or is defined, so it's the behaviour you should expect:

In a Boolean comparison, the Or operator always evaluates both expressions, which could include making procedure calls. The OrElse Operator (Visual Basic) performs short-circuiting, which means that if expression1 is True, then expression2 is not evaluated.

But you don't have to endure it. You can use OrElse to get short-circuiting behaviour.

So you probably want:

If (example Is Nothing OrElse Not example.Item = compare.Item) Then
    'Proceed
End If

I can't say it reads terribly nicely, but it should work...

Implementing a simple file download servlet

Try with Resource

File file = new File("Foo.txt");
try (PrintStream ps = new PrintStream(file)) {
   ps.println("Bar");
}
response.setContentType("application/octet-stream");
response.setContentLength((int) file.length());
response.setHeader( "Content-Disposition",
         String.format("attachment; filename=\"%s\"", file.getName()));

OutputStream out = response.getOutputStream();
try (FileInputStream in = new FileInputStream(file)) {
    byte[] buffer = new byte[4096];
    int length;
    while ((length = in.read(buffer)) > 0) {
        out.write(buffer, 0, length);
    }
}
out.flush();

How to create a table from select query result in SQL Server 2008

Please try:

SELECT * INTO NewTable FROM OldTable

When do you use POST and when do you use GET?

There is nothing you can't do per-se. The point is that you're not supposed to modify the server state on an HTTP GET. HTTP proxies assume that since HTTP GET does not modify the state then whether a user invokes HTTP GET one time or 1000 times makes no difference. Using this information they assume it is safe to return a cached version of the first HTTP GET. If you break the HTTP specification you risk breaking HTTP client and proxies in the wild. Don't do it :)

How to make picturebox transparent?

Just use the Form Paint method and draw every Picturebox on it, it allows transparency :

    private void frmGame_Paint(object sender, PaintEventArgs e)
    {
        DoubleBuffered = true;
        for (int i = 0; i < Controls.Count; i++)
            if (Controls[i].GetType() == typeof(PictureBox))
            {
                var p = Controls[i] as PictureBox;
                p.Visible = false;
                e.Graphics.DrawImage(p.Image, p.Left, p.Top, p.Width, p.Height);
            }
    }

How do I make Git ignore file mode (chmod) changes?

If you want to set filemode to false in config files recursively (including submodules) : find -name config | xargs sed -i -e 's/filemode = true/filemode = false/'

How can I list ALL DNS records?

In the absence of the ability to do zone transfers, I wrote this small bash script, dg:

#!/bin/bash
COMMON_SUBDOMAINS=(www mail smtp pop imap blog en ftp ssh login)
if [[ "$2" == "x" ]]; then
    dig +nocmd "$1" +noall +answer "${3:-any}"
    wild_ips="$(dig +short "*.$1" "${3:-any}" | tr '\n' '|')"
    wild_ips="${wild_ips%|}"
    for sub in "${COMMON_SUBDOMAINS[@]}"; do
        dig +nocmd "$sub.$1" +noall +answer "${3:-any}"
    done | grep -vE "${wild_ips}"
    dig +nocmd "*.$1" +noall +answer "${3:-any}"
else
    dig +nocmd "$1" +noall +answer "${2:-any}"
fi

Now I use dg example.com to get a nice, clean list of DNS records, or dg example.com x to include a bunch of other popular subdomains.

grep -vE "${wild_ips}" filters out records that could be the result of a wildcard DNS entry such as * 10800 IN A 1.38.216.82. Otherwise, a wildcard entry would make it appear as if there were records for each $COMMON_SUBDOMAN.

Note: This relies on ANY queries, which are blocked by some DNS providers such as CloudFlare.

How To Set A JS object property name from a variable

With ECMAScript 6, you can use variable property names with the object literal syntax, like this:

var keyName = 'myKey';
var obj = {
              [keyName]: 1
          };
obj.myKey;//1

This syntax is available in the following newer browsers:

Edge 12+ (No IE support), FF34+, Chrome 44+, Opera 31+, Safari 7.1+

(https://kangax.github.io/compat-table/es6/)

You can add support to older browsers by using a transpiler such as babel. It is easy to transpile an entire project if you are using a module bundler such as rollup or webpack.

How do I use typedef and typedef enum in C?

typedef enum state {DEAD,ALIVE} State;
|     | |                     | |   |^ terminating semicolon, required! 
|     | |   type specifier    | |   |
|     | |                     | ^^^^^  declarator (simple name)
|     | |                     |    
|     | ^^^^^^^^^^^^^^^^^^^^^^^  
|     |
^^^^^^^-- storage class specifier (in this case typedef)

The typedef keyword is a pseudo-storage-class specifier. Syntactically, it is used in the same place where a storage class specifier like extern or static is used. It doesn't have anything to do with storage. It means that the declaration doesn't introduce the existence of named objects, but rather, it introduces names which are type aliases.

After the above declaration, the State identifier becomes an alias for the type enum state {DEAD,ALIVE}. The declaration also provides that type itself. However that isn't typedef doing it. Any declaration in which enum state {DEAD,ALIVE} appears as a type specifier introduces that type into the scope:

enum state {DEAD, ALIVE} stateVariable;

If enum state has previously been introduced the typedef has to be written like this:

typedef enum state State;

otherwise the enum is being redefined, which is an error.

Like other declarations (except function parameter declarations), the typedef declaration can have multiple declarators, separated by a comma. Moreover, they can be derived declarators, not only simple names:

typedef unsigned long ulong, *ulongptr;
|     | |           | |  1 | |   2   |
|     | |           | |    | ^^^^^^^^^--- "pointer to" declarator
|     | |           | ^^^^^^------------- simple declarator
|     | ^^^^^^^^^^^^^-------------------- specifier-qualifier list
^^^^^^^---------------------------------- storage class specifier

This typedef introduces two type names ulong and ulongptr, based on the unsigned long type given in the specifier-qualifier list. ulong is just a straight alias for that type. ulongptr is declared as a pointer to unsigned long, thanks to the * syntax, which in this role is a kind of type construction operator which deliberately mimics the unary * for pointer dereferencing used in expressions. In other words ulongptr is an alias for the "pointer to unsigned long" type.

Alias means that ulongptr is not a distinct type from unsigned long *. This is valid code, requiring no diagnostic:

unsigned long *p = 0;
ulongptr q = p;

The variables q and p have exactly the same type.

The aliasing of typedef isn't textual. For instance if user_id_t is a typedef name for the type int, we may not simply do this:

unsigned user_id_t uid;  // error! programmer hoped for "unsigned int uid". 

This is an invalid type specifier list, combining unsigned with a typedef name. The above can be done using the C preprocessor:

#define user_id_t int
unsigned user_id_t uid;

whereby user_id_t is macro-expanded to the token int prior to syntax analysis and translation. While this may seem like an advantage, it is a false one; avoid this in new programs.

Among the disadvantages that it doesn't work well for derived types:

 #define silly_macro int *

 silly_macro not, what, you, think;

This declaration doesn't declare what, you and think as being of type "pointer to int" because the macro-expansion is:

 int * not, what, you, think;

The type specifier is int, and the declarators are *not, what, you and think. So not has the expected pointer type, but the remaining identifiers do not.

And that's probably 99% of everything about typedef and type aliasing in C.

Detect current device with UI_USER_INTERFACE_IDIOM() in Swift

Swift 3.0:

let userInterface = UIDevice.current.userInterfaceIdiom

if(userInterface == .pad){
    //iPads
}else if(userInterface == .phone){
    //iPhone
}else if(userInterface == .carPlay){
    //CarPlay
}else if(userInterface == .tv){
    //AppleTV
}

How to forcefully set IE's Compatibility Mode off from the server-side?

I found problems with the two common ways of doing this:

  1. Doing this with custom headers (<customHeaders>) in web.config allows different deployments of the same application to have this set differently. I see this as one more thing that can go wrong, so I think it's better if the application specifies this in code. Also, IIS6 doesn't support this.

  2. Including an HTML <meta> tag in a Web Forms Master Page or MVC Layout Page seems better than the above. However, if some pages don't inherit from these then the tag needs to be duplicated, so there's a potential maintainability and reliability problem.

  3. Network traffic could be reduced by only sending the X-UA-Compatible header to Internet Explorer clients.

Well-Structured Applications

If your application is structured in a way that causes all pages to ultimately inherit from a single root page, include the <meta> tag as shown in the other answers.

Legacy Applications

Otherwise, I think the best way to do this is to automatically add the HTTP header to all HTML responses. One way to do this is using an IHttpModule:

public class IeCompatibilityModeDisabler : IHttpModule
{
    public void Init(HttpApplication context)
    {
        context.PreSendRequestHeaders += (sender, e) => DisableCompatibilityModeIfApplicable();
    }

    private void DisableCompatibilityModeIfApplicable()
    {
        if (IsIe && IsPage)
            DisableCompatibilityMode();
    }

    private void DisableCompatibilityMode()
    {
        var response = Context.Response;
        response.AddHeader("X-UA-Compatible", "IE=edge");
    }

    private bool IsIe { get { return Context.Request.Browser.IsBrowser("IE"); } }

    private bool IsPage { get { return Context.Handler is Page; } }

    private HttpContext Context { get { return HttpContext.Current; } }

    public void Dispose() { }
}

IE=edge indicates that IE should use its latest rendering engine (rather than compatibility mode) to render the page.

It seems that HTTP modules are often registered in the web.config file, but this brings us back to the first problem. However, you can register them programmatically in Global.asax like this:

public class Global : HttpApplication
{
    private static IeCompatibilityModeDisabler module;

    void Application_Start(object sender, EventArgs e)
    {
        module = new IeCompatibilityModeDisabler();
    }

    public override void Init()
    {
        base.Init();
        module.Init(this);
    }
}

Note that it is important that the module is static and not instantiated in Init so that there is only one instance per application. Of course, in a real-world application an IoC container should probably be managing this.

Advantages

  • Overcomes the problems outlined at the start of this answer.

Disadvantages

  • Website admins don't have control over the header value. This could be a problem if a new version of Internet Explorer comes out and adversely affects the rendering of the website. However, this could be overcome by having the module read the header value from the application's configuration file instead of using a hard-coded value.
  • This may require modification to work with ASP.NET MVC.
  • This doesn't work for static HTML pages.
  • The PreSendRequestHeaders event in the above code doesn't seem to fire in IIS6. I haven't figured out how to resolve this bug yet.

How to check if a string is a number?

#include <stdio.h>
#include <string.h>
char isNumber(char *text)
{
    int j;
    j = strlen(text);
    while(j--)
    {
        if(text[j] > 47 && text[j] < 58)
            continue;

        return 0;
    }
    return 1;
}
int main(){
    char tmp[16];
    scanf("%s", tmp);

    if(isNumber(tmp))
        return printf("is a number\n");

    return printf("is not a number\n");
}

You can also check its stringfied value, which could also work with non Ascii

char isNumber(char *text)
{
    int j;
    j = strlen(text);
    while(j--)
    {
        if(text[j] >= '0' && text[j] <= '9')
            continue;

        return 0;
    }
    return 1;
}

Ajax Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource

I had the same problem when I was working on asp.net Mvc webApi because cors was not enabled. I solved this by enabling cors inside register method of webApiconfig

First install cors from here then

   public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        var cors = new EnableCorsAttribute("*", "*", "*");
        config.EnableCors(cors);



        config.EnableCors();
        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }

How to fix "Only one expression can be specified in the select list when the subquery is not introduced with EXISTS" error?

Try this one -

"SELECT 
       ID, Salt, password, BannedEndDate
     , (
          SELECT COUNT(1)
          FROM dbo.LoginFails l
          WHERE l.UserName = u.UserName
               AND IP = '" + Request.ServerVariables["REMOTE_ADDR"] + "'
      ) AS cnt
FROM dbo.Users u
WHERE u.UserName = '" + LoginModel.Username + "'"

Core Data: Quickest way to delete all instances of an entity

    func deleteAll(entityName: String) {

    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
    let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
    deleteRequest.resultType = .resultTypeObjectIDs
    guard let context = self.container?.viewContext
        else { print("error in deleteAll")
            return }

    do {
        let result = try context.execute(deleteRequest) as? NSBatchDeleteResult
        let objectIDArray = result?.result as? [NSManagedObjectID]
        let changes: [AnyHashable : Any] = [NSDeletedObjectsKey : objectIDArray as Any]
        NSManagedObjectContext.mergeChanges(fromRemoteContextSave: changes, into: [context])
    } catch {
        print(error.localizedDescription)
    }
}

Function pointer to member function

int (*x)() is not a pointer to member function. A pointer to member function is written like this: int (A::*x)(void) = &A::f;.

Passing 'this' to an onclick event

Yeah first method will work on any element called from elsewhere since it will always take the target element irrespective of id.

check this fiddle

http://jsfiddle.net/8cvBM/

How to move an element down a litte bit in html

You can use vertical-align to move items vertically.

Example:

<div>This is an <span style="vertical-align: -20px;">example</span></div>

This will move the span containing the word 'example' downwards 20 pixels compared to the rest of the text.

The intended use for this property is to align elements of different height (e.g. images with different sizes) along a set line. vertical-align: top will for instance align all images on a line with the top of each image aligning with each other. vertical-align: middle will align all images so that the middle of the images align with each other, regardless of the height of each image.

You can see visual examples in this CodePen by Chris Coyier.

Hope that helps!

How do I add a library (android-support-v7-appcompat) in IntelliJ IDEA

As a Library Project

You should add the resources in a library project as per http://developer.android.com/tools/support-library/setup.html

Section > Adding libraries with resources

You then add the android-support-v7-appcompat library in your workspace and then add it as a reference to your app project.

Defining all the resources in your app project will also work (but there are a lot of definitions to add and you have missed some of them), and it is not the recommended approach.

Include php files when they are in different folders

None of the above answers fixed this issue for me. I did it as following (Laravel with Ubuntu server):

<?php
     $footerFile = '/var/www/website/main/resources/views/emails/elements/emailfooter.blade.php';
     include($footerFile);
?>

Convert DataTable to CSV stream

public void CreateCSVFile(DataTable dt, string strFilePath,string separator)
        {               
            #region Export Grid to CSV
            // Create the CSV file to which grid data will be exported.

            StreamWriter sw = new StreamWriter(strFilePath, false); 
            int iColCount = dt.Columns.Count;
            for (int i = 0; i < iColCount; i++)
            {    
                sw.Write(dt.Columns[i]);    
                if (i < iColCount - 1)
                {
                    sw.Write(separator);
                }  
            }    

            sw.Write(sw.NewLine);

            // Now write all the rows.
            foreach (DataRow dr in dt.Rows)
            {
                for (int i = 0; i < iColCount; i++)
                {
                    if (!Convert.IsDBNull(dr[i]))
                    {
                        sw.Write(dr[i].ToString());  
                    }

                    if (i < iColCount - 1)
                    {
                        sw.Write(separator);
                    }
                }
                sw.Write(sw.NewLine);
            }

            sw.Close();
            #endregion
        }

Error: org.testng.TestNGException: Cannot find class in classpath: EmpClass

In my case I imported maven project as Default existing project in eclipse.After that I imported as maven project.That worked for me.

Create an ISO date object in javascript

I solved this problem instantiating a new Date object in node.js:...

In Javascript, send the Date().toISOString() to nodejs:...

var start_date = new Date(2012, 01, 03, 8, 30);

$.ajax({
    type: 'POST',
    data: { start_date: start_date.toISOString() },
    url: '/queryScheduleCollection',
    dataType: 'JSON'
}).done(function( response ) { ... });

Then use the ISOString to create a new Date object in nodejs:..

exports.queryScheduleCollection = function(db){
    return function(req, res){

        var start_date = new Date(req.body.start_date);

        db.collection('schedule_collection').find(
            { start_date: { $gte: start_date } }
        ).toArray( function (err,d){
            ...
            res.json(d)
        })
    }
};

Note: I'm using Express and Mongoskin.

nodeJs callbacks simple example

we are creating a simple function as

callBackFunction (data, function ( err, response ){
     console.log(response)
}) 

// callbackfunction 
function callBackFuntion (data, callback){
    //write your logic and return your result as
callback("",result) //if not error
callback(error, "") //if error
}

remove url parameters with javascript or jquery

For example we have:

example.com/list/search?q=Somethink

And you need use variable url like this by window.location.href:

example.com/list/edit

From url:

example.com/list/search?q=Somethink
example.com/list/
var url = (window.location.href);
    url = url.split('/search')[0];
    url = (url + '/edit');

This is simple solution:-)

Determine if two rectangles overlap each other?

Here's how it's done in the Java API:

public boolean intersects(Rectangle r) {
    int tw = this.width;
    int th = this.height;
    int rw = r.width;
    int rh = r.height;
    if (rw <= 0 || rh <= 0 || tw <= 0 || th <= 0) {
        return false;
    }
    int tx = this.x;
    int ty = this.y;
    int rx = r.x;
    int ry = r.y;
    rw += rx;
    rh += ry;
    tw += tx;
    th += ty;
    //      overflow || intersect
    return ((rw < rx || rw > tx) &&
            (rh < ry || rh > ty) &&
            (tw < tx || tw > rx) &&
            (th < ty || th > ry));
}

add scroll bar to table body

If you don't want to wrap a table under any div:

table{
  table-layout: fixed;
}
tbody{
      display: block;
    overflow: auto;
}

How to change the Title of the window in Qt?

You can also modify the windowTitle attribute in Qt Designer.

How to delete Certain Characters in a excel 2010 cell

If [John Smith] is in cell A1, then use this formula to do what you want:

=SUBSTITUTE(SUBSTITUTE(A1, "[", ""), "]", "")

The inner SUBSTITUTE replaces all instances of "[" with "" and returns a new string, then the other SUBSTITUTE replaces all instances of "]" with "" and returns the final result.

What is initial scale, user-scalable, minimum-scale, maximum-scale attribute in meta tag?

They are viewport meta tags, and is most applicable on mobile browsers.

width=device-width

This means, we are telling to the browser “my website adapts to your device width”.

initial-scale

This defines the scale of the website, This parameter sets the initial zoom level, which means 1 CSS pixel is equal to 1 viewport pixel. This parameter help when you're changing orientation, or preventing default zooming. Without this parameter, responsive site won't work.

maximum-scale

Maximum-scale defines the maximum zoom. When you access the website, top priority is maximum-scale=1, and it won’t allow the user to zoom.

minimum-scale

Minimum-scale defines the minimum zoom. This works the same as above, but it defines the minimum scale. This is useful, when maximum-scale is large, and you want to set minimum-scale.

user-scalable

User-scalable assigned to 1.0 means the website is allowing the user to zoom in or zoom out.

But if you assign it to user-scalable=no, it means the website is not allowing the user to zoom in or zoom out.

Position absolute and overflow hidden

What about position: relative for the outer div? In the example that hides the inner one. It also won't move it in its layout since you don't specify a top or left.

Meaning of "referencing" and "dereferencing" in C

find the below explanation:

int main()
{
    int a = 10;// say address of 'a' is 2000;
    int *p = &a; //it means 'p' is pointing[referencing] to 'a'. i.e p->2000
    int c = *p; //*p means dereferncing. it will give the content of the address pointed by 'p'. in this case 'p' is pointing to 2000[address of 'a' variable], content of 2000 is 10. so *p will give 10. 
}

conclusion :

  1. & [address operator] is used for referencing.
  2. * [star operator] is used for de-referencing .

In Python, how do I split a string and keep the separators?

>>> re.split('(\W)', 'foo/bar spam\neggs')
['foo', '/', 'bar', ' ', 'spam', '\n', 'eggs']

Omitting one Setter/Getter in Lombok

You can pass an access level to the @Getter and @Setter annotations. This is useful to make getters or setters protected or private. It can also be used to override the default.

With @Data, you have public access to the accessors by default. You can now use the special access level NONE to completely omit the accessor, like this:

@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private int mySecret;

Can we add div inside table above every <tr>?

You can not use tag to make group of more than one tag. If you want to make group of tag for any purpose like in ajax to change particular group or in CSS to change style of particular tag etc. then use

Ex.

<table>
  <tbody id="foods">
    <tr>
      <td>Group 1</td>
    </tr>
    <tr>
      <td>Group 1</td>
    </tr>
  </tbody>

  <tbody id="drinks">
    <tr>
      <td>Group 2</td>
    </tr>
    <tr>
      <td>Group 2</td>
    </tr>
  </tbody>
</table>

Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource

If you are using NodeJs for your server side, just add these to your route and you will be Ok

     res.header("Access-Control-Allow-Origin", "*");
     res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");

Your route will then look somehow like this

    router.post('/odin', function(req, res, next) {
      res.header("Access-Control-Allow-Origin", "*");
      res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");


    return res.json({Name: req.body.name, Phone: req.body.phone});
});

Client side for Ajax call

 var sendingData = {
   name: "Odinfono Emmanuel",
   phone: "1234567890"
}

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

    $.ajax({
        url: 'http://127.0.0.1:3000/odin',            
        method: 'POST',
        type: 'json',
        data: sendingData,
        success: function (response) {
            console.log(response);
        },
        error: function (error) {
            console.log(error);
        }
        });
    });
</script>

You should have something like this in your browser console as response

{ name: "Odinfono Emmanuel", phone: "1234567890"}

Enjoy coding....

Vertical divider CSS

<div class="headerdivider"></div>

and

.headerdivider {
    border-left: 1px solid #38546d;
    background: #16222c;
    width: 1px;
    height: 80px;
    position: absolute;
    right: 250px;
    top: 10px;
}

How to use absolute path in twig functions

I've used the following advice from the docs https://symfony.com/doc/current/console/request_context.html to get absolute urls in emails:

# config/services.yaml
parameters:
    router.request_context.host: 'example.org'
    router.request_context.scheme: 'https'

How to create a unique index on a NULL column?

It is possible to use filter predicates to specify which rows to include in the index.

From the documentation:

WHERE <filter_predicate> Creates a filtered index by specifying which rows to include in the index. The filtered index must be a nonclustered index on a table. Creates filtered statistics for the data rows in the filtered index.

Example:

CREATE TABLE Table1 (
  NullableCol int NULL
)

CREATE UNIQUE INDEX IX_Table1 ON Table1 (NullableCol) WHERE NullableCol IS NOT NULL;

How to make a dropdown readonly using jquery?

Easiest option for me was to make select as readonly and add:

onmousedown="return false" onkeydown="return false"

You don't need to write any extra logic. No hidden inputs or disabled and then re-enabled on form submit.

Extracting Ajax return data in jQuery

I have noticed that your success function has the parameter "html", and you are trying to add "data" to your elements html()... Change it so these both match:

$.ajax({
    type:"POST",
    url: "ajax.php",
    data:"id="+id ,
    success: function(data){
        $("#response").html(data);
    }
});

Cannot find vcvarsall.bat when running a Python script

THIS IS AN UP TO DATE ANSWER FOR WINDOWS USERS - VERY SIMPLE SOLUTION.

As pointed out by other, the problem is that python/cython etc. tries to find the same compiler they were built from, but this compiler does not exist on the computer. Most of the time, this compiler is a version of visual studio (2008, 2010 or 2013), but either such a compiler is not installed, or a newer version is installed and the system prevents from installing an older one. So, the solution is simple:

1) look at C:\Program Files (x86) and see if there is an installed version of Microsoft visual studio, and if it is newer than the version from which Python has been built. If not, install(/update to) the version from which Python has been built (see previous answers), or even a newest version and follow the next step.

2)If a newest version of Microsoft visual studio is already installed, we have to make Python/cython etc. believe that it is the version from which it has been built. And this is very simple: go to the the system environment variables and create the following variables, if they do not exist:

VS100COMNTOOLS

VS110COMNTOOLS

VS120COMNTOOLS

VS140COMNTOOLS

And set the field of these variables to

"C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\Tools" (if visual studio 2008 is installed), or "C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\Tools" (if visual studio 2010 is installed) or "C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Tools" (if visual studio 2013 is installed) or "C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\Tools" (if visual studio 2015 is installed).

This solution works for 32 bit versions of python. It may also work for 64 bit version but I've not tested; most probably, for 64 bit versions, the following additional steps must be performed:

3)add the path "C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC" to the %PATH% environment variable (change the number of the version of visual studio according to you version).

4) from the command line, run "vcvarsall.bat x86_amd64"

That's all.

What's the difference between "Write-Host", "Write-Output", or "[console]::WriteLine"?

Regarding [Console]::WriteLine() - you should use it if you are going to use pipelines in CMD (not in powershell). Say you want your ps1 to stream a lot of data to stdout, and some other utility to consume/transform it. If you use Write-Host in the script it will be much slower.

Git diff between current branch and master but not including unmerged master commits

According to Documentation

git diff Shows changes between the working tree and the index or a tree, changes between the index and a tree, changes between two trees, changes resulting from a merge, changes between two blob objects, or changes between two files on disk.

In git diff - There's a significant difference between two dots .. and 3 dots ... in the way we compare branches or pull requests in our repository. I'll give you an easy example which demonstrates it easily.

Example: Let's assume we're checking out new branch from master and pushing some code in.

  G---H---I feature (Branch)
 /
A---B---C---D master (Branch)
  • Two dots - If we want to show the diffs between all changes happened in the current time on both sides, We would use the git diff origin/master..feature or just git diff origin/master
    ,output: ( H, I against A, B, C, D )

  • Three dots - If we want to show the diffs between the last common ancestor (A), aka the check point we started our new branch ,we use git diff origin/master...feature,output: (H, I against A ).

  • I'd rather use the 3 dots in most circumstances.

Alternative to google finance api

I followed the top answer and started looking at yahoo finance. Their API can be accessed a number of different ways, but I found a nice reference for getting stock info as a CSV here: http://www.jarloo.com/

Using that I wrote this script. I'm not really a ruby guy but this might help you hack something together. I haven't come up with variable names for all the fields yahoo offers yet, so you can fill those in if you need them.

Here's the usage

TICKERS_SP500 = "GICS,CIK,MMM,ABT,ABBV,ACN,ACE,ACT,ADBE,ADT,AES,AET,AFL,AMG,A,GAS,APD,ARG,AKAM,AA,ALXN,ATI,ALLE,ADS,ALL,ALTR,MO,AMZN,AEE,AAL,AEP,AXP,AIG,AMT,AMP,ABC,AME,AMGN,APH,APC,ADI,AON,APA,AIV,AAPL,AMAT,ADM,AIZ,T,ADSK,ADP,AN,AZO,AVGO,AVB,AVY,BHI,BLL,BAC,BK,BCR,BAX,BBT,BDX,BBBY,BBY,BIIB,BLK,HRB,BA,BWA,BXP,BSX,BMY,BRCM,BFB,CHRW,CA,CVC,COG,CAM,CPB,COF,CAH,HSIC,KMX,CCL,CAT,CBG,CBS,CELG,CNP,CTL,CERN,CF,SCHW,CHK,CVX,CMG,CB,CI,XEC,CINF,CTAS,CSCO,C,CTXS,CLX,CME,CMS,COH,KO,CCE,CTSH,CL,CMA,CSC,CAG,COP,CNX,ED,STZ,GLW,COST,CCI,CSX,CMI,CVS,DHI,DHR,DRI,DVA,DE,DLPH,DAL,XRAY,DVN,DO,DTV,DFS,DG,DLTR,D,DOV,DOW,DPS,DTE,DD,DUK,DNB,ETFC,EMN,ETN,EBAY,ECL,EIX,EW,EA,EMC,EMR,ENDP,ESV,ETR,EOG,EQT,EFX,EQIX,EQR,ESS,EL,ES,EXC,EXPE,EXPD,ESRX,XOM,FFIV,FB,FDO,FAST,FDX,FIS,FITB,FSLR,FE,FISV,FLIR,FLS,FLR,FMC,FTI,F,FOSL,BEN,FCX,FTR,GME,GCI,GPS,GRMN,GD,GE,GGP,GIS,GM,GPC,GNW,GILD,GS,GT,GOOG,GWW,HAL,HBI,HOG,HAR,HRS,HIG,HAS,HCA,HCP,HCN,HP,HES,HPQ,HD,HON,HRL,HSP,HST,HCBK,HUM,HBAN,ITW,IR,TEG,INTC,ICE,IBM,IP,IPG,IFF,INTU,ISRG,IVZ,IRM,JEC,JNJ,JCI,JOY,JPM,JNPR,KSU,K,KEY,GMCR,KMB,KIM,KMI,KLAC,KSS,KRFT,KR,LB,LLL,LH,LRCX,LM,LEG,LEN,LVLT,LUK,LLY,LNC,LLTC,LMT,L,LO,LOW,LYB,MTB,MAC,M,MNK,MRO,MPC,MAR,MMC,MLM,MAS,MA,MAT,MKC,MCD,MHFI,MCK,MJN,MWV,MDT,MRK,MET,KORS,MCHP,MU,MSFT,MHK,TAP,MDLZ,MON,MNST,MCO,MS,MOS,MSI,MUR,MYL,NDAQ,NOV,NAVI,NTAP,NFLX,NWL,NFX,NEM,NWSA,NEE,NLSN,NKE,NI,NE,NBL,JWN,NSC,NTRS,NOC,NRG,NUE,NVDA,ORLY,OXY,OMC,OKE,ORCL,OI,PCAR,PLL,PH,PDCO,PAYX,PNR,PBCT,POM,PEP,PKI,PRGO,PFE,PCG,PM,PSX,PNW,PXD,PBI,PCL,PNC,RL,PPG,PPL,PX,PCP,PCLN,PFG,PG,PGR,PLD,PRU,PEG,PSA,PHM,PVH,QEP,PWR,QCOM,DGX,RRC,RTN,RHT,REGN,RF,RSG,RAI,RHI,ROK,COL,ROP,ROST,RCL,R,CRM,SNDK,SCG,SLB,SNI,STX,SEE,SRE,SHW,SIAL,SPG,SWKS,SLG,SJM,SNA,SO,LUV,SWN,SE,STJ,SWK,SPLS,SBUX,HOT,STT,SRCL,SYK,STI,SYMC,SYY,TROW,TGT,TEL,TE,THC,TDC,TSO,TXN,TXT,HSY,TRV,TMO,TIF,TWX,TWC,TJX,TMK,TSS,TSCO,RIG,TRIP,FOXA,TSN,TYC,USB,UA,UNP,UNH,UPS,URI,UTX,UHS,UNM,URBN,VFC,VLO,VAR,VTR,VRSN,VZ,VRTX,VIAB,V,VNO,VMC,WMT,WBA,DIS,WM,WAT,ANTM,WFC,WDC,WU,WY,WHR,WFM,WMB,WIN,WEC,WYN,WYNN,XEL,XRX,XLNX,XL,XYL,YHOO,YUM,ZMH,ZION,ZTS,SAIC,AP"

AllData = loadStockInfo(TICKERS_SP500, allParameters())

SpecificData = loadStockInfo("GOOG,CIK", "ask,dps")

loadStockInfo returns a hash, such that SpecificData["GOOG"]["name"] is "Google Inc."

Finally, the actual code to run that...

require 'net/http'

# Jack Franzen & Garin Bedian
# Based on http://www.jarloo.com/yahoo_finance/

$parametersData = Hash[[

    ["symbol", ["s", "Symbol"]],
    ["ask", ["a", "Ask"]],
    ["divYield", ["y", "Dividend Yield"]],
    ["bid", ["b", "Bid"]],
    ["dps", ["d", "Dividend per Share"]],
    #["noname", ["b2", "Ask (Realtime)"]],
    #["noname", ["r1", "Dividend Pay Date"]],
    #["noname", ["b3", "Bid (Realtime)"]],
    #["noname", ["q", "Ex-Dividend Date"]],
    #["noname", ["p", "Previous Close"]],
    #["noname", ["o", "Open"]],
    #["noname", ["c1", "Change"]],
    #["noname", ["d1", "Last Trade Date"]],
    #["noname", ["c", "Change &amp; Percent Change"]],
    #["noname", ["d2", "Trade Date"]],
    #["noname", ["c6", "Change (Realtime)"]],
    #["noname", ["t1", "Last Trade Time"]],
    #["noname", ["k2", "Change Percent (Realtime)"]],
    #["noname", ["p2", "Change in Percent"]],
    #["noname", ["c8", "After Hours Change (Realtime)"]],
    #["noname", ["m5", "Change From 200 Day Moving Average"]],
    #["noname", ["c3", "Commission"]],
    #["noname", ["m6", "Percent Change From 200 Day Moving Average"]],
    #["noname", ["g", "Day’s Low"]],
    #["noname", ["m7", "Change From 50 Day Moving Average"]],
    #["noname", ["h", "Day’s High"]],
    #["noname", ["m8", "Percent Change From 50 Day Moving Average"]],
    #["noname", ["k1", "Last Trade (Realtime) With Time"]],
    #["noname", ["m3", "50 Day Moving Average"]],
    #["noname", ["l", "Last Trade (With Time)"]],
    #["noname", ["m4", "200 Day Moving Average"]],
    #["noname", ["l1", "Last Trade (Price Only)"]],
    #["noname", ["t8", "1 yr Target Price"]],
    #["noname", ["w1", "Day’s Value Change"]],
    #["noname", ["g1", "Holdings Gain Percent"]],
    #["noname", ["w4", "Day’s Value Change (Realtime)"]],
    #["noname", ["g3", "Annualized Gain"]],
    #["noname", ["p1", "Price Paid"]],
    #["noname", ["g4", "Holdings Gain"]],
    #["noname", ["m", "Day’s Range"]],
    #["noname", ["g5", "Holdings Gain Percent (Realtime)"]],
    #["noname", ["m2", "Day’s Range (Realtime)"]],
    #["noname", ["g6", "Holdings Gain (Realtime)"]],
    #["noname", ["k", "52 Week High"]],
    #["noname", ["v", "More Info"]],
    #["noname", ["j", "52 week Low"]],
    #["noname", ["j1", "Market Capitalization"]],
    #["noname", ["j5", "Change From 52 Week Low"]],
    #["noname", ["j3", "Market Cap (Realtime)"]],
    #["noname", ["k4", "Change From 52 week High"]],
    #["noname", ["f6", "Float Shares"]],
    #["noname", ["j6", "Percent Change From 52 week Low"]],
    ["name", ["n", "Company Name"]],
    #["noname", ["k5", "Percent Change From 52 week High"]],
    #["noname", ["n4", "Notes"]],
    #["noname", ["w", "52 week Range"]],
    #["noname", ["s1", "Shares Owned"]],
    #["noname", ["x", "Stock Exchange"]],
    #["noname", ["j2", "Shares Outstanding"]],
    #["noname", ["v", "Volume"]],
    #["noname", ["a5", "Ask Size"]],
    #["noname", ["b6", "Bid Size"]],
    #["noname", ["k3", "Last Trade Size"]],
    #["noname", ["t7", "Ticker Trend"]],
    #["noname", ["a2", "Average Daily Volume"]],
    #["noname", ["t6", "Trade Links"]],
    #["noname", ["i5", "Order Book (Realtime)"]],
    #["noname", ["l2", "High Limit"]],
    #["noname", ["e", "Earnings per Share"]],
    #["noname", ["l3", "Low Limit"]],
    #["noname", ["e7", "EPS Estimate Current Year"]],
    #["noname", ["v1", "Holdings Value"]],
    #["noname", ["e8", "EPS Estimate Next Year"]],
    #["noname", ["v7", "Holdings Value (Realtime)"]],
    #["noname", ["e9", "EPS Estimate Next Quarter"]],
    #["noname", ["s6", "evenue"]],
    #["noname", ["b4", "Book Value"]],
    #["noname", ["j4", "EBITDA"]],
    #["noname", ["p5", "Price / Sales"]],
    #["noname", ["p6", "Price / Book"]],
    #["noname", ["r", "P/E Ratio"]],
    #["noname", ["r2", "P/E Ratio (Realtime)"]],
    #["noname", ["r5", "PEG Ratio"]],
    #["noname", ["r6", "Price / EPS Estimate Current Year"]],
    #["noname", ["r7", "Price / EPS Estimate Next Year"]],
    #["noname", ["s7", "Short Ratio"]

]]

def replaceCommas(data)
    s = ""
    inQuote = false
    data.split("").each do |a|
        if a=='"'
            inQuote = !inQuote
            s += '"'
        elsif !inQuote && a == ","
            s += "#"
        else
            s += a
        end
    end
    return s
end

def allParameters()
    s = ""
    $parametersData.keys.each do |i|
        s  = s + i + ","
    end
    return s
end

def prepareParameters(parametersText)
    pt = parametersText.split(",")
    if !pt.include? 'symbol'; pt.push("symbol"); end;
    if !pt.include? 'name'; pt.push("name"); end;
    p = []
    pt.each do |i|
        p.push([i, $parametersData[i][0]])
    end
    return p
end

def prepareURL(tickers, parameters)
    urlParameters = ""
    parameters.each do |i|
        urlParameters += i[1]
    end
    s = "http://download.finance.yahoo.com/d/quotes.csv?"
    s = s + "s=" + tickers + "&"
    s = s + "f=" + urlParameters
    return URI(s)
end

def loadStockInfo(tickers, parametersRaw)
    parameters = prepareParameters(parametersRaw)
    url = prepareURL(tickers, parameters)
    data = Net::HTTP.get(url)
    data = replaceCommas(data)
    h = CSVtoObject(data, parameters)
    logStockObjects(h, true)
end

#parse csv
def printCodes(substring, length)

    a = data.index(substring)
    b = data.byteslice(a, 10)
    puts "printing codes of string: "
    puts b
    puts b.split('').map(&:ord).to_s
end

def CSVtoObject(data, parameters)
    rawData = []
    lineBreaks = data.split(10.chr)
    lineBreaks.each_index do |i|
        rawData.push(lineBreaks[i].split("#"))
    end

    #puts "Found " + rawData.length.to_s + " Stocks"
    #puts "   w/ " + rawData[0].length.to_s + " Fields"

    h = Hash.new("MainHash")
    rawData.each_index do |i|
        o = Hash.new("StockObject"+i.to_s)
        #puts "parsing object" + rawData[i][0]
        rawData[i].each_index do |n|
            #puts "parsing parameter" + n.to_s + " " +parameters[n][0]
            o[ parameters[n][0] ] = rawData[i][n].gsub!(/^\"|\"?$/, '')
        end
        h[o["symbol"]] = o;
    end
    return h
end

def logStockObjects(h, concise)
    h.keys.each do |i|
        if concise
            puts "(" + h[i]["symbol"] + ")\t\t" + h[i]["name"]
        else
            puts ""
            puts h[i]["name"]
            h[i].keys.each do |p|
                puts "    " + $parametersData[p][1] + " : " + h[i][p].to_s
            end
        end
    end
end

How to show code but hide output in RMarkdown?

For completely silencing the output, here what works for me

```{r error=FALSE, warning=FALSE, message=FALSE}
invisible({capture.output({


# Your code here
2 * 2
# etc etc


})})
```

The 5 measures used above are

  1. error = FALSE
  2. warning = FALSE
  3. message = FALSE
  4. invisible()
  5. capture.output()

An Iframe I need to refresh every 30 seconds (but not the whole page)

add "id='myiframe'" to the iframe, then use this script :

<script>

function f1()
{
 var x=document.getElementById("myiframe");
   x.src=x.src+Math.floor(random()%100000);
}

setInterval(f1,30*1000);

</script>

Squaring all elements in a list

One more map solution:

def square(a):
    return map(pow, a, [2]*len(a))

Which maven dependencies to include for spring 3.0?

Use a BOM to solve version issues.

you may find that a third-party library, or another Spring project, pulls in a transitive dependency to an older release. If you forget to explicitly declare a direct dependency yourself, all sorts of unexpected issues can arise.

To overcome such problems Maven supports the concept of a "bill of materials" (BOM) dependency.

https://docs.spring.io/spring/docs/4.3.18.RELEASE/spring-framework-reference/html/overview.html#overview-maven-bom

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-framework-bom</artifactId>
  <version>3.2.12.RELEASE</version>
  <type>pom</type>
</dependency>

C# Wait until condition is true

You can use an async result and a delegate for this. If you read up on the documentation it should make it pretty clear what to do. I can write up some sample code if you like and attach it to this answer.

Action isExcelInteractive = IsExcelInteractive;

private async void btnOk_Click(object sender, EventArgs e)
{
    IAsyncResult result = isExcelInteractive.BeginInvoke(ItIsDone, null);
    result.AsyncWaitHandle.WaitOne();
    Console.WriteLine("YAY");
} 

static void IsExcelInteractive(){
   while (something_is_false) // do your check here
   {
       if(something_is_true)
          return true;
   }
   Thread.Sleep(1);
}

void ItIsDone(IAsyncResult result)
{
   this.isExcelInteractive.EndInvoke(result);
}

Apologies if this code isn't 100% complete, I don't have Visual Studio on this computer, but hopefully it gets you where you need to get to.

Why does pycharm propose to change method to static

Agreed with @jolvi, @ArundasR, and others, the warning happens on a member function that doesn't use self.

If you're sure PyCharm is wrong, that the function should not be a @staticmethod, and if you value zero warnings, you can make this one go away two different ways:

Workaround #1

def bar(self):
    self.is_not_used()
    doing_something_without_self()

def is_not_used(self):
    pass

Workaround #2 [Thanks @DavidPärsson]

# noinspection PyMethodMayBeStatic
def bar(self):
    doing_something_without_self()

The application I had for this (the reason I could not use @staticmethod) was in making a table of handler functions for responding to a protocol subtype field. All handlers had to be the same form of course (static or nonstatic). But some didn't happen to do anything with the instance. If I made those static I'd get "TypeError: 'staticmethod' object is not callable".

In support of the OP's consternation, suggesting you add staticmethod whenever you can, goes against the principle that it's easier to make code less restrictive later, than to make it more -- making a method static makes it less restrictive now, in that you can call class.f() instead of instance.f().

Guesses as to why this warning exists:

  • It advertises staticmethod. It makes developers aware of something they may well have intended.
  • As @JohnWorrall's points out, it gets your attention when self was inadvertently left out of the function.
  • It's a cue to rethink the object model; maybe the function does not belong in this class at all.

Ternary operation in CoffeeScript

Since everything is an expression, and thus results in a value, you can just use if/else.

a = if true then 5 else 10
a = if false then 5 else 10

You can see more about expression examples here.

How do I get the domain originating the request in express.js?

Recently faced a problem with fetching 'Origin' request header, then I found this question. But pretty confused with the results, req.get('host') is deprecated, that's why giving Undefined. Use,

    req.header('Origin');
    req.header('Host');
    // this method can be used to access other request headers like, 'Referer', 'User-Agent' etc.

Could not load file or assembly 'Microsoft.ReportViewer.WebForms'

I had this error when going from version 10.0.0.0, i.e. "Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />

to version 11.0.0.0, i.e.

"Microsoft.ReportViewer.WebForms, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"

It took a while until I understood that not only the version was changed but also the public token key, as you can see above.

WCF gives an unsecured or incorrectly secured fault error

In my case I was using certificates for authentication with certificateValidationMode set to "PeerTrust" and I had forgotten to install the client certificate in windows store (LocalMachine\TrustedPeople) to make it accepted by the server.

MsgBox "" vs MsgBox() in VBScript

To my knowledge these are the rules for calling subroutines and functions in VBScript:

  • When calling a subroutine or a function where you discard the return value don't use parenthesis
  • When calling a function where you assign or use the return value enclose the arguments in parenthesis
  • When calling a subroutine using the Call keyword enclose the arguments in parenthesis

Since you probably wont be using the Call keyword you only need to learn the rule that if you call a function and want to assign or use the return value you need to enclose the arguments in parenthesis. Otherwise, don't use parenthesis.

Here are some examples:

  • WScript.Echo 1, "two", 3.3 - calling a subroutine

  • WScript.Echo(1, "two", 3.3) - syntax error

  • Call WScript.Echo(1, "two", 3.3) - keyword Call requires parenthesis

  • MsgBox "Error" - calling a function "like" a subroutine

  • result = MsgBox("Continue?", 4) - calling a function where the return value is used

  • WScript.Echo (1 + 2)*3, ("two"), (((3.3))) - calling a subroutine where the arguments are computed by expressions involving parenthesis (note that if you surround a variable by parenthesis in an argument list it changes the behavior from call by reference to call by value)

  • WScript.Echo(1) - apparently this is a subroutine call using parenthesis but in reality the argument is simply the expression (1) and that is what tends to confuse people that are used to other programming languages where you have to specify parenthesis when calling subroutines

  • I'm not sure how to interpret your example, Randomize(). Randomize is a subroutine that accepts a single optional argument but even if the subroutine didn't have any arguments it is acceptable to call it with an empty pair of parenthesis. It seems that the VBScript parser has a special rule for an empty argument list. However, my advice is to avoid this special construct and simply call any subroutine without using parenthesis.

I'm quite sure that these syntactic rules applies across different versions of operating systems.

Adding timestamp to a filename with mv in BASH

First, thanks for the answers above! They lead to my solution.

I added this alias to my .bashrc file:

alias now='date +%Y-%m-%d-%H.%M.%S'

Now when I want to put a time stamp on a file such as a build log I can do this:

mvn clean install | tee build-$(now).log

and I get a file name like:

build-2021-02-04-03.12.12.log

Angular 2 two way binding using ngModel is not working

instead of ng-model you can use this code:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `<input #box (keyup)="0">
    <p>{{box.value}}</p>`,
})
export class AppComponent  {}

inside your app.component.ts

jQuery Ajax File Upload

Use FormData. It works really well :-) ...

var jform = new FormData();
jform.append('user',$('#user').val());
jform.append('image',$('#image').get(0).files[0]); // Here's the important bit

$.ajax({
    url: '/your-form-processing-page-url-here',
    type: 'POST',
    data: jform,
    dataType: 'json',
    mimeType: 'multipart/form-data', // this too
    contentType: false,
    cache: false,
    processData: false,
    success: function(data, status, jqXHR){
        alert('Hooray! All is well.');
        console.log(data);
        console.log(status);
        console.log(jqXHR);

    },
    error: function(jqXHR,status,error){
        // Hopefully we should never reach here
        console.log(jqXHR);
        console.log(status);
        console.log(error);
    }
});

How to get height of <div> in px dimension

Use height():

var result = $("#myDiv").height();
alert(result);

This will give you the unit-less computed height in pixels. "px" will be stripped from the result. I.e. if the height is 400px, the result will be 400, but the result will be in pixels.

If you want to do it without jQuery, you can use plain JavaScript:

var result = document.getElementById("myDiv").offsetHeight;

How to Display blob (.pdf) in an AngularJS app

I use AngularJS v1.3.4

HTML:

<button ng-click="downloadPdf()" class="btn btn-primary">download PDF</button>

JS controller:

'use strict';
angular.module('xxxxxxxxApp')
    .controller('xxxxController', function ($scope, xxxxServicePDF) {
        $scope.downloadPdf = function () {
            var fileName = "test.pdf";
            var a = document.createElement("a");
            document.body.appendChild(a);
            a.style = "display: none";
            xxxxServicePDF.downloadPdf().then(function (result) {
                var file = new Blob([result.data], {type: 'application/pdf'});
                var fileURL = window.URL.createObjectURL(file);
                a.href = fileURL;
                a.download = fileName;
                a.click();
            });
        };
});

JS services:

angular.module('xxxxxxxxApp')
    .factory('xxxxServicePDF', function ($http) {
        return {
            downloadPdf: function () {
            return $http.get('api/downloadPDF', { responseType: 'arraybuffer' }).then(function (response) {
                return response;
            });
        }
    };
});

Java REST Web Services - Spring MVC:

@RequestMapping(value = "/downloadPDF", method = RequestMethod.GET, produces = "application/pdf")
    public ResponseEntity<byte[]> getPDF() {
        FileInputStream fileStream;
        try {
            fileStream = new FileInputStream(new File("C:\\xxxxx\\xxxxxx\\test.pdf"));
            byte[] contents = IOUtils.toByteArray(fileStream);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.parseMediaType("application/pdf"));
            String filename = "test.pdf";
            headers.setContentDispositionFormData(filename, filename);
            ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(contents, headers, HttpStatus.OK);
            return response;
        } catch (FileNotFoundException e) {
           System.err.println(e);
        } catch (IOException e) {
            System.err.println(e);
        }
        return null;
    }

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

you can bind to multiple events by separating them with a space:

$(":input").on("keyup change", function(e) {
    // do stuff!
})

docs here.

hope that helps. cheers!

How to center horizontally div inside parent div

<div id='parent' style='width: 100%;text-align:center;'>
 <div id='child' style='width:50px; height:100px;margin:0px auto;'>Text</div>
</div>

Why does this CSS margin-top style not work?

try this:

#outer {
    width:500px; 
    height:200px; 
    background:#FFCCCC;
    margin:50px auto 0 auto;
    display:table;
}
#inner {
    background:#FFCC33;
    margin:50px 50px 50px 50px;
    padding:10px;
    display:block;
}?

http://jsfiddle.net/7AXTf/

Good luck

How can I debug my JavaScript code?

I found the new version of Internet Explorer 8 (press F12) is very good to debug JavaScript code.

Of course, Firebug is good if you use Firefox.

Failed to open/create the internal network Vagrant on Windows10

After a Windows 10 update my VirtualBox Host-Only Ethernet Adapter was actually gone from the OS' network adapters (view these under Control Panel -> Network and Sharing Center -> Change adapter settings). Had to reinstall VirtualBox to bring that back to the OS.

Then in the newer version of VirtualBox, the host-only adapters are under Global Tools (top right) -> Host Network Manager. Make sure the DHCP Server is enabled for the adapter.

Example config: enter image description here

Deny access to one specific folder in .htaccess

You can create a .htaccess file for the folder, wich should have denied access with

Deny from  all

or you can redirect to a custom 404 page

Redirect /includes/ 404.html

Compute a confidence interval from sample data

import numpy as np
import scipy.stats


def mean_confidence_interval(data, confidence=0.95):
    a = 1.0 * np.array(data)
    n = len(a)
    m, se = np.mean(a), scipy.stats.sem(a)
    h = se * scipy.stats.t.ppf((1 + confidence) / 2., n-1)
    return m, m-h, m+h

you can calculate like this way.

How to implement the factory method pattern in C++ correctly

Have you thought about not using a factory at all, and instead making nice use of the type system? I can think of two different approaches which do this sort of thing:

Option 1:

struct linear {
    linear(float x, float y) : x_(x), y_(y){}
    float x_;
    float y_;
};

struct polar {
    polar(float angle, float magnitude) : angle_(angle),  magnitude_(magnitude) {}
    float angle_;
    float magnitude_;
};


struct Vec2 {
    explicit Vec2(const linear &l) { /* ... */ }
    explicit Vec2(const polar &p) { /* ... */ }
};

Which lets you write things like:

Vec2 v(linear(1.0, 2.0));

Option 2:

you can use "tags" like the STL does with iterators and such. For example:

struct linear_coord_tag linear_coord {}; // declare type and a global
struct polar_coord_tag polar_coord {};

struct Vec2 {
    Vec2(float x, float y, const linear_coord_tag &) { /* ... */ }
    Vec2(float angle, float magnitude, const polar_coord_tag &) { /* ... */ }
};

This second approach lets you write code which looks like this:

Vec2 v(1.0, 2.0, linear_coord);

which is also nice and expressive while allowing you to have unique prototypes for each constructor.

ORA-00979 not a group by expression

Same error also come when UPPER or LOWER keyword not used in both place in select expression and group by expression .

Wrong :-

select a , count(*) from my_table group by UPPER(a) .

Right :-

select UPPER(a) , count(*) from my_table group by UPPER(a) .

Can Mysql Split a column?

Use

substring_index(`column`,',',1) ==> first value
substring_index(substring_index(`column`,',',-2),',',1)=> second value
substring_index(substring_index(`column`,',',-1),',',1)=> third value

in your where clause.

SELECT * FROM `table`
WHERE 
substring_index(`column`,',',1)<0 
AND
substring_index(`column`,',',1)>5

How to update a record using sequelize for node?

If Model.update statement does not work for you, you can try like this:

try{ 
    await sequelize.query('update posts set param=:param where conditionparam=:conditionparam', {replacements: {param: 'parameter', conditionparam:'condition'}, type: QueryTypes.UPDATE})
}
catch(err){
    console.log(err)
}

Clearing my form inputs after submission

Just include this line at the end of function and the Problem is solved easily!

document.getElementById("btnsubmit").value = "";

CSS overflow-x: visible; and overflow-y: hidden; causing scrollbar issue

After some serious searching it seems i've found the answer to my question:

from: http://www.brunildo.org/test/Overflowxy2.html

In Gecko, Safari, Opera, ‘visible’ becomes ‘auto’ also when combined with ‘hidden’ (in other words: ‘visible’ becomes ‘auto’ when combined with anything else different from ‘visible’). Gecko 1.8, Safari 3, Opera 9.5 are pretty consistent among them.

also the W3C spec says:

The computed values of ‘overflow-x’ and ‘overflow-y’ are the same as their specified values, except that some combinations with ‘visible’ are not possible: if one is specified as ‘visible’ and the other is ‘scroll’ or ‘auto’, then ‘visible’ is set to ‘auto’. The computed value of ‘overflow’ is equal to the computed value of ‘overflow-x’ if ‘overflow-y’ is the same; otherwise it is the pair of computed values of ‘overflow-x’ and ‘overflow-y’.

Short Version:

If you are using visible for either overflow-x or overflow-y and something other than visible for the other, the visible value is interpreted as auto.

Is it possible to read the value of a annotation in java?

While all the answers given so far are perfectly valid, one should also keep in mind the google reflections library for a more generic and easy approach to annotation scanning, e.g.

 Reflections reflections = new Reflections("my.project.prefix");

 Set<Field> ids = reflections.getFieldsAnnotatedWith(javax.persistence.Id.class);

Search input with an icon Bootstrap 4

Here's a fairly simple way to achieve it by enclosing both the magnifying glass icon and the input field inside a div with relative positioning.

Absolute positioning is applied to the icon, which takes it out of the normal document layout flow. The icon is then positioned inside the input. Left padding is applied to the input so that the user's input appears to the right of the icon.

Note that this example places the magnifying glass icon on the left instead of the right. This is recommended when using <input type="search"> as Chrome adds an X button in the right side of the searchbox. If we placed the icon there it would overlay the X button and look fugly.

Here is the needed Bootstrap markup.

<div class="position-relative">
    <i class="fa fa-search position-absolute"></i>
    <input class="form-control" type="search">
</div>

...and a couple CSS classes for the things which I couldn't do with Bootstrap classes:

i {
    font-size: 1rem;
    color: #333;
    top: .75rem;
    left: .75rem
}

input {
    padding-left: 2.5rem;
}

You may have to fiddle with the values for top, left, and padding-left.

How to increase Neo4j's maximum file open limit (ulimit) in Ubuntu?

You could alter the init script for neo4j to do a ulimit -n 40000 before running neo4j.

However, I can't help but feel you are barking up the wrong tree. Does neo4j legitimately need more than 10,000 open file descriptors? This sounds very much like a bug in neo4j or the way you are using it. I would try to address that.

Add borders to cells in POI generated Excel File

Setting up borders in the style used in the cells will accomplish this. Example:

style.setBorderBottom(HSSFCellStyle.BORDER_MEDIUM);
style.setBorderTop(HSSFCellStyle.BORDER_MEDIUM);
style.setBorderRight(HSSFCellStyle.BORDER_MEDIUM);
style.setBorderLeft(HSSFCellStyle.BORDER_MEDIUM);

PHP: Get key from array?

Try this

foreach(array_keys($array) as $nmkey)
    {
        echo $nmkey;
    }

The located assembly's manifest definition does not match the assembly reference

clean and rebuild the solution might not replace all the dll's from the output directory.

what i'll suggest is try renaming the folder from "bin" to "oldbin" or "obj" to "oldobj"

and then try build your silution again.

incase if you are using any third party dll's those you will need to copy into newly created "bin" or "obj" folder after successful build.

hope this will work for you.

Rails - How to use a Helper Inside a Controller

In Rails 5+ you can simply use the function as demonstrated below with simple example:

module ApplicationHelper
  # format datetime in the format #2018-12-01 12:12 PM
  def datetime_format(datetime = nil)
    if datetime
      datetime.strftime('%Y-%m-%d %H:%M %p')
    else
      'NA'
    end
  end
end

class ExamplesController < ApplicationController
  def index
    current_datetime = helpers.datetime_format DateTime.now
    raise current_datetime.inspect
  end
end

OUTPUT

"2018-12-10 01:01 AM"

git - pulling from specific branch

Laravel documentation example:

git pull https://github.com/laravel/docs.git 5.8

based on the command format:

git pull origin <branch>

How to loop and render elements in React-native?

You would usually use map for that kind of thing.

buttonsListArr = initialArr.map(buttonInfo => (
  <Button ... key={buttonInfo[0]}>{buttonInfo[1]}</Button>
);

(key is a necessary prop whenever you do mapping in React. The key needs to be a unique identifier for the generated component)

As a side, I would use an object instead of an array. I find it looks nicer:

initialArr = [
  {
    id: 1,
    color: "blue",
    text: "text1"
  },
  {
    id: 2,
    color: "red",
    text: "text2"
  },
];

buttonsListArr = initialArr.map(buttonInfo => (
  <Button ... key={buttonInfo.id}>{buttonInfo.text}</Button>
);

Formatting numbers (decimal places, thousands separators, etc) with CSS

If it helps...

I use the PHP function number_format() and the Narrow No-break Space (&#8239;). It is often used as an unambiguous thousands separator.

echo number_format(200000, 0, "", "&#8239;");

Because IE8 has some problems to render the Narrow No-break Space, I changed it for a SPAN

echo "<span class='number'>".number_format(200000, 0, "", "<span></span>")."</span>";
.number SPAN{
    padding: 0 1px; 
}

Difference between SurfaceView and View?

A few things I've noted:

  • SurfaceViews contain a nice rendering mechanism that allows threads to update the surface's content without using a handler (good for animation).
  • Surfaceviews cannot be transparent, they can only appear behind other elements in the view hierarchy.
  • I've found that they are much faster for animation than rendering onto a View.

For more information (and a great usage example) refer to the LunarLander project in the SDK 's examples section.

The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256

For Boto3 , use this code.

import boto3
from botocore.client import Config


s3 = boto3.resource('s3',
        aws_access_key_id='xxxxxx',
        aws_secret_access_key='xxxxxx',
        region_name='us-south-1',
        config=Config(signature_version='s3v4')
        )

Serializing class instance to JSON

I believe instead of inheritance as suggested in accepted answer, it's better to use polymorphism. Otherwise you have to have a big if else statement to customize encoding of every object. That means create a generic default encoder for JSON as:

def jsonDefEncoder(obj):
   if hasattr(obj, 'jsonEnc'):
      return obj.jsonEnc()
   else: #some default behavior
      return obj.__dict__

and then have a jsonEnc() function in each class you want to serialize. e.g.

class A(object):
   def __init__(self,lengthInFeet):
      self.lengthInFeet=lengthInFeet
   def jsonEnc(self):
      return {'lengthInMeters': lengthInFeet * 0.3 } # each foot is 0.3 meter

Then you call json.dumps(classInstance,default=jsonDefEncoder)

Case-insensitive string comparison in C++

My first thought for a non-unicode version was to do something like this:

bool caseInsensitiveStringCompare(const string& str1, const string& str2) {
    if (str1.size() != str2.size()) {
        return false;
    }
    for (string::const_iterator c1 = str1.begin(), c2 = str2.begin(); c1 != str1.end(); ++c1, ++c2) {
        if (tolower(static_cast<unsigned char>(*c1)) != tolower(static_cast<unsigned char>(*c2))) {
            return false;
        }
    }
    return true;
}

How to delete node from XML file using C#

You can use Linq to XML to do this:

XDocument doc = XDocument.Load("input.xml");
var q = from node in doc.Descendants("Setting")
        let attr = node.Attribute("name")
        where attr != null && attr.Value == "File1"
        select node;
q.ToList().ForEach(x => x.Remove());
doc.Save("output.xml");

Transport security has blocked a cleartext HTTP

If you are using Xcode 8.0+ and Swift 2.2+ or even Objective C:

Enter image description here

If you want to allow HTTP connections to any site, you can use this keys:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

If you know which domains you will connect to add:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>example.com</key>
        <dict>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <true/>
            <key>NSIncludesSubdomains</key>
            <true/>
        </dict>
    </dict>
</dict>

What is declarative programming?

The other answers already do a fantastic job explaining what declarative programming is, so I'm just going to provide some examples of why that might be useful.

Context Independence

Declarative Programs are context-independent. Because they only declare what the ultimate goal is, but not the intermediary steps to reach that goal, the same program can be used in different contexts. This is hard to do with imperative programs, because they often depend on the context (e.g. hidden state).

Take yacc as an example. It's a parser generator aka. compiler compiler, an external declarative DSL for describing the grammar of a language, so that a parser for that language can automatically be generated from the description. Because of its context independence, you can do many different things with such a grammar:

  • Generate a C parser for that grammar (the original use case for yacc)
  • Generate a C++ parser for that grammar
  • Generate a Java parser for that grammar (using Jay)
  • Generate a C# parser for that grammar (using GPPG)
  • Generate a Ruby parser for that grammar (using Racc)
  • Generate a tree visualization for that grammar (using GraphViz)
  • simply do some pretty-printing, fancy-formatting and syntax highlighting of the yacc source file itself and include it in your Reference Manual as a syntactic specification of your language

And many more …

Optimization

Because you don't prescribe the computer which steps to take and in what order, it can rearrange your program much more freely, maybe even execute some tasks in parallel. A good example is a query planner and query optimizer for a SQL database. Most SQL databases allow you to display the query that they are actually executing vs. the query that you asked them to execute. Often, those queries look nothing like each other. The query planner takes things into account that you wouldn't even have dreamed of: rotational latency of the disk platter, for example or the fact that some completely different application for a completely different user just executed a similar query and the table that you are joining with and that you worked so hard to avoid loading is already in memory anyway.

There is an interesting trade-off here: the machine has to work harder to figure out how to do something than it would in an imperative language, but when it does figure it out, it has much more freedom and much more information for the optimization stage.

How to update SQLAlchemy row entry?

Examples to clarify the important issue in accepted answer's comments

I didn't understand it until I played around with it myself, so I figured there would be others who were confused as well. Say you are working on the user whose id == 6 and whose no_of_logins == 30 when you start.

# 1 (bad)
user.no_of_logins += 1
# result: UPDATE user SET no_of_logins = 31 WHERE user.id = 6

# 2 (bad)
user.no_of_logins = user.no_of_logins + 1
# result: UPDATE user SET no_of_logins = 31 WHERE user.id = 6

# 3 (bad)
setattr(user, 'no_of_logins', user.no_of_logins + 1)
# result: UPDATE user SET no_of_logins = 31 WHERE user.id = 6

# 4 (ok)
user.no_of_logins = User.no_of_logins + 1
# result: UPDATE user SET no_of_logins = no_of_logins + 1 WHERE user.id = 6

# 5 (ok)
setattr(user, 'no_of_logins', User.no_of_logins + 1)
# result: UPDATE user SET no_of_logins = no_of_logins + 1 WHERE user.id = 6

The point

By referencing the class instead of the instance, you can get SQLAlchemy to be smarter about incrementing, getting it to happen on the database side instead of the Python side. Doing it within the database is better since it's less vulnerable to data corruption (e.g. two clients attempt to increment at the same time with a net result of only one increment instead of two). I assume it's possible to do the incrementing in Python if you set locks or bump up the isolation level, but why bother if you don't have to?

A caveat

If you are going to increment twice via code that produces SQL like SET no_of_logins = no_of_logins + 1, then you will need to commit or at least flush in between increments, or else you will only get one increment in total:

# 6 (bad)
user.no_of_logins = User.no_of_logins + 1
user.no_of_logins = User.no_of_logins + 1
session.commit()
# result: UPDATE user SET no_of_logins = no_of_logins + 1 WHERE user.id = 6

# 7 (ok)
user.no_of_logins = User.no_of_logins + 1
session.flush()
# result: UPDATE user SET no_of_logins = no_of_logins + 1 WHERE user.id = 6
user.no_of_logins = User.no_of_logins + 1
session.commit()
# result: UPDATE user SET no_of_logins = no_of_logins + 1 WHERE user.id = 6

What MIME type should I use for CSV?

RFC 7111

There is an RFC which covers it and says to use text/csv.

This RFC updates RFC 4180.


Excel

Recently I discovered an explicit mimetype for Excel application/vnd.ms-excel. It was registered with IANA in '96. Note the concerns raised about being at the mercy of the sender and having your machine violated.

Media Type: application/vnd.ms-excel

Name Microsoft Excel (tm)

Required parameters: None

Optional parameters: name

Encoding considerations: base64 preferred

Security considerations: As with most application types this data is intended for interpretation by a program that understands the data on the recipient's system. Recipients need to understand that they are at the "mercy" of the sender, when receiving this type of data, since data will be executed on their system, and the security of their machines can be violated.

OID { org-id ms-files(4) ms-excel (3) }

Object type spreadsheet

Comments This Media Type/OID is used to identify Microsoft Excel generically (i.e., independent of version, subtype, or platform format).

I wasn't aware that vendor extensions were allowed. Check out this answer to find out more - thanks starbeamrainbowlabs for the reference.

What's the difference between isset() and array_key_exists()?

The two are not exactly the same. I couldn't remember the exact differences, but they are outlined very well in What's quicker and better to determine if an array key exists in PHP?.

The common consensus seems to be to use isset whenever possible, because it is a language construct and therefore faster. However, the differences should be outlined above.

What are the various "Build action" settings in Visual Studio project properties and what do they do?

VS2010 has a property for 'Build Action', and also for 'Copy to Output Directory'. So an action of 'None' will still copy over to the build directory if the copy property is set to 'Copy if Newer' or 'Copy Always'.

So a Build Action of 'Content' should be reserved to indicate content you will access via 'Application.GetContentStream'

I used the 'Build Action' setting of 'None' and the 'Copy to Output Direcotry' setting of 'Copy if Newer' for some externally linked .config includes.

G.

PHP function to build query string from array

Implode will combine an array into a string for you, but to make an SQL query out a kay/value pair you'll have to write your own function.

C# How can I check if a URL exists/is valid?

You could issue a "HEAD" request rather than a "GET"?

(edit) - lol! Looks like I've done this before!; changed to wiki to avoid accusations of rep-garnering. So to test a URL without the cost of downloading the content:

// using MyClient from linked post
using(var client = new MyClient()) {
    client.HeadOnly = true;
    // fine, no content downloaded
    string s1 = client.DownloadString("http://google.com");
    // throws 404
    string s2 = client.DownloadString("http://google.com/silly");
}

You would try/catch around the DownloadString to check for errors; no error? It exists...


With C# 2.0 (VS2005):

private bool headOnly;
public bool HeadOnly {
    get {return headOnly;}
    set {headOnly = value;}
}

and

using(WebClient client = new MyClient())
{
    // code as before
}

Switching the order of block elements with CSS

As has already been suggested, Flexbox is the answer - particularly because you only need to support a single modern browser: Mobile Safari.

See: http://jsfiddle.net/thirtydot/hLUHL/

You can remove the -moz- prefixed properties if you like, I just left them in for future readers.

_x000D_
_x000D_
    #blockContainer {_x000D_
        display: -webkit-box;_x000D_
        display: -moz-box;_x000D_
        display: box;_x000D_
        _x000D_
        -webkit-box-orient: vertical;_x000D_
        -moz-box-orient: vertical;_x000D_
        box-orient: vertical;_x000D_
    }_x000D_
    #blockA {_x000D_
        -webkit-box-ordinal-group: 2;_x000D_
        -moz-box-ordinal-group: 2;_x000D_
        box-ordinal-group: 2;_x000D_
    }_x000D_
    #blockB {_x000D_
        -webkit-box-ordinal-group: 3;_x000D_
        -moz-box-ordinal-group: 3;_x000D_
        box-ordinal-group: 3;_x000D_
    }
_x000D_
    <div id="blockContainer">_x000D_
        <div id="blockA">Block A</div>_x000D_
        <div id="blockB">Block B</div>_x000D_
        <div id="blockC">Block C</div>_x000D_
    </div>
_x000D_
_x000D_
_x000D_

Split pandas dataframe in two if it has more than 10 rows

Below is a simple function implementation which splits a DataFrame to chunks and a few code examples:

import pandas as pd

def split_dataframe_to_chunks(df, n):
    df_len = len(df)
    count = 0
    dfs = []

    while True:
        if count > df_len-1:
            break

        start = count
        count += n
        #print("%s : %s" % (start, count))
        dfs.append(df.iloc[start : count])
    return dfs


# Create a DataFrame with 10 rows
df = pd.DataFrame([i for i in range(10)])

# Split the DataFrame to chunks of maximum size 2
split_df_to_chunks_of_2 = split_dataframe_to_chunks(df, 2)
print([len(i) for i in split_df_to_chunks_of_2])
# prints: [2, 2, 2, 2, 2]

# Split the DataFrame to chunks of maximum size 3
split_df_to_chunks_of_3 = split_dataframe_to_chunks(df, 3)
print([len(i) for i in split_df_to_chunks_of_3])
# prints [3, 3, 3, 1]

How to force a hover state with jQuery?

You will have to use a class, but don't worry, it's pretty simple. First we'll assign your :hover rules to not only apply to physically-hovered links, but also to links that have the classname hovered.

a:hover, a.hovered { color: #ccff00; }

Next, when you click #btn, we'll toggle the .hovered class on the #link.

$("#btn").click(function() {
   $("#link").toggleClass("hovered");
});

If the link has the class already, it will be removed. If it doesn't have the class, it will be added.

printing out a 2-D array in Matrix format

    int[][] matrix = {
        {1,2,3},
        {4,5,6},
        {7,8,9}
    };
    //use foreach loop as below to avoid IndexOutOfBoundException
    //need to check matrix != null if implements as a method
    //for each row in the matrix
    for (int[] row : matrix) {
        //for each number in the row
        for (int j : row) {
            System.out.print(j + " ");
        }
        System.out.println("");
    }

What is the single most influential book every programmer should read?

Software Tools by by Brian W. Kernighan and P. J. Plauger

It had a profound influence on how I write software.

Is there a limit on how much JSON can hold?

There is no fixed limit on how large a JSON data block is or any of the fields.

There are limits to how much JSON the JavaScript implementation of various browsers can handle (e.g. around 40MB in my experience). See this question for example.

JPA Hibernate Persistence exception [PersistenceUnit: default] Unable to build Hibernate SessionFactory

The issue is that you are not able to get a connection to MYSQL database and hence it is throwing an error saying that cannot build a session factory.

Please see the error below:

 Caused by: java.sql.SQLException: Access denied for user ''@'localhost' (using password: NO) 

which points to username not getting populated.

Please recheck system properties

dataSource.setUsername(System.getProperty("root"));

some packages seems to be missing as well pointing to a dependency issue:

package org.gjt.mm.mysql does not exist

Please run a mvn dependency:tree command to check for dependencies

Add directives from directive in AngularJS

In cases where you have multiple directives on a single DOM element and where the order in which they’re applied matters, you can use the priority property to order their application. Higher numbers run first. The default priority is 0 if you don’t specify one.

EDIT: after the discussion, here's the complete working solution. The key was to remove the attribute: element.removeAttr("common-things");, and also element.removeAttr("data-common-things"); (in case users specify data-common-things in the html)

angular.module('app')
  .directive('commonThings', function ($compile) {
    return {
      restrict: 'A',
      replace: false, 
      terminal: true, //this setting is important, see explanation below
      priority: 1000, //this setting is important, see explanation below
      compile: function compile(element, attrs) {
        element.attr('tooltip', '{{dt()}}');
        element.attr('tooltip-placement', 'bottom');
        element.removeAttr("common-things"); //remove the attribute to avoid indefinite loop
        element.removeAttr("data-common-things"); //also remove the same attribute with data- prefix in case users specify data-common-things in the html

        return {
          pre: function preLink(scope, iElement, iAttrs, controller) {  },
          post: function postLink(scope, iElement, iAttrs, controller) {  
            $compile(iElement)(scope);
          }
        };
      }
    };
  });

Working plunker is available at: http://plnkr.co/edit/Q13bUt?p=preview

Or:

angular.module('app')
  .directive('commonThings', function ($compile) {
    return {
      restrict: 'A',
      replace: false,
      terminal: true,
      priority: 1000,
      link: function link(scope,element, attrs) {
        element.attr('tooltip', '{{dt()}}');
        element.attr('tooltip-placement', 'bottom');
        element.removeAttr("common-things"); //remove the attribute to avoid indefinite loop
        element.removeAttr("data-common-things"); //also remove the same attribute with data- prefix in case users specify data-common-things in the html

        $compile(element)(scope);
      }
    };
  });

DEMO

Explanation why we have to set terminal: true and priority: 1000 (a high number):

When the DOM is ready, angular walks the DOM to identify all registered directives and compile the directives one by one based on priority if these directives are on the same element. We set our custom directive's priority to a high number to ensure that it will be compiled first and with terminal: true, the other directives will be skipped after this directive is compiled.

When our custom directive is compiled, it will modify the element by adding directives and removing itself and use $compile service to compile all the directives (including those that were skipped).

If we don't set terminal:true and priority: 1000, there is a chance that some directives are compiled before our custom directive. And when our custom directive uses $compile to compile the element => compile again the already compiled directives. This will cause unpredictable behavior especially if the directives compiled before our custom directive have already transformed the DOM.

For more information about priority and terminal, check out How to understand the `terminal` of directive?

An example of a directive that also modifies the template is ng-repeat (priority = 1000), when ng-repeat is compiled, ng-repeat make copies of the template element before other directives get applied.

Thanks to @Izhaki's comment, here is the reference to ngRepeat source code: https://github.com/angular/angular.js/blob/master/src/ng/directive/ngRepeat.js

How to set a DateTime variable in SQL Server 2008?

Try using Select instead of Print

DECLARE @Test AS DATETIME 

SET @Test = '2011-02-15'

Select @Test

How to autowire RestTemplate using annotations

@Autowired
private RestOperations restTemplate;

You can only autowire interfaces with implementations.

BOOLEAN or TINYINT confusion

The Newest MySQL Versions have the new BIT data type in which you can specify the number of bits in the field, for example BIT(1) to use as Boolean type, because it can be only 0 or 1.

Fitting polynomial model to data in R

Which model is the "best fitting model" depends on what you mean by "best". R has tools to help, but you need to provide the definition for "best" to choose between them. Consider the following example data and code:

x <- 1:10
y <- x + c(-0.5,0.5)

plot(x,y, xlim=c(0,11), ylim=c(-1,12))

fit1 <- lm( y~offset(x) -1 )
fit2 <- lm( y~x )
fit3 <- lm( y~poly(x,3) )
fit4 <- lm( y~poly(x,9) )
library(splines)
fit5 <- lm( y~ns(x, 3) )
fit6 <- lm( y~ns(x, 9) )

fit7 <- lm( y ~ x + cos(x*pi) )

xx <- seq(0,11, length.out=250)
lines(xx, predict(fit1, data.frame(x=xx)), col='blue')
lines(xx, predict(fit2, data.frame(x=xx)), col='green')
lines(xx, predict(fit3, data.frame(x=xx)), col='red')
lines(xx, predict(fit4, data.frame(x=xx)), col='purple')
lines(xx, predict(fit5, data.frame(x=xx)), col='orange')
lines(xx, predict(fit6, data.frame(x=xx)), col='grey')
lines(xx, predict(fit7, data.frame(x=xx)), col='black')

Which of those models is the best? arguments could be made for any of them (but I for one would not want to use the purple one for interpolation).

How to upgrade docker-compose to latest version

First, remove the old version:

If installed via apt-get

sudo apt-get remove docker-compose

If installed via curl

sudo rm /usr/local/bin/docker-compose

If installed via pip

pip uninstall docker-compose

Then find the newest version on the release page at GitHub or by curling the API if you have jq installed (thanks to dragon788 and frbl for this improvement):

VERSION=$(curl --silent https://api.github.com/repos/docker/compose/releases/latest | jq .name -r)

Finally, download to your favorite $PATH-accessible location and set permissions:

DESTINATION=/usr/local/bin/docker-compose
sudo curl -L https://github.com/docker/compose/releases/download/${VERSION}/docker-compose-$(uname -s)-$(uname -m) -o $DESTINATION
sudo chmod 755 $DESTINATION

How to set bot's status

setGame has been discontinued. You must use client.user.setActivity.

Don't forget, if you are setting a streaming status, you MUST specify a Twitch URL

An example is here:

client.user.setActivity("with depression", {
  type: "STREAMING",
  url: "https://www.twitch.tv/example-url"
});

How to export data to an excel file using PHPExcel

Try the below complete example for the same

<?php
  $objPHPExcel = new PHPExcel();
  $query1 = "SELECT * FROM employee";
  $exec1 = mysql_query($query1) or die ("Error in Query1".mysql_error());
  $serialnumber=0;
  //Set header with temp array
  $tmparray =array("Sr.Number","Employee Login","Employee Name");
  //take new main array and set header array in it.
  $sheet =array($tmparray);

  while ($res1 = mysql_fetch_array($exec1))
  {
    $tmparray =array();
    $serialnumber = $serialnumber + 1;
    array_push($tmparray,$serialnumber);
    $employeelogin = $res1['employeelogin'];
    array_push($tmparray,$employeelogin);
    $employeename = $res1['employeename'];
    array_push($tmparray,$employeename);   
    array_push($sheet,$tmparray);
  }
   header('Content-type: application/vnd.ms-excel');
   header('Content-Disposition: attachment; filename="name.xlsx"');
  $worksheet = $objPHPExcel->getActiveSheet();
  foreach($sheet as $row => $columns) {
    foreach($columns as $column => $data) {
        $worksheet->setCellValueByColumnAndRow($column, $row + 1, $data);
    }
  }

  //make first row bold
  $objPHPExcel->getActiveSheet()->getStyle("A1:I1")->getFont()->setBold(true);
  $objPHPExcel->setActiveSheetIndex(0);
  $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
  $objWriter->save(str_replace('.php', '.xlsx', __FILE__));
?>

How to change the color of progressbar in C# .NET 3.5?

Vertical Bar UP For Down in red color :

using System;
using System.Windows.Forms;
using System.Drawing;



public class VerticalProgressBar : ProgressBar
{


    protected override CreateParams CreateParams
    {
        get
        {
            CreateParams cp = base.CreateParams;
            cp.Style |= 0x04;
            return cp;

        }
    }
    private SolidBrush brush = null;

    public VerticalProgressBar()
    {
        this.SetStyle(ControlStyles.UserPaint, true);
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        if (brush == null || brush.Color != this.ForeColor)
            brush = new SolidBrush(this.ForeColor);

        Rectangle rec = new Rectangle(0, 0, this.Width, this.Height);
        if (ProgressBarRenderer.IsSupported)
        ProgressBarRenderer.DrawVerticalBar(e.Graphics, rec);
        rec.Height = (int)(rec.Height * ((double)Value / Maximum)) - 4;
        rec.Width = rec.Width - 4;
        e.Graphics.FillRectangle(brush, 2, 2, rec.Width, rec.Height);

    } 
}

What is the difference between "px", "dip", "dp" and "sp"?

I will elaborate more on how exactly does dp convert to px:

  • If running on an mdpi device, a 150 x 150 px image will take up 150 * 150 dp of screen space.
  • If running on an hdpi device, a 150 x 150 px image will take up 100 * 100 dp of screen space.
  • If running on an xhdpi device, a 150x150 px image will take up 75 * 75 dp of screen space.

The other way around: say, you want to add an image to your application and you need it to fill a 100 * 100 dp control. You'll need to create different size images for supported screen sizes:

  • 100 * 100 px image for mdpi
  • 150 * 150 px image for hdpi
  • 200 * 200 px image for xhdpi

Changing iframe src with Javascript

You can solve it by making the iframe in javascript

_x000D_
_x000D_
  document.write(" <iframe  id='frame' name='frame' src='" + srcstring + "' width='600'  height='315'   allowfullscreen></iframe>");
_x000D_
_x000D_
_x000D_

AJAX Mailchimp signup form integration

Use jquery.ajaxchimp plugin to achieve that. It's dead easy!

<form method="post" action="YOUR_SUBSCRIBE_URL_HERE">
  <input type="text" name="EMAIL" placeholder="e-mail address" />
  <input type="submit" name="subscribe" value="subscribe!" />        
  <p class="result"></p>
</form>

JavaScript:

$(function() {
  $('form').ajaxChimp({
    callback: function(response) {
      $('form .result').text(response.msg);
    }
  });
})

Delete everything in a MongoDB database

Here are some useful delete operations for mongodb using mongo shell

To delete particular document in collections: db.mycollection.remove( {name:"stack"} )

To delete all documents in collections: db.mycollection.remove()

To delete any particular collection : db.mycollection.drop()

to delete database : first go to that database by use mydb command and then

db.dropDatabase()

How to change node.js's console font color?

This is a list of available colours (both background and foreground) in the console with some available actions (like reset, reverse, etc).

const colours = {
    reset: "\x1b[0m",
    bright: "\x1b[1m",
    dim: "\x1b[2m",
    underscore: "\x1b[4m",
    blink: "\x1b[5m",
    reverse: "\x1b[7m",
    hidden: "\x1b[8m",
    
    fg: {
        black: "\x1b[30m",
        red: "\x1b[31m",
        green: "\x1b[32m",
        yellow: "\x1b[33m",
        blue: "\x1b[34m",
        magenta: "\x1b[35m",
        cyan: "\x1b[36m",
        white: "\x1b[37m",
        crimson: "\x1b[38m" // Scarlet
    },
    bg: {
        black: "\x1b[40m",
        red: "\x1b[41m",
        green: "\x1b[42m",
        yellow: "\x1b[43m",
        blue: "\x1b[44m",
        magenta: "\x1b[45m",
        cyan: "\x1b[46m",
        white: "\x1b[47m",
        crimson: "\x1b[48m"
    }
};

Here's an example of how to use it:

console.log(colours.bg.blue, colours.fg.white, "I am a white message with a blue background", colours.reset) ; 
// Make sure that you don't forget "colours.reset" at the so that you can reset the console back to it's original colours.

Or you can install some utility modules:

npm install console-info console-warn console-error --save-dev

These modules will show something like the following to the console when you use them:

Example of the utility modules that I've mentioned.

How do I use T-SQL's Case/When?

declare @n int = 7,
    @m int = 3;

select 
    case 
        when @n = 1 then
            'SOMETEXT'
    else
        case 
            when @m = 1 then
                'SOMEOTHERTEXT'
            when @m = 2 then
                'SOMEOTHERTEXTGOESHERE'
        end
    end as col1
-- n=1 => returns SOMETEXT regardless of @m
-- n=2 and m=1 => returns SOMEOTHERTEXT
-- n=2 and m=2 => returns SOMEOTHERTEXTGOESHERE
-- n=2 and m>2 => returns null (no else defined for inner case)

SQL Server: Get table primary key using sql query

I also found another one for SQL Server:

SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE OBJECTPROPERTY(OBJECT_ID(CONSTRAINT_SCHEMA + '.' + QUOTENAME(CONSTRAINT_NAME)), 'IsPrimaryKey') = 1
AND TABLE_NAME = 'TableName' AND TABLE_SCHEMA = 'Schema'

Android custom dropdown/popup menu

Update: To create a popup menu in android with Kotlin refer my answer here.

To create a popup menu in android with Java:

Create a layout file activity_main.xml under res/layout directory which contains only one button.

Filename: activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    xmlns:tools="http://schemas.android.com/tools"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent"  
    android:paddingBottom="@dimen/activity_vertical_margin"  
    android:paddingLeft="@dimen/activity_horizontal_margin"  
    android:paddingRight="@dimen/activity_horizontal_margin"  
    android:paddingTop="@dimen/activity_vertical_margin"  
    tools:context=".MainActivity" >  

    <Button  
        android:id="@+id/button1"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_alignParentLeft="true"  
        android:layout_alignParentTop="true"  
        android:layout_marginLeft="62dp"  
        android:layout_marginTop="50dp"  
        android:text="Show Popup" />  

</RelativeLayout>  

Create a file popup_menu.xml under res/menu directory

It contains three items as shown below.

Filename: poupup_menu.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android" >  

    <item  
        android:id="@+id/one"  
        android:title="One"/>  

    <item  
        android:id="@+id/two"  
        android:title="Two"/>  

    <item  
        android:id="@+id/three"  
        android:title="Three"/>  

</menu>  

MainActivity class which displays the popup menu on button click.

Filename: MainActivity.java

public class MainActivity extends Activity {  
    private Button button1;  

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button1 = (Button) findViewById(R.id.button1);
        button1.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //Creating the instance of PopupMenu
                PopupMenu popup = new PopupMenu(MainActivity.this, button1);
                //Inflating the Popup using xml file
                popup.getMenuInflater()
                    .inflate(R.menu.popup_menu, popup.getMenu());

                //registering popup with OnMenuItemClickListener
                popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    public boolean onMenuItemClick(MenuItem item) {
                        Toast.makeText(
                            MainActivity.this,
                            "You Clicked : " + item.getTitle(),
                            Toast.LENGTH_SHORT
                        ).show();
                        return true;
                    }
                });

                popup.show(); //showing popup menu
            }
        }); //closing the setOnClickListener method
    }
}

To add programmatically:

PopupMenu menu = new PopupMenu(this, view);

menu.getMenu().add("One");
menu.getMenu().add("Two");
menu.getMenu().add("Three");

menu.show();

Follow this link for creating menu programmatically.

Plotting a 2D heatmap with Matplotlib

Here's how to do it from a csv:

import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import griddata

# Load data from CSV
dat = np.genfromtxt('dat.xyz', delimiter=' ',skip_header=0)
X_dat = dat[:,0]
Y_dat = dat[:,1]
Z_dat = dat[:,2]

# Convert from pandas dataframes to numpy arrays
X, Y, Z, = np.array([]), np.array([]), np.array([])
for i in range(len(X_dat)):
        X = np.append(X, X_dat[i])
        Y = np.append(Y, Y_dat[i])
        Z = np.append(Z, Z_dat[i])

# create x-y points to be used in heatmap
xi = np.linspace(X.min(), X.max(), 1000)
yi = np.linspace(Y.min(), Y.max(), 1000)

# Interpolate for plotting
zi = griddata((X, Y), Z, (xi[None,:], yi[:,None]), method='cubic')

# I control the range of my colorbar by removing data 
# outside of my range of interest
zmin = 3
zmax = 12
zi[(zi<zmin) | (zi>zmax)] = None

# Create the contour plot
CS = plt.contourf(xi, yi, zi, 15, cmap=plt.cm.rainbow,
                  vmax=zmax, vmin=zmin)
plt.colorbar()  
plt.show()

where dat.xyz is in the form

x1 y1 z1
x2 y2 z2
...

How to display length of filtered ng-repeat data

For completeness, in addition to previous answers (perform calculation of visible people inside controller) you can also perform that calculations in your HTML template as in the example below.

Assuming your list of people is in data variable and you filter people using query model, the following code will work for you:

<p>Number of visible people: {{(data|filter:query).length}}</p>
<p>Total number of people: {{data.length}}</p>
  • {{data.length}} - prints total number of people
  • {{(data|filter:query).length}} - prints filtered number of people

Note that this solution works fine if you want to use filtered data only once in a page. However, if you use filtered data more than once e.g. to present items and to show length of filtered list, I would suggest using alias expression (described below) for AngularJS 1.3+ or the solution proposed by @Wumms for AngularJS version prior to 1.3.

New Feature in Angular 1.3

AngularJS creators also noticed that problem and in version 1.3 (beta 17) they added "alias" expression which will store the intermediate results of the repeater after the filters have been applied e.g.

<div ng-repeat="person in data | filter:query as results">
    <!-- template ... -->
</div>

<p>Number of visible people: {{results.length}}</p>

The alias expression will prevent multiple filter execution issue.

I hope that will help.