Programs & Examples On #Codepoint

Put quotes around a variable string in JavaScript

In case of array like

result = [ '2015',  '2014',  '2013',  '2011' ],

it gets tricky if you are using escape sequence like:

result = [ \'2015\',  \'2014\',  \'2013\',  \'2011\' ].

Instead, good way to do it is to wrap the array with single quotes as follows:

result = "'"+result+"'";

Set value for particular cell in pandas DataFrame using index

Here is a summary of the valid solutions provided by all users, for data frames indexed by integer and string.

df.iloc, df.loc and df.at work for both type of data frames, df.iloc only works with row/column integer indices, df.loc and df.at supports for setting values using column names and / or integer indices.

When the specified index does not exist, both df.loc and df.at would append the newly inserted rows/columns to the existing data frame, but df.iloc would raise "IndexError: positional indexers are out-of-bounds". A working example tested in Python 2.7 and 3.7 is as follows:

import numpy as np, pandas as pd

df1 = pd.DataFrame(index=np.arange(3), columns=['x','y','z'])
df1['x'] = ['A','B','C']
df1.at[2,'y'] = 400

# rows/columns specified does not exist, appends new rows/columns to existing data frame
df1.at['D','w'] = 9000
df1.loc['E','q'] = 499

# using df[<some_column_name>] == <condition> to retrieve target rows
df1.at[df1['x']=='B', 'y'] = 10000
df1.loc[df1['x']=='B', ['z','w']] = 10000

# using a list of index to setup values
df1.iloc[[1,2,4], 2] = 9999
df1.loc[[0,'D','E'],'w'] = 7500
df1.at[[0,2,"D"],'x'] = 10
df1.at[:, ['y', 'w']] = 8000

df1
>>> df1
     x     y     z     w      q
0   10  8000   NaN  8000    NaN
1    B  8000  9999  8000    NaN
2   10  8000  9999  8000    NaN
D   10  8000   NaN  8000    NaN
E  NaN  8000  9999  8000  499.0

error running apache after xampp install

Try those methods, it should work:

  • quit/exit Skype (make sure it's not running) because it reserves localhost:80
  • disable Anti-virus (Try first to disable skype and running again, if it didn't work do this step)
  • Right click on xampp control panel and run as administrator

How to determine an interface{} value's "real" type?

Type switches can also be used with reflection stuff:

var str = "hello!"
var obj = reflect.ValueOf(&str)

switch obj.Elem().Interface().(type) {
case string:
    log.Println("obj contains a pointer to a string")
default:
    log.Println("obj contains something else")
}

How can I transition height: 0; to height: auto; using CSS?

This is regular problem I've solved like this

http://jsfiddle.net/ipeshev/d1dfr0jz/

Try to set delay of closed state to some negative number and play a little bit with the value. You will see the difference.It can be made almost to lie the human eye ;).

It works in major browsers, but good enough for me. It is strange but give some results.

.expandable {
    max-height: 0px;
    overflow: hidden;
    transition: all 1s linear -0.8s;
}

button:hover ~ .expandable {
    max-height: 9000px;
    transition: all 1s ease-in-out;
}

Why does Eclipse complain about @Override on interface methods?

Using the @Override annotation on methods that implement those declared by an interface is only valid from Java 6 onward. It's an error in Java 5.

Make sure that your IDE projects are setup to use a Java 6 JRE, and that the "source compatibility" is set to 1.6 or greater:

  1. Open the Window > Preferences dialog
  2. Browse to Java > Compiler.
  3. There, set the "Compiler compliance level" to 1.6.

Remember that Eclipse can override these global settings for a specific project, so check those too.


Update:

The error under Java 5 isn't just with Eclipse; using javac directly from the command line will give you the same error. It is not valid Java 5 source code.

However, you can specify the -target 1.5 option to JDK 6's javac, which will produce a Java 5 version class file from the Java 6 source code.

Count number of 1's in binary representation

I saw the following solution from another website:

int count_one(int x){
    x = (x & (0x55555555)) + ((x >> 1) & (0x55555555));
    x = (x & (0x33333333)) + ((x >> 2) & (0x33333333));
    x = (x & (0x0f0f0f0f)) + ((x >> 4) & (0x0f0f0f0f));
    x = (x & (0x00ff00ff)) + ((x >> 8) & (0x00ff00ff));
    x = (x & (0x0000ffff)) + ((x >> 16) & (0x0000ffff));
    return x;
}

How to uninstall a windows service and delete its files without rebooting

I am using the InstallUtil.exe packed with .NET Framework.

The usage to uninstall is: InstallUtil '\path\to\assembly\with\the\installer\classes' /u so for example: installutil MyService.HostService.exe /u

The /u switch stands for uninstall, without it the util performs normal installation of the service. The utility stops the service if it is running and I never had problems with Windows keeping lock on the service files. You can read about other options of InstallUtil on MSDN.

P.S.:if you don't have installutil in your path variable use full path like this: C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe "C:\MyServiceFolder\MyService.HostService.exe" /u or if you need 64bit version it can be found in 'C:\Windows\Microsoft.NET\Framework64\v4.0.30319\' .The version number in path varies depending on .NET version.

How to prevent scanf causing a buffer overflow in C?

It's not that much work to make a function that's allocating the needed memory for your string. That's a little c-function i wrote some time ago, i always use it to read in strings.

It will return the read string or if a memory error occurs NULL. But be aware that you have to free() your string and always check for it's return value.

#define BUFFER 32

char *readString()
{
    char *str = malloc(sizeof(char) * BUFFER), *err;
    int pos;
    for(pos = 0; str != NULL && (str[pos] = getchar()) != '\n'; pos++)
    {
        if(pos % BUFFER == BUFFER - 1)
        {
            if((err = realloc(str, sizeof(char) * (BUFFER + pos + 1))) == NULL)
                free(str);
            str = err;
        }
    }
    if(str != NULL)
        str[pos] = '\0';
    return str;
}

How to save image in database using C#

This is a method that uses a FileUpload control in asp.net:

byte[] buffer = new byte[fu.FileContent.Length];
Stream s = fu.FileContent;
s.Read(buffer, 0, buffer.Length);
//Then save 'buffer' to the varbinary column in your db where you want to store the image.

Use NSInteger as array index

According to the error message, you declared myLoc as a pointer to an NSInteger (NSInteger *myLoc) rather than an actual NSInteger (NSInteger myLoc). It needs to be the latter.

What's the difference between emulation and simulation?

Coming from the hardware development world. . .

Simulation tests functionality. 2+2 = 4 etc

Emulation tests the functionality on the specific environment (64-bit, 16-bit, fingers and toes).

Here is a food example:

You have two pieces of bread, one knife, peanut butter and jelly and will be giving them to a kindergartner. You write instructions on how to make a sandwich.

In simulation, you would act out the process, pretend you opened the jars, pretend spreading the peanut butter etc.

If at the end of the instructions your are left with only jelly and not peanut butter then you failed the simulation and you need to fix your instructions. On the other hand if you have a complete "sandwich" then the instructions should be valid

In emulation, you would use close representations of the actual parts (same bread, knife peanut butter etc). What happens if you gave your kindergartner a cheap plastic knife and really really thick peanut butter?? The knife would break in emulation and the instructions would need to be clarified or fixed to accommodate this problem. In this case you might suggest warming up the peanut butter in the microwave.

In practice: Consider a 64-bit system that you are programming in and a 32bit system that will actually be running the code. You add two very very large numbers and print the result. In simulation everything works (you managed to get the code right to add two numbers) In emulation however you find that you get the wrong answer. What happened? The emulation of the 32-bit system was unable to handle the large numbers. This is an example of correct functionality (i.e. simulation) but not proper support for your runtime environment (emulation)

How to view files in binary from bash?

sudo apt-get install bless

Bless is GUI tool which can view, edit, seach and a lot more. Its very light weight.

Convert UTF-8 encoded NSData to NSString

If the data is not null-terminated, you should use -initWithData:encoding:

NSString* newStr = [[NSString alloc] initWithData:theData encoding:NSUTF8StringEncoding];

If the data is null-terminated, you should instead use -stringWithUTF8String: to avoid the extra \0 at the end.

NSString* newStr = [NSString stringWithUTF8String:[theData bytes]];

(Note that if the input is not properly UTF-8-encoded, you will get nil.)


Swift variant:

let newStr = String(data: data, encoding: .utf8)
// note that `newStr` is a `String?`, not a `String`.

If the data is null-terminated, you could go though the safe way which is remove the that null character, or the unsafe way similar to the Objective-C version above.

// safe way, provided data is \0-terminated
let newStr1 = String(data: data.subdata(in: 0 ..< data.count - 1), encoding: .utf8)
// unsafe way, provided data is \0-terminated
let newStr2 = data.withUnsafeBytes(String.init(utf8String:))

Java LinkedHashMap get first or last entry

LinkedHashMap current implementation (Java 8) keeps track of its tail. If performance is a concern and/or the map is large in size, you could access that field via reflection.

Because the implementation may change it is probably a good idea to have a fallback strategy too. You may want to log something if an exception is thrown so you know that the implementation has changed.

It could look like:

public static <K, V> Entry<K, V> getFirst(Map<K, V> map) {
  if (map.isEmpty()) return null;
  return map.entrySet().iterator().next();
}

public static <K, V> Entry<K, V> getLast(Map<K, V> map) {
  try {
    if (map instanceof LinkedHashMap) return getLastViaReflection(map);
  } catch (Exception ignore) { }
  return getLastByIterating(map);
}

private static <K, V> Entry<K, V> getLastByIterating(Map<K, V> map) {
  Entry<K, V> last = null;
  for (Entry<K, V> e : map.entrySet()) last = e;
  return last;
}

private static <K, V> Entry<K, V> getLastViaReflection(Map<K, V> map) throws NoSuchFieldException, IllegalAccessException {
  Field tail = map.getClass().getDeclaredField("tail");
  tail.setAccessible(true);
  return (Entry<K, V>) tail.get(map);
}

Count number of times value appears in particular column in MySQL

SELECT column_name, COUNT(column_name)
FROM table_name
GROUP BY column_name

How do I pass a method as a parameter in Python

Not exactly what you want, but a related useful tool is getattr(), to use method's name as a parameter.

class MyClass:
   def __init__(self):
      pass
   def MyMethod(self):
      print("Method ran")

# Create an object
object = MyClass()
# Get all the methods of a class
method_list = [func for func in dir(MyClass) if callable(getattr(MyClass, func))]
# You can use any of the methods in method_list
# "MyMethod" is the one we want to use right now

# This is the same as running "object.MyMethod()"
getattr(object,'MyMethod')()

How to convert a set to a list in python?

[EDITED] It's seems you earlier have redefined "list", using it as a variable name, like this:

list = set([1,2,3,4]) # oops
#...
first_list = [1,2,3,4]
my_set=set(first_list)
my_list = list(my_set)

And you'l get

Traceback (most recent call last):
  File "<console>", line 1, in <module>
TypeError: 'set' object is not callable

What are Runtime.getRuntime().totalMemory() and freeMemory()?

Runtime#totalMemory - the memory that the JVM has allocated thus far. This isn't necessarily what is in use or the maximum.

Runtime#maxMemory - the maximum amount of memory that the JVM has been configured to use. Once your process reaches this amount, the JVM will not allocate more and instead GC much more frequently.

Runtime#freeMemory - I'm not sure if this is measured from the max or the portion of the total that is unused. I am guessing it is a measurement of the portion of total which is unused.

Lightweight workflow engine for Java

Yes, in my perspective there is no reason why you should write your own. Most of the Open Source BPM/Workflow frameworks are extremely flexible, you just need to learn the basics. If you choose jBPM you will get much more than a simple workflow engine, so it depends what are you trying to build.

Cheers

How to get css background color on <tr> tag to span entire row

I prefer to use border-spacing as it allows more flexibility. For instance, you could do

table {
  border-spacing: 0 2px;
}

Which would only collapse the vertical borders and leave the horizontal ones in tact, which is what it sounds like the OP was actually looking for.

Note that border-spacing: 0 is not the same as border-collapse: collapse. You will need to use the latter if you want to add your own border to a tr as seen here.

Best way to implement multi-language/globalization in large .NET project

I've seen projects implemented using a number of different approaches, each have their merits and drawbacks.

  • One did it in the config file (not my favourite)
  • One did it using a database - this worked pretty well, but was a pain in the you know what to maintain.
  • One used resource files the way you're suggesting and I have to say it was my favourite approach.
  • The most basic one did it using an include file full of strings - ugly.

I'd say the resource method you've chosen makes a lot of sense. It would be interesting to see other people's answers too as I often wonder if there's a better way of doing things like this. I've seen numerous resources that all point to the using resources method, including one right here on SO.

jQuery change method on input type="file"

is the ajax uploader refreshing your input element? if so you should consider using .live() method.

 $('#imageFile').live('change', function(){ uploadFile(); });

update:

from jQuery 1.7+ you should use now .on()

 $(parent_element_selector_here or document ).on('change','#imageFile' , function(){ uploadFile(); });

TypeScript error TS1005: ';' expected (II)

  • Remove C:\Program Files (x86)\Microsoft SDKs\TypeScript\1.0 directory.

  • Now run :

    npm install -g typescript 
    

    this will install the latest version and then re-try.

How to print all information from an HTTP request to the screen, in PHP

Putting together answers from Peter Bailey and Cmyker you get something like:

<?php
foreach ($_SERVER as $key => $value) {
    if (strpos($key, 'HTTP_') === 0) {
        $chunks = explode('_', $key);
        $header = '';
        for ($i = 1; $y = sizeof($chunks) - 1, $i < $y; $i++) {
            $header .= ucfirst(strtolower($chunks[$i])).'-';
        }
        $header .= ucfirst(strtolower($chunks[$i])).': '.$value;
        echo $header."\n";
    }
}
$body = file_get_contents('php://input');
if ($body != '') {
  print("\n$body\n\n");
}
?>

which works with the php -S built-in webserver, which is quite a handy feature of PHP.

How to check SQL Server version

TL;DR

SQLCMD -S (LOCAL) -E -V 16 -Q "IF(ISNULL(CAST(SERVERPROPERTY('ProductMajorVersion') AS INT),0)<11) RAISERROR('You need SQL 2012 or later!',16,1)"
IF ERRORLEVEL 1 GOTO :ExitFail

This uses SQLCMD (comes with SQL Server) to connect to the local server instance using Windows auth, throw an error if a version check fails and return the @@ERROR as the command line ERRORLEVEL if >= 16 (and the second line goes to the :ExitFail label if the aforementioned ERRORLEVEL is >= 1).

Watchas, Gotchas & More Info

For SQL 2000+ you can use the SERVERPROPERTY to determine a lot of this info.

While SQL 2008+ supports the ProductMajorVersion & ProductMinorVersion properties, ProductVersion has been around since 2000 (remembering that if a property is not supported the function returns NULL).

If you are interested in earlier versions you can use the PARSENAME function to split the ProductVersion (remembering the "parts" are numbered right to left i.e. PARSENAME('a.b.c', 1) returns c).

Also remember that PARSENAME('a.b.c', 4) returns NULL, because SQL 2005 and earlier only used 3 parts in the version number!

So for SQL 2008+ you can simply use:

SELECT
    SERVERPROPERTY('ProductVersion') AS ProductVersion,
    CAST(SERVERPROPERTY('ProductMajorVersion')  AS INT) AS ProductMajorVersion,
    CAST(SERVERPROPERTY ('ProductMinorVersion') AS INT) AS ProductMinorVersion;

For SQL 2000-2005 you can use:

SELECT
    SERVERPROPERTY('ProductVersion') AS ProductVersion,
    CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS SYSNAME), CASE WHEN SERVERPROPERTY('ProductVersion') IS NULL THEN 3 ELSE 4 END) AS INT) AS ProductVersion_Major,
    CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS SYSNAME), CASE WHEN SERVERPROPERTY('ProductVersion') IS NULL THEN 2 ELSE 3 END) AS INT) AS ProductVersion_Minor,
    CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS SYSNAME), CASE WHEN SERVERPROPERTY('ProductVersion') IS NULL THEN 1 ELSE 2 END) AS INT) AS ProductVersion_Revision,
    CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS SYSNAME), CASE WHEN SERVERPROPERTY('ProductVersion') IS NULL THEN 0 ELSE 1 END) AS INT) AS ProductVersion_Build;

(the PARSENAME(...,0) is a hack to improve readability)

So a check for a SQL 2000+ version would be:

IF (CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS SYSNAME), CASE WHEN SERVERPROPERTY('ProductVersion') IS NULL THEN 3 ELSE 4 END) AS INT) < 10) -- SQL2008
OR (
    (CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS SYSNAME), CASE WHEN SERVERPROPERTY('ProductVersion') IS NULL THEN 3 ELSE 4 END) AS INT) = 10) -- SQL2008
AND (CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS SYSNAME), CASE WHEN SERVERPROPERTY('ProductVersion') IS NULL THEN 2 ELSE 1 END) AS INT) < 5)  -- R2 (this may need to be 50)
   )
    RAISERROR('You need SQL 2008R2 or later!', 16, 1);

This is a lot simpler if you're only only interested in SQL 2008+ because SERVERPROPERTY('ProductMajorVersion') returns NULL for earlier versions, so you can use:

IF (ISNULL(CAST(SERVERPROPERTY('ProductMajorVersion') AS INT), 0) < 11) -- SQL2012
    RAISERROR('You need SQL 2012 or later!', 16, 1);

And you can use the ProductLevel and Edition (or EngineEdition) properties to determine RTM / SPn / CTPn and Dev / Std / Ent / etc respectively.

SELECT
    CAST(SERVERPROPERTY('ProductVersion') AS SYSNAME) AS ProductVersion,
    CAST(SERVERPROPERTY('ProductLevel') AS SYSNAME)   AS ProductLevel,
    CAST(SERVERPROPERTY('Edition') AS SYSNAME)        AS Edition,
    CAST(SERVERPROPERTY('EngineEdition') AS INT)      AS EngineEdition;

FYI the major SQL version numbers are:

  • 8 = SQL 2000
  • 9 = SQL 2005
  • 10 = SQL 2008 (and 10.5 = SQL 2008R2)
  • 11 = SQL 2012
  • 12 = SQL 2014
  • 13 = SQL 2016
  • 14 = SQL 2017

And this all works for SQL Azure too!

EDITED: You may also want to check your DB compatibility level since it could be set to a lower compatibility.

IF EXISTS (SELECT * FROM sys.databases WHERE database_id=DB_ID() AND [compatibility_level] < 110)
    RAISERROR('Database compatibility level must be SQL2008R2 or later (110)!', 16, 1)

Python | change text color in shell

I just described very popular library clint. Which has more features apart of coloring the output on terminal.

By the way it support MAC, Linux and Windows terminals.

Here is the example of using it:

Installing (in Ubuntu)

pip install clint

To add color to some string

colored.red('red string')

Example: Using for color output (django command style)

from django.core.management.base import BaseCommand
from clint.textui import colored


class Command(BaseCommand):
    args = ''
    help = 'Starting my own django long process. Use ' + colored.red('<Ctrl>+c') + ' to break.'

    def handle(self, *args, **options):
        self.stdout.write('Starting the process (Use ' + colored.red('<Ctrl>+c') + ' to break)..')
        # ... Rest of my command code ...

Display unescaped HTML in Vue.js

You can read that here

If you use

{{<br />}}

it'll be escaped. If you want raw html, you gotta use

{{{<br />}}}

EDIT (Feb 5 2017): As @hitautodestruct points out, in vue 2 you should use v-html instead of triple curly braces.

JPA getSingleResult() or null

So all of the "try to rewrite without an exception" solution in this page has a minor problem. Either its not throwing NonUnique exception, nor throw it in some wrong cases too (see below).

I think the proper solution is (maybe) this:

public static <L> L getSingleResultOrNull(TypedQuery<L> query) {
    List<L> results = query.getResultList();
    L foundEntity = null;
    if(!results.isEmpty()) {
        foundEntity = results.get(0);
    }
    if(results.size() > 1) {
        for(L result : results) {
            if(result != foundEntity) {
                throw new NonUniqueResultException();
            }
        }
    }
    return foundEntity;
}

Its returning with null if there is 0 element in the list, returning nonunique if there are different elements in the list, but not returning nonunique when one of your select is not properly designed and returns the same object more then one times.

Feel free to comment.

Keyboard shortcuts in WPF

Special case: your shortcut doesn't trigger if the focus is on an element that "isn't native". In my case for example, a focus on a WpfCurrencyTextbox won't trigger shortcuts defined in your XAML (defined like in oliwa's answer).

I fixed this issue by making my shortcut global with the NHotkey package.

In short, for XAML, all you need to do is to replace

<KeyBinding Gesture="Ctrl+Alt+Add" Command="{Binding IncrementCommand}" />

by

<KeyBinding Gesture="Ctrl+Alt+Add" Command="{Binding IncrementCommand}"
            HotkeyManager.RegisterGlobalHotkey="True" />

Answer has also been posted to: How can I register a global hot key to say CTRL+SHIFT+(LETTER) using WPF and .NET 3.5?

Read from a gzip file in python

Try gzipping some data through the gzip libary like this...

import gzip
content = "Lots of content here"
f = gzip.open('Onlyfinnaly.log.gz', 'wb')
f.write(content)
f.close()

... then run your code as posted ...

import gzip
f=gzip.open('Onlyfinnaly.log.gz','rb')
file_content=f.read()
print file_content

This method worked for me as for some reason the gzip library fails to read some files.

Use string value from a cell to access worksheet of same name

You need INDIRECT function:

=INDIRECT("'"&A5&"'!G7")

LINQ to SQL: Multiple joins ON multiple Columns. Is this possible?

In LINQ2SQL you seldom need to join explicitly when using inner joins.

If you have proper foreign key relationships in your database you will automatically get a relation in the LINQ designer (if not you can create a relation manually in the designer, although you should really have proper relations in your database)

parent-child relation

Then you can just access related tables with the "dot-notation"

var q = from child in context.Childs
        where child.Parent.col2 == 4
        select new
        {
            childCol1 = child.col1,
            parentCol1 = child.Parent.col1,
        };

will generate the query

SELECT [t0].[col1] AS [childCol1], [t1].[col1] AS [parentCol1]
FROM [dbo].[Child] AS [t0]
INNER JOIN [dbo].[Parent] AS [t1] ON ([t1].[col1] = [t0].[col1]) AND ([t1].[col2] = [t0].[col2])
WHERE [t1].[col2] = @p0
-- @p0: Input Int (Size = -1; Prec = 0; Scale = 0) [4]
-- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 4.0.30319.1

In my opinion this is much more readable and lets you concentrate on your special conditions and not the actual mechanics of the join.

Edit
This is of course only applicable when you want to join in the line with our database model. If you want to join "outside the model" you need to resort to manual joins as in the answer from Quintin Robinson

An unhandled exception occurred during the execution of the current web request. ASP.NET

  1. If you are facing this problem (Enter windows + R) an delete temp(%temp%)and windows temp.
  2. Some file is not deleted that time stop IIS(Internet information service) and delete that all remaining files .

Check your problem is solved.

Super-simple example of C# observer/observable with delegates

The observer pattern is usually implemented with events.

Here's an example:

using System;

class Observable
{
    public event EventHandler SomethingHappened;

    public void DoSomething() =>
        SomethingHappened?.Invoke(this, EventArgs.Empty);
}

class Observer
{
    public void HandleEvent(object sender, EventArgs args)
    {
        Console.WriteLine("Something happened to " + sender);
    }
}

class Test
{
    static void Main()
    {
        Observable observable = new Observable();
        Observer observer = new Observer();
        observable.SomethingHappened += observer.HandleEvent;

        observable.DoSomething();
    }
}

See the linked article for a lot more detail.

Note that the above example uses C# 6 null-conditional operator to implement DoSomething safely to handle cases where SomethingHappened has not been subscribed to, and is therefore null. If you're using an older version of C#, you'd need code like this:

public void DoSomething()
{
    var handler = SomethingHappened;
    if (handler != null)
    {
        handler(this, EventArgs.Empty);
    }
}

Python: Finding differences between elements of a list

My way

>>>v = [1,2,3,4,5]
>>>[v[i] - v[i-1] for i, value in enumerate(v[1:], 1)]
[1, 1, 1, 1]

Position last flex item at the end of container

Flexible Box Layout Module - 8.1. Aligning with auto margins

Auto margins on flex items have an effect very similar to auto margins in block flow:

  • During calculations of flex bases and flexible lengths, auto margins are treated as 0.

  • Prior to alignment via justify-content and align-self, any positive free space is distributed to auto margins in that dimension.

Therefore you could use margin-top: auto to distribute the space between the other elements and the last element.

This will position the last element at the bottom.

p:last-of-type {
  margin-top: auto;
}

_x000D_
_x000D_
.container {
  display: flex;
  flex-direction: column;
  border: 1px solid #000;
  min-height: 200px;
  width: 100px;
}
p {
  height: 30px;
  background-color: blue;
  margin: 5px;
}
p:last-of-type {
  margin-top: auto;
}
_x000D_
<div class="container">
  <p></p>
  <p></p>
  <p></p>
</div>
_x000D_
_x000D_
_x000D_

vertical example


Likewise, you can also use margin-left: auto or margin-right: auto for the same alignment horizontally.

p:last-of-type {
  margin-left: auto;
}

_x000D_
_x000D_
.container {
  display: flex;
  width: 100%;
  border: 1px solid #000;
}
p {
  height: 50px;
  width: 50px;
  background-color: blue;
  margin: 5px;
}
p:last-of-type {
  margin-left: auto;
}
_x000D_
<div class="container">
  <p></p>
  <p></p>
  <p></p>
  <p></p>
</div>
_x000D_
_x000D_
_x000D_

horizontal example

How to convert datatype:object to float64 in python?

convert_objects is deprecated.

For pandas >= 0.17.0, use pd.to_numeric

df["2nd"] = pd.to_numeric(df["2nd"])

Selecting Folder Destination in Java?

You could try something like this (as shown here: Select a Directory with a JFileChooser):

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;


public class DemoJFileChooser extends JPanel
   implements ActionListener {
   JButton go;

   JFileChooser chooser;
   String choosertitle;

  public DemoJFileChooser() {
    go = new JButton("Do it");
    go.addActionListener(this);
    add(go);
   }

  public void actionPerformed(ActionEvent e) {            
    chooser = new JFileChooser(); 
    chooser.setCurrentDirectory(new java.io.File("."));
    chooser.setDialogTitle(choosertitle);
    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    //
    // disable the "All files" option.
    //
    chooser.setAcceptAllFileFilterUsed(false);
    //    
    if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { 
      System.out.println("getCurrentDirectory(): " 
         +  chooser.getCurrentDirectory());
      System.out.println("getSelectedFile() : " 
         +  chooser.getSelectedFile());
      }
    else {
      System.out.println("No Selection ");
      }
     }

  public Dimension getPreferredSize(){
    return new Dimension(200, 200);
    }

  public static void main(String s[]) {
    JFrame frame = new JFrame("");
    DemoJFileChooser panel = new DemoJFileChooser();
    frame.addWindowListener(
      new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
          System.exit(0);
          }
        }
      );
    frame.getContentPane().add(panel,"Center");
    frame.setSize(panel.getPreferredSize());
    frame.setVisible(true);
    }
}

How to make a redirection on page load in JSF 1.x

FacesContext context = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse)context.getExternalContext().getResponse();
response.sendRedirect("somePage.jsp");

How do you do exponentiation in C?

use the pow function (it takes floats/doubles though).

man pow:

   #include <math.h>

   double pow(double x, double y);
   float powf(float x, float y);
   long double powl(long double x, long double y);

EDIT: For the special case of positive integer powers of 2, you can use bit shifting: (1 << x) will equal 2 to the power x. There are some potential gotchas with this, but generally, it would be correct.

Android BroadcastReceiver within Activity

You forget to write .show() at the end, which is used to show the toast message.

Toast.makeText(getApplicationContext(), "received", Toast.LENGTH_SHORT).show();

It is a common mistake that programmer does, but i am sure after this you won't repeat the mistake again... :D

Correct Semantic tag for copyright info - html5

In a link, if you put rel=license it: Indicates that the main content of the current document is covered by the copyright license described by the referenced document. Source: http://www.w3.org/wiki/HTML/Elements/link

So, for example, <a rel="license" href="https://creativecommons.org/licenses/by/4.0/">Copyrighted but you can use what's here as long as you credit me</a> gives a human something to read and lets computers know that the rest of the page is licensed under the CC BY 4.0 license.

When would you use the Builder Pattern?

While going through Microsoft MVC framework, I got a thought about builder pattern. I came across the pattern in the ControllerBuilder class. This class is to return the controller factory class, which is then used to build concrete controller.

Advantage I see in using builder pattern is that, you can create a factory of your own and plug it into the framework.

@Tetha, there can be a restaurant (Framework) run by Italian guy, that serves Pizza. In order to prepare pizza Italian guy (Object Builder) uses Owen (Factory) with a pizza base (base class).

Now Indian guy takes over the restaurant from Italian guy. Indian restaurant (Framework) servers dosa instead of pizza. In order to prepare dosa Indian guy (object builder) uses Frying Pan (Factory) with a Maida (base class)

If you look at scenario, food is different,way food is prepared is different, but in the same restaurant (under same framework). Restaurant should be build in such a way that it can support Chinese, Mexican or any cuisine. Object builder inside framework facilitates to plugin kind of cuisine you want. for example

class RestaurantObjectBuilder
{
   IFactory _factory = new DefaultFoodFactory();

   //This can be used when you want to plugin the 
   public void SetFoodFactory(IFactory customFactory)
   {
        _factory = customFactory;
   }

   public IFactory GetFoodFactory()
   {
      return _factory;
   }
}

How to resolve Error listenerStart when deploying web-app in Tomcat 5.5?

Answered provided by Tom Saleeba is very helpful. Today I also struggled with the same error

Apr 28, 2015 7:53:27 PM org.apache.catalina.core.StandardContext startInternal SEVERE: Error listenerStart

I followed the suggestion and added the logging.properties file. And below was my reason of failure:

java.lang.IllegalStateException: Cannot set web app root system property when WAR file is not expanded

The root cause of the issue was a listener (Log4jConfigListener) that I added into the web.xml. And as per the link SEVERE: Exception org.springframework.web.util.Log4jConfigListener , this listener cannot be added within a WAR that is not expanded.

It may be helpful for someone to know that this was happening on OpenShift JBoss gear.

Fragment transaction animation: slide in and slide out

There is three way to transaction animation in fragment.

Transitions

So need to use one of the built-in Transitions, use the setTranstion() method:

getSupportFragmentManager()
        .beginTransaction()
        .setTransition( FragmentTransaction.TRANSIT_FRAGMENT_OPEN )
        .show( m_topFragment )
        .commit()

Custom Animations

You can also customize the animation by using the setCustomAnimations() method:

getSupportFragmentManager()
        .beginTransaction()
        .setCustomAnimations( R.anim.slide_up, 0, 0, R.anim.slide_down)
        .show( m_topFragment )
        .commit()

slide_up.xml

<?xml version="1.0" encoding="utf-8"?>
<objectAnimator
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:interpolator="@android:anim/accelerate_decelerate_interpolator"
        android:propertyName="translationY"
        android:valueType="floatType"
        android:valueFrom="1280"
        android:valueTo="0"
        android:duration="@android:integer/config_mediumAnimTime"/>

slide_down.xml

<?xml version="1.0" encoding="utf-8"?>
<objectAnimator
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:interpolator="@android:anim/accelerate_decelerate_interpolator"
        android:propertyName="translationY"
        android:valueType="floatType"
        android:valueFrom="0"
        android:valueTo="1280"
        android:duration="@android:integer/config_mediumAnimTime"/>

Multiple Animations

Finally, It's also possible to kick-off multiple fragment animations in a single transaction. This allows for a pretty cool effect where one fragment is sliding up and the other slides down at the same time:

getSupportFragmentManager()
        .beginTransaction()
        .setCustomAnimations( R.anim.abc_slide_in_top, R.anim.abc_slide_out_top ) // Top Fragment Animation
        .show( m_topFragment )
        .setCustomAnimations( R.anim.abc_slide_in_bottom, R.anim.abc_slide_out_bottom ) // Bottom Fragment Animation
        .show( m_bottomFragment )
        .commit()

To more detail you can visit URL

Note:- You can check animation according to your requirement because above may be have issue.

Sending command line arguments to npm script

I find it's possible to just pass variables exactly as you would to Node.js:

// index.js
console.log(process.env.TEST_ENV_VAR)
// package.json
...
"scripts": { "start": "node index.js" },
...
TEST_ENV_VAR=hello npm start

Prints out "hello"

http://localhost/phpMyAdmin/ unable to connect

http://localhost:(port number of phpmyadmin)/phpmyadmin/

For example: http://localhost:8080/phpmyadmin/

It works great!

Index of Currently Selected Row in DataGridView

You can try this code :

int columnIndex = dataGridView.CurrentCell.ColumnIndex;
int rowIndex = dataGridView.CurrentCell.RowIndex;

How can I get Git to follow symlinks?

Conversion from symlinks could be useful. Link in a Git folder instead of a symlink by a script.

Remove non-numeric characters (except periods and commas) from a string

You could use filter_var to remove all illegal characters except digits, dot and the comma.

  • The FILTER_SANITIZE_NUMBER_FLOAT filter is used to remove all non-numeric character from the string.
  • FILTER_FLAG_ALLOW_FRACTION is allowing fraction separator " . "
  • The purpose of FILTER_FLAG_ALLOW_THOUSAND to get comma from the string.

Code

$var1 = '12.322,11T';

echo filter_var($var1, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION | FILTER_FLAG_ALLOW_THOUSAND);

Output

12.322,11

To read more about filter_var() and Sanitize filters

How can I use a carriage return in a HTML tooltip?

I am on firefox 68.7.0esr and the &#013; doesn't work. Breaking the lines via <CR> did work so I am going with that since it simple and forward. i.e.

<option title="Constraint PSC/SCS/Activity
Definition Constraint Checker
Database Start Notifier">CnCk

Sorting arrays in javascript by object key value

Here is yet another one-liner for you:

your_array.sort((a, b) => a.distance === b.distance ? 0 : a.distance > b.distance || -1);

Java 8 Iterable.forEach() vs foreach loop

The better practice is to use for-each. Besides violating the Keep It Simple, Stupid principle, the new-fangled forEach() has at least the following deficiencies:

  • Can't use non-final variables. So, code like the following can't be turned into a forEach lambda:
Object prev = null;
for(Object curr : list)
{
    if( prev != null )
        foo(prev, curr);
    prev = curr;
}
  • Can't handle checked exceptions. Lambdas aren't actually forbidden from throwing checked exceptions, but common functional interfaces like Consumer don't declare any. Therefore, any code that throws checked exceptions must wrap them in try-catch or Throwables.propagate(). But even if you do that, it's not always clear what happens to the thrown exception. It could get swallowed somewhere in the guts of forEach()

  • Limited flow-control. A return in a lambda equals a continue in a for-each, but there is no equivalent to a break. It's also difficult to do things like return values, short circuit, or set flags (which would have alleviated things a bit, if it wasn't a violation of the no non-final variables rule). "This is not just an optimization, but critical when you consider that some sequences (like reading the lines in a file) may have side-effects, or you may have an infinite sequence."

  • Might execute in parallel, which is a horrible, horrible thing for all but the 0.1% of your code that needs to be optimized. Any parallel code has to be thought through (even if it doesn't use locks, volatiles, and other particularly nasty aspects of traditional multi-threaded execution). Any bug will be tough to find.

  • Might hurt performance, because the JIT can't optimize forEach()+lambda to the same extent as plain loops, especially now that lambdas are new. By "optimization" I do not mean the overhead of calling lambdas (which is small), but to the sophisticated analysis and transformation that the modern JIT compiler performs on running code.

  • If you do need parallelism, it is probably much faster and not much more difficult to use an ExecutorService. Streams are both automagical (read: don't know much about your problem) and use a specialized (read: inefficient for the general case) parallelization strategy (fork-join recursive decomposition).

  • Makes debugging more confusing, because of the nested call hierarchy and, god forbid, parallel execution. The debugger may have issues displaying variables from the surrounding code, and things like step-through may not work as expected.

  • Streams in general are more difficult to code, read, and debug. Actually, this is true of complex "fluent" APIs in general. The combination of complex single statements, heavy use of generics, and lack of intermediate variables conspire to produce confusing error messages and frustrate debugging. Instead of "this method doesn't have an overload for type X" you get an error message closer to "somewhere you messed up the types, but we don't know where or how." Similarly, you can't step through and examine things in a debugger as easily as when the code is broken into multiple statements, and intermediate values are saved to variables. Finally, reading the code and understanding the types and behavior at each stage of execution may be non-trivial.

  • Sticks out like a sore thumb. The Java language already has the for-each statement. Why replace it with a function call? Why encourage hiding side-effects somewhere in expressions? Why encourage unwieldy one-liners? Mixing regular for-each and new forEach willy-nilly is bad style. Code should speak in idioms (patterns that are quick to comprehend due to their repetition), and the fewer idioms are used the clearer the code is and less time is spent deciding which idiom to use (a big time-drain for perfectionists like myself!).

As you can see, I'm not a big fan of the forEach() except in cases when it makes sense.

Particularly offensive to me is the fact that Stream does not implement Iterable (despite actually having method iterator) and cannot be used in a for-each, only with a forEach(). I recommend casting Streams into Iterables with (Iterable<T>)stream::iterator. A better alternative is to use StreamEx which fixes a number of Stream API problems, including implementing Iterable.

That said, forEach() is useful for the following:

  • Atomically iterating over a synchronized list. Prior to this, a list generated with Collections.synchronizedList() was atomic with respect to things like get or set, but was not thread-safe when iterating.

  • Parallel execution (using an appropriate parallel stream). This saves you a few lines of code vs using an ExecutorService, if your problem matches the performance assumptions built into Streams and Spliterators.

  • Specific containers which, like the synchronized list, benefit from being in control of iteration (although this is largely theoretical unless people can bring up more examples)

  • Calling a single function more cleanly by using forEach() and a method reference argument (ie, list.forEach (obj::someMethod)). However, keep in mind the points on checked exceptions, more difficult debugging, and reducing the number of idioms you use when writing code.

Articles I used for reference:

EDIT: Looks like some of the original proposals for lambdas (such as http://www.javac.info/closures-v06a.html Google Cache) solved some of the issues I mentioned (while adding their own complications, of course).

How to check if a function exists on a SQL database

Why not just:

IF object_id('YourFunctionName', 'FN') IS NOT NULL
BEGIN
    DROP FUNCTION [dbo].[YourFunctionName]
END
GO

The second argument of object_id is optional, but can help to identify the correct object. There are numerous possible values for this type argument, particularly:

  • FN : Scalar function
  • IF : Inline table-valued function
  • TF : Table-valued-function
  • FS : Assembly (CLR) scalar-function
  • FT : Assembly (CLR) table-valued function

insert vertical divider line between two nested divs, not full height

Can't think of a only css solution, but couldn't you just had a div between those 2 and set in the css the properties to look like a line like shown in the image? If you are using divs as they were table cells this is a pretty simple solution to the problem

How to declare a global variable in php?

If a variable is declared outside of a function its already in global scope. So there is no need to declare. But from where you calling this variable must have access to this variable. If you are calling from inside a function you have to use global keyword:

$variable = 5;

function name()
{
    global $variable;

    $value = $variable + 5;

    return $value;  

}

Using global keyword outside a function is not an error. If you want to include this file inside a function you can declare the variable as global.

config.php

global $variable;

$variable = 5;

other.php

function name()
{
    require_once __DIR__ . '/config.php';
}

You can use $GLOBALS as well. It's a superglobal so it has access everywhere.

$GLOBALS['variable'] = 5;

function name()
{
    echo $GLOBALS['variable'];
}

Depending on your choice you can choose either.

How can I put a database under git (version control)?

Storing each level of database changes under git versioning control is like pushing your entire database with each commit and restoring your entire database with each pull. If your database is so prone to crucial changes and you cannot afford to loose them, you can just update your pre_commit and post_merge hooks. I did the same with one of my projects and you can find the directions here.

Change default timeout for mocha

Adding this for completeness. If you (like me) use a script in your package.json file, just add the --timeout option to mocha:

"scripts": {
  "test": "mocha 'test/**/*.js' --timeout 10000",
  "test-debug": "mocha --debug 'test/**/*.js' --timeout 10000"
},

Then you can run npm run test to run your test suite with the timeout set to 10,000 milliseconds.

z-index not working with position absolute

The second div is position: static (the default) so the z-index does not apply to it.

You need to position (set the position property to anything other than static, you probably want relative in this case) anything you want to give a z-index to.

Difference between 3NF and BCNF in simple terms (must be able to explain to an 8-year old)

This is an old question with valuable answers, but I was still a bit confused until I found a real life example that shows the issue with 3NF. Maybe not suitable for an 8-year old child but hope it helps.

Tomorrow I'll meet the teachers of my eldest daughter in one of those quarterly parent/teachers meetings. Here's what my diary looks like (names and rooms have been changed):

Teacher   | Date             | Room
----------|------------------|-----
Mr Smith  | 2018-12-18 18:15 | A12 
Mr Jones  | 2018-12-18 18:30 | B10 
Ms Doe    | 2018-12-18 18:45 | C21 
Ms Rogers | 2018-12-18 19:00 | A08 

There's only one teacher per room and they never move. If you have a look, you'll see that: (1) for every attribute Teacher, Date, Room, we have only one value per row. (2) super-keys are: (Teacher, Date, Room), (Teacher, Date) and (Date, Room) and candidate keys are obviously (Teacher, Date) and (Date, Room).

(Teacher, Room) is not a superkey because I will complete the table next quarter and I may have a row like this one (Mr Smith did not move!):

Teacher  | Date             | Room
---------|------------------| ----
Mr Smith | 2019-03-19 18:15 | A12

What can we conclude? (1) is an informal but correct formulation of 1NF. From (2) we see that there is no "non prime attribute": 2NF and 3NF are given for free.

My diary is 3NF. Good! No. Not really because no data modeler would accept this in a DB schema. The Room attribute is dependant on the Teacher attribute (again: teachers do not move!) but the schema does not reflect this fact. What would a sane data modeler do? Split the table in two:

Teacher   | Date
----------|-----------------
Mr Smith  | 2018-12-18 18:15
Mr Jones  | 2018-12-18 18:30
Ms Doe    | 2018-12-18 18:45
Ms Rogers | 2018-12-18 19:00

And

Teacher   | Room
----------|-----
Mr Smith  | A12
Mr Jones  | B10
Ms Doe    | C21
Ms Rogers | A08

But 3NF does not deal with prime attributes dependencies. This is the issue: 3NF compliance is not enough to ensure a sound table schema design under some circumstances.

With BCNF, you don't care if the attribute is a prime attribute or not in 2NF and 3NF rules. For every non trivial dependency (subsets are obviously determined by their supersets), the determinant is a complete super key. In other words, nothing is determined by something else than a complete super key (excluding trivial FDs). (See other answers for formal definition).

As soon as Room depends on Teacher, Room must be a subset of Teacher (that's not the case) or Teacher must be a super key (that's not the case in my diary, but thats the case when you split the table).

To summarize: BNCF is more strict, but in my opinion easier to grasp, than 3NF:

  • in most of cases, BCNF is identical to 3NF;
  • in other cases, BCNF is what you think/hope 3NF is.

Hide text using css

This is one way:

h1 {
    text-indent: -9999px;                 /* sends the text off-screen */
    background-image: url(/the_img.png);  /* shows image */
    height: 100px;                        /* be sure to set height & width */
    width: 600px;
    white-space: nowrap;            /* because only the first line is indented */
}

h1 a {
    outline: none;  /* prevents dotted line when link is active */
}

Here is another way to hide the text while avoiding the huge 9999 pixel box that the browser will create:

h1 {
    background-image: url(/the_img.png);  /* shows image */
    height: 100px;                        /* be sure to set height & width */
    width:  600px;

    /* Hide the text. */
    text-indent: 100%;
    white-space: nowrap;
    overflow: hidden;
}

Cast a Double Variable to Decimal

You only use the M for a numeric literal, when you cast it's just:

decimal dtot = (decimal)doubleTotal;

Note that a floating point number is not suited to keep an exact value, so if you first add numbers together and then convert to Decimal you may get rounding errors. You may want to convert the numbers to Decimal before adding them together, or make sure that the numbers aren't floating point numbers in the first place.

"Unable to get the VLookup property of the WorksheetFunction Class" error

I was having the same problem. It seems that passing Me.ComboBox1.Value as an argument for the Vlookup function is causing the issue. What I did was assign this value to a double and then put it into the Vlookup function.

Dim x As Double
x = Me.ComboBox1.Value
Me.TextBox1.Value = Application.WorksheetFunction.VLookup(x, Worksheets("Sheet3").Range("Names"), 2, False) 

Or, for a shorter method, you can just convert the type within the Vlookup function using Cdbl(<Value>).

So it would end up being

Me.TextBox1.Value = Application.WorksheetFunction.VLookup(Cdbl(Me.ComboBox1.Value), Worksheets("Sheet3").Range("Names"), 2, False) 

Strange as it may sound, it works for me.

Hope this helps.

javax.validation.ValidationException: HV000183: Unable to load 'javax.el.ExpressionFactory'

Regarding the Hibernate validator documentation page, you have to define a dependency to a JSR-341 implementation:

<dependency>
   <groupId>org.glassfish</groupId>
   <artifactId>javax.el</artifactId>
   <version>3.0.1-b11</version>
</dependency>

How to fix homebrew permissions?

I tried everything on this page, I ended up using this solution:

brew uninstall --force brew-cask; brew untap $tap_name; brew update; brew cleanup; brew cask cleanup;

My situation was similar to the OP, however my issue was specifically caused by running sudo with brew cask, and then getting my password incorrect. After this, I was stuck with permissions preventing the installation.

Looping from 1 to infinity in Python

Simplest and best:

i = 0
while not there_is_reason_to_break(i):
    # some code here
    i += 1

It may be tempting to choose the closest analogy to the C code possible in Python:

from itertools import count

for i in count():
    if thereIsAReasonToBreak(i):
        break

But beware, modifying i will not affect the flow of the loop as it would in C. Therefore, using a while loop is actually a more appropriate choice for porting that C code to Python.

How to create permanent PowerShell Aliases

UPDATED - January 2021

It's possible to store in a profile.ps1 file any PowerShell code to be executed each time PowerShell starts. There are at least 6 different paths where to store the code depending on which user has to execute it. We will consider only 2 of them: the "all users" and the "only your user" paths (follow the previous link for further options).

To answer your question, you only have to create a profile.ps1 file containing the code you want to be executed, that is:

New-Alias Goto Set-Location

and save it in the proper path:

  • "$Home\Documents" (usually C:\Users<yourname>\Documents): Only your user will execute the code. This is the reccomanded place.
    You can quickly find your profile location by running echo $profile in PowerShell
  • $PsHome (C:\Windows\System32\WindowsPowerShell\v1.0): Every user will execute the code.

IMPORTANT: Remember you need to restart your PowerShell instances to apply the changes.

TIPS

  • If both paths contain a profile.ps1 file, the all-users one is executed first, then the user-specific one. This means the user-specific commands will overwrite variables in case of duplicates or conflicts.

  • Always put the code in the user-specific profile if there is no need to extend its execution to every user. This is safer because you don't pollute other users' space (usually, you don't want to do that).
    Another advantage is that you don't need administrator rights to add the file to your user-space (you do for anything in C:\Windows\System32).

  • If you really need to execute the profile code for every user, mind that the $PsHome path is different for 32bit and 64bit instances of PowerShell. You should consider both environments if you want to always execute the profile code.
    The paths are:

    • C:\Windows\System32\WindowsPowerShell\v1.0 for the 64bit environment
    • C:\Windows\SysWow64\WindowsPowerShell\v1.0 for the 32bit one (Yeah I know, the folder naming is counterintuitive, but it's correct).

How to get number of rows using SqlDataReader in C#

to complete of Pit answer and for better perfromance : get all in one query and use NextResult method.

using (var sqlCon = new SqlConnection("Server=127.0.0.1;Database=MyDb;User Id=Me;Password=glop;"))
{
    sqlCon.Open();
    var com = sqlCon.CreateCommand();
    com.CommandText = "select * from BigTable;select @@ROWCOUNT;";
    using (var reader = com.ExecuteReader())
    {
        while(reader.read()){
            //iterate code
        }
        int totalRow = 0 ;
        reader.NextResult(); // 
        if(reader.read()){
            totalRow = (int)reader[0];
        }
    }
    sqlCon.Close();
}

Switching to landscape mode in Android Emulator

10 years later, I run into the same problem... For me, the issue is that it was literally disabled in my emulator.

Go to the running emulator, and drag down from the top menu area to make it show the action buttons and notifications. Those action buttons show what features are enabled/disabled, like Wifi, airplane mode, and....rotate.

In my emulator, the 3rd button from the left was the "rotate" button, and it was gray. Once I tapped on it to toggle it on, boom, my app would now switch to landscape mode when I rotated it.

Can you get the number of lines of code from a GitHub repository?

Firefox add-on Github SLOC

I wrote a small firefox addon that prints the number of lines of code on github project pages: Github SLOC

Simple line plots using seaborn

Yes, you can do the same in Seaborn directly. This is done with tsplot() which allows either a single array as input, or two arrays where the other is 'time' i.e. x-axis.

import seaborn as sns

data =  [1,5,3,2,6] * 20
time = range(100)

sns.tsplot(data, time)

enter image description here

Max parallel http connections in a browser?

My understanding is that the connection limit is not changeable on the client side. The connection limit must be changed on the server to have any effect. By default, many servers will only allow 2 connections per unique client.

The client is not the browser, it is the client machine issuing the TCP/IP requests.

To see the effect very clearly, use something like JMeter to fire off a bunch of web service calls to your server host - it will accept the first two and will not accept another until one of the two is completed. The amazing thing about this is that for a SOA shop, this is critical, yet hardly anyone is really aware of it.

Thymeleaf using path variables to th:href

I think you can try this:

<a th:href="${'/category/edit/' + {category.id}}">view</a>

Or if you have "idCategory" this:

<a th:href="${'/category/edit/' + {category.idCategory}}">view</a>

android pinch zoom

In honeycomb, API level 11, it is possible, We can use setScalaX and setScaleY with pivot point
I have explained it here
Zooming a view completely
Pinch Zoom to view completely

How to convert Map keys to array?

Map.keys() returns a MapIterator object which can be converted to Array using Array.from:

let keys = Array.from( myMap.keys() );
// ["a", "b"]

EDIT: you can also convert iterable object to array using spread syntax

let keys =[ ...myMap.keys() ];
// ["a", "b"]

Understanding events and event handlers in C#

Here is a code example which may help:

using System;
using System.Collections.Generic;
using System.Text;

namespace Event_Example
{
  // First we have to define a delegate that acts as a signature for the
  // function that is ultimately called when the event is triggered.
  // You will notice that the second parameter is of MyEventArgs type.
  // This object will contain information about the triggered event.

  public delegate void MyEventHandler(object source, MyEventArgs e);

  // This is a class which describes the event to the class that receives it.
  // An EventArgs class must always derive from System.EventArgs.

  public class MyEventArgs : EventArgs
  {
    private string EventInfo;

    public MyEventArgs(string Text) {
      EventInfo = Text;
    }

    public string GetInfo() {
      return EventInfo;
    }
  }

  // This next class is the one which contains an event and triggers it
  // once an action is performed. For example, lets trigger this event
  // once a variable is incremented over a particular value. Notice the
  // event uses the MyEventHandler delegate to create a signature
  // for the called function.

  public class MyClass
  {
    public event MyEventHandler OnMaximum;

    private int i;
    private int Maximum = 10;

    public int MyValue
    {
      get { return i; }
      set
      {
        if(value <= Maximum) {
          i = value;
        }
        else 
        {
          // To make sure we only trigger the event if a handler is present
          // we check the event to make sure it's not null.
          if(OnMaximum != null) {
            OnMaximum(this, new MyEventArgs("You've entered " +
              value.ToString() +
              ", but the maximum is " +
              Maximum.ToString()));
          }
        }
      }
    }
  }

  class Program
  {
    // This is the actual method that will be assigned to the event handler
    // within the above class. This is where we perform an action once the
    // event has been triggered.

    static void MaximumReached(object source, MyEventArgs e) {
      Console.WriteLine(e.GetInfo());
    }

    static void Main(string[] args) {
      // Now lets test the event contained in the above class.
      MyClass MyObject = new MyClass();
      MyObject.OnMaximum += new MyEventHandler(MaximumReached);
      for(int x = 0; x <= 15; x++) {
        MyObject.MyValue = x;
      }
      Console.ReadLine();
    }
  }
}

Compile Views in ASP.NET MVC

You can use aspnet_compiler for this:

C:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_compiler -v /Virtual/Application/Path/Or/Path/In/IIS/Metabase -p C:\Path\To\Your\WebProject -f -errorstack C:\Where\To\Put\Compiled\Site

where "/Virtual/Application/Path/Or/Path/In/IIS/Metabase" is something like this: "/MyApp" or "/lm/w3svc2/1/root/"

Also there is a AspNetCompiler Task on MSDN, showing how to integrate aspnet_compiler with MSBuild:

<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
    <Target Name="PrecompileWeb">
        <AspNetCompiler
            VirtualPath="/MyWebSite"
            PhysicalPath="c:\inetpub\wwwroot\MyWebSite\"
            TargetPath="c:\precompiledweb\MyWebSite\"
            Force="true"
            Debug="true"
        />
    </Target>
</Project>

How do I find the length of an array?

As others have said, you can use the sizeof(arr)/sizeof(*arr), but this will give you the wrong answer for pointer types that aren't arrays.

template<class T, size_t N>
constexpr size_t size(T (&)[N]) { return N; }

This has the nice property of failing to compile for non-array types (Visual Studio has _countof which does this). The constexpr makes this a compile time expression so it doesn't have any drawbacks over the macro (at least none I know of).

You can also consider using std::array from C++11, which exposes its length with no overhead over a native C array.

C++17 has std::size() in the <iterator> header which does the same and works for STL containers too (thanks to @Jon C).

How to know what the 'errno' means?

Error code 2 means "File/Directory not found". In general, you could use the perror function to print a human readable string.

ORA-00932: inconsistent datatypes: expected - got CLOB

I found that selecting a clob column in CTE caused this explosion. ie

with cte as (
    select
        mytable1.myIntCol,
        mytable2.myClobCol
    from mytable1
    join mytable2 on ...
)
select myIntCol, myClobCol
from cte
where ...

presumably because oracle can't handle a clob in a temporary table.

Because my values were longer than 4K, I couldn't use to_char().
My work around was to select it from the final select, ie

with cte as (
    select
        mytable1.myIntCol
    from mytable1
)
select myIntCol, myClobCol
from cte
join mytable2 on ...
where ...

Too bad if this causes a performance problem.

How to get Printer Info in .NET?

It's been a long time since I've worked in a Windows environment, but I would suggest that you look at using WMI.

Remove leading or trailing spaces in an entire column of data

If it's the same number of characters at the beginning of the cell each time, you can use the text to columns command and select the fixed width option to chop the cell data into two columns. Then just delete the unwanted stuff in the first column.

no operator "<<" matches these operands

It looks like you're comparing strings incorrectly. To compare a string to another, use the std::string::compare function.

Example

     while ((wrong < MAX_WRONG) && (soFar.compare(THE_WORD) != 0)) 

NoSQL Use Case Scenarios or WHEN to use NoSQL

It really is an "it depends" kinda question. Some general points:

  • NoSQL is typically good for unstructured/"schemaless" data - usually, you don't need to explicitly define your schema up front and can just include new fields without any ceremony
  • NoSQL typically favours a denormalised schema due to no support for JOINs per the RDBMS world. So you would usually have a flattened, denormalized representation of your data.
  • Using NoSQL doesn't mean you could lose data. Different DBs have different strategies. e.g. MongoDB - you can essentially choose what level to trade off performance vs potential for data loss - best performance = greater scope for data loss.
  • It's often very easy to scale out NoSQL solutions. Adding more nodes to replicate data to is one way to a) offer more scalability and b) offer more protection against data loss if one node goes down. But again, depends on the NoSQL DB/configuration. NoSQL does not necessarily mean "data loss" like you infer.
  • IMHO, complex/dynamic queries/reporting are best served from an RDBMS. Often the query functionality for a NoSQL DB is limited.
  • It doesn't have to be a 1 or the other choice. My experience has been using RDBMS in conjunction with NoSQL for certain use cases.
  • NoSQL DBs often lack the ability to perform atomic operations across multiple "tables".

You really need to look at and understand what the various types of NoSQL stores are, and how they go about providing scalability/data security etc. It's difficult to give an across-the-board answer as they really are all different and tackle things differently.

For MongoDb as an example, check out their Use Cases to see what they suggest as being "well suited" and "less well suited" uses of MongoDb.

how to force maven to update local repo

Even though this is an old question, I 've stumbled upon this issue multiple times and until now never figured out how to fix it. The update maven indices is a term coined by IntelliJ, and if it still doesn't work after you've compiled the first project, chances are that you are using 2 different maven installations.

Press CTRL+Shift+A to open up the Actions menu. Type Maven and go to Maven Settings. Check the Home Directory to use the same maven as you use via the command line

Iterating over and deleting from Hashtable in Java

You need to use an explicit java.util.Iterator to iterate over the Map's entry set rather than being able to use the enhanced For-loop syntax available in Java 6. The following example iterates over a Map of Integer, String pairs, removing any entry whose Integer key is null or equals 0.

Map<Integer, String> map = ...

Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator();

while (it.hasNext()) {
  Map.Entry<Integer, String> entry = it.next();

  // Remove entry if key is null or equals 0.
  if (entry.getKey() == null || entry.getKey() == 0) {
    it.remove();
  }
}

Make Https call using HttpClient

Simply specify HTTPS in the URI.

new Uri("https://foobar.com/");

Foobar.com will need to have a trusted SSL cert or your calls will fail with untrusted error.

EDIT Answer: ClientCertificates with HttpClient

WebRequestHandler handler = new WebRequestHandler();
X509Certificate2 certificate = GetMyX509Certificate();
handler.ClientCertificates.Add(certificate);
HttpClient client = new HttpClient(handler);

EDIT Answer2: If the server you are connecting to has disabled SSL, TLS 1.0, and 1.1 and you are still running .NET framework 4.5(or below) you need to make a choice

  1. Upgrade to .Net 4.6+ (Supports TLS 1.2 by default)
  2. Add registry changes to instruct 4.5 to connect over TLS1.2 ( See: salesforce writeup for compat and keys to change OR checkout IISCrypto see Ronald Ramos answer comments)
  3. Add application code to manually configure .NET to connect over TLS1.2 (see Ronald Ramos answer)

How to disable button in React.js

I have had a similar problem, turns out we don't need hooks to do these, we can make an conditional render and it will still work fine.

<Button
    type="submit"
    disabled={
        name === "" || email === "" || password === "" ? true : false
    }
    fullWidth
    variant="contained"
    color="primary"
    className={classes.submit}>
    SignUP
</Button>

How the single threaded non blocking IO model works in Node.js

Node.js is built upon libuv, a cross-platform library that abstracts apis/syscalls for asynchronous (non-blocking) input/output provided by the supported OSes (Unix, OS X and Windows at least).

Asynchronous IO

In this programming model open/read/write operation on devices and resources (sockets, filesystem, etc.) managed by the file-system don't block the calling thread (as in the typical synchronous c-like model) and just mark the process (in kernel/OS level data structure) to be notified when new data or events are available. In case of a web-server-like app, the process is then responsible to figure out which request/context the notified event belongs to and proceed processing the request from there. Note that this will necessarily mean you'll be on a different stack frame from the one that originated the request to the OS as the latter had to yield to a process' dispatcher in order for a single threaded process to handle new events.

The problem with the model I described is that it's not familiar and hard to reason about for the programmer as it's non-sequential in nature. "You need to make request in function A and handle the result in a different function where your locals from A are usually not available."

Node's model (Continuation Passing Style and Event Loop)

Node tackles the problem leveraging javascript's language features to make this model a little more synchronous-looking by inducing the programmer to employ a certain programming style. Every function that requests IO has a signature like function (... parameters ..., callback) and needs to be given a callback that will be invoked when the requested operation is completed (keep in mind that most of the time is spent waiting for the OS to signal the completion - time that can be spent doing other work). Javascript's support for closures allows you to use variables you've defined in the outer (calling) function inside the body of the callback - this allows to keep state between different functions that will be invoked by the node runtime independently. See also Continuation Passing Style.

Moreover, after invoking a function spawning an IO operation the calling function will usually return control to node's event loop. This loop will invoke the next callback or function that was scheduled for execution (most likely because the corresponding event was notified by the OS) - this allows the concurrent processing of multiple requests.

You can think of node's event loop as somewhat similar to the kernel's dispatcher: the kernel would schedule for execution a blocked thread once its pending IO is completed while node will schedule a callback when the corresponding event has occured.

Highly concurrent, no parallelism

As a final remark, the phrase "everything runs in parallel except your code" does a decent job of capturing the point that node allows your code to handle requests from hundreds of thousands open socket with a single thread concurrently by multiplexing and sequencing all your js logic in a single stream of execution (even though saying "everything runs in parallel" is probably not correct here - see Concurrency vs Parallelism - What is the difference?). This works pretty well for webapp servers as most of the time is actually spent on waiting for network or disk (database / sockets) and the logic is not really CPU intensive - that is to say: this works well for IO-bound workloads.

Setting Android Theme background color

Okay turned out that I made a really silly mistake. The device I am using for testing is running Android 4.0.4, API level 15.

The styles.xml file that I was editing is in the default values folder. I edited the styles.xml in values-v14 folder and it works all fine now.

Why won't eclipse switch the compiler to Java 8?

<build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.6.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

How to write "Html.BeginForm" in Razor

The following code works fine:

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

and generates as expected:

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

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

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

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

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

Global keyboard capture in C# application

My rep is too low to comment, but concerning the CallbackOnCollectedDelegate exception, I modified the public void SetupKeyboardHooks() in C4d's answer to look like this:

public void SetupKeyboardHooks(out object hookProc)
{
  _globalKeyboardHook = new GlobalKeyboardHook();
  _globalKeyboardHook.KeyboardPressed += OnKeyPressed;


  hookProc = _globalKeyboardHook.GcSafeHookProc;
}

where GcSafeHookProc is just a public getter for _hookProc in OPs

_hookProc = LowLevelKeyboardProc; // we must keep alive _hookProc, because GC is not aware about SetWindowsHookEx behaviour.

and stored the hookProc as a private field in the class calling the SetupKeyboardHooks(...), therefore keeping the reference alive, save from garbage collection, no more CallbackOnCollectedDelegate exception. Seems having this additional reference in the GlobalKeyboardHook class is not sufficient. Maybe make sure that this reference is also disposed when closing your app.

How to extract table as text from the PDF using Python?

If your pdf is text-based and not a scanned document (i.e. if you can click and drag to select text in your table in a PDF viewer), then you can use the module camelot-py with

import camelot
tables = camelot.read_pdf('foo.pdf')

You then can choose how you want to save the tables (as csv, json, excel, html, sqlite), and whether the output should be compressed in a ZIP archive.

tables.export('foo.csv', f='csv', compress=False)

Edit: tabula-py appears roughly 6 times faster than camelot-py so that should be used instead.

import camelot
import cProfile
import pstats
import tabula

cmd_tabula = "tabula.read_pdf('table.pdf', pages='1', lattice=True)"
prof_tabula = cProfile.Profile().run(cmd_tabula)
time_tabula = pstats.Stats(prof_tabula).total_tt

cmd_camelot = "camelot.read_pdf('table.pdf', pages='1', flavor='lattice')"
prof_camelot = cProfile.Profile().run(cmd_camelot)
time_camelot = pstats.Stats(prof_camelot).total_tt

print(time_tabula, time_camelot, time_camelot/time_tabula)

gave

1.8495559890000015 11.057014036000016 5.978199147125147

HTML input - name vs. id

IDs must be unique

...within page DOM element tree so each control is individually accessible by its id on the client side (within browser page) by

  • Javascript scripts loaded in the page
  • CSS styles defined on the page

Having non-unique IDs on your page will still render your page, but it certainly won't be valid. Browsers are quite forgiving when parsing invalid HTML. but don't do that just because it seems that it works.

Names are quite often unique but can be shared

...within page DOM between several controls of the same type (think of radio buttons) so when data gets POSTed to server only a particular value gets sent. So when you have several radio buttons on your page, only the selected one's value gets posted back to server even though there are several related radio button controls with the same name.

Addendum to sending data to server: When data gets sent to server (usually by means of HTTP POST request) all data gets sent as name-value pairs where name is the name of the input HTML control and value is its value as entered/selected by the user. This is always true for non-Ajax requests. In Ajax requests name-value pairs can be independent of HTML input controls on the page, because developers can send whatever they want to the server. Quite often values are also read from input controls, but I'm just trying to say that this is not necessarily the case.

When names can be duplicated

It may sometimes be beneficial that names are shared between controls of any form input type. But when? You didn't state what your server platform may be, but if you used something like Asp.net MVC you get the benefit of automatic data validation (client and server) and also binding sent data to strong types. That means that those names have to match type property names.

Now suppose you have this scenario:

  • you have a view with a list of items of the same type
  • user usually works with one item at a time, so they will only enter data with one item alone and send it to server

So your view's model (since it displays a list) is of type IEnumerable<SomeType> but your server side only accepts one single item of type SomeType.

How about name sharing then?

Each item is wrapped within its own FORM element and input elements within it have the same names so when data gets to the server (from any element) it gets correctly bound to the string type expected by the controller action.

This particular scenario can be seen on my Creative stories mini-site. You won't understand the language, but you can check out those multiple forms and shared names. Never mind that IDs are also duplicated (which is a rule violation) but that could be solved. It just doesn't matter in this case.

Create dynamic variable name

try this one, user json to serialize and deserialize:

 using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Web.Script.Serialization;

    namespace ConsoleApplication1
    {
       public class Program
       {
          static void Main(string[] args)
          {
              object newobj = new object();

              for (int i = 0; i < 10; i++)
              {
                List<int> temp = new List<int>();

                temp.Add(i);
                temp.Add(i + 1);

                 newobj = newobj.AddNewField("item_" + i.ToString(), temp.ToArray());
              }

         }

     }

      public static class DynamicExtention
      {
          public static object AddNewField(this object obj, string key, object value)
          {
              JavaScriptSerializer js = new JavaScriptSerializer();

              string data = js.Serialize(obj);

              string newPrametr = "\"" + key + "\":" + js.Serialize(value);

              if (data.Length == 2)
             {
                 data = data.Insert(1, newPrametr);
              }
            else
              {
                  data = data.Insert(data.Length-1, ","+newPrametr);
              }

              return js.DeserializeObject(data);
          }
      }
   }

Netbeans how to set command line arguments in Java

For passing arguments to Run Project command either you have to set the arguments in the Project properties Run panel

Delete commit on gitlab

We've had similar problem and it was not enough to only remove commit and force push to GitLab.
It was still available in GitLab interface using url:

https://gitlab.example.com/<group>/<project>/commit/<commit hash>

We've had to remove project from GitLab and recreate it to get rid of this commit in GitLab UI.

Is there a way to iterate over a dictionary?

This is iteration using block approach:

    NSDictionary *dict = @{@"key1":@1, @"key2":@2, @"key3":@3};

    [dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        NSLog(@"%@->%@",key,obj);
        // Set stop to YES when you wanted to break the iteration.
    }];

With autocompletion is very fast to set, and you do not have to worry about writing iteration envelope.

What is the simplest way to convert a Java string from all caps (words separated by underscores) to CamelCase (no word separators)?

A simple snnipet:

 public static String camelCase(String in) {
    if (in == null || in.length() < 1) { return ""; } //validate in
    String out = "";
    for (String part : in.toLowerCase().split("_")) {
        if (part.length() < 1) { //validate length
            continue;
        }
        out += part.substring(0, 1).toUpperCase();
        if (part.length() > 1) { //validate length
            out += part.substring(1);
        }
    }
    return out;
}

Simplest way to do grouped barplot

with ggplot2:

library(ggplot2)
Animals <- read.table(
  header=TRUE, text='Category        Reason Species
1   Decline       Genuine      24
2  Improved       Genuine      16
3  Improved Misclassified      85
4   Decline Misclassified      41
5   Decline     Taxonomic       2
6  Improved     Taxonomic       7
7   Decline       Unclear      41
8  Improved       Unclear     117')

ggplot(Animals, aes(factor(Reason), Species, fill = Category)) + 
  geom_bar(stat="identity", position = "dodge") + 
  scale_fill_brewer(palette = "Set1")

Bar Chart

Delegates in swift?

It is not that different from obj-c. First, you have to specify the protocol in your class declaration, like following:

class MyClass: NSUserNotificationCenterDelegate

The implementation will look like following:

// NSUserNotificationCenterDelegate implementation
func userNotificationCenter(center: NSUserNotificationCenter, didDeliverNotification notification: NSUserNotification) {
    //implementation
}

func userNotificationCenter(center: NSUserNotificationCenter, didActivateNotification notification: NSUserNotification) {
    //implementation
}

func userNotificationCenter(center: NSUserNotificationCenter, shouldPresentNotification notification: NSUserNotification) -> Bool {
    //implementation
    return true
}

Of course, you have to set the delegate. For example:

NSUserNotificationCenter.defaultUserNotificationCenter().delegate = self;

How can I use jQuery to make an input readonly?

<html xmlns="http://www.w3.org/1999/xhtml">
<head >
    <title></title>

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

</head>
<body>
    <div>
        <input id="fieldName" name="fieldName" type="text" class="text_box" value="Firstname" />
    </div>
</body>

<script type="text/javascript">
    $(function()
    {
        $('#fieldName').attr('disabled', 'disabled');

    });
</script>
</html>

How to add a href link in PHP?

you have problems with " :

 <a href=<?php echo "'www.someotherwebsite.com'><img src='". url::file_loc('img'). "media/img/twitter.png' style='vertical-align: middle' border='0'></a>"; ?>

Unable to convert MySQL date/time value to System.DateTime

i added both Convert Zero Datetime=True & Allow Zero Datetime=True and it works fine

Why do people say that Ruby is slow?

I would say Ruby is slow because not much effort has been spent in making the interpreter faster. Same applies to Python. Smalltalk is just as dynamic as Ruby or Python but performs better by a magnitude, see http://benchmarksgame.alioth.debian.org. Since Smalltalk was more or less replaced by Java and C# (that is at least 10 years ago) no more performance optimization work had been done for it and Smalltalk is still ways faster than Ruby and Python. The people at Xerox Parc and at OTI/IBM had the money to pay the people that work on making Smalltalk faster. What I don't understand is why Google doesn't spend the money for making Python faster as they are a big Python shop. Instead they spend money on development of languages like Go...

How can I show and hide elements based on selected option with jQuery?

<script>  
$(document).ready(function(){
    $('#colorselector').on('change', function() {
      if ( this.value == 'red')
      {
        $("#divid").show();
      }
      else
      {
        $("#divid").hide();
      }
    });
});
</script>

Do like this for every value

Prevent multiple instances of a given app in .NET?

Normally it's done with a named Mutex (use new Mutex( "your app name", true ) and check the return value), but there's also some support classes in Microsoft.VisualBasic.dll that can do it for you.

Get age from Birthdate

Try this function...

function calculate_age(birth_month,birth_day,birth_year)
{
    today_date = new Date();
    today_year = today_date.getFullYear();
    today_month = today_date.getMonth();
    today_day = today_date.getDate();
    age = today_year - birth_year;

    if ( today_month < (birth_month - 1))
    {
        age--;
    }
    if (((birth_month - 1) == today_month) && (today_day < birth_day))
    {
        age--;
    }
    return age;
}

OR

function getAge(dateString) 
{
    var today = new Date();
    var birthDate = new Date(dateString);
    var age = today.getFullYear() - birthDate.getFullYear();
    var m = today.getMonth() - birthDate.getMonth();
    if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) 
    {
        age--;
    }
    return age;
}

See Demo.

How to convert JSON string to array

$data = json_encode($result, true);

echo $data;

Deserialize a json string to an object in python

If you want to save lines of code and leave the most flexible solution, we can deserialize the json string to a dynamic object:

p = lambda:None
p.__dict__ = json.loads('{"action": "print", "method": "onData", "data": "Madan Mohan"}')


>>>> p.action
output: u'print'

>>>> p.method
output: u'onData'

How can I get a list of all classes within current module in Python?

If you want to have all the classes, that belong to the current module, you could use this :

import sys, inspect
def print_classes():
    is_class_member = lambda member: inspect.isclass(member) and member.__module__ == __name__
    clsmembers = inspect.getmembers(sys.modules[__name__], is_class_member)

If you use Nadia's answer and you were importing other classes on your module, that classes will be being imported too.

So that's why member.__module__ == __name__ is being added to the predicate used on is_class_member. This statement checks that the class really belongs to the module.

A predicate is a function (callable), that returns a boolean value.

Android Studio suddenly cannot resolve symbols

Another very subtle cause:

Multi-flavor library should be compiled in specific way than a normal single-flavored. Otherwise it silently produces cannot resolve symbols error.

Multi flavor app based on multi flavor library in Android Gradle

Determine on iPhone if user has enabled push notifications

Unfortunately none of these solutions provided really solve the problem because at the end of the day the APIs are seriously lacking when it comes to providing the pertinent information. You can make a few guesses however using currentUserNotificationSettings (iOS8+) just isn't sufficient in its current form to really answer the question. Although a lot of the solutions here seem to suggest that either that or isRegisteredForRemoteNotifications is more of a definitive answer it really is not.

Consider this:

with isRegisteredForRemoteNotifications documentation states:

Returns YES if the application is currently registered for remote notifications, taking into account any systemwide settings...

However if you throw a simply NSLog into your app delegate to observe the behavior it is clear this does not behave the way we are anticipating it will work. It actually pertains directly to remote notifications having been activated for this app/device. Once activated for the first time this will always return YES. Even turning them off in settings (notifications) will still result in this returning YES this is because, as of iOS8, an app may register for remote notifications and even send to a device without the user having notifications enabled, they just may not do Alerts, Badges and Sound without the user turning that on. Silent notifications are a good example of something you may continue to do even with notifications turned off.

As far as currentUserNotificationSettings it indicates one of four things:

Alerts are on Badges are on Sound is on None are on.

This gives you absolutely no indication whatsoever about the other factors or the Notification switch itself.

A user may in fact turn off badges, sound and alerts but still have show on lockscreen or in notification center. This user should still be receiving push notifications and be able to see them both on the lock screen and in the notification center. They have the notification switch on. BUT currentUserNotificationSettings will return: UIUserNotificationTypeNone in that case. This is not truly indicative of the users actual settings.

A few guesses one can make:

  • if isRegisteredForRemoteNotifications is NO then you can assume that this device has never successfully registered for remote notifications.
  • after the first time of registering for remote notifications a callback to application:didRegisterUserNotificationSettings: is made containing user notification settings at this time since this is the first time a user has been registered the settings should indicate what the user selected in terms of the permission request. If the settings equate to anything other than: UIUserNotificationTypeNone then push permission was granted, otherwise it was declined. The reason for this is that from the moment you begin the remote registration process the user only has the ability to accept or decline, with the initial settings of an acceptance being the settings you setup during the registration process.

Creating a procedure in mySql with parameters

Its very easy to create procedure in Mysql. Here, in my example I am going to create a procedure which is responsible to fetch all data from student table according to supplied name.

DELIMITER //
CREATE PROCEDURE getStudentInfo(IN s_name VARCHAR(64))
BEGIN
SELECT * FROM student_database.student s where s.sname = s_name;
END//
DELIMITER;

In the above example ,database and table names are student_database and student respectively. Note: Instead of s_name, you can also pass @s_name as global variable.

How to call procedure? Well! its very easy, simply you can call procedure by hitting this command

$mysql> CAll getStudentInfo('pass_required_name');

enter image description here

How to filter by IP address in Wireshark?

You can also limit the filter to only part of the ip address.

E.G. To filter 123.*.*.* you can use ip.addr == 123.0.0.0/8. Similar effects can be achieved with /16 and /24.

See WireShark man pages (filters) and look for Classless InterDomain Routing (CIDR) notation.

... the number after the slash represents the number of bits used to represent the network.

Renaming a branch in GitHub

I've found three commands on how you can change your Git branch name, and these commands are a faster way to do that:

git branch -m old_branch new_branch         # Rename branch locally
git push origin :old_branch                 # Delete the old branch
git push --set-upstream origin new_branch   # Push the new branch, set local branch to track the new remote

If you need step-by-step you can read this great article:

How to Rename Git Local and Remote Branches

How to add CORS request in header in Angular 5

A POST with httpClient in Angular 6 was also doing an OPTIONS request:

Headers General:

Request URL:https://hp-probook/perl-bin/muziek.pl/=/postData
Request Method:OPTIONS
Status Code:200 OK
Remote Address:127.0.0.1:443
Referrer Policy:no-referrer-when-downgrade

My Perl REST server implements the OPTIONS request with return code 200.

The next POST request Header:

Accept:*/*
Accept-Encoding:gzip, deflate, br
Accept-Language:nl-NL,nl;q=0.8,en-US;q=0.6,en;q=0.4
Access-Control-Request-Headers:content-type
Access-Control-Request-Method:POST
Connection:keep-alive
Host:hp-probook
Origin:http://localhost:4200
Referer:http://localhost:4200/
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.109 Safari/537.36

Notice Access-Control-Request-Headers:content-type.

So, my backend perl script uses the following headers:


 -"Access-Control-Allow-Origin" => '*',
 -"Access-Control-Allow-Methods" => 'GET,POST,PATCH,DELETE,PUT,OPTIONS',
 -"Access-Control-Allow-Headers" => 'Origin, Content-Type, X-Auth-Token, content-type',

With this setup the GET and POST worked for me!

How can I fill out a Python string with spaces?

Correct way of doing this would be to use Python's format syntax as described in the official documentation

For this case it would simply be:
'{:10}'.format('hi')
which outputs:
'hi '

Explanation:

format_spec ::=  [[fill]align][sign][#][0][width][,][.precision][type]
fill        ::=  <any character>
align       ::=  "<" | ">" | "=" | "^"
sign        ::=  "+" | "-" | " "
width       ::=  integer
precision   ::=  integer
type        ::=  "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"

Pretty much all you need to know is there ^.

Update: as of python 3.6 it's even more convenient with literal string interpolation!

foo = 'foobar'
print(f'{foo:10} is great!')
# foobar     is great!

VS Code - Search for text in all files in a directory

Select your folder, Press ? + ? + F Don't know about windows but this works for mac :)

How to hide UINavigationBar 1px bottom line

Objective C Answer to Above Question

// removing 1px line of navigation bar

[[UINavigationBar appearance] setBackgroundImage:[[UIImage alloc]init] forBarMetrics:UIBarMetricsDefault];
[[UINavigationBar appearance] setShadowImage:[[UIImage alloc] init]];
[[UINavigationBar appearance] setTranslucent:NO];
[[UINavigationBar appearance] setTintColor:[UIColor yourColor]];

How to remove anaconda from windows completely?

In my computer there wasn't a uninstaller in the Start Menu as well. But it worked it the Control Panel > Programs > Uninstall a Program, and selecting Python(Anaconda64bits) in the menu. (Note that I'm using Win10)

Coerce multiple columns to factors at once

Choose some columns to coerce to factors:

cols <- c("A", "C", "D", "H")

Use lapply() to coerce and replace the chosen columns:

data[cols] <- lapply(data[cols], factor)  ## as.factor() could also be used

Check the result:

sapply(data, class)
#        A         B         C         D         E         F         G 
# "factor" "integer"  "factor"  "factor" "integer" "integer" "integer" 
#        H         I         J 
# "factor" "integer" "integer" 

Embedding JavaScript engine into .NET

Try Javascript .NET. It is hosted on GitHub It was originally hosted on CodePlex, here)

Project discussions: http://javascriptdotnet.codeplex.com/discussions

It implements Google V8. You can compile and run JavaScript directly from .NET code with it, and supply CLI objects to be used by the JavaScript code as well. It generates native code from JavaScript.

Returning an array using C

Your method will return a local stack variable that will fail badly. To return an array, create one outside the function, pass it by address into the function, then modify it, or create an array on the heap and return that variable. Both will work, but the first doesn't require any dynamic memory allocation to get it working correctly.

void returnArray(int size, char *retArray)
{
  // work directly with retArray or memcpy into it from elsewhere like
  // memcpy(retArray, localArray, size); 
}

#define ARRAY_SIZE 20

int main(void)
{
  char foo[ARRAY_SIZE];
  returnArray(ARRAY_SIZE, foo);
}

Can not get a simple bootstrap modal to work

I run into this issue too. I was including bootstrap.js AND bootstrap-modal.js. If you already have bootstrap.js, you don't need to include popover.

Any way to limit border length?

You can define one border per side only. You would have to add an extra element for that!

What __init__ and self do in Python?

In short:

  1. self as it suggests, refers to itself- the object which has called the method. That is, if you have N objects calling the method, then self.a will refer to a separate instance of the variable for each of the N objects. Imagine N copies of the variable a for each object
  2. __init__ is what is called as a constructor in other OOP languages such as C++/Java. The basic idea is that it is a special method which is automatically called when an object of that Class is created

How to get size of mysql database?

If you want the list of all database sizes sorted, you can use :

SELECT * 
FROM   (SELECT table_schema AS `DB Name`, 
           ROUND(SUM(data_length + index_length) / 1024 / 1024, 1) AS `DB Size in MB`
        FROM   information_schema.tables 
        GROUP  BY `DB Name`) AS tmp_table 
ORDER  BY `DB Size in MB` DESC; 

Label axes on Seaborn Barplot

You can also set the title of your chart by adding the title parameter as follows

ax.set(xlabel='common xlabel', ylabel='common ylabel', title='some title')

How to cherry pick from 1 branch to another

When you cherry-pick, it creates a new commit with a new SHA. If you do:

git cherry-pick -x <sha>

then at least you'll get the commit message from the original commit appended to your new commit, along with the original SHA, which is very useful for tracking cherry-picks.

How to make a button redirect to another page using jQuery or just Javascript

You can use:

  location.href = "newpage.html"

in the button's onclick event.

How do I perform an insert and return inserted identity with Dapper?

KB:2019779,"You may receive incorrect values when using SCOPE_IDENTITY() and @@IDENTITY", The OUTPUT clause is the safest mechanism:

string sql = @"
DECLARE @InsertedRows AS TABLE (Id int);
INSERT INTO [MyTable] ([Stuff]) OUTPUT Inserted.Id INTO @InsertedRows
VALUES (@Stuff);
SELECT Id FROM @InsertedRows";

var id = connection.Query<int>(sql, new { Stuff = mystuff}).Single();

How do I print the content of a .txt file in Python?

Opening a file in python for reading is easy:

f = open('example.txt', 'r')

To get everything in the file, just use read()

file_contents = f.read()

And to print the contents, just do:

print (file_contents)

Don't forget to close the file when you're done.

f.close()

Connection reset by peer: mod_fcgid: error reading data from FastCGI server

As already mentioned this could be happening due to fcgi handler permission issues. If you're using suexec - don't forget to check if apache has this module enabled.

Pythonic way to create a long multi-line string

If you don't want a multiline string, but just have a long single line string, you can use parentheses. Just make sure you don't include commas between the string segments (then it will be a tuple).

query = ('SELECT   action.descr as "action", '
         'role.id as role_id,'
         'role.descr as role'
         ' FROM '
         'public.role_action_def,'
         'public.role,'
         'public.record_def, '
         'public.action'
         ' WHERE role.id = role_action_def.role_id AND'
         ' record_def.id = role_action_def.def_id AND'
         ' action.id = role_action_def.action_id AND'
         ' role_action_def.account_id = '+account_id+' AND'
         ' record_def.account_id='+account_id+' AND'
         ' def_id='+def_id)

In a SQL statement like what you're constructing, multiline strings would also be fine. But if the extra white space a multiline string would contain would be a problem, then this would be a good way to achieve what you want.

How to bind an enum to a combobox control in WPF?

I used another solution using MarkupExtension.

  1. I made class which provides items source:

    public class EnumToItemsSource : MarkupExtension
    {
        private readonly Type _type;
    
        public EnumToItemsSource(Type type)
        {
            _type = type;
        }
    
        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            return Enum.GetValues(_type)
                .Cast<object>()
                .Select(e => new { Value = (int)e, DisplayName = e.ToString() });
        }
    }
    
  2. That's almost all... Now use it in XAML:

        <ComboBox DisplayMemberPath="DisplayName"
              ItemsSource="{persons:EnumToItemsSource {x:Type enums:States}}"
              SelectedValue="{Binding Path=WhereEverYouWant}"
              SelectedValuePath="Value" />
    
  3. Change 'enums:States' to your enum

Single-threaded apartment - cannot instantiate ActiveX control

Go ahead and add [STAThread] to the main entry of your application, this indicates the COM threading model is single-threaded apartment (STA)

example:

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new WebBrowser());
    }
}

Determining if a number is prime

//simple function to determine if a number is a prime number
//to state if it is a prime number


#include <iostream>

using namespace std;


int isPrime(int x);  //functioned defined after int main()


int main()
{
 int y;
    cout<<"enter value"<<endl;

    cin>>y;

    isPrime(y);    

  return 0;

 } //end of main function


//-------------function

  int isPrime(int x)
 {
   int counter =0;
     cout<<"factors of "<<x<<" are "<<"\n\n";    //print factors of the number

     for (int i =0; i<=x; i++)

     {
       for (int j =0; j<=x; j++)

         {
           if (i * j == x)      //check if the number has multiples;
                {

                  cout<<i<<" ,  ";  //output provided for the reader to see the
                                    // muliples
                  ++counter;        //counts the number of factors

                 }


          }


    }
  cout<<"\n\n";

  if(counter>2) 
     { 
      cout<<"value is not a prime number"<<"\n\n";
     }

  if(counter<=2)
     {
       cout<<"value is a prime number"<<endl;
     }
 }

Fit background image to div

you also use this:

background-size:contain;
height: 0;
width: 100%;
padding-top: 66,64%; 

I don't know your div-values, but let's assume you've got those.

height: auto;
max-width: 600px;

Again, those are just random numbers. It could quite hard to make the background-image (if you would want to) with a fixed width for the div, so better use max-width. And actually it isn't complicated to fill a div with an background-image, just make sure you style the parent element the right way, so the image has a place it can go into.

Chris

How to import functions from different js file in a Vue+webpack+vue-loader project

I was trying to organize my vue app code, and came across this question , since I have a lot of logic in my component and can not use other sub-coponents , it makes sense to use many functions in a separate js file and call them in the vue file, so here is my attempt

1)The Component (.vue file)

//MyComponent.vue file
<template>
  <div>
  <div>Hello {{name}}</div>
  <button @click="function_A">Read Name</button>
  <button @click="function_B">Write Name</button>
  <button @click="function_C">Reset</button>
  <div>{{message}}</div>
  </div>
 </template>


<script>
import Mylib from "./Mylib"; // <-- import
export default {
  name: "MyComponent",
  data() {
    return {
      name: "Bob",
      message: "click on the buttons"
    };
  },
  methods: {
    function_A() {
      Mylib.myfuncA(this); // <---read data
    },
    function_B() {
      Mylib.myfuncB(this); // <---write data
    },
    function_C() {
      Mylib.myfuncC(this); // <---write data
    }
  }
};
</script>

2)The External js file

//Mylib.js
let exports = {};

// this (vue instance) is passed as that , so we
// can read and write data from and to it as we please :)
exports.myfuncA = (that) => {
  that.message =
  "you hit ''myfuncA'' function that is located in Mylib.js  and data.name = " +
    that.name;
};

exports.myfuncB = (that) => {
  that.message =
  "you hit ''myfuncB'' function that is located in Mylib.js and now I will change the name to Nassim";
  that.name = "Nassim"; // <-- change name to Nassim
};

exports.myfuncC = (that) => {
  that.message =
  "you hit ''myfuncC'' function that is located in Mylib.js and now I will change the name back to Bob";
  that.name = "Bob"; // <-- change name to Bob
};

export default exports;

enter image description here 3)see it in action : https://codesandbox.io/s/distracted-pare-vuw7i?file=/src/components/MyComponent.vue


edit

after getting more experience with Vue , I found out that you could use mixins too to split your code into different files and make it easier to code and maintain see https://vuejs.org/v2/guide/mixins.html

How to call a button click event from another method

we have 2 form in this project. in main form change

private void button1_Click(object sender, EventArgs e) { // work }

to

public void button1_Click(object sender, EventArgs e) { // work }

and in other form, when we need above function

        private void button2_Click(object sender, EventArgs e)
    {
        main_page() obj = new main_page();
        obj.button2_Click(sender, e);
    }

What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?

You'll also get this error if you forget a new:

String s = String();

versus

String s = new String();

because the call without the new keyword will try and look for a (local) method called String without arguments - and that method signature is likely not defined.

Why am I getting "Thread was being aborted" in ASP.NET?

Nope, ThreadAbortException is thrown by a simple Response.Redirect

Guid is all 0's (zeros)?

In the spirit of being complete, the answers that instruct you to use Guid.NewGuid() are correct.

In addressing your subsequent edit, you'll need to post the code for your RequestObject class. I'm suspecting that your guid property is not marked as a DataMember, and thus is not being serialized over the wire. Since default(Guid) is the same as new Guid() (i.e. all 0's), this would explain the behavior you're seeing.

Alphanumeric, dash and underscore but no spaces regular expression check JavaScript

Try this

"[A-Za-z0-9_-]+"

Should allow underscores and hyphens

How to make a deep copy of Java ArrayList

Cloning the objects before adding them. For example, instead of newList.addAll(oldList);

for(Person p : oldList) {
    newList.add(p.clone());
}

Assuming clone is correctly overriden inPerson.

Check if registry key exists using VBScript

I found the solution.

dim bExists
ssig="Unable to open registry key"

set wshShell= Wscript.CreateObject("WScript.Shell")
strKey = "HKEY_USERS\.Default\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Digest\"
on error resume next
present = WshShell.RegRead(strKey)
if err.number<>0 then
    if right(strKey,1)="\" then    'strKey is a registry key
        if instr(1,err.description,ssig,1)<>0 then
            bExists=true
        else
            bExists=false
        end if
    else    'strKey is a registry valuename
        bExists=false
    end if
    err.clear
else
    bExists=true
end if
on error goto 0
if bExists=vbFalse then
    wscript.echo strKey & " does not exist."
else
    wscript.echo strKey & " exists."
end if

In DB2 Display a table's definition

DB2 Version 11.0

Columns:
--------
SELECT NAME,COLTYPE,NULLS,LENGTH,SCALE,DEFAULT,DEFAULTVALUE FROM SYSIBM.SYSCOLUMNS where TBcreator ='ME' and TBNAME ='MY_TABLE' ORDER BY COLNO;

Indexes:
--------
SELECT P.SPACE, K.IXNAME, I.UNIQUERULE, I.CLUSTERING, K.COLNAME, K.COLNO, K.ORDERING
FROM SYSIBM.SYSINDEXES I
    JOIN SYSIBM.SYSINDEXPART P
        ON I.NAME = P.IXNAME
        AND I.CREATOR = P.IXCREATOR
    JOIN SYSIBM.SYSKEYS K
        ON P.IXNAME = K.IXNAME
        AND P.IXCREATOR = K.IXCREATOR
WHERE I.TBcreator ='ME' and I.TBNAME ='MY_TABLE'
ORDER BY K.IXNAME, K.COLSEQ;

Get each line from textarea

It works for me:

if (isset($_POST['MyTextAreaName'])){
    $array=explode( "\r\n", $_POST['MyTextAreaName'] );

now, my $array will have all the lines I need

    for ($i = 0; $i <= count($array); $i++) 
    {
        echo (trim($array[$i]) . "<br/>");
    }

(make sure to close the if block with another curly brace)

}

How to get Activity's content view?

There is no "isContentViewSet" method. You may put some dummy requestWindowFeature call into try/catch block before setContentView like this:

try {
  requestWindowFeature(Window.FEATURE_CONTEXT_MENU);
  setContentView(...)
} catch (AndroidRuntimeException e) {
  // do smth or nothing
}

If content view was already set, requestWindowFeature will throw an exception.

macro run-time error '9': subscript out of range

"Subscript out of range" indicates that you've tried to access an element from a collection that doesn't exist. Is there a "Sheet1" in your workbook? If not, you'll need to change that to the name of the worksheet you want to protect.

Setting a divs background image to fit its size?

You could use the CSS3 background-size property for this.

.header .logo {
background-size: 100%;
}

How do I remove a substring from the end of a string in Python?

I used the built-in rstrip function to do it like follow:

string = "test.com"
suffix = ".com"
newstring = string.rstrip(suffix)
print(newstring)
test

How to debug external class library projects in visual studio?

This has bugged me for some time. What I usually end up doing is rebuilding my external library using debug mode, then copy both .dll and the .pdb file to the bin of my website. This allows me to step into the libarary code.

When should I use "this" in a class?

this is a reference to the current object. It is used in the constructor to distinguish between the local and the current class variable which have the same name. e.g.:

public class circle {
    int x;
    circle(int x){
        this.x =x;
        //class variable =local variable 
    }
} 

this can also be use to call one constructor from another constructor. e.g.:

public class circle {
    int x;

    circle() { 
        this(1);
    }

    circle(int x) {
        this.x = x; 
    }
}

best practice font size for mobile

The font sizes in your question are an example of what ratio each header should be in comparison to each other, rather than what size they should be themselves (in pixels).

So in response to your question "Is there a 'best practice' for these for mobile phones? - say iphone screen size?", yes there probably is - but you might find what someone says is "best practice" does not work for your layout.

However, to help get you on the right track, this article about building responsive layouts provides a good example of how to calculate the base font-size in pixels in relation to device screen sizes.

The suggested font-sizes for screen resolutions suggested from that article are as follows:

@media (min-width: 858px) {
    html {
        font-size: 12px;
    }
}

@media (min-width: 780px) {
    html {
        font-size: 11px;
    }
}

@media (min-width: 702px) {
    html {
        font-size: 10px;
    }
}

@media (min-width: 724px) {
    html {
        font-size: 9px;
    }
}

@media (max-width: 623px) {
    html {
        font-size: 8px;
    }
}

Text Editor which shows \r\n?

If you have Mathematica, you can try with this command:

ReadList["filename.txt", Record, RecordSeparators -> {}] // InputForm

That will show all the /r and /n

Difference between DOMContentLoaded and load events

  • domContentLoaded: marks the point when both the DOM is ready and there are no stylesheets that are blocking JavaScript execution - meaning we can now (potentially) construct the render tree. Many JavaScript frameworks wait for this event before they start executing their own logic. For this reason the browser captures the EventStart and EventEnd timestamps to allow us to track how long this execution took.

  • loadEvent: as a final step in every page load the browser fires an “onload” event which can trigger additional application logic.

source

What is the difference between “int” and “uint” / “long” and “ulong”?

u means unsigned, so ulong is a large number without sign. You can store a bigger value in ulong than long, but no negative numbers allowed.

A long value is stored in 64-bit,with its first digit to show if it's a positive/negative number. while ulong is also 64-bit, with all 64 bit to store the number. so the maximum of ulong is 2(64)-1, while long is 2(63)-1.

How to make a JFrame Modal in Swing java

The only code that have worked for me:

childFrame.setAlwaysOnTop(true);

This code should be called on the main/parent frame before making the child/modal frame visible. Your child/modal frame should also have this code:

parentFrame.setFocusableWindowState(false);
this.mainFrame.setEnabled(false);

Function that creates a timestamp in c#

You could use the DateTime.Ticks property, which is a long and universal storable, always increasing and usable on the compact framework as well. Just make sure your code isn't used after December 31st 9999 ;)

"Use of undeclared type" in Swift, even though type is internal, and exists in same module

Sometimes errors can be very silly

Before checking all the solutions up here , make sure you have imported all the basic stuff

     import Foundation
     import UIKit

It is quite a possibility that when you import some files from outside to your project, which may miss this basic things as I experienced once .

Java, looping through result set

Result Set are actually contains multiple rows of data, and use a cursor to point out current position. So in your case, rs4.getString(1) only get you the data in first column of first row. In order to change to next row, you need to call next()

a quick example

while (rs.next()) {
    String sid = rs.getString(1);
    String lid = rs.getString(2);
    // Do whatever you want to do with these 2 values
}

there are many useful method in ResultSet, you should take a look :)

How to call a function after a div is ready?

Thus far, the only way to "listen" on DOM events, like inserting or modifying Elements, was to use the such called Mutation Events. For instance

document.body.addEventListener('DOMNodeInserted', function( event ) {
    console.log('whoot! a new Element was inserted, see my event object for details!');
}, false);

Further reading on that: MDN

The Problem with Mutation Events was (is) they never really made their way into any official spec because of inconcistencies and stuff. After a while, this events were implemented in all modern browser, but they were declared as deprecated, in other words you don't want to use them.


The official replacement for the Mutation Events is the MutationObserver() object.

Further reading on that: MDN

The syntax at present looks like

var observer = new MutationObserver(function( mutations ) {
    mutations.forEach(function( mutation ) {
         console.log( mutation.type );
    }); 
});

var config = { childList: true };

observer.observe( document.body, config );

At this time, the API has been implemented in newer Firefox, Chrome and Safari versions. I'm not sure about IE and Opera. So the tradeoff here is definitely that you can only target for topnotch browsers.

Detect when browser receives file download

In my experience, there are two ways to handle this:

  1. Set a short-lived cookie on the download, and have JavaScript continually check for its existence. Only real issue is getting the cookie lifetime right - too short and the JS can miss it, too long and it might cancel the download screens for other downloads. Using JS to remove the cookie upon discovery usually fixes this.
  2. Download the file using fetch/XHR. Not only do you know exactly when the file download finishes, if you use XHR you can use progress events to show a progress bar! Save the resulting blob with msSaveBlob in IE/Edge and a download link (like this one) in Firefox/Chrome. The problem with this method is that iOS Safari doesn't seem to handle downloading blobs right - you can convert the blob into a data URL with a FileReader and open that in a new window, but that's opening the file, not saving it.

Conditional WHERE clause in SQL Server

To answer the underlying question of how to use a CASE expression in the WHERE clause:

First remember that the value of a CASE expression has to have a normal data type value, not a boolean value. It has to be a varchar, or an int, or something. It's the same reason you can't say SELECT Name, 76 = Age FROM [...] and expect to get 'Frank', FALSE in the result set.

Additionally, all expressions in a WHERE clause need to have a boolean value. They can't have a value of a varchar or an int. You can't say WHERE Name; or WHERE 'Frank';. You have to use a comparison operator to make it a boolean expression, so WHERE Name = 'Frank';

That means that the CASE expression must be on one side of a boolean expression. You have to compare the CASE expression to something. It can't stand by itself!

Here:

WHERE 
    DateDropped = 0
    AND CASE
            WHEN @JobsOnHold  = 1 AND DateAppr >= 0 THEN 'True'
            WHEN DateAppr != 0 THEN 'True'
            ELSE 'False'
        END = 'True'

Notice how in the end the CASE expression on the left will turn the boolean expression into either 'True' = 'True' or 'False' = 'True'.

Note that there's nothing special about 'False' and 'True'. You can use 0 and 1 if you'd rather, too.

You can typically rewrite the CASE expression into boolean expressions we're more familiar with, and that's generally better for performance. However, sometimes is easier or more maintainable to use an existing expression than it is to convert the logic.

Combating AngularJS executing controller twice

AngularJS docs - ngController
Note that you can also attach controllers to the DOM by declaring it in a route definition via the $route service. A common mistake is to declare the controller again using ng-controller in the template itself. This will cause the controller to be attached and executed twice.

When you use ngRoute with the ng-view directive, the controller gets attached to that dom element by default (or ui-view if you use ui-router). So you will not need to attach it again in the template.

Difference between int32, int, int32_t, int8 and int8_t

Always keep in mind that 'size' is variable if not explicitly specified so if you declare

 int i = 10;

On some systems it may result in 16-bit integer by compiler and on some others it may result in 32-bit integer (or 64-bit integer on newer systems).

In embedded environments this may end up in weird results (especially while handling memory mapped I/O or may be consider a simple array situation), so it is highly recommended to specify fixed size variables. In legacy systems you may come across

 typedef short INT16;
 typedef int INT32;
 typedef long INT64; 

Starting from C99, the designers added stdint.h header file that essentially leverages similar typedefs.

On a windows based system, you may see entries in stdin.h header file as

 typedef signed char       int8_t;
 typedef signed short      int16_t;
 typedef signed int        int32_t;
 typedef unsigned char     uint8_t;

There is quite more to that like minimum width integer or exact width integer types, I think it is not a bad thing to explore stdint.h for a better understanding.

Format JavaScript date as yyyy-mm-dd

I use this way to get the date in format yyyy-mm-dd :)

var todayDate = new Date().toISOString().slice(0,10);

Javascript seconds to minutes and seconds

A one liner (doesnt work with hours):

 function sectostr(time) {
    return ~~(time / 60) + ":" + (time % 60 < 10 ? "0" : "") + time % 60;
 }

How do I create the small icon next to the website tab for my site?

It is called favicon.ico and you can generate it from this site.

http://www.favicon.cc/

What is the difference between parseInt() and Number()?

Because none mentioned, when using Number and parseInt with numeric separator, they also behave differently:

const num1 = 5_0; // 50
const num2 = Number(5_0); // 50
const num3 = Number("5_0"); // NaN
const num4 = parseInt(5_0); // 50
const num5 = parseInt("5_0"); // 5

Multiline string literal in C#

As a side-note, with C# 6.0 you can now combine interpolated strings with the verbatim string literal:

string camlCondition = $@"
<Where>
    <Contains>
        <FieldRef Name='Resource'/>
        <Value Type='Text'>{(string)parameter}</Value>
    </Contains>
</Where>";

'printf' vs. 'cout' in C++

printf is a function whereas cout is a variable.

cmake and libpthread

target_compile_options solution above is wrong, it won't link the library.

Use:

SET(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} -pthread")

OR

target_link_libraries(XXX PUBLIC pthread)

OR

set_target_properties(XXX PROPERTIES LINK_LIBRARIES -pthread)

using batch echo with special characters

You can escape shell metacharacters with ^:

echo ^<?xml version="1.0" encoding="utf-8" ?^> > myfile.xml

Note that since echo is a shell built-in it doesn't follow the usual conventions regarding quoting, so just quoting the argument will output the quotes instead of removing them.

Disabling SSL Certificate Validation in Spring RestTemplate

If you are using rest template, you can use this piece of code

    fun getClientHttpRequestFactory(): ClientHttpRequestFactory {
        val timeout = envTimeout.toInt()
        val config = RequestConfig.custom()
            .setConnectTimeout(timeout)
            .setConnectionRequestTimeout(timeout)
            .setSocketTimeout(timeout)
            .build()

        val acceptingTrustStrategy = TrustStrategy { chain: Array<X509Certificate?>?, authType: String? -> true }

        val sslContext: SSLContext = SSLContexts.custom()
            .loadTrustMaterial(null, acceptingTrustStrategy)
            .build()

        val csf = SSLConnectionSocketFactory(sslContext)

        val client = HttpClientBuilder
            .create()
            .setDefaultRequestConfig(config)
            .setSSLSocketFactory(csf)
            .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
            .build()
        return HttpComponentsClientHttpRequestFactory(client)
    }

    @Bean
    fun getRestTemplate(): RestTemplate {
        return RestTemplate(getClientHttpRequestFactory())
    }

A SELECT statement that assigns a value to a variable must not be combined with data-retrieval operations

declare @cur cursor
declare @idx int       
declare @Approval_No varchar(50) 

declare @ReqNo varchar(100)
declare @M_Id  varchar(100)
declare @Mail_ID varchar(100)
declare @temp  table
(
val varchar(100)
)
declare @temp2  table
(
appno varchar(100),
mailid varchar(100),
userod varchar(100)
)


    declare @slice varchar(8000)       
    declare @String varchar(100)
    --set @String = '1200096,1200095,1200094,1200093,1200092,1200092'
set @String = '20131'


    select @idx = 1       
        if len(@String)<1 or @String is null  return       

    while @idx!= 0       
    begin       
        set @idx = charindex(',',@String)       
        if @idx!=0       
            set @slice = left(@String,@idx - 1)       
        else       
            set @slice = @String

            --select @slice       
            insert into @temp values(@slice)
        set @String = right(@String,len(@String) - @idx)       
        if len(@String) = 0 break


    end
    -- select distinct(val) from @temp


SET @cur = CURSOR FOR select distinct(val) from @temp


--open cursor    
OPEN @cur    
--fetchng id into variable    
FETCH NEXT    
    FROM @cur into @Approval_No 

      --
    --loop still the end    
     while @@FETCH_STATUS = 0  
    BEGIN   


select distinct(Approval_Sr_No) as asd, @ReqNo=Approval_Sr_No,@M_Id=AM_ID,@Mail_ID=Mail_ID from WFMS_PRAO,WFMS_USERMASTER where  WFMS_PRAO.AM_ID=WFMS_USERMASTER.User_ID
and Approval_Sr_No=@Approval_No

   insert into @temp2 values(@ReqNo,@M_Id,@Mail_ID)  

FETCH NEXT    
      FROM @cur into @Approval_No    
 end  
    --close cursor    
    CLOSE @cur    

select * from @tem

How can I echo HTML in PHP?

Try this:

<?php
    echo <<<HTML

    Your HTML tags here

HTML;
?>

How to set custom header in Volley Request

You can make a custom Request class that extends the StringRequest and override the getHeaders() method inside it like this:

public class CustomVolleyRequest extends StringRequest {

    public CustomVolleyRequest(int method, String url,
                           Response.Listener<String> listener,
                           Response.ErrorListener errorListener) {
        super(method, url, listener, errorListener);
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        Map<String, String> headers = new HashMap<>();
        headers.put("key1","value1");
        headers.put("key2","value2");
        return headers;
    }
}

stdlib and colored output in C

You can output special color control codes to get colored terminal output, here's a good resource on how to print colors.

For example:

printf("\033[22;34mHello, world!\033[0m");  // shows a blue hello world

EDIT: My original one used prompt color codes, which doesn't work :( This one does (I tested it).

How to create hyperlink to call phone number on mobile devices?

You can also use callto:########### replacing the email code mail with call, at least according to W3Cschool site but I haven't had an opportunity to test it out.

Sending data through POST request from a node.js server to a node.js server

You can also use Requestify, a really cool and very simple HTTP client I wrote for nodeJS + it supports caching.

Just do the following for executing a POST request:

var requestify = require('requestify');

requestify.post('http://example.com', {
    hello: 'world'
})
.then(function(response) {
    // Get the response body (JSON parsed or jQuery object for XMLs)
    response.getBody();
});

PHP 5 disable strict standards error

All above solutions are correct. But, when we are talking about a normal PHP application, they have to included in every page, that it requires. A way to solve this, is through .htaccess at root folder. Just to hide the errors. [Put one of the followling lines in the file]

php_flag display_errors off

Or

php_value display_errors 0

Next, to set the error reporting

php_value error_reporting 30719

If you are wondering how the value 30719 came, E_ALL (32767), E_STRICT (2048) are actually constant that hold numeric value and (32767 - 2048 = 30719)

permission denied - php unlink

You (as in the process that runs b.php, either you through CLI or a webserver) need write access to the directory in which the files are located. You are updating the directory content, so access to the file is not enough.

Note that if you use the PHP chmod() function to set the mode of a file or folder to 777 you should use 0777 to make sure the number is correctly interpreted as an octal number.

Increase bootstrap dropdown menu width

Add the following css class

.dropdown-menu {
    width: 300px !important;
    height: 400px !important;
}

Of course you can use what matches your need.

Is embedding background image data into CSS as Base64 good or bad practice?

It's not a good idea when you want your images and style information to be cached separately. Also if you encode a large image or a significant number of images in to your css file it will take the browser longer to download the file leaving your site without any of the style information until the download completes. For small images that you don't intend on changing often if ever it is a fine solution.

as far as generating the base64 encoding:

How to hide .php extension in .htaccess

1) Are you sure mod_rewrite module is enabled? Check phpinfo()

2) Your above rule assumes the URL starts with "folder". Is this correct? Did you acutally want to have folder in the URL? This would match a URL like:

/folder/thing -> /folder/thing.php

If you actually want

/thing -> /folder/thing.php

You need to drop the folder from the match expression.

I usually use this to route request to page without php (but yours should work which leads me to think that mod_rewrite may not be enabled):

RewriteRule ^([^/\.]+)/?$ $1.php  [L,QSA]

3) Assuming you are declaring your rules in an .htaccess file, does your installation allow for setting Options (AllowOverride) overrides in .htaccess files? Some shared hosts do not.

When the server finds an .htaccess file (as specified by AccessFileName) it needs to know which directives declared in that file can override earlier access information.

Xampp MySQL not starting - "Attempting to start MySQL service..."

If you have MySQL already installed on your windows then go to services.msc file on your windows and right click the MySQL file and stop the service, now open your XAMPP and start MySQL. Now MySQL will start on the port 3306.

How to remove tab indent from several lines in IDLE?

By default, IDLE has it on Shift-Left Bracket. However, if you want, you can customise it to be Shift-Tab by clicking Options --> Configure IDLE --> Keys --> Use a Custom Key Set --> dedent-region --> Get New Keys for Selection

Then you can choose whatever combination you want. (Don't forget to click apply otherwise all the settings would not get affected.)

git repo says it's up-to-date after pull but files are not updated

For me my forked branch was not in sync with the master branch. So I went to bitbucket and synced and merged my forked branch and then tried to take the pull. Then it worked fine.

Make xargs execute the command once for each line of input

find path -type f | xargs -L1 command 

is all you need.

Get java.nio.file.Path object from java.io.File

From the documentation:

Paths associated with the default provider are generally interoperable with the java.io.File class. Paths created by other providers are unlikely to be interoperable with the abstract path names represented by java.io.File. The toPath method may be used to obtain a Path from the abstract path name represented by a java.io.File object. The resulting Path can be used to operate on the same file as the java.io.File object. In addition, the toFile method is useful to construct a File from the String representation of a Path.

(emphasis mine)

So, for toFile:

Returns a File object representing this path.

And toPath:

Returns a java.nio.file.Path object constructed from the this abstract path.

Python Anaconda - How to Safely Uninstall

In my case Anaconda3 was not installed in home directory. Instead, it was installed in root. Therefore, I had to do the following to get it uninstalled:

sudo rm -rf /anaconda3/bin/python

Is there a way to create multiline comments in Python?

From the accepted answer...

You can use triple-quoted strings. When they're not a docstring (first thing in a class/function/module), they are ignored.

This is simply not true. Unlike comments, triple-quoted strings are still parsed and must be syntactically valid, regardless of where they appear in the source code.

If you try to run this code...

def parse_token(token):
    """
    This function parses a token.
    TODO: write a decent docstring :-)
    """

    if token == '\\and':
        do_something()

    elif token == '\\or':
        do_something_else()

    elif token == '\\xor':
        '''
        Note that we still need to provide support for the deprecated
        token \xor. Hopefully we can drop support in libfoo 2.0.
        '''
        do_a_different_thing()

    else:
        raise ValueError

You'll get either...

ValueError: invalid \x escape

...on Python 2.x or...

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 79-80: truncated \xXX escape

...on Python 3.x.

The only way to do multi-line comments which are ignored by the parser is...

elif token == '\\xor':
    # Note that we still need to provide support for the deprecated
    # token \xor. Hopefully we can drop support in libfoo 2.0.
    do_a_different_thing()

How to prevent sticky hover effects for buttons on touch devices

This is what I have come up with so far after studying the rest of the answers. It should be able to support touch-only, mouse-only or hybrid users.

Create a separate hover class for the hover effect. By default, add this hover class to our button.

We do not want to detect the presence of touch support and disable all hover effects from the very beginning. As mentioned by others, hybrid devices are gaining popularity; people may have touch support but want to use a mouse and vice versa. Therefore, only remove the hover class when the user actually touches the button.

The next problem is, what if the user wants to go back to using a mouse after touching the button? To solve that, we need to find an opportune moment to add back the hover class which we have removed.

However, we cannot add it back immediately after removing it, because the hover state is still active. We may not want to destroy and recreate the entire button as well.

So, I thought of using a busy-waiting algorithm (using setInterval) to check the hover state. Once the hover state is deactivated, we can then add back the hover class and stop the busy-waiting, bringing us back to the original state where the user can use either mouse or touch.

I know busy-waiting isn't that great but I'm not sure if there is an appropriate event. I've considered to add it back in the mouseleave event, but it was not very robust. For example, when an alert pops up after the button is touched, the mouse position shifts but the mouseleave event is not triggered.

_x000D_
_x000D_
var button = document.getElementById('myButton');_x000D_
_x000D_
button.ontouchstart = function(e) {_x000D_
  console.log('ontouchstart');_x000D_
  $('.button').removeClass('button-hover');_x000D_
  startIntervalToResetHover();_x000D_
};_x000D_
_x000D_
button.onclick = function(e) {_x000D_
  console.log('onclick');_x000D_
}_x000D_
_x000D_
var intervalId;_x000D_
_x000D_
function startIntervalToResetHover() {_x000D_
  // Clear the previous one, if any._x000D_
  if (intervalId) {_x000D_
    clearInterval(intervalId);_x000D_
  }_x000D_
  _x000D_
  intervalId = setInterval(function() {_x000D_
    // Stop if the hover class already exists._x000D_
    if ($('.button').hasClass('button-hover')) {_x000D_
      clearInterval(intervalId);_x000D_
      intervalId = null;_x000D_
      return;_x000D_
    }_x000D_
    _x000D_
    // Checking of hover state from _x000D_
    // http://stackoverflow.com/a/8981521/2669960._x000D_
    var isHovered = !!$('.button').filter(function() {_x000D_
      return $(this).is(":hover");_x000D_
    }).length;_x000D_
    _x000D_
    if (isHovered) {_x000D_
      console.log('Hover state is active');_x000D_
    } else {_x000D_
      console.log('Hover state is inactive');_x000D_
      $('.button').addClass('button-hover');_x000D_
      console.log('Added back the button-hover class');_x000D_
      _x000D_
      clearInterval(intervalId);_x000D_
      intervalId = null;_x000D_
    }_x000D_
  }, 1000);_x000D_
}
_x000D_
.button {_x000D_
  color: green;_x000D_
  border: none;_x000D_
}_x000D_
_x000D_
.button-hover:hover {_x000D_
  background: yellow;_x000D_
  border: none;_x000D_
}_x000D_
_x000D_
.button:active {_x000D_
  border: none;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button id='myButton' class='button button-hover'>Hello</button>
_x000D_
_x000D_
_x000D_

Edit: Another approach I tried is to call e.preventDefault() within ontouchstart or ontouchend. It appears to stop the hover effect when the button is touched, but it also stops the button click animation and prevents the onclick function from being called when the button is touched, so you have to call those manually in the ontouchstart or ontouchend handler. Not a very clean solution.

Removing spaces from string

Try this:

String urle = HOST + url + value;

Then return the values from:

urle.replace(" ", "%20").trim();

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

In addition to Trevor Burnham's answer if you want to deal with disabled javascript and defer css loading

HTML5

<html class="no-js">

    <head>...</head>

    <body>

        <header>...</header>

        <main>...</main>

        <footer>...</footer>

    </body>

</html>

CSS

//at the beginning of the page

    .js main, .js footer{

        opacity:0;

    }

JAVASCRIPT

//at the beginning of the page before loading jquery

    var h = document.querySelector("html");

    h.className += ' ' + 'js';

    h.className = h.className.replace(
    new RegExp('( |^)' + 'no-js' + '( |$)', 'g'), ' ').trim();

JQUERY

//somewhere at the end of the page after loading jquery

        $(window).load(function() {

            $('main').css('opacity',1);
            $('footer').css('opacity',1);

        });

RESOURCES