Programs & Examples On #Wxhttp

Maximum call stack size exceeded error

The problem with detecting stackoverflows is sometimes the stack trace will unwind and you won't be able to see what's actually going on.

I've found some of Chrome's newer debugging tools useful for this.

Hit the Performance tab, make sure Javascript samples are enabled and you'll get something like this.

It's pretty obvious where the overflow is here! If you click on extendObject you'll be able to actually see the exact line number in the code.

enter image description here

You can also see timings which may or may not be helpful or a red herring.

enter image description here


Another useful trick if you can't actually find the problem is to put lots of console.log statements where you think the problem is. The previous step above can help you with this.

In Chrome if you repeatedly output identical data it will display it like this showing where the problem is more clearly. In this instance the stack hit 7152 frames before it finally crashed:

enter image description here

How to remove close button on the jQuery UI dialog?

None of the above works. The solution that really works is:

$(function(){
  //this is your dialog:
  $('#mydiv').dialog({
    // Step 1. Add an extra class to our dialog to address the dialog directly. Make sure that this class is not used anywhere else:
    dialogClass: 'my-extra-class' 
  })
  // Step 2. Hide the close 'X' button on the dialog that you marked with your extra class
  $('.my-extra-class').find('.ui-dialog-titlebar-close').css('display','none');
  // Step 3. Enjoy your dialog without the 'X' link
})

Please check if it works for you.

How do I clone a generic List in Java?

This should also work:

ArrayList<String> orig = new ArrayList<String>();
ArrayList<String> copy = (ArrayList<String>) orig.clone()

What's the best UI for entering date of birth?

I normally use both -- a datepicker that populates a textfield in the correct format. Advanced users can edit the textfield directly, mouse-happy users can pick using the datepicker.

If you're worried about space, I usually have just the textfield with a little calendar icon next to it. If you click on the calendar icon it brings up the datepicker as a popup.

Also I find it good practice to pre-populate the textfield with text that indicates the correct format (i.e.: "DD/MM/YYYY"). When the user focuses the textfield that text disappears so they can enter their own.

Can an Android App connect directly to an online mysql database

It is actually very easy. But there is no way you can achieve it directly. You need to select a service side technology. You can use anything for this part. And this is what we call a RESTful API or a SOAP API. It depends on you what to select. I have done many project with both. I would prefer REST. So what will happen you will have some scripts in your web server, and you know the URLs. For example we need to make a user registration. And for this we have

mydomain.com/v1/userregister.php

Now from the android side you will send an HTTP request to the above URL. And the above URL will handle the User Registration and will give you a response that whether the operation succeed or not.

For a complete detailed explanation of the above concept. You can visit the following link.

**Android MySQL Tutorial to Perform CRUD Operation**

How to retrieve a module's path?

If you want to retrieve the package's root path from any of its modules, the following works (tested on Python 3.6):

from . import __path__ as ROOT_PATH
print(ROOT_PATH)

The main __init__.py path can also be referenced by using __file__ instead.

Hope this helps!

Controlling fps with requestAnimationFrame?

For throttling FPS to any value, pls see jdmayfields answer. However, for a very quick and easy solution to halve your frame rate, you can simply do your computations only every 2nd frame by:

requestAnimationFrame(render);
function render() {
  // ... computations ...
  requestAnimationFrame(skipFrame);
}
function skipFrame() { requestAnimationFrame(render); }

Similarly you could always call render but use a variable to control whether you do computations this time or not, allowing you to also cut FPS to a third or fourth (in my case, for a schematic webgl-animation 20fps is still enough while considerably lowering computational load on the clients)

adb command for getting ip address assigned by operator

Try this command for Version <= Marshmallow,

adb devices

List of devices attached 38ccdc87 device

adb tcpip 5555

restarting in TCP mode port: 5555

adb shell ip addr show wlan0

24: wlan0: mtu 1500 qdisc mq state UP qlen 1000 link/ether ac:c1:ee:6b:22:f1 brd ff:ff:ff:ff:ff:ff inet 192.168.0.18/24 brd 192.168.0.255 scope global wlan0 valid_lft forever preferred_lft forever inet6 fd01::1d45:6b7a:a3b:5f4d/64 scope global temporary dynamic valid_lft 287sec preferred_lft 287sec inet6 fd01::aec1:eeff:fe6b:22f1/64 scope global dynamic valid_lft 287sec preferred_lft 287sec inet6 fe80::aec1:eeff:fe6b:22f1/64 scope link valid_lft forever preferred_lft forever

To connect to your device run this

adb connect 192.168.0.18

connected to 192.168.0.18:5555

Make sure you have adb inside this location android-sdk\platform-tools

Cannot construct instance of - Jackson

You cannot instantiate an abstract class, Jackson neither. You should give Jackson information on how to instantiate MyAbstractClass with a concrete type.

See this answer on stackoverflow: Jackson JSON library: how to instantiate a class that contains abstract fields

And maybe also see Jackson Polymorphic Deserialization

Select and display only duplicate records in MySQL

Try this query:

SELECT id, COUNT( payer_email ) `tot`
FROM paypal_ipn_orders
GROUP BY id
HAVING `tot` >1

Does it help?

High CPU Utilization in java application - why?

Your first approach should be to find all references to Thread.sleep and check that:

  1. Sleeping is the right thing to do - you should use some sort of wait mechanism if possible - perhaps careful use of a BlockingQueue would help.

  2. If sleeping is the right thing to do, are you sleeping for the right amount of time - this is often a very difficult question to answer.

The most common mistake in multi-threaded design is to believe that all you need to do when waiting for something to happen is to check for it and sleep for a while in a tight loop. This is rarely an effective solution - you should always try to wait for the occurrence.

The second most common issue is to loop without sleeping. This is even worse and is a little less easy to track down.

How to convert an ArrayList containing Integers to primitive int array?

It bewilders me that we encourage one-off custom methods whenever a perfectly good, well used library like Apache Commons has solved the problem already. Though the solution is trivial if not absurd, it is irresponsible to encourage such a behavior due to long term maintenance and accessibility.

Just go with Apache Commons

Generate random numbers using C++11 random library

Here's something that I just wrote along those lines::

#include <random>
#include <chrono>
#include <thread>

using namespace std;

//==============================================================
// RANDOM BACKOFF TIME
//==============================================================
class backoff_time_t {
  public:
    random_device                      rd;
    mt19937                            mt;
    uniform_real_distribution<double>  dist;

    backoff_time_t() : rd{}, mt{rd()}, dist{0.5, 1.5} {}

    double rand() {
      return dist(mt);
    }
};

thread_local backoff_time_t backoff_time;


int main(int argc, char** argv) {
   double x1 = backoff_time.rand();
   double x2 = backoff_time.rand();
   double x3 = backoff_time.rand();
   double x4 = backoff_time.rand();
   return 0;
}

~

Powershell: Get FQDN Hostname

A cleaner format FQDN remotely

[System.Net.Dns]::GetHostByName('remotehost').HostName

jquery change div text

Put the title in its own span.

<span id="dialog_title_span">'+dialog_title+'</span>
$('#dialog_title_span').text("new dialog title");

Google Chrome forcing download of "f.txt" file

FYI, after reading this thread, I took a look at my installed programs and found that somehow, shortly after upgrading to Windows 10 (possibly/probably? unrelated), an ASK search app was installed as well as a Chrome extension (Windows was kind enough to remind to check that). Since removing, I have not have the f.txt issue.

Get yesterday's date in bash on Linux, DST-safe

date under Mac OSX is slightly different.

For yesterday

date -v-1d +%F

For Last week

date -v-1w +%F

Foreach loop in java for a custom object list

If this code fails to operate on every item in the list, it must be because something is throwing an exception before you have completed the list; the likeliest candidate is the method called "insertOrThrow". You could wrap that call in a try-catch structure to handle the exception for whichever items are failing without exiting the loop and the method prematurely.

Scanner only reads first word instead of line

Use input.nextLine(); instead of input.next();

How can I capitalize the first letter of each word in a string?

Here's a summary of different ways to do it, they will work for all these inputs:

""           => ""       
"a b c"      => "A B C"             
"foO baR"    => "FoO BaR"      
"foo    bar" => "Foo    Bar"   
"foo's bar"  => "Foo's Bar"    
"foo's1bar"  => "Foo's1bar"    
"foo 1bar"   => "Foo 1bar"     

- The simplest solution is to split the sentence into words and capitalize the first letter then join it back together:

# Be careful with multiple spaces, and empty strings
# for empty words w[0] would cause an index error, 
# but with w[:1] we get an empty string as desired
def cap_sentence(s):
  return ' '.join(w[:1].upper() + w[1:] for w in s.split(' ')) 

- If you don't want to split the input string into words first, and using fancy generators:

# Iterate through each of the characters in the string and capitalize 
# the first char and any char after a blank space
from itertools import chain 
def cap_sentence(s):
  return ''.join( (c.upper() if prev == ' ' else c) for c, prev in zip(s, chain(' ', s)) )

- Or without importing itertools:

def cap_sentence(s):
  return ''.join( (c.upper() if i == 0 or s[i-1] == ' ' else c) for i, c in enumerate(s) )

- Or you can use regular expressions, from steveha's answer:

# match the beginning of the string or a space, followed by a non-space
import re
def cap_sentence(s):
  return re.sub("(^|\s)(\S)", lambda m: m.group(1) + m.group(2).upper(), s)

Now, these are some other answers that were posted, and inputs for which they don't work as expected if we are using the definition of a word being the start of the sentence or anything after a blank space:

  return s.title()

# Undesired outputs: 
"foO baR"    => "Foo Bar"       
"foo's bar"  => "Foo'S Bar" 
"foo's1bar"  => "Foo'S1Bar"     
"foo 1bar"   => "Foo 1Bar"      

  return ' '.join(w.capitalize() for w in s.split())    
  # or
  import string
  return string.capwords(s)

# Undesired outputs:
"foO baR"    => "Foo Bar"      
"foo    bar" => "Foo Bar"      

using ' ' for the split will fix the second output, but capwords() still won't work for the first

  return ' '.join(w.capitalize() for w in s.split(' '))    
  # or
  import string
  return string.capwords(s, ' ')

# Undesired outputs:
"foO baR"    => "Foo Bar"      

Be careful with multiple blank spaces

  return ' '.join(w[0].upper() + w[1:] for w in s.split())
# Undesired outputs:
"foo    bar" => "Foo Bar"                 

Asynchronously wait for Task<T> to complete with timeout

Using Stephen Cleary's excellent AsyncEx library, you can do:

TimeSpan timeout = TimeSpan.FromSeconds(10);

using (var cts = new CancellationTokenSource(timeout))
{
    await myTask.WaitAsync(cts.Token);
}

TaskCanceledException will be thrown in the event of a timeout.

How to find path of active app.config file?

The first time I realized that the Unit testing project referenced the app.config in that project rather then the app.config associated with my production code project (off course, DOH) I just added a line in the Post Build Event of the Prod project that will copy the app.config to the bin folder of the test project.

Problem solved

I haven't noticed any weird side effects so far, but I am not sure that this is the right solution, but at least it seems to work.

Things possible in IntelliJ that aren't possible in Eclipse?

A few other things:

  • propagate parameters/exceptions when changing method signature, very handy for updating methods deep inside the call stack
  • SQL code validation in the strings passed as arguments to jdbc calls (and the whole newly bundled language injection stuff)
  • implemented in/overwritten in icons for interfaces & classes (and their methods) and the smart implementation navigation (Ctrl+Alt+Click or Ctrl+Alt+B)
  • linking between the EJB 2.1 interfaces and bean classes (including refactoring support); old one, but still immensely valuable when working on older projects

CSV file written with Python has blank lines between each row

Use the method defined below to write data to the CSV file.

open('outputFile.csv', 'a',newline='')

Just add an additional newline='' parameter inside the open method :

def writePhoneSpecsToCSV():
    rowData=["field1", "field2"]
    with open('outputFile.csv', 'a',newline='') as csv_file:
        writer = csv.writer(csv_file)
        writer.writerow(rowData)

This will write CSV rows without creating additional rows!

SQL how to increase or decrease one for a int column in one command

UPDATE Orders Order
SET Order.Quantity =  Order.Quantity - 1
WHERE SomeCondition(Order)

As far as I know there is no build-in support for INSERT-OR-UPDATE in SQL. I suggest to create a stored procedure or use a conditional query to achiev this. Here you can find a collection of solutions for different databases.

Make a UIButton programmatically in Swift

Swift 4.2 - XCode 10.1

Using a closure

let button: UIButton = {
  let button = UIButton(type: .system)
  button.titleLabel?.font = UIFont.systemFont(ofSize: 20)
  ...
  return button
}()

Convert a number range to another range, maintaining ratio

NewValue = (((OldValue - OldMin) * (NewMax - NewMin)) / (OldMax - OldMin)) + NewMin

Or a little more readable:

OldRange = (OldMax - OldMin)  
NewRange = (NewMax - NewMin)  
NewValue = (((OldValue - OldMin) * NewRange) / OldRange) + NewMin

Or if you want to protect for the case where the old range is 0 (OldMin = OldMax):

OldRange = (OldMax - OldMin)
if (OldRange == 0)
    NewValue = NewMin
else
{
    NewRange = (NewMax - NewMin)  
    NewValue = (((OldValue - OldMin) * NewRange) / OldRange) + NewMin
}

Note that in this case we're forced to pick one of the possible new range values arbitrarily. Depending on context, sensible choices could be: NewMin (see sample), NewMax or (NewMin + NewMax) / 2

get parent's view from a layout

If you are trying to find a View from your Fragment then try doing it like this:

int w = ((EditText)getActivity().findViewById(R.id.editText1)).getLayoutParams().width;

is there a post render callback for Angular JS directive?

None of the solutions worked for me accept from using a timeout. This is because I was using a template that was dynamically being created during the postLink.

Note however, there can be a timeout of '0' as the timeout adds the function being called to the browser's queue which will occur after the angular rendering engine as this is already in the queue.

Refer to this: http://blog.brunoscopelliti.com/run-a-directive-after-the-dom-has-finished-rendering

Create a .txt file if doesn't exist, and if it does append a new line

From microsoft documentation, you can create file if not exist and append to it in a single call File.AppendAllText Method (String, String)

.NET Framework (current version) Other Versions

Opens a file, appends the specified string to the file, and then closes the file. If the file does not exist, this method creates a file, writes the specified string to the file, then closes the file. Namespace: System.IO Assembly: mscorlib (in mscorlib.dll)

Syntax C#C++F#VB public static void AppendAllText( string path, string contents ) Parameters path Type: System.String The file to append the specified string to. contents Type: System.String The string to append to the file.

AppendAllText

Carriage return in C?

From 5.2.2/2 (character display semantics) :

\b (backspace) Moves the active position to the previous position on the current line. If the active position is at the initial position of a line, the behavior of the display device is unspecified.

\n (new line) Moves the active position to the initial position of the next line.

\r (carriage return) Moves the active position to the initial position of the current line.

Here, your code produces :

  • <new_line>ab
  • \b : back one character
  • write si : overrides the b with s (producing asi on the second line)
  • \r : back at the beginning of the current line
  • write ha : overrides the first two characters (producing hai on the second line)

In the end, the output is :

\nhai

database attached is read only

Another Way which worked for me is:

After dettaching before you attach

  • -> go to the .mdf file -> right click & select properties on the file -> security tab -> Check Group or usernames:

    for your name\account (optional) and for "NT SERVICE\MSSQLSERVER"(NB)

List item

-> if not there than click on edit button -> click on add button

  and enter\search NT SERVICE\MSSQLSERVER
  • -> click on OK -> give full rights -> apply then ok

    then ok again do this for .ldf file too.

then attach

fork() and wait() with two child processes

brilliant example Jonathan Leffler, to make your code work on SLES, I needed to add an additional header to allow the pid_t object :)

#include <sys/types.h>

Python: List vs Dict for look up table

I did some benchmarking and it turns out that dict is faster than both list and set for large data sets, running python 2.7.3 on an i7 CPU on linux:

  • python -mtimeit -s 'd=range(10**7)' '5*10**6 in d'

    10 loops, best of 3: 64.2 msec per loop

  • python -mtimeit -s 'd=dict.fromkeys(range(10**7))' '5*10**6 in d'

    10000000 loops, best of 3: 0.0759 usec per loop

  • python -mtimeit -s 'from sets import Set; d=Set(range(10**7))' '5*10**6 in d'

    1000000 loops, best of 3: 0.262 usec per loop

As you can see, dict is considerably faster than list and about 3 times faster than set. In some applications you might still want to choose set for the beauty of it, though. And if the data sets are really small (< 1000 elements) lists perform pretty well.

AngularJS $location not changing the path

Instead of $location.path(...) to change or refresh the page, I used the service $window. In Angular this service is used as interface to the window object, and the window object contains a property location which enables you to handle operations related to the location or URL stuff.

For example, with window.location you can assign a new page, like this:

$window.location.assign('/');

Or refresh it, like this:

$window.location.reload();

It worked for me. It's a little bit different from you expect but works for the given goal.

endforeach in loops?

It's the end statement for the alternative syntax:

foreach ($foo as $bar) :
    ...
endforeach;

Useful to make code more readable if you're breaking out of PHP:

<?php foreach ($foo as $bar) : ?>
    <div ...>
        ...
    </div>
<?php endforeach; ?>

What is the difference between . (dot) and $ (dollar sign)?

The most important part about $ is that it has the lowest operator precedence.

If you type info you'll see this:

?> :info ($)
($) :: (a -> b) -> a -> b
    -- Defined in ‘GHC.Base’
infixr 0 $

This tells us it is an infix operator with right-associativity that has the lowest possible precedence. Normal function application is left-associative and has highest precedence (10). So $ is something of the opposite.

So then we use it where normal function application or using () doesn't work.

So, for example, this works:

?> head . sort $ "example"
?> e

but this does not:

?> head . sort "example"

because . has lower precedence than sort and the type of (sort "example") is [Char]

?> :type (sort "example")
(sort "example") :: [Char]

But . expects two functions and there isn't a nice short way to do this because of the order of operations of sort and .

How to convert a Java String to an ASCII byte array?

String s = "ASCII Text";
byte[] bytes = s.getBytes("US-ASCII");

What is trunk, branch and tag in Subversion?

The "trunk", "branches", and "tags" directories are conventions in Subversion. Subversion does not require you to have these directories nor assign special meaning to them. However, this convention is very common and, unless you have a really good reason, you should follow the convention. The book links that other readers have given describe the convention and how to use it.

What is the purpose of "pip install --user ..."?

Just a warning:

According to this issue, --user is currently not valid inside a virtual env's pip, since a user location doesn't really make sense for a virtual environment.

So do not use pip install --user some_pkg inside a virtual environment, otherwise, virtual environment's pip will be confused. See this answer for more details.

How to get std::vector pointer to the raw data?

Take a pointer to the first element instead:

process_data (&something [0]);

python and sys.argv

BTW you can pass the error message directly to sys.exit:

if len(sys.argv) < 2:
    sys.exit('Usage: %s database-name' % sys.argv[0])

if not os.path.exists(sys.argv[1]):
    sys.exit('ERROR: Database %s was not found!' % sys.argv[1])

Best way to define private methods for a class in Objective-C

Defining your private methods in the @implementation block is ideal for most purposes. Clang will see these within the @implementation, regardless of declaration order. There is no need to declare them in a class continuation (aka class extension) or named category.

In some cases, you will need to declare the method in the class continuation (e.g. if using the selector between the class continuation and the @implementation).

static functions are very good for particularly sensitive or speed critical private methods.

A convention for naming prefixes can help you avoid accidentally overriding private methods (I find the class name as a prefix safe).

Named categories (e.g. @interface MONObject (PrivateStuff)) are not a particularly good idea because of potential naming collisions when loading. They're really only useful for friend or protected methods (which are very rarely a good choice). To ensure you are warned of incomplete category implementations, you should actually implement it:

@implementation MONObject (PrivateStuff)
...HERE...
@end

Here's a little annotated cheat sheet:

MONObject.h

@interface MONObject : NSObject

// public declaration required for clients' visibility/use.
@property (nonatomic, assign, readwrite) bool publicBool;

// public declaration required for clients' visibility/use.
- (void)publicMethod;

@end

MONObject.m

@interface MONObject ()
@property (nonatomic, assign, readwrite) bool privateBool;

// you can use a convention where the class name prefix is reserved
// for private methods this can reduce accidental overriding:
- (void)MONObject_privateMethod;

@end

// The potentially good thing about functions is that they are truly
// inaccessible; They may not be overridden, accidentally used,
// looked up via the objc runtime, and will often be eliminated from
// backtraces. Unlike methods, they can also be inlined. If unused
// (e.g. diagnostic omitted in release) or every use is inlined,
// they may be removed from the binary:
static void PrivateMethod(MONObject * pObject) {
    pObject.privateBool = true;
}

@implementation MONObject
{
    bool anIvar;
}

static void AnotherPrivateMethod(MONObject * pObject) {
    if (0 == pObject) {
        assert(0 && "invalid parameter");
        return;
    }

    // if declared in the @implementation scope, you *could* access the
    // private ivars directly (although you should rarely do this):
    pObject->anIvar = true;
}

- (void)publicMethod
{
    // declared below -- but clang can see its declaration in this
    // translation:
    [self privateMethod];
}

// no declaration required.
- (void)privateMethod
{
}

- (void)MONObject_privateMethod
{
}

@end

Another approach which may not be obvious: a C++ type can be both very fast and provide a much higher degree of control, while minimizing the number of exported and loaded objc methods.

How to check if a line has one of the strings in a list?

One approach is to combine the search strings into a regex pattern as in this answer.

Bash command line and input limit

The limit for the length of a command line is not imposed by the shell, but by the operating system. This limit is usually in the range of hundred kilobytes. POSIX denotes this limit ARG_MAX and on POSIX conformant systems you can query it with

$ getconf ARG_MAX    # Get argument limit in bytes

E.g. on Cygwin this is 32000, and on the different BSDs and Linux systems I use it is anywhere from 131072 to 2621440.

If you need to process a list of files exceeding this limit, you might want to look at the xargs utility, which calls a program repeatedly with a subset of arguments not exceeding ARG_MAX.

To answer your specific question, yes, it is possible to attempt to run a command with too long an argument list. The shell will error with a message along "argument list too long".

Note that the input to a program (as read on stdin or any other file descriptor) is not limited (only by available program resources). So if your shell script reads a string into a variable, you are not restricted by ARG_MAX. The restriction also does not apply to shell-builtins.

Convert multiple rows into one with comma as separator

DECLARE @EmployeeList varchar(100)

SELECT @EmployeeList = COALESCE(@EmployeeList + ', ', '') + 
   CAST(Emp_UniqueID AS varchar(5))
FROM SalesCallsEmployees
WHERE SalCal_UniqueID = 1

SELECT @EmployeeList

source: http://www.sqlteam.com/article/using-coalesce-to-build-comma-delimited-string

Loading DLLs at runtime in C#

Members must be resolvable at compile time to be called directly from C#. Otherwise you must use reflection or dynamic objects.

Reflection

namespace ConsoleApplication1
{
    using System;
    using System.Reflection;

    class Program
    {
        static void Main(string[] args)
        {
            var DLL = Assembly.LoadFile(@"C:\visual studio 2012\Projects\ConsoleApplication1\ConsoleApplication1\DLL.dll");

            foreach(Type type in DLL.GetExportedTypes())
            {
                var c = Activator.CreateInstance(type);
                type.InvokeMember("Output", BindingFlags.InvokeMethod, null, c, new object[] {@"Hello"});
            }

            Console.ReadLine();
        }
    }
}

Dynamic (.NET 4.0)

namespace ConsoleApplication1
{
    using System;
    using System.Reflection;

    class Program
    {
        static void Main(string[] args)
        {
            var DLL = Assembly.LoadFile(@"C:\visual studio 2012\Projects\ConsoleApplication1\ConsoleApplication1\DLL.dll");

            foreach(Type type in DLL.GetExportedTypes())
            {
                dynamic c = Activator.CreateInstance(type);
                c.Output(@"Hello");
            }

            Console.ReadLine();
        }
    }
}

Using Predicate in Swift

In swift 2.2

func filterContentForSearchText(searchText: String, scope: String) {
    var resultPredicate = NSPredicate(format: "name contains[c]         %@", searchText)
    searchResults = (recipes as NSArray).filteredArrayUsingPredicate(resultPredicate)
}

In swift 3.0

func filterContent(forSearchText searchText: String, scope: String) {
        var resultPredicate = NSPredicate(format: "name contains[c]         %@", searchText)
        searchResults = recipes.filtered(using: resultPredicate)
    }

How does the class_weight parameter in scikit-learn work?

First off, it might not be good to just go by recall alone. You can simply achieve a recall of 100% by classifying everything as the positive class. I usually suggest using AUC for selecting parameters, and then finding a threshold for the operating point (say a given precision level) that you are interested in.

For how class_weight works: It penalizes mistakes in samples of class[i] with class_weight[i] instead of 1. So higher class-weight means you want to put more emphasis on a class. From what you say it seems class 0 is 19 times more frequent than class 1. So you should increase the class_weight of class 1 relative to class 0, say {0:.1, 1:.9}. If the class_weight doesn't sum to 1, it will basically change the regularization parameter.

For how class_weight="auto" works, you can have a look at this discussion. In the dev version you can use class_weight="balanced", which is easier to understand: it basically means replicating the smaller class until you have as many samples as in the larger one, but in an implicit way.

How do you display code snippets in MS Word preserving format and syntax highlighting?

Maybe this is overly simple, but have you tried pasting in your code and setting the font on it to Courier New?

non static method cannot be referenced from a static context

Violating the Java naming conventions (variable names and method names start with lowercase, class names start with uppercase) is contributing to your confusion.

The variable Random is only "in scope" inside the main method. It's not accessible to any methods called by main. When you return from main, the variable disappears (it's part of the stack frame).

If you want all of the methods of your class to use the same Random instance, declare a member variable:

class MyObj {
  private final Random random = new Random();
  public void compTurn() {
    while (true) {
      int a = random.nextInt(10);
      if (possibles[a] == 1) 
        break;
    }
  }
}

combining two string variables

you need to take out the quotes:

soda = a + b

(You want to refer to the variables a and b, not the strings "a" and "b")

Is there a way to list open transactions on SQL Server 2000 database?

Use this because whenever transaction open more than one transaction then below will work SELECT * FROM sys.sysprocesses WHERE open_tran <> 0

Text to speech(TTS)-Android

A minimalistic example to quickly test the TTS system:

private TextToSpeech textToSpeechSystem;

@Override
protected void onStart() {
  super.onStart();
  textToSpeechSystem = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
        @Override
        public void onInit(int status) {
            if (status == TextToSpeech.SUCCESS) {
                String textToSay = "Hello world, this is a test message!";
                textToSpeechSystem.speak(textToSay, TextToSpeech.QUEUE_ADD, null);
            }
        }
   });
}

If you don't use localized messages textToSpeechSystem.setLanguage(..) is important as well, since your users probably don't all have English set as their default language so the pronunciation of the words will be wrong. But for testing TTS in general this snippet is enough

Related links: https://developer.android.com/reference/android/speech/tts/TextToSpeech

Get PostGIS version

Since some of the functions depend on other libraries like GEOS and proj4 you might want to get their versions too. Then use:

SELECT PostGIS_full_version();

What does ${} (dollar sign and curly braces) mean in a string in Javascript?

You can also perform Implicit Type Conversions with template literals. Example:

let fruits = ["mango","orange","pineapple","papaya"];

console.log(`My favourite fruits are ${fruits}`);
// My favourite fruits are mango,orange,pineapple,papaya

mysqld: Can't change dir to data. Server doesn't start

What I did (Windows 10) for a new installation:

  1. Start cmd in admin mode (run as administrator by hitting windows key, typing cmd, right clicking on it and selecting "Run as Administrator"

  2. Change into "MySQL Server X.Y" directory (for me the full path is C:\Program Files\MySQL\MySQL Server 5.7")

  3. using notepad create a my.ini with a mysqld section that points at your data directory

    [mysqld]
    datadir="X:\Your Directory Path and Name"
    
  4. created the directory identified in my.ini above.

  5. change into bin Directory under server directory and execute: mysqld --initialize

  6. Once complete, started the service and it came up fine.

Declaring variables in Excel Cells

I also just found out how to do this with the Excel Name Manager (Formulas > Defined Names Section > Name Manager).

You can define a variable that doesn't have to "live" within a cell and then you can use it in formulas.

Excel Name Manager

Referring to a Column Alias in a WHERE Clause

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

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

uppercase first character in a variable with bash

It can be done in pure bash with bash-3.2 as well:

# First, get the first character.
fl=${foo:0:1}

# Safety check: it must be a letter :).
if [[ ${fl} == [a-z] ]]; then
    # Now, obtain its octal value using printf (builtin).
    ord=$(printf '%o' "'${fl}")

    # Fun fact: [a-z] maps onto 0141..0172. [A-Z] is 0101..0132.
    # We can use decimal '- 40' to get the expected result!
    ord=$(( ord - 40 ))

    # Finally, map the new value back to a character.
    fl=$(printf '%b' '\'${ord})
fi

echo "${fl}${foo:1}"

HTTP test server accepting GET/POST requests

I am not sure if anyone would take this much pain to test GET and POST calls. I took Python Flask module and wrote a function that does something similar to what @Robert shared.

from flask import Flask, request
app = Flask(__name__)

@app.route('/method', methods=['GET', 'POST'])
@app.route('/method/<wish>', methods=['GET', 'POST'])
def method_used(wish=None):
    if request.method == 'GET':
        if wish:
            if wish in dir(request):
                ans = None
                s = "ans = str(request.%s)" % wish
                exec s
                return ans
            else:
                return 'This wish is not available. The following are the available wishes: %s' % [method for method in dir(request) if '_' not in method]
        else:
            return 'This is just a GET method'
    else:
        return "You are using POST"

When I run this, this follows:

C:\Python27\python.exe E:/Arindam/Projects/Flask_Practice/first.py
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 581-155-269
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

Now lets try some calls. I am using the browser.

http://127.0.0.1:5000/method

This is just a GET method

http://127.0.0.1:5000/method/NotCorrect

This wish is not available. The following are the available wishes: ['application', 'args', 'authorization', 'blueprint', 'charset', 'close', 'cookies', 'data', 'date', 'endpoint', 'environ', 'files', 'form', 'headers', 'host', 'json', 'method', 'mimetype', 'module', 'path', 'pragma', 'range', 'referrer', 'scheme', 'shallow', 'stream', 'url', 'values']

http://127.0.0.1:5000/method/environ

{'wsgi.multiprocess': False, 'HTTP_COOKIE': 'csrftoken=YFKYYZl3DtqEJJBwUlap28bLG1T4Cyuq', 'SERVER_SOFTWARE': 'Werkzeug/0.12.2', 'SCRIPT_NAME': '', 'REQUEST_METHOD': 'GET', 'PATH_INFO': '/method/environ', 'SERVER_PROTOCOL': 'HTTP/1.1', 'QUERY_STRING': '', 'werkzeug.server.shutdown': , 'HTTP_USER_AGENT': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36', 'HTTP_CONNECTION': 'keep-alive', 'SERVER_NAME': '127.0.0.1', 'REMOTE_PORT': 49569, 'wsgi.url_scheme': 'http', 'SERVER_PORT': '5000', 'werkzeug.request': , 'wsgi.input': , 'HTTP_HOST': '127.0.0.1:5000', 'wsgi.multithread': False, 'HTTP_UPGRADE_INSECURE_REQUESTS': '1', 'HTTP_ACCEPT': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,/;q=0.8', 'wsgi.version': (1, 0), 'wsgi.run_once': False, 'wsgi.errors': ', mode 'w' at 0x0000000002042150>, 'REMOTE_ADDR': '127.0.0.1', 'HTTP_ACCEPT_LANGUAGE': 'en-US,en;q=0.8', 'HTTP_ACCEPT_ENCODING': 'gzip, deflate, sdch, br'}

How to use passive FTP mode in Windows command prompt?

This is a common problem . when we start the ftp connection only the external ip opens the port for pasv connection. but the ip behind the NAT doesn't open the connection so passive connection fails with PASV command

we need to specify that while opening the connection so open connection with

ftp -p {host}

What is the difference between .*? and .* regular expressions?

On greedy vs non-greedy

Repetition in regex by default is greedy: they try to match as many reps as possible, and when this doesn't work and they have to backtrack, they try to match one fewer rep at a time, until a match of the whole pattern is found. As a result, when a match finally happens, a greedy repetition would match as many reps as possible.

The ? as a repetition quantifier changes this behavior into non-greedy, also called reluctant (in e.g. Java) (and sometimes "lazy"). In contrast, this repetition will first try to match as few reps as possible, and when this doesn't work and they have to backtrack, they start matching one more rept a time. As a result, when a match finally happens, a reluctant repetition would match as few reps as possible.

References


Example 1: From A to Z

Let's compare these two patterns: A.*Z and A.*?Z.

Given the following input:

eeeAiiZuuuuAoooZeeee

The patterns yield the following matches:

Let's first focus on what A.*Z does. When it matched the first A, the .*, being greedy, first tries to match as many . as possible.

eeeAiiZuuuuAoooZeeee
   \_______________/
    A.* matched, Z can't match

Since the Z doesn't match, the engine backtracks, and .* must then match one fewer .:

eeeAiiZuuuuAoooZeeee
   \______________/
    A.* matched, Z still can't match

This happens a few more times, until finally we come to this:

eeeAiiZuuuuAoooZeeee
   \__________/
    A.* matched, Z can now match

Now Z can match, so the overall pattern matches:

eeeAiiZuuuuAoooZeeee
   \___________/
    A.*Z matched

By contrast, the reluctant repetition in A.*?Z first matches as few . as possible, and then taking more . as necessary. This explains why it finds two matches in the input.

Here's a visual representation of what the two patterns matched:

eeeAiiZuuuuAoooZeeee
   \__/r   \___/r      r = reluctant
    \____g____/        g = greedy

Example: An alternative

In many applications, the two matches in the above input is what is desired, thus a reluctant .*? is used instead of the greedy .* to prevent overmatching. For this particular pattern, however, there is a better alternative, using negated character class.

The pattern A[^Z]*Z also finds the same two matches as the A.*?Z pattern for the above input (as seen on ideone.com). [^Z] is what is called a negated character class: it matches anything but Z.

The main difference between the two patterns is in performance: being more strict, the negated character class can only match one way for a given input. It doesn't matter if you use greedy or reluctant modifier for this pattern. In fact, in some flavors, you can do even better and use what is called possessive quantifier, which doesn't backtrack at all.

References


Example 2: From A to ZZ

This example should be illustrative: it shows how the greedy, reluctant, and negated character class patterns match differently given the same input.

eeAiiZooAuuZZeeeZZfff

These are the matches for the above input:

Here's a visual representation of what they matched:

         ___n
        /   \              n = negated character class
eeAiiZooAuuZZeeeZZfff      r = reluctant
  \_________/r   /         g = greedy
   \____________/g

Related topics

These are links to questions and answers on stackoverflow that cover some topics that may be of interest.

One greedy repetition can outgreed another

const vs constexpr on variables

A constexpr symbolic constant must be given a value that is known at compile time. For example:

?constexpr int max = 100; 
void use(int n)
{
    constexpr int c1 = max+7; // OK: c1 is 107
    constexpr int c2 = n+7;   // Error: we don’t know the value of c2
    // ...
}

To handle cases where the value of a “variable” that is initialized with a value that is not known at compile time but never changes after initialization, C++ offers a second form of constant (a const). For Example:

?constexpr int max = 100; 
void use(int n)
{
    constexpr int c1 = max+7; // OK: c1 is 107
    const int c2 = n+7; // OK, but don’t try to change the value of c2
    // ...
    c2 = 7; // error: c2 is a const
}

Such “const variables” are very common for two reasons:

  1. C++98 did not have constexpr, so people used const.
  2. List item “Variables” that are not constant expressions (their value is not known at compile time) but do not change values after initialization are in themselves widely useful.

Reference : "Programming: Principles and Practice Using C++" by Stroustrup

Showing empty view when ListView is empty

Activity code, its important to extend ListActivity.

package com.example.mylistactivity;

import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import com.example.mylistactivity.R;

// It's important to extend ListActivity rather than Activity
public class MyListActivity extends ListActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mylist);

        // shows list view
        String[] values = new String[] { "foo", "bar" };

        // shows empty view
        values = new String[] { };

        setListAdapter(new ArrayAdapter<String>(
                this,
                android.R.layout.simple_list_item_1,
                android.R.id.text1,
                values));
    }
}

Layout xml, the id in both views are important.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <!-- the android:id is important -->
    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"/>

    <!-- the android:id is important -->
    <TextView
        android:id="@android:id/empty"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:text="i am empty"/>
</LinearLayout>

if statement in ng-click

This maybe irrelevant and of no use, but as it's javascript, you don't have to use the ternary as suggested above in the ng-click statement. You should also be able to use the lazy evaluation ("or die") syntax as well. So for your example above:

<input  ng-click="{{if(profileForm.$valid) updateMyProfile()}}" name="submit" id="submit" value="Save" class="submit" type="submit">

would become:

<input  ng-click="profileForm.$valid && updateMyProfile()" name="submit" id="submit" value="Save" class="submit" type="submit">

In this case, if the profile is not valid then nothing happens, otherwise, updateMyProfile() is called. Like in the link @falinsky provides above.

Initializing C dynamic arrays

You need to allocate a block of memory and use it as an array as:

int *arr = malloc (sizeof (int) * n); /* n is the length of the array */
int i;

for (i=0; i<n; i++)
{
  arr[i] = 0;
}

If you need to initialize the array with zeros you can also use the memset function from C standard library (declared in string.h).

memset (arr, 0, sizeof (int) * n);

Here 0 is the constant with which every locatoin of the array will be set. Note that the last argument is the number of bytes to be set the the constant. Because each location of the array stores an integer therefore we need to pass the total number of bytes as this parameter.

Also if you want to clear the array to zeros, then you may want to use calloc instead of malloc. calloc will return the memory block after setting the allocated byte locations to zero.

After you have finished, free the memory block free (arr).

EDIT1

Note that if you want to assign a particular integer in locations of an integer array using memset then it will be a problem. This is because memset will interpret the array as a byte array and assign the byte you have given, to every byte of the array. So if you want to store say 11243 in each location then it will not be possible.

EDIT2

Also note why every time setting an int array to 0 with memset may not work: Why does "memset(arr, -1, sizeof(arr)/sizeof(int))" not clear an integer array to -1? as pointed out by @Shafik Yaghmour

Can I write or modify data on an RFID tag?

Some RFID chips are read-write, the majority are read-only. You can find out if your chip is read-only by checking the datasheet.

How do I check in SQLite whether a table exists?

This is my code for SQLite Cordova:

get_columnNames('LastUpdate', function (data) {
    if (data.length > 0) { // In data you also have columnNames
        console.log("Table full");
    }
    else {
        console.log("Table empty");
    }
});

And the other one:

function get_columnNames(tableName, callback) {
    myDb.transaction(function (transaction) {
        var query_exec = "SELECT name, sql FROM sqlite_master WHERE type='table' AND name ='" + tableName + "'";
        transaction.executeSql(query_exec, [], function (tx, results) {
            var columnNames = [];
            var len = results.rows.length;
            if (len>0){
                var columnParts = results.rows.item(0).sql.replace(/^[^\(]+\(([^\)]+)\)/g, '$1').split(','); ///// RegEx
                for (i in columnParts) {
                    if (typeof columnParts[i] === 'string')
                        columnNames.push(columnParts[i].split(" ")[0]);
                };
                callback(columnNames);
            }
            else callback(columnNames);
        });
    });
}

jQuery/JavaScript to replace broken images

I use lazy load and have to do this in order to make it work properly:

lazyload();

var errorURL = "https://example.com/thisimageexist.png";

$(document).ready(function () {
  $('[data-src]').on("error", function () {
    $(this).attr('src', errorURL);
  });
});

Difference between using gradlew and gradle

The difference lies in the fact that ./gradlew indicates you are using a gradle wrapper. The wrapper is generally part of a project and it facilitates installation of gradle. If you were using gradle without the wrapper you would have to manually install it - for example, on a mac brew install gradle and then invoke gradle using the gradle command. In both cases you are using gradle, but the former is more convenient and ensures version consistency across different machines.

Each Wrapper is tied to a specific version of Gradle, so when you first run one of the commands above for a given Gradle version, it will download the corresponding Gradle distribution and use it to execute the build.

Not only does this mean that you don’t have to manually install Gradle yourself, but you are also sure to use the version of Gradle that the build is designed for. This makes your historical builds more reliable

Read more here - https://docs.gradle.org/current/userguide/gradle_wrapper.html

Also, Udacity has a neat, high level video explaining the concept of the gradle wrapper - https://www.youtube.com/watch?v=1aA949H-shk

How to find files that match a wildcard string in Java?

Might not help you right now, but JDK 7 is intended to have glob and regex file name matching as part of "More NIO Features".

Navigation drawer: How do I set the selected item at startup?

This is my solution, very simple.

Here is my menu.xml file:

<group
    android:id="@+id/grp1"
    android:checkableBehavior="single">
    <item
        android:id="@+id/nav_all_deals"
        android:checked="true"
        android:icon="@drawable/ic_all_deals"
        android:title="@string/all_deals" />
    <item
        android:id="@+id/nav_news_and_events"
        android:icon="@drawable/ic_news"
        android:title="@string/news_and_events" />
    <item
        android:id="@+id/nav_histories"
        android:icon="@drawable/ic_histories"
        android:title="@string/histories" />
</group>

Above menu will highlight the first menu item. Below line will do something(eg: show the first fragment, etc). NOTE: write after 'configure your drawer code'

onNavigationItemSelected(mNavigationView.getMenu().getItem(0));

Simple search MySQL database using php

First add HTML code:

<form action="" method="post">
<input type="text" name="search">
<input type="submit" name="submit" value="Search">
</form>

Now added PHP code:

<?php
$search_value=$_POST["search"];
$con=new mysqli($servername,$username,$password,$dbname);
if($con->connect_error){
    echo 'Connection Faild: '.$con->connect_error;
    }else{
        $sql="select * from information where First_Name like '%$search_value%'";

        $res=$con->query($sql);

        while($row=$res->fetch_assoc()){
            echo 'First_name:  '.$row["First_Name"];


            }       

        }
?>

WooCommerce return product object by id

global $woocommerce;
var_dump($woocommerce->customer->get_country());
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
    $product = new WC_product($cart_item['product_id']);
    var_dump($product);
}

Java java.sql.SQLException: Invalid column index on preparing statement

Everywhere inside the query string, the wildcard should be ? instead of '?'. That should solve the problem.

EDIT :

To add to that, you need to change date '?' to to_date(?, 'yyyy-mm-dd'). Please try that and let me know.

Get an element by index in jQuery

You could skip the jquery and just use CSS style tagging:

 <ul>
 <li>India</li>
 <li>Indonesia</li>
 <li style="background-color:#343434;">China</li>
 <li>United States</li>
 <li>United Kingdom</li>
 </ul>

javascript close current window

To close your current window using JS, do this. First open the current window to trick your current tab into thinking it has been opened by a script. Then close it using window.close(). The below script should go into the parent window, not the child window. You could run this after running the script to open the child.

<script type="text/javascript">
    window.open('','_parent',''); 
    window.close();
</script>

Execute a SQL Stored Procedure and process the results

Dim sqlConnection1 As New SqlConnection("Your Connection String")
Dim cmd As New SqlCommand

cmd.CommandText = "StoredProcedureName"
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = sqlConnection1

sqlConnection1.Open()

Dim adapter As System.Data.SqlClient.SqlDataAdapter
Dim dsdetailwk As New DataSet

Try
   adapter = New System.Data.SqlClient.SqlDataAdapter
   adapter.SelectCommand = cmd
   adapter.Fill(dsdetailwk, "delivery")
   Catch Err As System.Exception
End Try

sqlConnection1.Close()

datagridview1.DataSource = dsdetailwk.Tables(0)

How to change active class while click to another link in bootstrap use jquery?

_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
$(document).ready(function () {_x000D_
        var url = window.location;_x000D_
        $('ul.nav a[href="' + url + '"]').parent().addClass('active');_x000D_
        $('ul.nav a').filter(function () {_x000D_
            return this.href == url;_x000D_
        }).parent().addClass('active').parent().parent().addClass('active');_x000D_
    });_x000D_
    _x000D_
    This works perfectly
_x000D_
_x000D_
_x000D_

Combining multiple condition in single case statement in Sql Server

select ROUND(CASE 

WHEN  CONVERT( float, REPLACE( isnull( value1,''),',',''))='' AND CONVERT( float, REPLACE( isnull( value2,''),',',''))='' then  CONVERT( float, REPLACE( isnull( value3,''),',',''))

WHEN  CONVERT( float, REPLACE( isnull( value1,''),',',''))='' AND CONVERT( float, REPLACE( isnull( value2,''),',',''))!='' then  CONVERT( float, REPLACE( isnull( value3,''),',',''))

WHEN  CONVERT( float, REPLACE( isnull( value1,''),',',''))!='' AND CONVERT( float, REPLACE( isnull( value2,''),',',''))='' then  CONVERT( float, REPLACE( isnull( value3,''),',',''))

else CONVERT( float, REPLACE(isnull( value1,''),',','')) end,0)  from Tablename where    ID="123" 

What is the difference between Python's list methods append and extend?

Append and extend are one of the extensibility mechanisms in python.

Append: Adds an element to the end of the list.

my_list = [1,2,3,4]

To add a new element to the list, we can use append method in the following way.

my_list.append(5)

The default location that the new element will be added is always in the (length+1) position.

Insert: The insert method was used to overcome the limitations of append. With insert, we can explicitly define the exact position we want our new element to be inserted at.

Method descriptor of insert(index, object). It takes two arguments, first being the index we want to insert our element and second the element itself.

Example: my_list = [1,2,3,4]
my_list[4, 'a']
my_list
[1,2,3,4,'a']

Extend: This is very useful when we want to join two or more lists into a single list. Without extend, if we want to join two lists, the resulting object will contain a list of lists.

a = [1,2]
b = [3]
a.append(b)
print (a)
[1,2,[3]]

If we try to access the element at pos 2, we get a list ([3]), instead of the element. To join two lists, we'll have to use append.

a = [1,2]
b = [3]
a.extend(b)
print (a)
[1,2,3]

To join multiple lists

a = [1]
b = [2]
c = [3]
a.extend(b+c)
print (a)
[1,2,3]

How can I permanently enable line numbers in IntelliJ?

Just an update for Android Studio 1.5.1 on Windows:

Go to File -> Settings -> follow picture enter image description here

How do I compare version numbers in Python?

... and getting back to easy ... for simple scripts you can use:

import sys
needs = (3, 9) # or whatever
pvi = sys.version_info.major, sys.version_info.minor    

later in your code

try:
    assert pvi >= needs
except:
    print("will fail!")
    # etc.

How can you use php in a javascript function

You can't run PHP code with Javascript. When the user recieves the page, the server will have evaluated and run all PHP code, and taken it out. So for example, this will work:

alert( <?php echo "\"Hello\""; ?> );

Because server will have evaluated it to this:

alert("Hello");

However, you can't perform any operations in PHP with it.

This:

function Inc()
{
<?php
$num = 2;
echo $num;
?>
}

Will simply have been evaluated to this:

function Inc()
{
    2
}

If you wan't to call a PHP script, you'll have to call a different page which returns a value from a set of parameters.

This, for example, will work:

script.php

$num = $_POST["num"];
echo $num * 2;

Javascript(jQuery) (on another page):

$.post('script.php', { num: 5 }, function(result) { 
   alert(result); 
});

This should alert 10.

Good luck!

Edit: Just incrementing a number on the page can be done easily in jQuery like this: http://jsfiddle.net/puVPc/

When is it appropriate to use UDP instead of TCP?

UDP can be used when an app cares more about "real-time" data instead of exact data replication. For example, VOIP can use UDP and the app will worry about re-ordering packets, but in the end VOIP doesn't need every single packet, but more importantly needs a continuous flow of many of them. Maybe you here a "glitch" in the voice quality, but the main purpose is that you get the message and not that it is recreated perfectly on the other side. UDP is also used in situations where the expense of creating a connection and syncing with TCP outweighs the payload. DNS queries are a perfect example. One packet out, one packet back, per query. If using TCP this would be much more intensive. If you dont' get the DNS response back, you just retry.

How stable is the git plugin for eclipse?

You can integrate Git-GUI with Eclipse as an alternative to EGit.

See this two part YouTube tutorial specific to Windows:
http://www.youtube.com/watch?v=DcM1xOiaidk
http://www.youtube.com/watch?v=1OrPJClD92s

How to jquery alert confirm box "yes" & "no"

See following snippet :

_x000D_
_x000D_
$(document).on("click", "a.deleteText", function() {_x000D_
    if (confirm('Are you sure ?')) {_x000D_
        $(this).prev('span.text').remove();_x000D_
    }_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<div class="container">_x000D_
    <span class="text">some text</span>_x000D_
    <a href="#" class="deleteText"><span class="delete-icon"> x Delete </span></a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

What is the difference between association, aggregation and composition?

Association is generalized concept of relations. It includes both Composition and Aggregation.

Composition(mixture) is a way to wrap simple objects or data types into a single unit. Compositions are a critical building block of many basic data structures

Aggregation(collection) differs from ordinary composition in that it does not imply ownership. In composition, when the owning object is destroyed, so are the contained objects. In aggregation, this is not necessarily true.

Both denotes relationship between object and only differ in their strength.

Trick to remember the difference : has A -Aggregation and Own - cOmpositoin

enter image description here

Now let observe the following image

relations

enter image description here

Analogy:

Composition: The following picture is image composition i.e. using individual images making one image.
enter image description here

Aggregation : collection of image in single location

enter image description here

For example, A university owns various departments, and each department has a number of professors. If the university closes, the departments will no longer exist, but the professors in those departments will continue to exist. Therefore, a University can be seen as a composition of departments, whereas departments have an aggregation of professors. In addition, a Professor could work in more than one department, but a department could not be part of more than one university.

How do you update Xcode on OSX to the latest version?

I used the Command_Line_Tools_OS_X_10.XX_for_Xcode_7.2.dmg and therefore had to download the latest version from here.

python requests get cookies

Alternatively, you can use requests.Session and observe cookies before and after a request:

>>> import requests
>>> session = requests.Session()
>>> print(session.cookies.get_dict())
{}
>>> response = session.get('http://google.com')
>>> print(session.cookies.get_dict())
{'PREF': 'ID=5514c728c9215a9a:FF=0:TM=1406958091:LM=1406958091:S=KfAG0U9jYhrB0XNf', 'NID': '67=TVMYiq2wLMNvJi5SiaONeIQVNqxSc2RAwVrCnuYgTQYAHIZAGESHHPL0xsyM9EMpluLDQgaj3db_V37NjvshV-eoQdA8u43M8UwHMqZdL-S2gjho8j0-Fe1XuH5wYr9v'}

Getting files by creation date in .NET

This returns the last modified date and its age.

DateTime.Now.Subtract(System.IO.File.GetLastWriteTime(FilePathwithName).Date)

Cannot insert explicit value for identity column in table 'table' when IDENTITY_INSERT is set to OFF

Simply If you getting this error on SQL server then run this query-

SET IDENTITY_INSERT tableName ON

This is working only for a single table of database e.g If the table name is student then query look like this:

SET IDENTITY_INSERT student ON

If you getting this error on your web application or you using entity framework then first run this query on SQL server and Update your entity model (.edmx file) and build your project and this error will be resolved

Java Web Service client basic authentication

Some context additional about basic authentication, it consists in a header which contains the key/value pair:

Authorization: Basic Z2VybWFuOmdlcm1hbg==

where "Authorization" is the headers key, and the headers value has a string ( "Basic" word plus blank space) concatenated to "Z2VybWFuOmdlcm1hbg==", which are the user and password in base 64 joint by double dot

String name = "username";
String password = "secret";
String authString = name + ":" + password;
String authStringEnc = new BASE64Encoder().encode(authString.getBytes());
...
objectXXX.header("Authorization", "Basic " + authStringEnc);

Steps to send a https request to a rest service in Node js

The easiest way is to use the request module.

request('https://example.com/url?a=b', function (error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log(body);
  }
});

Count the number of commits on a Git branch

One way to do it is list the log for your branch and count the lines.

git log <branch_name> --oneline | wc -l

Add a summary row with totals

If you want to display more column values without an aggregation function use GROUPING SETS instead of ROLLUP:

SELECT
  Type = ISNULL(Type, 'Total'),
  SomeIntColumn = ISNULL(SomeIntColumn, 0),
  TotalSales = SUM(TotalSales)
FROM atable
GROUP BY GROUPING SETS ((Type, SomeIntColumn ), ())
ORDER BY SomeIntColumn --Displays summary row as the first row in query result

How can I get the line number which threw exception?

Update to the answer

    // Get stack trace for the exception with source file information
    var st = new StackTrace(ex, true);
    // Get the top stack frame
    var frame = st.GetFrame(st.FrameCount-1);
    // Get the line number from the stack frame
    var line = frame.GetFileLineNumber();

Is it good practice to make the constructor throw an exception?

This is totally valid, I do it all the time. I usually use IllegalArguemntException if it is a result of parameter checking.

In this case I wouldn't suggest asserts because they are turned off in a deployment build and you always want to stop this from happening, but they are valid if your group does ALL it's testing with asserts turned on and you think the chance of missing a parameter problem at runtime is more acceptable than throwing an exception that is maybe more likely to cause a runtime crash.

Also, an assert would be more difficult for the caller to trap, this is easy.

You probably want to list it as a "throws" in your method's javadocs along with the reason so that callers aren't surprised.

Resolve Javascript Promise outside function scope

I find myself missing the Deferred pattern as well in certain cases. You can always create one on top of a ES6 Promise:

export default class Deferred<T> {
    private _resolve: (value: T) => void = () => {};
    private _reject: (value: T) => void = () => {};

    private _promise: Promise<T> = new Promise<T>((resolve, reject) => {
        this._reject = reject;
        this._resolve = resolve;
    })

    public get promise(): Promise<T> {
        return this._promise;
    }

    public resolve(value: T) {
        this._resolve(value);
    }

    public reject(value: T) {
        this._reject(value);
    }
}

Java collections convert a string to a list of characters

List<String> result = Arrays.asList("abc".split(""));

How do I convert date/time from 24-hour format to 12-hour AM/PM?

Use smaller h

// 24 hrs 
H:i 
// output 14:20

// 12 hrs 
h:i 
// output 2:20

Visual Studio build fails: unable to copy exe-file from obj\debug to bin\debug

When I faced a similar issue, the only thing that seemed to work was:

  • Right click the project, going to Settings, and making sure that both Debug and Release builds target the same settings, or have the settings in there that the application tries to load or save.
  • Deleting the C:\Users(YourUserAccount)\AppData\Local(YourAppName) folder.
  • Making sure that no files that I had in there were considered "Blocked". Right-clicking my project's included files, I realized that one icon was actually blocked and considered bad because it was downloaded from the internet. I had to click the Unblock button (in example, check this out: http://devierkoeden.com/Images/Articles/Dynamicweb/CustomModules/Part1/BlockedFiles.png - "This file came from another computer and might be blocked to help protect this computer.").

Share cookie between subdomain and domain

Be careful if you are working on localhost ! If you store your cookie in js like this:

document.cookie = "key=value;domain=localhost"

It might not be accessible to your subdomain, like sub.localhost. In order to solve this issue you need to use Virtual Host. For exemple you can configure your virtual host with ServerName localhost.com then you will be able to store your cookie on your domain and subdomain like this:

document.cookie = "key=value;domain=localhost.com"

Undefined or null for AngularJS

You can always add it exactly for your application

angular.isUndefinedOrNull = function(val) {
    return angular.isUndefined(val) || val === null 
}

Is quitting an application frowned upon?

It took me longer to read this Q&A than to actually implement a semi-proper Android Application Lifecycle.

It's a GPS app that polls for points and sends the current location to a webservice every few seconds using a thread... This could be polling every 5 minutes in Ted's case for an update, then onStop can simply start the update activity Ted was soo concerned about if one was found (asynchronous Ted, don't code like a Windows programmer or your programs will run like Windows programs ... eww, it's not that hard).

I did some initial code in onCreate to set up things for the activity lifetime, including checkUpdate.start();:

...

@Override
public void onStart() {
    super.onStart();
    isRemote = true;
    checkUpdate.resume();

    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 0, luh);
}

@Override
public void onPause() {
    isRemote = false;
    checkUpdate.suspend();
    locationManager.removeUpdates(luh);
    super.onStop();
}

This code may be completely wrong, but it works. This is one of my first Android applications.

Voilà, an application that doesn't consume CPU when it's in the background, yet is instantly ready to reopen because it is in RAM (although not holding RAM as is the Android lifecycle) ... an app is always ready, it's a phone, guys/gals. If an app was to use up all the RAM and couldn't be shut down by the OS then the thing might stop ringing =P That's why the OS needs to be able to close your app when it's in the background (if your application isn't a resource hog it won't be closed BTW), so let's just write better applications.

How to get the current branch name in Git?

Well simple enough, I got it in a one liner (bash)

git branch | sed -n '/\* /s///p'

(credit: Limited Atonement)

And while I am there, the one liner to get the remote tracking branch (if any)

git rev-parse --symbolic-full-name --abbrev-ref @{u}

Maven fails to find local artifact

If you have <repositories/> defined in your pom.xml apparently your local repository is ignored.

clear javascript console in Google Chrome

On the Chrome console right click with the mouse and We have the option to clear the console

Iterate through 2 dimensional array

Simple idea: get the lenght of the longest row, iterate over each column printing the content of a row if it has elements. The below code might have some off-by-one errors as it was coded in a simple text editor.

  int longestRow = 0;
  for (int i = 0; i < array.length; i++) {
    if (array[i].length > longestRow) {
      longestRow = array[i].length;
    }
  }

  for (int j = 0; j < longestRow; j++) {
    for (int i = 0; i < array.length; i++) {
      if(array[i].length > j) {
        System.out.println(array[i][j]);
      }
    }
  }

Git, fatal: The remote end hung up unexpectedly

Contrary to one of the other answers - I had the problem on push using ssh - I switched to https and it was fixed.

git remote remove origin
git remote add origin https://github..com/user/repo
git push --set-upstream origin master

Handling back button in Android Navigation Component

Just add these lines

     override fun onBackPressed() {
            if(navController.popBackStack().not()) {
            //Last fragment: Do your operation here 
            finish()
   } 

navController.popBackStack() will just pop your fragment if this is not your last fragment

DOM element to corresponding vue.js component

The proper way to do with would be to use the v-el directive to give it a reference. Then you can do this.$$[reference].

Update for vue 2

In Vue 2 refs are used for both elements and components: http://vuejs.org/guide/migration.html#v-el-and-v-ref-replaced

How to change the font color of a disabled TextBox?

In addition to the answer by @spoon16 and @Cheetah, I always set the tabstop property to False on the textbox to prevent the text from being selected by default.

Alternatively, you can also do something like this:

private void FormFoo_Load(...) {
    txtFoo.Select(0, 0);
}

or

private void FormFoo_Load(...) {
    txtFoo.SelectionLength = 0;
}

Convert milliseconds to date (in Excel)

Converting your value in milliseconds to days is simply (MsValue / 86,400,000)

We can get 1/1/1970 as numeric value by DATE(1970,1,1)

= (MsValueCellReference / 86400000) + DATE(1970,1,1)

Using your value of 1271664970687 and formatting it as dd/mm/yyyy hh:mm:ss gives me a date and time of 19/04/2010 08:16:11

How to programmatically take a screenshot on Android?

public class ScreenShotActivity extends Activity{

private RelativeLayout relativeLayout;
private Bitmap myBitmap;

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

    relativeLayout = (RelativeLayout)findViewById(R.id.relative1);
    relativeLayout.post(new Runnable() {
        public void run() {

            //take screenshot
            myBitmap = captureScreen(relativeLayout);

            Toast.makeText(getApplicationContext(), "Screenshot captured..!", Toast.LENGTH_LONG).show();

            try {
                if(myBitmap!=null){
                    //save image to SD card
                    saveImage(myBitmap);
                }
                Toast.makeText(getApplicationContext(), "Screenshot saved..!", Toast.LENGTH_LONG).show();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    });

}

public static Bitmap captureScreen(View v) {

    Bitmap screenshot = null;
    try {

        if(v!=null) {

            screenshot = Bitmap.createBitmap(v.getMeasuredWidth(),v.getMeasuredHeight(), Config.ARGB_8888);
            Canvas canvas = new Canvas(screenshot);
            v.draw(canvas);
        }

    }catch (Exception e){
        Log.d("ScreenShotActivity", "Failed to capture screenshot because:" + e.getMessage());
    }

    return screenshot;
}

public static void saveImage(Bitmap bitmap) throws IOException{

    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 40, bytes);
    File f = new File(Environment.getExternalStorageDirectory() + File.separator + "test.png");
    f.createNewFile();
    FileOutputStream fo = new FileOutputStream(f);
    fo.write(bytes.toByteArray());
    fo.close();
}

}

ADD PERMISSION

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

How to calculate difference in hours (decimal) between two dates in SQL Server?

Just subtract the two datetime values and multiply by 24:

  Select Cast((@DateTime2 - @DateTime1) as Float) * 24.0

a test script might be:

  Declare @Dt1 dateTime Set @Dt1 = '12 Jan 2009 11:34:12'
  Declare @Dt2 dateTime Set @Dt2 = getdate()

  Select Cast((@Dt2 - @Dt1) as Float) * 24.0

This works because all datetimes are stored internally as a pair of integers, the first integer is the number of days since 1 Jan 1900, and the second integer (representing the time) is the number of (1) ticks since Midnight. (For SmallDatetimes the time portion integer is the number of minutes since midnight). Any arithmetic done on the values uses the time portion as a fraction of a day. 6am = 0.25, noon = 0.5, etc... See MSDN link here for more details.

So Cast((@Dt2 - @Dt1) as Float) gives you total days between two datetimes. Multiply by 24 to convert to hours. If you need total minutes, Multiple by Minutes per day (24 * 60 = 1440) instead of 24...

NOTE 1: This is not the same as a dotNet or javaScript tick - this tick is about 3.33 milliseconds.

ES6 Class Multiple inheritance

I spent half a week trying to figure this out myself, and wrote a whole article on it, https://github.com/latitov/OOP_MI_Ct_oPlus_in_JS, and hope it helps some of you.

In short, here's how MI can be implemented in JavaScript:

    class Car {
        constructor(brand) {
            this.carname = brand;
        }
        show() {
            return 'I have a ' + this.carname;
        }
    }

    class Asset {
        constructor(price) {
            this.price = price;
        }
        show() {
            return 'its estimated price is ' + this.price;
        }
    }

    class Model_i1 {        // extends Car and Asset (just a comment for ourselves)
        //
        constructor(brand, price, usefulness) {
            specialize_with(this, new Car(brand));
            specialize_with(this, new Asset(price));
            this.usefulness = usefulness;
        }
        show() {
            return Car.prototype.show.call(this) + ", " + Asset.prototype.show.call(this) + ", Model_i1";
        }
    }

    mycar = new Model_i1("Ford Mustang", "$100K", 16);
    document.getElementById("demo").innerHTML = mycar.show();

And here's specialize_with() one-liner:

function specialize_with(o, S) { for (var prop in S) { o[prop] = S[prop]; } }

Again, please look at https://github.com/latitov/OOP_MI_Ct_oPlus_in_JS.

How to build a JSON array from mysql database

Is something like this what you want to do?

$return_arr = array();

$fetch = mysql_query("SELECT * FROM table"); 

while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
    $row_array['id'] = $row['id'];
    $row_array['col1'] = $row['col1'];
    $row_array['col2'] = $row['col2'];

    array_push($return_arr,$row_array);
}

echo json_encode($return_arr);

It returns a json string in this format:

[{"id":"1","col1":"col1_value","col2":"col2_value"},{"id":"2","col1":"col1_value","col2":"col2_value"}]

OR something like this:

$year = date('Y');
$month = date('m');

$json_array = array(

//Each array below must be pulled from database
    //1st record
    array(
    'id' => 111,
    'title' => "Event1",
    'start' => "$year-$month-10",
    'url' => "http://yahoo.com/"
),

     //2nd record
     array(
    'id' => 222,
    'title' => "Event2",
    'start' => "$year-$month-20",
    'end' => "$year-$month-22",
    'url' => "http://yahoo.com/"
)

);

echo json_encode($json_array);

Using % for host when creating a MySQL user

The percent symbol means: any host, including remote and local connections.

The localhost allows only local connections.

(so to start off, if you don't need remote connections to your database, you can get rid of the appuser@'%' user right away)

So, yes, they are overlapping, but...

...there is a reason for setting both types of accounts, this is explained in the mysql docs: http://dev.mysql.com/doc/refman/5.7/en/adding-users.html.

If you have an have an anonymous user on your localhost, which you can spot with:

select Host from mysql.user where User='' and Host='localhost';

and if you just create the user appuser@'%' (and you not the appuser@'localhost'), then when the appuser mysql user connects from the local host, the anonymous user account is used (it has precedence over your appuser@'%' user).

And the fix for this is (as one can guess) to create the appuser@'localhost' (which is more specific that the local host anonymous user and will be used if your appuser connects from the localhost).

Space between two rows in a table?

Or just add a blank with the height of the margin in between the rows you would like to add the spacing

How to check for an empty struct?

Keep in mind that with pointers to struct you'd have to dereference the variable and not compare it with a pointer to empty struct:

session := &Session{}
if (Session{}) == *session {
    fmt.Println("session is empty")
}

Check this playground.

Also here you can see that a struct holding a property which is a slice of pointers cannot be compared the same way...

Why shouldn't I use mysql_* functions in PHP?

There are many reasons, but perhaps the most important one is that those functions encourage insecure programming practices because they do not support prepared statements. Prepared statements help prevent SQL injection attacks.

When using mysql_* functions, you have to remember to run user-supplied parameters through mysql_real_escape_string(). If you forget in just one place or if you happen to escape only part of the input, your database may be subject to attack.

Using prepared statements in PDO or mysqli will make it so that these sorts of programming errors are more difficult to make.

Get selected option text with JavaScript

 <select class="cS" onChange="fSel2(this.value);">
     <option value="0">S?lectionner</option>
     <option value="1">Un</option>
     <option value="2" selected>Deux</option>
     <option value="3">Trois</option>
 </select>

 <select id="iS1" onChange="fSel(options[this.selectedIndex].value);">
     <option value="0">S?lectionner</option>
     <option value="1">Un</option>
     <option value="2" selected>Deux</option>
     <option value="3">Trois</option>
 </select><br>

 <select id="iS2" onChange="fSel3(options[this.selectedIndex].text);">
     <option value="0">S?lectionner</option>
     <option value="1">Un</option>
     <option value="2" selected>Deux</option>
     <option value="3">Trois</option>
 </select>

 <select id="iS3" onChange="fSel3(options[this.selectedIndex].textContent);">
     <option value="0">S?lectionner</option>
     <option value="1">Un</option>
     <option value="2" selected>Deux</option>
     <option value="3">Trois</option>
 </select>

 <select id="iS4" onChange="fSel3(options[this.selectedIndex].label);">
     <option value="0">S?lectionner</option>
     <option value="1">Un</option>
     <option value="2" selected>Deux</option>
     <option value="3">Trois</option>
 </select>

 <select id="iS4" onChange="fSel3(options[this.selectedIndex].innerHTML);">
     <option value="0">S?lectionner</option>
     <option value="1">Un</option>
     <option value="2" selected>Deux</option>
     <option value="3">Trois</option>
 </select>

 <script type="text/javascript"> "use strict";
   const s=document.querySelector(".cS");

 // options[this.selectedIndex].value
 let fSel = (sIdx) => console.log(sIdx,
     s.options[sIdx].text, s.options[sIdx].textContent, s.options[sIdx].label);

 let fSel2= (sIdx) => { // this.value
     console.log(sIdx, s.options[sIdx].text,
         s.options[sIdx].textContent, s.options[sIdx].label);
 }

 // options[this.selectedIndex].text
 // options[this.selectedIndex].textContent
 // options[this.selectedIndex].label
 // options[this.selectedIndex].innerHTML
 let fSel3= (sIdx) => {
     console.log(sIdx);
 }
 </script> // fSel

But :

 <script type="text/javascript"> "use strict";
    const x=document.querySelector(".cS"),
          o=x.options, i=x.selectedIndex;
    console.log(o[i].value,
                o[i].text , o[i].textContent , o[i].label , o[i].innerHTML);
 </script> // .cS"

And also this :

 <select id="iSel" size="3">
     <option value="one">Un</option>
     <option value="two">Deux</option>
     <option value="three">Trois</option>
 </select>


 <script type="text/javascript"> "use strict";
    const i=document.getElementById("iSel");
    for(let k=0;k<i.length;k++) {
        if(k == i.selectedIndex) console.log("Selected ".repeat(3));
        console.log(`${Object.entries(i.options)[k][1].value}`+
                    ` => ` +
                    `${Object.entries(i.options)[k][1].innerHTML}`);
        console.log(Object.values(i.options)[k].value ,
                    " => ",
                    Object.values(i.options)[k].innerHTML);
        console.log("=".repeat(25));
    }
 </script>

What is hashCode used for? Is it unique?

This is from the msdn article here:

https://blogs.msdn.microsoft.com/tomarcher/2006/05/10/are-hash-codes-unique/

"While you will hear people state that hash codes generate a unique value for a given input, the fact is that, while difficult to accomplish, it is technically feasible to find two different data inputs that hash to the same value. However, the true determining factors regarding the effectiveness of a hash algorithm lie in the length of the generated hash code and the complexity of the data being hashed."

So just use a hash algorithm suitable to your data size and it will have unique hashcodes.

How to remove text from a string?

Ex:-

var value="Data-123";
var removeData=value.replace("Data-","");
alert(removeData);

Hopefully this will work for you.

How to echo (or print) to the js console with php

<?php
   echo '<script>console.log("Your stuff here")</script>';
?>

NoSuchMethodError in javax.persistence.Table.indexes()[Ljavax/persistence/Index

I could solve the issue simply by replacing the JPA api jar file which is located jboss7/modules/javax/persistence/api/main with 'hibernate-jpa-2.1-api'. also with updating module.xml in the directory.

java.io.IOException: Could not locate executable null\bin\winutils.exe in the Hadoop binaries. spark Eclipse on windows 7

Follow this:

  1. Create a bin folder in any directory(to be used in step 3).

  2. Download winutils.exe and place it in the bin directory.

  3. Now add System.setProperty("hadoop.home.dir", "PATH/TO/THE/DIR"); in your code.

Platform.runLater and Task in JavaFX

  • Platform.runLater: If you need to update a GUI component from a non-GUI thread, you can use that to put your update in a queue and it will be handled by the GUI thread as soon as possible.
  • Task implements the Worker interface which is used when you need to run a long task outside the GUI thread (to avoid freezing your application) but still need to interact with the GUI at some stage.

If you are familiar with Swing, the former is equivalent to SwingUtilities.invokeLater and the latter to the concept of SwingWorker.

The javadoc of Task gives many examples which should clarify how they can be used. You can also refer to the tutorial on concurrency.

jquery datatables hide column

if anyone gets in here again this worked for me...

"aoColumnDefs": [{ "bVisible": false, "aTargets": [0] }]

How can I get a JavaScript stack trace when I throw an exception?

Edit 2 (2017):

In all modern browsers you can simply call: console.trace(); (MDN Reference)

Edit 1 (2013):

A better (and simpler) solution as pointed out in the comments on the original question is to use the stack property of an Error object like so:

function stackTrace() {
    var err = new Error();
    return err.stack;
}

This will generate output like this:

DBX.Utils.stackTrace@http://localhost:49573/assets/js/scripts.js:44
DBX.Console.Debug@http://localhost:49573/assets/js/scripts.js:9
.success@http://localhost:49573/:462
x.Callbacks/c@http://localhost:49573/assets/js/jquery-1.10.2.min.js:4
x.Callbacks/p.fireWith@http://localhost:49573/assets/js/jquery-1.10.2.min.js:4
k@http://localhost:49573/assets/js/jquery-1.10.2.min.js:6
.send/r@http://localhost:49573/assets/js/jquery-1.10.2.min.js:6

Giving the name of the calling function along with the URL, its calling function, and so on.

Original (2009):

A modified version of this snippet may somewhat help:

function stacktrace() { 
  function st2(f) {
    return !f ? [] : 
        st2(f.caller).concat([f.toString().split('(')[0].substring(9) + '(' + f.arguments.join(',') + ')']);
  }
  return st2(arguments.callee.caller);
}

Sorting dictionary keys in python

>>> mydict = {'a':1,'b':3,'c':2}
>>> sorted(mydict, key=lambda key: mydict[key])
['a', 'c', 'b']

CSS Font "Helvetica Neue"

This font is not standard on all devices. It is installed by default on some Macs, but rarely on PCs and mobile devices.

To use this font on all devices, use a @font-face declaration in your CSS to link to it on your domain if you wish to use it.

@font-face { font-family: Delicious; src: url('Delicious-Roman.otf'); } 
@font-face { font-family: Delicious; font-weight: bold; src: url('Delicious-Bold.otf'); }

Taken from css3.info

remove inner shadow of text input

border-style:solid; will override the inset style. Which is what you asked.

border:none will remove the border all together.

border-width:1px will set it up to be kind of like before the background change.

border:1px solid #cccccc is more specific and applies all three, width, style and color.

Example: https://jsbin.com/quleh/2/edit?html,output

Can't fix Unsupported major.minor version 52.0 even after fixing compatibility

Several possiblies that causes this problem. The root cause is mismatched of compiler version between projects and IDE. For windows environment you can refer to this blog to do the detail troubleshooting.

Difference between Spring MVC and Struts MVC

The main difference between struts & spring MVC is about the difference between Aspect Oriented Programming (AOP) & Object oriented programming (OOP).

Spring makes application loosely coupled by using Dependency Injection.The core of the Spring Framework is the IoC container.

OOP can do everything that AOP does but different approach. In other word, AOP complements OOP by providing another way of thinking about program structure.

Practically, when you want to apply same changes for many files. It should be exhausted work with Struts to add same code for tons of files. Instead Spring write new changes somewhere else and inject to the files.

Some related terminologies of AOP is cross-cutting concerns, Aspect, Dependency Injection...

Convert ArrayList to String array in Android

Well in general:

List<String> names = new ArrayList<String>();
names.add("john");
names.add("ann");

String[] namesArr = new String[names.size()];
for (int i = 0; i < names.size(); i++) {
    namesArr[i] = names.get(i);  
}

Or better yet, using built in:

List<String> names = new ArrayList<String>();
String[] namesArr = names.toArray(new String[names.size()]);

What's the difference between & and && in MATLAB?

Both are logical AND operations. The && though, is a "short-circuit" operator. From the MATLAB docs:

They are short-circuit operators in that they evaluate their second operand only when the result is not fully determined by the first operand.

See more here.

jQuery iframe load() event?

Along the lines of Tim Down's answer but leveraging jQuery (mentioned by the OP) and loosely coupling the containing page and the iframe, you could do the following:

In the iframe:

<script>
    $(function() {
        var w = window;
        if (w.frameElement != null
                && w.frameElement.nodeName === "IFRAME"
                && w.parent.jQuery) {
            w.parent.jQuery(w.parent.document).trigger('iframeready');
        }
    });
</script>

In the containing page:

<script>
    function myHandler() {
        alert('iframe (almost) loaded');
    }
    $(document).on('iframeready', myHandler);
</script>

The iframe fires an event on the (potentially existing) parent window's document - please beware that the parent document needs a jQuery instance of itself for this to work. Then, in the parent window you attach a handler to react to that event.

This solution has the advantage of not breaking when the containing page does not contain the expected load handler. More generally speaking, it shouldn't be the concern of the iframe to know its surrounding environment.

Please note, that we're leveraging the DOM ready event to fire the event - which should be suitable for most use cases. If it's not, simply attach the event trigger line to the window's load event like so:

$(window).on('load', function() { ... });

Floating point inaccuracy examples

Another example, in C

printf (" %.20f \n", 3.6);

incredibly gives

3.60000000000000008882

How to decide when to use Node.js?

I believe Node.js is best suited for real-time applications: online games, collaboration tools, chat rooms, or anything where what one user (or robot? or sensor?) does with the application needs to be seen by other users immediately, without a page refresh.

I should also mention that Socket.IO in combination with Node.js will reduce your real-time latency even further than what is possible with long polling. Socket.IO will fall back to long polling as a worst case scenario, and instead use web sockets or even Flash if they are available.

But I should also mention that just about any situation where the code might block due to threads can be better addressed with Node.js. Or any situation where you need the application to be event-driven.

Also, Ryan Dahl said in a talk that I once attended that the Node.js benchmarks closely rival Nginx for regular old HTTP requests. So if we build with Node.js, we can serve our normal resources quite effectively, and when we need the event-driven stuff, it's ready to handle it.

Plus it's all JavaScript all the time. Lingua Franca on the whole stack.

How to add custom validation to an AngularJS form?

Some great examples and libs presented in this thread, but they didn't quite have what I was looking for. My approach: angular-validity -- a promise based validation lib for asynchronous validation, with optional Bootstrap styling baked-in.

An angular-validity solution for the OP's use case might look something like this:

<input  type="text" name="field4" ng-model="field4"
        validity="eval"
        validity-eval="!(field1 && field2 && field3 && !field4)"
        validity-message-eval="This field is required">

Here's a Fiddle, if you want to take it for a spin. The lib is available on GitHub, has detailed documentation, and plenty of live demos.

React "after render" code?

I had weird situation when i need to print react component which receives big amount of data and paint in on canvas. I've tried all mentioned approaches, non of them worked reliably for me, with requestAnimationFrame inside setTimeout i get empty canvas in 20% of the time, so i did the following:

nRequest = n => range(0,n).reduce(
(acc,val) => () => requestAnimationFrame(acc), () => requestAnimationFrame(this.save)
);

Basically i made a chain of requestAnimationFrame's, not sure is this good idea or not but this works in 100% of the cases for me so far (i'm using 30 as a value for n variable).

TSQL - Cast string to integer or return default value

I would rather create a function like TryParse or use T-SQL TRY-CATCH block to get what you wanted.

ISNUMERIC doesn't always work as intended. The code given before will fail if you do:

SET @text = '$'

$ sign can be converted to money datatype, so ISNUMERIC() returns true in that case. It will do the same for '-' (minus), ',' (comma) and '.' characters.

git push to specific branch

If your Local branch and remote branch is the same name then you can just do it:

git push origin branchName

When your local and remote branch name is different then you can just do it:

git push origin localBranchName:remoteBranchName

Avoid synchronized(this) in Java?

The java.util.concurrent package has vastly reduced the complexity of my thread safe code. I only have anecdotal evidence to go on, but most work I have seen with synchronized(x) appears to be re-implementing a Lock, Semaphore, or Latch, but using the lower-level monitors.

With this in mind, synchronizing using any of these mechanisms is analogous to synchronizing on an internal object, rather than leaking a lock. This is beneficial in that you have absolute certainty that you control the entry into the monitor by two or more threads.

Failed to load resource under Chrome

Kabir's solution is correct. My image URL was

/images/ads/homepage/small-banners01.png, 

and this was tripping up AdBlock. This wasn't a cross-domain issue for me, and it failed on both localhost and on the web.

I was using Chrome's network tab to debug and finding very confusing results for these specific images that failed to load. The first request would return no response (Status "(pending)"). Later down the line, there was a second request that listed the original URL and then "Redirect" as the Initiator. The redirect request headers were all for this identical short line of base64-encoded data, and each returned no response, although the status was "Successful":

GET      data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAACklEQVR4nGMAAQAABQABDQottAAAAABJRU5ErkJggg== HTTP/1.1

Later I noticed that these inline styles were added to all the image elements:

    display: none !important;
    visibility: hidden !important;
    opacity: 0 !important;

Finally, I did not receive any "failed to load resource" messages in the console, but rather this:

Port error: Could not establish connection. Receiving end does not exist.

If any of these things is happening to you, it probably has something to do with AdBlock. Turn it off and/or rename your image files.

Also, because of the inline CSS created by AdBlock, the layout of my promotions slider was being thrown off. While I was able to fix the layout issues with CSS before finding Kabir's solution, the CSS was somewhat unnecessary and affected the flexibility of the slider to handle images of multiple sizes.

I guess the lesson is: Be careful what you name your images. These images weren't malicious or annoying as much as they were alerting visitors to current promotions and specials in an unobtrusive way.

"Exception has been thrown by the target of an invocation" error (mscorlib)

I know its kind of odd but I experienced this error for a c# application and finally I found out the problem is the Icon of the form! when I changed it everything just worked fine.

I should say that I had this error just in XP not in 7 or 8 .

C# Macro definitions in Preprocessor

Since C# 7.0 supports using static directive and Local functions you don't need preprocessor macros for most cases.

Properties file with a list as the value for an individual key

If this is for some configuration file processing, consider using Apache configuration. https://commons.apache.org/proper/commons-configuration/javadocs/v1.10/apidocs/index.html?org/apache/commons/configuration/PropertiesConfiguration.html It has way to multiple values to single key- The format is bit different though

key=value1,value2,valu3 gives three values against same key.

How to get GMT date in yyyy-mm-dd hh:mm:ss in PHP

Use below date function to get current time in MySQL format/(As requested on question also)

echo date("Y-m-d H:i:s", time());

how to force maven to update local repo

If you are installing into local repository, there is no special index/cache update needed.

Make sure that:

  1. You have installed the first artifact in your local repository properly. Simply copying the file to .m2 may not work as expected. Make sure you install it by mvn install

  2. The dependency in 2nd project is setup correctly. Check on any typo in groupId/artifactId/version, or unmatched artifact type/classifier.

How to Deserialize XML document

I don't think .net is 'picky about deserializing arrays'. The first xml document is not well formed. There is no root element, although it looks like there is. The canonical xml document has a root and at least 1 element (if at all). In your example:

<Root> <-- well, the root
  <Cars> <-- an element (not a root), it being an array
    <Car> <-- an element, it being an array item
    ...
    </Car>
  </Cars>
</Root>

Junit - run set up method once

When setUp() is in a superclass of the test class (e.g. AbstractTestBase below), the accepted answer can be modified as follows:

public abstract class AbstractTestBase {
    private static Class<? extends AbstractTestBase> testClass;
    .....
    public void setUp() {
        if (this.getClass().equals(testClass)) {
            return;
        }

        // do the setup - once per concrete test class
        .....
        testClass = this.getClass();
    }
}

This should work for a single non-static setUp() method but I'm unable to produce an equivalent for tearDown() without straying into a world of complex reflection... Bounty points to anyone who can!

Email Address Validation for ASP.NET

Preventing XSS is a different issue from validating input.

Regarding XSS: You should not try to check input for XSS or related exploits. You should prevent XSS exploits, SQL injection and so on by escaping correctly when inserting strings into a different language where some characters are "magic", eg, when inserting strings in HTML or SQL. For example a name like O'Reilly is perfectly valid input, but could cause a crash or worse if inserted unescaped into SQL. You cannot prevent that kind of problems by validating input.

Validation of user input makes sense to prevent missing or malformed data, eg. a user writing "asdf" in the zip-code field and so on. Wrt. e-mail adresses, the syntax is so complex though, that it doesnt provide much benefit to validate it using a regex. Just check that it contains a "@".

Unsupported method: BaseConfig.getApplicationIdSuffix()

Change your gradle version or update it

dependencies {
    classpath 'com.android.tools.build:gradle:3.0.1'
}

alt+enter and choose "replace with specific version".

Convert date field into text in Excel

You don't need to convert the original entry - you can use TEXT function in the concatenation formula, e.g. with date in A1 use a formula like this

="Today is "&TEXT(A1,"dd-mm-yyyy")

You can change the "dd-mm-yyyy" part as required

Use component from another module

Whatever you want to use from another module, just put it in the export array. Like this-

 @NgModule({
  declarations: [TaskCardComponent],
  exports: [TaskCardComponent],
  imports: [MdCardModule]
})

IBOutlet and IBAction

IBAction and IBOutlet are macros defined to denote variables and methods that can be referred to in Interface Builder.

IBAction resolves to void and IBOutlet resolves to nothing, but they signify to Xcode and Interface builder that these variables and methods can be used in Interface builder to link UI elements to your code.

If you're not going to be using Interface Builder at all, then you don't need them in your code, but if you are going to use it, then you need to specify IBAction for methods that will be used in IB and IBOutlet for objects that will be used in IB.

Best practices with STDIN in Ruby?

Following are some things I found in my collection of obscure Ruby.

So, in Ruby, a simple no-bells implementation of the Unix command cat would be:

#!/usr/bin/env ruby
puts ARGF.read

ARGF is your friend when it comes to input; it is a virtual file that gets all input from named files or all from STDIN.

ARGF.each_with_index do |line, idx|
    print ARGF.filename, ":", idx, ";", line
end

# print all the lines in every file passed via command line that contains login
ARGF.each do |line|
    puts line if line =~ /login/
end

Thank goodness we didn’t get the diamond operator in Ruby, but we did get ARGF as a replacement. Though obscure, it actually turns out to be useful. Consider this program, which prepends copyright headers in-place (thanks to another Perlism, -i) to every file mentioned on the command-line:

#!/usr/bin/env ruby -i

Header = DATA.read

ARGF.each_line do |e|
  puts Header if ARGF.pos - e.length == 0
  puts e
end

__END__
#--
# Copyright (C) 2007 Fancypants, Inc.
#++

Credit to:

Making the iPhone vibrate

For an iPhone 7/7 Plus or newer, use these three Haptic feedback APIs.

Available APIs

For notifications:

let generator = UINotificationFeedbackGenerator()
generator.notificationOccured(style: .error)

Available styles are .error, .success, and .warning. Each has its own distinctive feel.
From the docs:

A concrete UIFeedbackGenerator subclass that creates haptics to communicate successes, failures, and warnings.

For simple vibrations:

let generator = UIImpactFeedbackGenerator(style: .medium)
generator.impactOccured()

Available styles are .heavy, .medium, and .light. These are simple vibrations with varying degrees of "hardness".
From the docs:

A concrete UIFeedbackGenerator subclass that creates haptics to simulate physical impacts

For when the user selected an item

let generator = UISelectionFeedbackGenerator()
generator.selectionChanged()

This is the least noticeable of all the haptics, and so is the most suitable for when haptics should not be taking over the app experience.
From the docs:

A concrete UIFeedbackGenerator subclass that creates haptics to indicate a change in selection.

Notes

There are a couple of things worth remembering when using these APIs.

Note A

You do not actually create the haptic. You request the system generate a haptic. The system will decide based on the below:

  • If haptics are possible on the device (whether it has a Taptic Engine in this case)
  • Whether the app may record audio (haptics do not generate during recording to prevent unwanted interference)
  • Whether haptics are enabled in system Settings.

Therefore, the system will silently ignore your request for a haptic if it is not possible. If this is due to an unsupported device, you could try this:

func haptic() {
    // Get whether the device can generate haptics or not
    // If feedbackSupportLevel is nil, will assign 0
    let feedbackSupportLevel = UIDevice.current.value(forKey: "_feedbackSupportLevel") as? Int ?? 0

    switch feedbackSupportLevel { 
    case 2:
        // 2 means the device has a Taptic Engine
        // Put Taptic Engine code here, using the APIs explained above

    case 1: 
    // 1 means no Taptic Engine, but will support AudioToolbox
    // AudioToolbox code from the myriad of other answers!

    default: // 0
        // No haptic support
        // Do something else, like a beeping noise or LED flash instead of haptics
    }

Substitute the comments in the switch-case statements, and this haptic generation code will be portable to other iOS devices. It will generate the highest level of haptic possible.

Note B

  • Due to the fact that generating haptics is a hardware-level task, there may be latency between when you call the haptic-generation code, and when it actually happens. For this reason, the Taptic Engine APIs all have a prepare() method, to put it in a state of readiness. Using your Game Over example: You may know that the game is about to end, by the user having very low HP, or a dangerous monster being near them.
  • If you don't generate a haptic within a few seconds, the Taptic Engine will go back into an idle state (to save battery life)


In this case, preparing the Taptic Engine would create a higher-quality, more responsive experience.

For example, let's say your app uses a pan gesture recogniser to change the portion of the world visible. You want a haptic to generate when the user 'looks' round 360 degrees. Here is how you could use prepare():

@IBAction func userChangedViewablePortionOfWorld(_ gesture: UIPanGestureRecogniser!) {

    haptic = UIImpactFeedbackGenerator(style: .heavy)

    switch gesture.state {
        case .began:
            // The user started dragging the screen.
            haptic.prepare()

        case .changed:
            // The user trying to 'look' in another direction
            // Code to change viewable portion of the virtual world

            if virtualWorldViewpointDegreeMiddle = 360.0 { 
                haptic.impactOccured()
            }
        
        default:
            break

} 

Where should I put the CSS and Javascript code in an HTML webpage?

You should put it in the <head>. I typically put style references above JS and I order my JS from top to bottom if some of them are dependent on others, but I beleive all of the references are loaded before the page is rendered.

How to log PostgreSQL queries?

There is an extension in postgresql for this. It's name is "pg_stat_statements". https://www.postgresql.org/docs/9.4/pgstatstatements.html

Basically you have to change postgresql.conf file a little bit:

shared_preload_libraries= 'pg_stat_statements'
pg_stat_statements.track = 'all'

Then you have to log in DB and run this command:

create extension pg_stat_statements;

It will create new view with name "pg_stat_statements". In this view you can see all the executed queries.

ECMAScript 6 class destructor

If there is no such mechanism, what is a pattern/convention for such problems?

The term 'cleanup' might be more appropriate, but will use 'destructor' to match OP

Suppose you write some javascript entirely with 'function's and 'var's. Then you can use the pattern of writing all the functions code within the framework of a try/catch/finally lattice. Within finally perform the destruction code.

Instead of the C++ style of writing object classes with unspecified lifetimes, and then specifying the lifetime by arbitrary scopes and the implicit call to ~() at scope end (~() is destructor in C++), in this javascript pattern the object is the function, the scope is exactly the function scope, and the destructor is the finally block.

If you are now thinking this pattern is inherently flawed because try/catch/finally doesn't encompass asynchronous execution which is essential to javascript, then you are correct. Fortunately, since 2018 the asynchronous programming helper object Promise has had a prototype function finally added to the already existing resolve and catch prototype functions. That means that that asynchronous scopes requiring destructors can be written with a Promise object, using finally as the destructor. Furthermore you can use try/catch/finally in an async function calling Promises with or without await, but must be aware that Promises called without await will be execute asynchronously outside the scope and so handle the desctructor code in a final then.

In the following code PromiseA and PromiseB are some legacy API level promises which don't have finally function arguments specified. PromiseC DOES have a finally argument defined.

async function afunc(a,b){
    try {
        function resolveB(r){ ... }
        function catchB(e){ ... }
        function cleanupB(){ ... }
        function resolveC(r){ ... }
        function catchC(e){ ... }
        function cleanupC(){ ... }
        ...
        // PromiseA preced by await sp will finish before finally block.  
        // If no rush then safe to handle PromiseA cleanup in finally block 
        var x = await PromiseA(a);
        // PromiseB,PromiseC not preceded by await - will execute asynchronously
        // so might finish after finally block so we must provide 
        // explicit cleanup (if necessary)
        PromiseB(b).then(resolveB,catchB).then(cleanupB,cleanupB);
        PromiseC(c).then(resolveC,catchC,cleanupC);
    }
    catch(e) { ... }
    finally { /* scope destructor/cleanup code here */ }
}

I am not advocating that every object in javascript be written as a function. Instead, consider the case where you have a scope identified which really 'wants' a destructor to be called at its end of life. Formulate that scope as a function object, using the pattern's finally block (or finally function in the case of an asynchronous scope) as the destructor. It is quite like likely that formulating that functional object obviated the need for a non-function class which would otherwise have been written - no extra code was required, aligning scope and class might even be cleaner.

Note: As others have written, we should not confuse destructors and garbage collection. As it happens C++ destructors are often or mainly concerned with manual garbage collection, but not exclusively so. Javascript has no need for manual garbage collection, but asynchronous scope end-of-life is often a place for (de)registering event listeners, etc..

Gradle finds wrong JAVA_HOME even though it's correctly set

Before running the command try entering:

export JAVA_HOME="path_to_java_home"

Where path_to_java_home is the folder where your bin/java is.

If java is properly installed you can find it's location, by using the command:

readlink -f $(which java)

Don't forget to remove bin/java from the end of the path while putting it into JAVA_HOME

SELECT INTO a table variable in T-SQL

You could try using temporary tables...if you are not doing it from an application. (It may be ok to run this manually)

SELECT name, location INTO #userData FROM myTable
INNER JOIN otherTable ON ...
WHERE age>30

You skip the effort to declare the table that way... Helps for adhoc queries...This creates a local temp table which wont be visible to other sessions unless you are in the same session. Maybe a problem if you are running query from an app.

if you require it to running on an app, use variables declared this way :

DECLARE @userData TABLE(
    name varchar(30) NOT NULL,
    oldlocation varchar(30) NOT NULL
);

INSERT INTO @userData
SELECT name, location FROM myTable
INNER JOIN otherTable ON ...
WHERE age > 30;

Edit: as many of you mentioned updated visibility to session from connection. Creating temp tables is not an option for web applications, as sessions can be reused, stick to temp variables in those cases

How can I simulate a click to an anchor tag?

There is a simpler way to achieve it,

HTML

<a href="https://getbootstrap.com/" id="fooLinkID" target="_blank">Bootstrap is life !</a>

JavaScript

// Simulating click after 3 seconds
setTimeout(function(){
  document.getElementById('fooLinkID').click();
}, 3 * 1000);

Using plain javascript to simulate a click along with addressing the target property.

You can check working example here on jsFiddle.

CSS grid wrapping

Here's my attempt. Excuse the fluff, I was feeling extra creative.

My method is a parent div with fixed dimensions. The rest is just fitting the content inside that div accordingly.

This will rescale the images regardless of the aspect ratio. There will be no hard cropping either.

_x000D_
_x000D_
body {_x000D_
    background: #131418;_x000D_
    text-align: center;_x000D_
    margin: 0 auto;_x000D_
}_x000D_
_x000D_
.my-image-parent {_x000D_
    display: inline-block;_x000D_
    width: 300px;_x000D_
    height: 300px;_x000D_
    line-height: 300px; /* Should match your div height */_x000D_
    text-align: center;_x000D_
    font-size: 0;_x000D_
}_x000D_
_x000D_
/* Start demonstration background fluff */_x000D_
    .bg1 {background: url(https://unsplash.it/801/799);}_x000D_
    .bg2 {background: url(https://unsplash.it/799/800);}_x000D_
    .bg3 {background: url(https://unsplash.it/800/799);}_x000D_
    .bg4 {background: url(https://unsplash.it/801/801);}_x000D_
    .bg5 {background: url(https://unsplash.it/802/800);}_x000D_
    .bg6 {background: url(https://unsplash.it/800/802);}_x000D_
    .bg7 {background: url(https://unsplash.it/802/802);}_x000D_
    .bg8 {background: url(https://unsplash.it/803/800);}_x000D_
    .bg9 {background: url(https://unsplash.it/800/803);}_x000D_
    .bg10 {background: url(https://unsplash.it/803/803);}_x000D_
    .bg11 {background: url(https://unsplash.it/803/799);}_x000D_
    .bg12 {background: url(https://unsplash.it/799/803);}_x000D_
    .bg13 {background: url(https://unsplash.it/806/799);}_x000D_
    .bg14 {background: url(https://unsplash.it/805/799);}_x000D_
    .bg15 {background: url(https://unsplash.it/798/804);}_x000D_
    .bg16 {background: url(https://unsplash.it/804/799);}_x000D_
    .bg17 {background: url(https://unsplash.it/804/804);}_x000D_
    .bg18 {background: url(https://unsplash.it/799/804);}_x000D_
    .bg19 {background: url(https://unsplash.it/798/803);}_x000D_
    .bg20 {background: url(https://unsplash.it/803/797);}_x000D_
/* end demonstration background fluff */_x000D_
_x000D_
.my-image {_x000D_
    width: auto;_x000D_
    height: 100%;_x000D_
    vertical-align: middle;_x000D_
    background-size: contain;_x000D_
    background-position: center;_x000D_
    background-repeat: no-repeat;_x000D_
}
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg1"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg2"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg3"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg4"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg5"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg6"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg7"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg8"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg9"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg10"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg11"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg12"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg13"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg14"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg15"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg16"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg17"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg18"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg19"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg20"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Changing the row height of a datagridview

Try

datagridview.RowTemplate.MinimumHeight = 25;//25 is height.

I did that and it worked fine!

How to specify font attributes for all elements on an html web page?

If you specify CSS attributes for your body element it should apply to anything within <body></body> so long as you don't override them later in the stylesheet.

What's the fastest way to do a bulk insert into Postgres?

You can use COPY table TO ... WITH BINARY which is "somewhat faster than the text and CSV formats." Only do this if you have millions of rows to insert, and if you are comfortable with binary data.

Here is an example recipe in Python, using psycopg2 with binary input.

What are the differences between json and simplejson Python modules?

json is simplejson, added to the stdlib. But since json was added in 2.6, simplejson has the advantage of working on more Python versions (2.4+).

simplejson is also updated more frequently than Python, so if you need (or want) the latest version, it's best to use simplejson itself, if possible.

A good practice, in my opinion, is to use one or the other as a fallback.

try:
    import simplejson as json
except ImportError:
    import json

Open new popup window without address bars in firefox & IE

I know this is a very old question, yes, I agree we can not hide address bar in modern browsers, but we can hide the url in address bar (e.g show url about:blank), following is my work around solution.

var iframe = '<html><head><style>body, html {width: 100%; height: 100%; margin: 0; padding: 0}</style></head><body><iframe src="https://www.w3schools.com" style="height:calc(100% - 4px);width:calc(100% - 4px)"></iframe></html></body>';

var win = window.open("","","width=600,height=480,toolbar=no,menubar=no,resizable=yes");
win.document.write(iframe);

Get Client Machine Name in PHP

What's this "other information"? An IP address?

In PHP, you use $_SERVER['REMOTE_ADDR'] to get the IP address of the remote client, then you can use gethostbyaddr() to try and conver that IP into a hostname - but not all IPs have a reverse mapping configured.

Rails 3 check if attribute changed

Check out ActiveModel::Dirty (available on all models by default). The documentation is really good, but it lets you do things such as:

@user.street1_changed? # => true/false

jQuery get value of selected radio button

  1. In your code, jQuery just looks for the first instance of an input with name q12_3, which in this case has a value of 1. You want an input with name q12_3 that is :checked.
$(function(){
    $("#submit").click(function() {     
        alert($("input[name=q12_3]:checked").val());
    });
});
  1. Note that the above code is not the same as using .is(":checked"). jQuery's is() function returns a boolean (true or false) and not an element.

Restart container within pod

Is it possible to restart a single container

Not through kubectl, although depending on the setup of your cluster you can "cheat" and docker kill the-sha-goes-here, which will cause kubelet to restart the "failed" container (assuming, of course, the restart policy for the Pod says that is what it should do)

how do I restart the pod

That depends on how the Pod was created, but based on the Pod name you provided, it appears to be under the oversight of a ReplicaSet, so you can just kubectl delete pod test-1495806908-xn5jn and kubernetes will create a new one in its place (the new Pod will have a different name, so do not expect kubectl get pods to return test-1495806908-xn5jn ever again)

Returning binary file from controller in ASP.NET Web API

For anyone having the problem of the API being called more than once while downloading a fairly large file using the method in the accepted answer, please set response buffering to true System.Web.HttpContext.Current.Response.Buffer = true;

This makes sure that the entire binary content is buffered on the server side before it is sent to the client. Otherwise you will see multiple request being sent to the controller and if you do not handle it properly, the file will become corrupt.

How do I find the location of my Python site-packages directory?

A modern stdlib way is using sysconfig module, available in version 2.7 and 3.2+. Unlike the current accepted answer, this method still works regardless of whether or not you have a virtual environment active.

Note: sysconfig (source) is not to be confused with the distutils.sysconfig submodule (source) mentioned in several other answers here. The latter is an entirely different module and it's lacking the get_paths function discussed below.

Python currently uses eight paths (docs):

  • stdlib: directory containing the standard Python library files that are not platform-specific.
  • platstdlib: directory containing the standard Python library files that are platform-specific.
  • platlib: directory for site-specific, platform-specific files.
  • purelib: directory for site-specific, non-platform-specific files.
  • include: directory for non-platform-specific header files.
  • platinclude: directory for platform-specific header files.
  • scripts: directory for script files.
  • data: directory for data files.

In most cases, users finding this question would be interested in the 'purelib' path (in some cases, you might be interested in 'platlib' too). The purelib path is where ordinary Python packages will be installed by tools like pip.

At system level, you'll see something like this:

# Linux
$ python3 -c "import sysconfig; print(sysconfig.get_path('purelib'))"
/usr/local/lib/python3.8/site-packages

# macOS (brew installed python3.8)
$ python3 -c "import sysconfig; print(sysconfig.get_path('purelib'))"
/usr/local/Cellar/[email protected]/3.8.3/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages

# Windows
C:\> py -c "import sysconfig; print(sysconfig.get_path('purelib'))"
C:\Users\wim\AppData\Local\Programs\Python\Python38\Lib\site-packages

With a venv, you'll get something like this

# Linux
/tmp/.venv/lib/python3.8/site-packages

# macOS
/private/tmp/.venv/lib/python3.8/site-packages

# Windows
C:\Users\wim\AppData\Local\Temp\.venv\Lib\site-packages

The function sysconfig.get_paths() returns a dict of all of the relevant installation paths, example on Linux:

>>> import sysconfig
>>> sysconfig.get_paths()
{'stdlib': '/usr/local/lib/python3.8',
 'platstdlib': '/usr/local/lib/python3.8',
 'purelib': '/usr/local/lib/python3.8/site-packages',
 'platlib': '/usr/local/lib/python3.8/site-packages',
 'include': '/usr/local/include/python3.8',
 'platinclude': '/usr/local/include/python3.8',
 'scripts': '/usr/local/bin',
 'data': '/usr/local'}

A shell script is also available to display these details, which you can invoke by executing sysconfig as a module:

python -m sysconfig

What's the difference between a null pointer and a void pointer?

Usually a null pointer (which can be of any type, including a void pointer !) points to:

  • the address 0, against which most CPU instructions sets can do a very fast compare-and-branch (to check for uninitialized or invalid pointers, for instance) with optimal code size/performance for the ISA.

  • an address that's illegal for user code to access (such as 0x00000000 in many cases), so that if a code actually tries to access data at or near this address, the OS or debugger can easily stop or trap a program with this bug.

A void pointer is usually a method of cheating or turning-off compiler type checking, for instance if you want to return a pointer to one type, or an unknown type, to use as another type. For instance malloc() returns a void pointer to a type-less chunk of memory, the type of which you can cast to later use as a pointer to bytes, short ints, double floats, typePotato's, or whatever.

Call web service in excel

Yes You Can!

I worked on a project that did that (see comment). Unfortunately no code samples from that one, but googling revealed these:

How you can integrate data from several Web services using Excel and VBA

STEP BY STEP: Consuming Web Services through VBA (Excel or Word)

VBA: Consume Soap Web Services

Typescript interface default values

You can use the Partial mapped type as explained in the documentation: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-1.html

In your example, you'll have:

interface IX {
    a: string;
    b: any;
    c: AnotherType;
}

let x: Partial<IX> = {
    a: 'abc'
}

How to convert string to Date in Angular2 \ Typescript?

You can use date filter to convert in date and display in specific format.

In .ts file (typescript):

let dateString = '1968-11-16T00:00:00' 
let newDate = new Date(dateString);

In HTML:

{{dateString |  date:'MM/dd/yyyy'}}

Below are some formats which you can implement :

Backend:

public todayDate = new Date();

HTML :

<select>
<option value=""></option>
<option value="MM/dd/yyyy">[{{todayDate | date:'MM/dd/yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy">[{{todayDate | date:'EEEE, MMMM d, yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm a">[{{todayDate | date:'EEEE, MMMM d, yyyy h:mm a'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm:ss a">[{{todayDate | date:'EEEE, MMMM d, yyyy h:mm:ss a'}}]</option>
<option value="MM/dd/yyyy h:mm a">[{{todayDate | date:'MM/dd/yyyy h:mm a'}}]</option>
<option value="MM/dd/yyyy h:mm:ss a">[{{todayDate | date:'MM/dd/yyyy h:mm:ss a'}}]</option>
<option value="MMMM d">[{{todayDate | date:'MMMM d'}}]</option>   
<option value="yyyy-MM-ddTHH:mm:ss">[{{todayDate | date:'yyyy-MM-ddTHH:mm:ss'}}]</option>
<option value="h:mm a">[{{todayDate | date:'h:mm a'}}]</option>
<option value="h:mm:ss a">[{{todayDate | date:'h:mm:ss a'}}]</option>      
<option value="EEEE, MMMM d, yyyy hh:mm:ss a">[{{todayDate | date:'EEEE, MMMM d, yyyy hh:mm:ss a'}}]</option>
<option value="MMMM yyyy">[{{todayDate | date:'MMMM yyyy'}}]</option> 
</select>

Return a 2d array from a function

A better alternative to using pointers to pointers is to use std::vector. That takes care of the details of memory allocation and deallocation.

std::vector<std::vector<int>> create2DArray(unsigned height, unsigned width)
{
   return std::vector<std::vector<int>>(height, std::vector<int>(width, 0));
}

What's the difference between including files with JSP include directive, JSP include action and using JSP Tag Files?

Main advantage of <jsp:include /> over <%@ include > is:

<jsp:include /> allows to pass parameters

<jsp:include page="inclusion.jsp">
    <jsp:param name="menu" value="objectValue"/>
</jsp:include>

which is not possible in <%@include file="somefile.jsp" %>

MySQL selecting yesterday's date

I adapted one of the above answers from cdhowie as I could not get it to work. This seems to work for me. I suspect it's also possible to do this with the UNIX_TIMESTAMP function been used.

SELECT * FROM your_table

WHERE UNIX_TIMESTAMP(DateVisited) >= UNIX_TIMESTAMP(CAST(NOW() - INTERVAL 1 DAY AS DATE))
  AND UNIX_TIMESTAMP(DateVisited) <= UNIX_TIMESTAMP(CAST(NOW() AS DATE));

How many bytes does one Unicode character take?

Check out this Unicode code converter. For example, enter 0x2009, where 2009 is the Unicode number for thin space, in the "0x... notation" field, and click Convert. The hexadecimal number E2 80 89 (3 bytes) appears in the "UTF-8 code units" field.

jQuery - What are differences between $(document).ready and $(window).load?

$(window).load is an event that fires when the DOM and all the content (everything) on the page is fully loaded like CSS, images and frames. One best example is if we want to get the actual image size or to get the details of anything we use it.

$(document).ready() indicates that code in it need to be executed once the DOM got loaded and ready to be manipulated by script. It won't wait for the images to load for executing the jQuery script.

<script type = "text/javascript">
    //$(window).load was deprecated in 1.8, and removed in jquery 3.0
    // $(window).load(function() {
    //     alert("$(window).load fired");
    // });

    $(document).ready(function() {
        alert("$(document).ready fired");
    });
</script>

$(window).load fired after the $(document).ready().

$(document).ready(function(){

}) 
//and 
$(function(){

}); 
//and
jQuery(document).ready(function(){

});

Above 3 are same, $ is the alias name of jQuery, you may face conflict if any other JavaScript Frameworks uses the same dollar symbol $. If u face conflict jQuery team provide a solution no-conflict read more.

$(window).load was deprecated in 1.8, and removed in jquery 3.0

Joining pandas dataframes by column names

you can use the left_on and right_on options as follows:

pd.merge(frame_1, frame_2, left_on='county_ID', right_on='countyid')

I was not sure from the question if you only wanted to merge if the key was in the left hand dataframe. If that is the case then the following will do that (the above will in effect do a many to many merge)

pd.merge(frame_1, frame_2, how='left', left_on='county_ID', right_on='countyid')

How do I read a large csv file with pandas?

The function read_csv and read_table is almost the same. But you must assign the delimiter “,” when you use the function read_table in your program.

def get_from_action_data(fname, chunk_size=100000):
    reader = pd.read_csv(fname, header=0, iterator=True)
    chunks = []
    loop = True
    while loop:
        try:
            chunk = reader.get_chunk(chunk_size)[["user_id", "type"]]
            chunks.append(chunk)
        except StopIteration:
            loop = False
            print("Iteration is stopped")

    df_ac = pd.concat(chunks, ignore_index=True)

PHP not displaying errors even though display_errors = On

Just want to add another pitfall here in case someone finds this question with a problem similar to mine.

When you are using Chrome (Or Chromium) and PHP triggers an error in PHP code which is located inside of a HTML attribute then Chrome removes the whole HTML element so you can't see the PHP error in your browser.

Here is an example:

<p>
  <a href="<?=missingFunc()?>">test</a>
</p>

When calling this code in Chrome you only get a HTML document with the starting <p> tag. The rest is missing. No error message and no other HTML code after this <p>. This is not a PHP issue. When you open this page in Firefox then you can see the error message (When viewing the HTML code). So this is a Chrome issue.

Don't know if there is a workaround somewhere. When this happens to you then you have to test the page in Firefox or check the Apache error log.

Invalid postback or callback argument. Event validation is enabled using '<pages enableEventValidation="true"/>'

For us the problem was happening randomly only in the production environment. The RegisterForEventValidation did nothing for us.

Finally, we figured out that the web farm in which the asp.net app was running, two IIS servers had different .net versions installed. So it appears they had different rules for encrypting the asp.net validation hash. Updating them solved most of the problem.

Also, we configured the machineKey(compatibilityMode) (the same in both servers), httpRuntime(targetFramework), ValidationSettings:UnobtrusiveValidationMode, pages(renderAllHiddenFieldsAtTopOfForm) in the web.config of both servers.

We used this site to generate the key https://www.allkeysgenerator.com/Random/ASP-Net-MachineKey-Generator.aspx

We spent a lot of time solving this, I hope this helps somebody.

<appSettings>
   <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
...
</appSettings>
<system.web>
   <machineKey compatibilityMode="Framework45" decryptionKey="somekey" validationKey="otherkey" validation="SHA1" decryption="AES />
   <pages [...] controlRenderingCompatibilityVersion="4.0" enableEventValidation="true" renderAllHiddenFieldsAtTopOfForm="true" />
   <httpRuntime [...] requestValidationMode="2.0" targetFramework="4.5" />
...
</system.web>

Converting string to numeric

As csgillespie said. stringsAsFactors is default on TRUE, which converts any text to a factor. So even after deleting the text, you still have a factor in your dataframe.

Now regarding the conversion, there's a more optimal way to do so. So I put it here as a reference :

> x <- factor(sample(4:8,10,replace=T))
> x
 [1] 6 4 8 6 7 6 8 5 8 4
Levels: 4 5 6 7 8
> as.numeric(levels(x))[x]
 [1] 6 4 8 6 7 6 8 5 8 4

To show it works.

The timings :

> x <- factor(sample(4:8,500000,replace=T))
> system.time(as.numeric(as.character(x)))
   user  system elapsed 
   0.11    0.00    0.11 
> system.time(as.numeric(levels(x))[x])
   user  system elapsed 
      0       0       0 

It's a big improvement, but not always a bottleneck. It gets important however if you have a big dataframe and a lot of columns to convert.

How to check type of variable in Java?

I wasn't happy with any of these answers, and the one that's right has no explanation and negative votes so I searched around, found some stuff and edited it so that it is easy to understand. Have a play with it, not as straight forward as one would hope.

//move your variable into an Object type
Object obj=whatYouAreChecking;
System.out.println(obj);

// moving the class type into a Class variable
Class cls=obj.getClass();
System.out.println(cls);

// convert that Class Variable to a neat String
String answer = cls.getSimpleName();
System.out.println(answer);

Here is a method:

public static void checkClass (Object obj) {
    Class cls = obj.getClass();
    System.out.println("The type of the object is: " + cls.getSimpleName());       
}