Programs & Examples On #Yui datatable

The YUI DataTable control provides a simple yet powerful API to display screen-reader accessible tabular data on a web page. Notable features include sortable columns, pagination, scrolling, row selection, resizeable columns, and inline cell editing.

What is JAVA_HOME? How does the JVM find the javac path stored in JAVA_HOME?

The command prompt wouldn't use JAVA_HOME to find javac.exe, it would use PATH.

Calculate text width with JavaScript

jQuery:

(function($) {

 $.textMetrics = function(el) {

  var h = 0, w = 0;

  var div = document.createElement('div');
  document.body.appendChild(div);
  $(div).css({
   position: 'absolute',
   left: -1000,
   top: -1000,
   display: 'none'
  });

  $(div).html($(el).html());
  var styles = ['font-size','font-style', 'font-weight', 'font-family','line-height', 'text-transform', 'letter-spacing'];
  $(styles).each(function() {
   var s = this.toString();
   $(div).css(s, $(el).css(s));
  });

  h = $(div).outerHeight();
  w = $(div).outerWidth();

  $(div).remove();

  var ret = {
   height: h,
   width: w
  };

  return ret;
 }

})(jQuery);

Find the files that have been changed in last 24 hours

This command worked for me

find . -mtime -1 -print

How to read file binary in C#?

Well, reading it isn't hard, just use FileStream to read a byte[]. Converting it to text isn't really generally possible or meaningful unless you convert the 1's and 0's to hex. That's easy to do with the BitConverter.ToString(byte[]) overload. You'd generally want to dump 16 or 32 bytes in each line. You could use Encoding.ASCII.GetString() to try to convert the bytes to characters. A sample program that does this:

using System;
using System.IO;
using System.Text;

class Program {
    static void Main(string[] args) {
        // Read the file into <bits>
        var fs = new FileStream(@"c:\temp\test.bin", FileMode.Open);
        var len = (int)fs.Length;
        var bits = new byte[len];
        fs.Read(bits, 0, len);
        // Dump 16 bytes per line
        for (int ix = 0; ix < len; ix += 16) {
            var cnt = Math.Min(16, len - ix);
            var line = new byte[cnt];
            Array.Copy(bits, ix, line, 0, cnt);
            // Write address + hex + ascii
            Console.Write("{0:X6}  ", ix);
            Console.Write(BitConverter.ToString(line));
            Console.Write("  ");
            // Convert non-ascii characters to .
            for (int jx = 0; jx < cnt; ++jx)
                if (line[jx] < 0x20 || line[jx] > 0x7f) line[jx] = (byte)'.';
            Console.WriteLine(Encoding.ASCII.GetString(line));
        }
        Console.ReadLine();
    }
}

Difference between DOMContentLoaded and load events

From the Mozilla Developer Center:

The DOMContentLoaded event is fired when the document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading (the load event can be used to detect a fully-loaded page).

How to convert a huge list-of-vector to a matrix more efficiently?

It would help to have sample information about your output. Recursively using rbind on bigger and bigger things is not recommended. My first guess at something that would help you:

z <- list(1:3,4:6,7:9)
do.call(rbind,z)

See a related question for more efficiency, if needed.

How to initialize private static members in C++?

For future viewers of this question, I want to point out that you should avoid what monkey0506 is suggesting.

Header files are for declarations.

Header files get compiled once for every .cpp file that directly or indirectly #includes them, and code outside of any function is run at program initialization, before main().

By putting: foo::i = VALUE; into the header, foo:i will be assigned the value VALUE (whatever that is) for every .cpp file, and these assignments will happen in an indeterminate order (determined by the linker) before main() is run.

What if we #define VALUE to be a different number in one of our .cpp files? It will compile fine and we will have no way of knowing which one wins until we run the program.

Never put executed code into a header for the same reason that you never #include a .cpp file.

include guards (which I agree you should always use) protect you from something different: the same header being indirectly #included multiple times while compiling a single .cpp file

Laravel 5.2 Missing required parameters for [Route: user.profile] [URI: user/{nickname}/profile]

My Solution in laravel 5.2

{{ Form::open(['route' => ['votes.submit', $video->id],  'method' => 'POST']) }}
    <button type="submit" class="btn btn-primary">
        <span class="glyphicon glyphicon-thumbs-up"></span> Votar
    </button>
{{ Form::close() }}

My Routes File (under middleware)

Route::post('votar/{id}', [
    'as' => 'votes.submit',
    'uses' => 'VotesController@submit'
]);

Route::delete('votar/{id}', [
    'as' => 'votes.destroy',
    'uses' => 'VotesController@destroy'
]);

How to detect if user select cancel InputBox VBA Excel

If the user clicks Cancel, a zero-length string is returned. You can't differentiate this from entering an empty string. You can however make your own custom InputBox class...

EDIT to properly differentiate between empty string and cancel, according to this answer.

Your example

Private Sub test()
    Dim result As String
    result = InputBox("Enter Date MM/DD/YYY", "Date Confirmation", Now)
    If StrPtr(result) = 0 Then
        MsgBox ("User canceled!")
    ElseIf result = vbNullString Then
        MsgBox ("User didn't enter anything!")
    Else
        MsgBox ("User entered " & result)
    End If
End Sub

Would tell the user they canceled when they delete the default string, or they click cancel.

See http://msdn.microsoft.com/en-us/library/6z0ak68w(v=vs.90).aspx

Wamp Server not goes to green color

CMD > netstat -ao > look for any line like 0.0.0.0:80 and look at the PID value (e.g. 4796)

Open Task Manager > Processes tab > View > Select Column > Tick on PID (Process Identifier) > OK to create new column

Look at the processes list in Task Manager > Sort by PID (the new column) and find the 4796 to know which program is using Port 80. Mine is Bit-Torrent. After close (exit) Bit-Torrent, Wampserver should work as usual.

Floating Point Exception C++ Why and what is it?

Problem is in the for loop in the code snippet:
for (i > 0; i--;)

Here, your intention seems to be entering the loop if (i > 0) and decrement the value of i by one after the completion of for loop.

Does it work like that? lets see.

Look at the for() loop syntax:

**for ( initialization; condition check; increment/decrement ) {  
    statements;  
}**

Initialization gets executed only once in the beginning of the loop. Pay close attention to ";" in your code snippet and map it with for loop syntax.

Initialization : i > 0 : Gets executed only once. Doesn't have any impact in your code.

Condition check : i -- : post decrement.

              Here, i is used for condition check and then it is decremented. 
              Decremented value will be used in statements within for loop. 
              This condition check is working as increment/decrement too in your code. 

Lets stop here and see floating point exception.

what is it? One easy example is Divide by 0. Same is happening with your code.

When i reaches 1 in condition check, condition check validates to be true.
Because of post decrement i will be 0 when it enters for loop.

Modulo operation at line #9 results in divide by zero operation.  

With this background you should be able to fix the problem in for loop.

type checking in javascript

These days, ECMAScript 6 (ECMA-262) is "in the house". Use Number.isInteger(x) to ask the question you want to ask with respect to the type of x:

js> var x = 3
js> Number.isInteger(x)
true
js> var y = 3.1
js> Number.isInteger(y)
false

Is it worth using Python's re.compile?

In general, I find it is easier to use flags (at least easier to remember how), like re.I when compiling patterns than to use flags inline.

>>> foo_pat = re.compile('foo',re.I)
>>> foo_pat.findall('some string FoO bar')
['FoO']

vs

>>> re.findall('(?i)foo','some string FoO bar')
['FoO']

The entity name must immediately follow the '&' in the entity reference

If you use XHTML, for some reason, note that XHTML 1.0 C 4 says: “Use external scripts if your script uses < or & or ]]> or --.” That is, don’t embed script code inside a script element but put it into a separate JavaScript file and refer to it with <script src="foo.js"></script>.

FirstOrDefault: Default value other than null

As I understand it, in Linq the method FirstOrDefault() can return a Default value of something other than null.

No. Or rather, it always returns the default value for the element type... which is either a null reference, the null value of a nullable value type, or the natural "all zeroes" value for a non-nullable value type.

Is there any particular way that this can be set up so that if there is no value for a particular query some predefined value is returned as the default value?

For reference types, you can just use:

var result = query.FirstOrDefault() ?? otherDefaultValue;

Of course this will also give you the "other default value" if the first value is present, but is a null reference...

How to display special characters in PHP

Try This

Input:

<!DOCTYPE html>
<html>
<body>

<?php
$str = "This is some <b>bold</b> text.";
echo htmlspecialchars($str);
?>

<p>Converting &lt; and &gt; into entities are often used to prevent browsers from using it as an HTML element. <br />This can be especially useful to prevent code from running when users have access to display input on your homepage.</p>

</body>
</html>

Output:

This is some <b>bold</b> text.

Converting < and > into entities are often used to prevent browsers from using it as an HTML element. This can be especially useful to prevent code from running when users have access to display input on your homepage.

Spring - applicationContext.xml cannot be opened because it does not exist

Please do This code - it worked

 AbstractApplicationContext context= new ClassPathXmlApplicationContext("spring-config.xml");

o/w: Delete main method class and recreate it while recreating please uncheck Inherited abstract method its worked

Return value from a VBScript function

To return a value from a VBScript function, assign the value to the name of the function, like this:

Function getNumber
    getNumber = "423"
End Function

Is it possible to set ENV variables for rails development environment in my code?

The system environment and rails' environment are different things. ENV let's you work with the rails' environment, but if what you want to do is to change the system's environment in runtime you can just surround the command with backticks.

# ruby code
`export admin_password="secret"`
# more ruby code

preferredStatusBarStyle isn't called

Swift 3 iOS 10 Solution:

override var preferredStatusBarStyle: UIStatusBarStyle {
    return .lightContent
 }

How to view the current heap size that an application is using?

Personal favourite for when jvisualvm is overkill or you need cli-only: jvmtop

JvmTop 0.8.0 alpha   amd64  8 cpus, Linux 2.6.32-27, load avg 0.12
https://github.com/patric-r/jvmtop

PID MAIN-CLASS      HPCUR HPMAX NHCUR NHMAX    CPU     GC    VM USERNAME   #T DL
3370 rapperSimpleApp  165m  455m  109m  176m  0.12%  0.00% S6U37 web        21
11272 ver.resin.Resin [ERROR: Could not attach to VM]
27338 WatchdogManager   11m   28m   23m  130m  0.00%  0.00% S6U37 web        31
19187 m.jvmtop.JvmTop   20m 3544m   13m  130m  0.93%  0.47% S6U37 web        20
16733 artup.Bootstrap  159m  455m  166m  304m  0.12%  0.00% S6U37 web        46

No 'Access-Control-Allow-Origin' header is present on the requested resource error

Just FYI, I noticed this information from the jQuery documentation which I believe applies to this issue:

Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, port, or protocol.

Changing the hosts file like @thanix didn't work for me, but the extension mentioned by @dkruchok did solve the problem.

How to extract epoch from LocalDate and LocalDateTime?

'Millis since unix epoch' represents an instant, so you should use the Instant class:

private long toEpochMilli(LocalDateTime localDateTime)
{
  return localDateTime.atZone(ZoneId.systemDefault())
    .toInstant().toEpochMilli();
}

SQL WHERE condition is not equal to?

You can do like this

DELETE FROM table WHERE id NOT IN ( 2 )

OR

DELETE FROM table WHERE id <>  2 

As @Frank Schmitt noted, you might want to be careful about the NULL values too. If you want to delete everything which is not 2(including the NULLs) then add OR id IS NULL to the WHERE clause.

How to find indices of all occurrences of one string in another in JavaScript?

I would recommend Tim's answer. However, this comment by @blazs states "Suppose searchStr=aaa and that str=aaaaaa. Then instead of finding 4 occurences your code will find only 2 because you're making skips by searchStr.length in the loop.", which is true by looking at Tim's code, specifically this line here: startIndex = index + searchStrLen; Tim's code would not be able to find an instance of the string that's being searched that is within the length of itself. So, I've modified Tim's answer:

_x000D_
_x000D_
function getIndicesOf(searchStr, str, caseSensitive) {
    var startIndex = 0, index, indices = [];
    if (!caseSensitive) {
        str = str.toLowerCase();
        searchStr = searchStr.toLowerCase();
    }
    while ((index = str.indexOf(searchStr, startIndex)) > -1) {
        indices.push(index);
        startIndex = index + 1;
    }
    return indices;
}
var searchStr = prompt("Enter a string.");
var str = prompt("What do you want to search for in the string?");
var indices = getIndicesOf(str, searchStr);

document.getElementById("output").innerHTML = indices + "";
_x000D_
<div id="output"></div>
_x000D_
_x000D_
_x000D_

Changing it to + 1 instead of + searchStrLen will allow the index 1 to be in the indices array if I have an str of aaaaaa and a searchStr of aaa.

P.S. If anyone would like comments in the code to explain how the code works, please say so, and I'll be happy to respond to the request.

How to style icon color, size, and shadow of Font Awesome Icons

Given that they're simply fonts, then you should be able to style them as fonts:

#elementID {
    color: #fff;
    text-shadow: 1px 1px 1px #ccc;
    font-size: 1.5em;
}

How can I get npm start at a different directory?

npm start --prefix path/to/your/app

& inside package.json add the following script

"scripts": {
   "preinstall":"cd $(pwd)"
}

Use IntelliJ to generate class diagram

Try Ctrl+Alt+U

Also check if the UML plugin is activated (settings -> plugin, settings can be opened by Ctrl+Alt+S

How do I do logging in C# without using 3rd party libraries?

I used to write my own error logging until I discovered ELMAH. I've never been able to get the emailing part down quite as perfectly as ELMAH does.

Remote debugging Tomcat with Eclipse

Can you check if this works?

JPDA_OPTS="-agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n"

catalina.sh jpda start

SyntaxError: Non-ASCII character '\xa3' in file when function returns '£'

First add the # -*- coding: utf-8 -*- line to the beginning of the file and then use u'foo' for all your non-ASCII unicode data:

def NewFunction():
    return u'£'

or use the magic available since Python 2.6 to make it automatic:

from __future__ import unicode_literals

How to play ringtone/alarm sound in Android

You can push a MP3 file in your /sdcard folder using DDMS, restart the emulator, then open the Media application, browse to your MP3 file, long press on it and select "Use as phone ringtone".

Error is gone!

Edit: same trouble with notification sounds (e.g. for SMS) solved using Ringdroid application

curl: (60) SSL certificate problem: unable to get local issuer certificate

Try reinstalling curl in Ubuntu, and updating my CA certs with sudo update-ca-certificates --fresh which updated the certs

Unicode, UTF, ASCII, ANSI format differences

Going down your list:

  • "Unicode" isn't an encoding, although unfortunately, a lot of documentation imprecisely uses it to refer to whichever Unicode encoding that particular system uses by default. On Windows and Java, this often means UTF-16; in many other places, it means UTF-8. Properly, Unicode refers to the abstract character set itself, not to any particular encoding.
  • UTF-16: 2 bytes per "code unit". This is the native format of strings in .NET, and generally in Windows and Java. Values outside the Basic Multilingual Plane (BMP) are encoded as surrogate pairs. These used to be relatively rarely used, but now many consumer applications will need to be aware of non-BMP characters in order to support emojis.
  • UTF-8: Variable length encoding, 1-4 bytes per code point. ASCII values are encoded as ASCII using 1 byte.
  • UTF-7: Usually used for mail encoding. Chances are if you think you need it and you're not doing mail, you're wrong. (That's just my experience of people posting in newsgroups etc - outside mail, it's really not widely used at all.)
  • UTF-32: Fixed width encoding using 4 bytes per code point. This isn't very efficient, but makes life easier outside the BMP. I have a .NET Utf32String class as part of my MiscUtil library, should you ever want it. (It's not been very thoroughly tested, mind you.)
  • ASCII: Single byte encoding only using the bottom 7 bits. (Unicode code points 0-127.) No accents etc.
  • ANSI: There's no one fixed ANSI encoding - there are lots of them. Usually when people say "ANSI" they mean "the default locale/codepage for my system" which is obtained via Encoding.Default, and is often Windows-1252 but can be other locales.

There's more on my Unicode page and tips for debugging Unicode problems.

The other big resource of code is unicode.org which contains more information than you'll ever be able to work your way through - possibly the most useful bit is the code charts.

When to use 'npm start' and when to use 'ng serve'?

If you want to run angular app ported from another machine without ng command then edit package.json as follows

"scripts": {
    "ng": "ng",
    "start": "node node_modules/.bin/ng serve",
    "build": "node node_modules/.bin/ng build",
    "test": "node node_modules/.bin/ng test",
    "lint": "node node_modules/.bin/ng lint",
    "e2e": "node node_modules/.bin/ng e2e"
  }

Finally run usual npm start command to start build server.

How do I create a shortcut via command-line in Windows?

Cannot be done with pure batch.Check the shortcutJS.bat - it is a jscript/bat hybrid and should be used with .bat extension:

call shortcutJS.bat -linkfile "%~n0.lnk" -target  "%~f0" -linkarguments "some arguments"

With -help you can check the other options (you can set icon , admin permissions and etc.)

Thymeleaf using path variables to th:href

You can use like

  1. My table is bellow like..

    <table>
       <thead>
        <tr>
            <th>Details</th>
        </tr>
    </thead>
    <tbody>
        <tr th:each="user: ${staffList}">
            <td><a th:href="@{'/details-view/'+ ${user.userId}}">Details</a></td>
        </tr>
     </tbody>
    </table>
    
  2. Here is my controller ..

    @GetMapping(value = "/details-view/{userId}")
    public String details(@PathVariable String userId) { 
    
        Logger.getLogger(getClass().getName()).info("userId-->" + userId);
    
     return "user-details";
    }
    

How to change the plot line color from blue to black?

The usual way to set the line color in matplotlib is to specify it in the plot command. This can either be done by a string after the data, e.g. "r-" for a red line, or by explicitely stating the color argument.

import matplotlib.pyplot as plt

plt.plot([1,2,3], [2,3,1], "r-") # red line
plt.plot([1,2,3], [5,5,3], color="blue") # blue line

plt.show()

See also the plot command's documentation.

In case you already have a line with a certain color, you can change that with the lines2D.set_color() method.

line, = plt.plot([1,2,3], [4,5,3], color="blue")
line.set_color("black")


Setting the color of a line in a pandas plot is also best done at the point of creating the plot:

import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({ "x" : [1,2,3,5], "y" : [3,5,2,6]})
df.plot("x", "y", color="r") #plot red line

plt.show()

If you want to change this color later on, you can do so by

plt.gca().get_lines()[0].set_color("black")

This will get you the first (possibly the only) line of the current active axes.
In case you have more axes in the plot, you could loop through them

for ax in plt.gcf().axes:
    ax.get_lines()[0].set_color("black")

and if you have more lines you can loop over them as well.

How to update Android Studio automatically?

These steps are for the people who already have Android Studio installed on their Windows machine >>>

Steps to download the update:

  1. Google for “Update android studio”
  2. Choose the result from “tools.android.com”
  3. Download the zip file (it’s around 500 MB).

Steps to install Android Studio from a .zip folder:

  1. Open the .zip folder using Windows Explorer.
  2. click on 'Extract all' (or 'Extract all files') option in the ribbon.
  3. Go to the extract location. And then to android-studio\bin and run studio.exe ifyou’re on 32bit OS, or studio64.exe if you’re on 64bit OS.

By then, the Andriod Studio should open and configure your uppdates enter image description here

What is the actual use of Class.forName("oracle.jdbc.driver.OracleDriver") while connecting to a database?

Pre Java 6 the DriverManager class wouldn't have known which JDBC driver you wanted to use. Class.forName("...") was a way on pre-loading the driver classes.

If you are using Java 6 you no longer need to do this.

Best practices for styling HTML emails

I've fought the HTML email battle before. Here are some of my tips about styling for maximum compatibility between email clients.

  • Inline styles are you best friend. Absolutely don't link style sheets and do not use a <style> tag (GMail, for example, strips that tag and all it's contents).

  • Against your better judgement, use and abuse tables. <div>s just won't cut it (especially in Outlook).

  • Don't use background images, they're spotty and will annoy you.

  • Remember that some email clients will automatically transform typed out hyperlinks into links (if you don't anchor <a> them yourself). This can sometimes achieve negative effects (say if you're putting a style on each of the hyperlinks to appear a different color).

  • Be careful hyperlinking an actual link with something different. For example, don't type out http://www.google.com and then link it to https://gmail.com/. Some clients will flag the message as Spam or Junk.

  • Save your images in as few colors as possible to save on size.

  • If possible, embed your images in your email. The email won't have to reach out to an external web server to download them and they won't appear as attachments to the email.

And lastly, test, test, test! Each email client does things way differently than a browser would do.

JavaScript chop/slice/trim off last character in string

You can use the substring method of JavaScript string objects:

s = s.substring(0, s.length - 4)

It unconditionally removes the last four characters from string s.

However, if you want to conditionally remove the last four characters, only if they are exactly _bar:

var re = /_bar$/;
s.replace(re, "");

Find a string between 2 known values

I strip before and after data.

 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;
 using System.Threading.Tasks;
 using System.Text.RegularExpressions;

 namespace testApp
 {
     class Program
     {
         static void Main(string[] args)
         {
             string tempString = "morenonxmldata<tag1>0002</tag1>morenonxmldata";
             tempString = Regex.Replace(tempString, "[\\s\\S]*<tag1>", "");//removes all leading data
             tempString = Regex.Replace(tempString, "</tag1>[\\s\\S]*", "");//removes all trailing data

             Console.WriteLine(tempString);
             Console.ReadLine();
         }
     }
 }

No newline at end of file

It indicates that you do not have a newline (usually '\n', aka CR or CRLF) at the end of file.

That is, simply speaking, the last byte (or bytes if you're on Windows) in the file is not a newline.

The message is displayed because otherwise there is no way to tell the difference between a file where there is a newline at the end and one where is not. Diff has to output a newline anyway, or the result would be harder to read or process automatically.

Note that it is a good style to always put the newline as a last character if it is allowed by the file format. Furthermore, for example, for C and C++ header files it is required by the language standard.

Is there a standardized method to swap two variables in Python?

I know three ways to swap variables, but a, b = b, a is the simplest. There is

XOR (for integers)

x = x ^ y
y = y ^ x
x = x ^ y

Or concisely,

x ^= y
y ^= x
x ^= y

Temporary variable

w = x
x = y
y = w
del w

Tuple swap

x, y = y, x

How to figure out the SMTP server host?

You can use the dig/host command to look up the MX records to see which mail server is handling mails for this domain.

On Linux you can do it as following for example:

$ host google.com
google.com has address 74.125.127.100
google.com has address 74.125.67.100
google.com has address 74.125.45.100
google.com mail is handled by 10 google.com.s9a2.psmtp.com.
google.com mail is handled by 10 smtp2.google.com.
google.com mail is handled by 10 google.com.s9a1.psmtp.com.
google.com mail is handled by 100 google.com.s9b2.psmtp.com.
google.com mail is handled by 10 smtp1.google.com.
google.com mail is handled by 100 google.com.s9b1.psmtp.com.

(as you can see, google has quite a lot of mail servers)

If you are working with windows, you might use nslookup (?) or try some web tool (e.g. that one) to display the same information.

Although that will only tell you the mail server for that domain. All other settings which are required can't be gathered that way. You might have to ask the provider.

Http Post request with content type application/x-www-form-urlencoded not working in Spring

The solution can be found here https://github.com/spring-projects/spring-framework/issues/22734

you can create two separate post request mappings. For example.

@PostMapping(path = "/test", consumes = "application/json")
public String test(@RequestBody User user) {
  return user.toString();
}

@PostMapping(path = "/test", consumes = "application/x-www-form-urlencoded")
public String test(User user) {
  return user.toString();
}

Python: download a file from an FTP server

requests library doesn't support ftp links.

To download a file from FTP server you could:

import urllib 

urllib.urlretrieve('ftp://server/path/to/file', 'file')
# if you need to pass credentials:
#   urllib.urlretrieve('ftp://username:password@server/path/to/file', 'file')

Or:

import shutil
import urllib2
from contextlib import closing

with closing(urllib2.urlopen('ftp://server/path/to/file')) as r:
    with open('file', 'wb') as f:
        shutil.copyfileobj(r, f)

Python3:

import shutil
import urllib.request as request
from contextlib import closing

with closing(request.urlopen('ftp://server/path/to/file')) as r:
    with open('file', 'wb') as f:
        shutil.copyfileobj(r, f)

Access restriction on class due to restriction on required library rt.jar?

My guess is that you are trying to replace a standard class which ships with Java 5 with one in a library you have.

This is not allowed under the terms of the license agreement, however AFAIK it wasn't enforced until Java 5.

I have seen this with QName before and I "fixed" it by removing the class from the jar I had.

EDIT http://www.manpagez.com/man/1/java/ notes for the option "-Xbootclasspath:"

"Applications that use this option for the purpose of overriding a class in rt.jar should not be deployed as doing so would contravene the Java 2 Runtime Environment binary code license."

The http://www.idt.mdh.se/rc/sumo/aJile/Uppackat/jre/LICENSE

"Java Technology Restrictions. You may not modify the Java Platform Interface ("JPI", identified as classes contained within the "java" package or any subpackages of the "java" package), by creating additional classes within the JPI or otherwise causing the addition to or modification of the classes in the JPI. In the event that you create an additional class and associated API(s) which (i) extends the functionality of the Java platform, and (ii) is exposed to third party software developers for the purpose of developing additional software which invokes such additional API, you must promptly publish broadly an accurate specification for such API for free use by all developers. You may not create, or authorize your licensees to create, additional classes, interfaces, or subpackages that are in any way identified as "java", "javax", "sun" or similar convention as specified by Sun in any naming convention designation."

Binary search (bisection) in Python

I agree that @DaveAbrahams's answer using the bisect module is the correct approach. He did not mention one important detail in his answer.

From the docs bisect.bisect_left(a, x, lo=0, hi=len(a))

The bisection module does not require the search array to be precomputed ahead of time. You can just present the endpoints to the bisect.bisect_left instead of it using the defaults of 0 and len(a).

Even more important for my use, looking for a value X such that the error of a given function is minimized. To do that, I needed a way to have the bisect_left's algorithm call my computation instead. This is really simple.

Just provide an object that defines __getitem__ as a

For example, we could use the bisect algorithm to find a square root with arbitrary precision!

import bisect

class sqrt_array(object):
    def __init__(self, digits):
        self.precision = float(10**(digits))
    def __getitem__(self, key):
        return (key/self.precision)**2.0

sa = sqrt_array(4)

# "search" in the range of 0 to 10 with a "precision" of 0.0001
index = bisect.bisect_left(sa, 7, 0, 10*10**4)
print 7**0.5
print index/(10**4.0)

How to clone object in C++ ? Or Is there another solution?

The typical solution to this is to write your own function to clone an object. If you are able to provide copy constructors and copy assignement operators, this may be as far as you need to go.

class Foo
{ 
public:
  Foo();
  Foo(const Foo& rhs) { /* copy construction from rhs*/ }
  Foo& operator=(const Foo& rhs) {};
};

// ...

Foo orig;
Foo copy = orig;  // clones orig if implemented correctly

Sometimes it is beneficial to provide an explicit clone() method, especially for polymorphic classes.

class Interface
{
public:
  virtual Interface* clone() const = 0;
};

class Foo : public Interface
{
public:
  Interface* clone() const { return new Foo(*this); }
};

class Bar : public Interface
{
public:
  Interface* clone() const { return new Bar(*this); }
};


Interface* my_foo = /* somehow construct either a Foo or a Bar */;
Interface* copy = my_foo->clone();

EDIT: Since Stack has no member variables, there's nothing to do in the copy constructor or copy assignment operator to initialize Stack's members from the so-called "right hand side" (rhs). However, you still need to ensure that any base classes are given the opportunity to initialize their members.

You do this by calling the base class:

Stack(const Stack& rhs) 
: List(rhs)  // calls copy ctor of List class
{
}

Stack& operator=(const Stack& rhs) 
{
  List::operator=(rhs);
  return * this;
};

How to present UIActionSheet iOS Swift?

Swift :

The sample code given below works both on iPhone and iPad.

 guard let viewRect = sender as? UIView else {
                return
            }

        let cameraSettingsAlert = UIAlertController(title: NSLocalizedString("Please choose a course", comment: ""), message: NSLocalizedString("", comment: ""), preferredStyle: .ActionSheet)
        cameraSettingsAlert.modalPresentationStyle = .Popover

        let photoResolutionAction = UIAlertAction(title: NSLocalizedString("Photo Resolution", comment: ""), style: .Default) { action in

        }
        let cameraOrientationAction = UIAlertAction(title: NSLocalizedString("Camera Orientation", comment: ""), style: .Default) { action in

        }
        let flashModeAction = UIAlertAction(title: NSLocalizedString("Flash Mode", comment: ""), style: .Default) { action in

        }
        let timeStampOnPhotoAction = UIAlertAction(title: NSLocalizedString("Time Stamp on Photo", comment: ""), style: .Default) { action in

        }
        let cancel = UIAlertAction(title: NSLocalizedString("Cancel", comment: ""), style: .Cancel) { action in

        }
        cameraSettingsAlert.addAction(cancel)
        cameraSettingsAlert.addAction(cameraOrientationAction)
        cameraSettingsAlert.addAction(flashModeAction)
        cameraSettingsAlert.addAction(timeStampOnPhotoAction)
        cameraSettingsAlert.addAction(photoResolutionAction)

        if let presenter = cameraSettingsAlert.popoverPresentationController {
            presenter.sourceView = viewRect;
            presenter.sourceRect = viewRect.bounds;
        }
        presentViewController(cameraSettingsAlert, animated: true, completion: nil)

In Javascript/jQuery what does (e) mean?

$(this).click(function(e) {
    // does something
});

In reference to the above code
$(this) is the element which as some variable.
click is the event that needs to be performed.
the parameter e is automatically passed from js to your function which holds the value of $(this) value and can be used further in your code to do some operation.

Get current time in seconds since the Epoch on Linux, Bash

So far, all the answers use the external program date.

Since Bash 4.2, printf has a new modifier %(dateformat)T that, when used with argument -1 outputs the current date with format given by dateformat, handled by strftime(3) (man 3 strftime for informations about the formats).

So, for a pure Bash solution:

printf '%(%s)T\n' -1

or if you need to store the result in a variable var:

printf -v var '%(%s)T' -1

No external programs and no subshells!

Since Bash 4.3, it's even possible to not specify the -1:

printf -v var '%(%s)T'

(but it might be wiser to always give the argument -1 nonetheless).

If you use -2 as argument instead of -1, Bash will use the time the shell was started instead of the current date. This can be used to compute elapsed times

$ printf -v beg '%(%s)T\n' -2
$ printf -v now '%(%s)T\n' -1
$ echo beg=$beg now=$now elapsed=$((now-beg))
beg=1583949610 now=1583953032 elapsed=3422

Not showing placeholder for input type="date" field

To summarize the date inputs problem:

  • You have to display them (i.e. avoid display:none) otherwise the input UI will not be triggered ;
  • a placeholder is contradictory with them (as per the spec, and because they have to display a specific UI) ;
  • converting them to another input type for the unfocused time do allows placeholders, but focus then triggers the wrong input UI (keyboard), at least for a small time, because focus events cannot be cancelled.
  • inserting (before) or adding (after) content doesn't prevent the date input value to be displayed.

The solution I found to meet those requirements is to use the usual trick to style native form elements : ensure the element is displayed but not visible, and display its expected style through its associated label. Typically, the label will display as the input (including a placeholder), but over it.

So, an HTML like:

<div class="date-input>
  <input id="myInput" type="date"> 
  <label for="myInput"> 
    <span class="place-holder">Enter a date</span> 
  </label>
</div>

Could be styled as:

.date-input {
  display: inline-block;
  position: relative;
}
/* Fields overriding */
input[type=date] + label {
  position: absolute;  /* Same origin as the input, to display over it */
  background: white;   /* Opaque background to hide the input behind */
  left: 0;             /* Start at same x coordinate */
}

/* Common input styling */
input[type=date], label {  
  /* Must share same size to display properly (focus, etc.) */
  width: 15em;
  height: 1em;
  font-size: 1em;
}

Any event (click, focus) on such an associated label will be reflected on the field itself, and so trigger the date input UI.

Should you want to test such a solution live, you can run this Angular version from your tablet or mobile.

Change type of varchar field to integer: "cannot be cast automatically to type integer"

Try this, it will work for sure.

When writing Rails migrations to convert a string column to an integer you'd usually say:

change_column :table_name, :column_name, :integer

However, PostgreSQL will complain:

PG::DatatypeMismatch: ERROR:  column "column_name" cannot be cast automatically to type integer
HINT:  Specify a USING expression to perform the conversion.

The "hint" basically tells you that you need to confirm you want this to happen, and how data shall be converted. Just say this in your migration:

change_column :table_name, :column_name, 'integer USING CAST(column_name AS integer)'

The above will mimic what you know from other database adapters. If you have non-numeric data, results may be unexpected (but you're converting to an integer, after all).

Why call git branch --unset-upstream to fixup?

TL;DR version: remote-tracking branch origin/master used to exist, but does not now, so local branch source is tracking something that does not exist, which is suspicious at best—it means a different Git feature is unable to do anything for you—and Git is warning you about it. You have been getting along just fine without having the "upstream tracking" feature work as intended, so it's up to you whether to change anything.

For another take on upstream settings, see Why do I have to "git push --set-upstream origin <branch>"?


This warning is a new thing in Git, appearing first in Git 1.8.5. The release notes contain just one short bullet-item about it:

  • "git branch -v -v" (and "git status") did not distinguish among a branch that is not based on any other branch, a branch that is in sync with its upstream branch, and a branch that is configured with an upstream branch that no longer exists.

To describe what it means, you first need to know about "remotes", "remote-tracking branches", and how Git handles "tracking an upstream". (Remote-tracking branches is a terribly flawed term—I've started using remote-tracking names instead, which I think is a slight improvement. Below, though, I'll use "remote-tracking branch" for consistency with Git documentation.)

Each "remote" is simply a name, like origin or octopress in this case. Their purpose is to record things like the full URL of the places from which you git fetch or git pull updates. When you use git fetch remote,1 Git goes to that remote (using the saved URL) and brings over the appropriate set of updates. It also records the updates, using "remote-tracking branches".

A "remote-tracking branch" (or remote-tracking name) is simply a recording of a branch name as-last-seen on some "remote". Each remote is itself a Git repository, so it has branches. The branches on remote "origin" are recorded in your local repository under remotes/origin/. The text you showed says that there's a branch named source on origin, and branches named 2.1, linklog, and so on on octopress.

(A "normal" or "local" branch, of course, is just a branch-name that you have created in your own repository.)

Last, you can set up a (local) branch to "track" a "remote-tracking branch". Once local branch L is set to track remote-tracking branch R, Git will call R its "upstream" and tell you whether you're "ahead" and/or "behind" the upstream (in terms of commits). It's normal (even recommend-able) for the local branch and remote-tracking branches to use the same name (except for the remote prefix part), like source and origin/source, but that's not actually necessary.

And in this case, that's not happening. You have a local branch source tracking a remote-tracking branch origin/master.

You're not supposed to need to know the exact mechanics of how Git sets up a local branch to track a remote one, but they are relevant below, so I'll show how this works. We start with your local branch name, source. There are two configuration entries using this name, spelled branch.source.remote and branch.source.merge. From the output you showed, it's clear that these are both set, so that you'd see the following if you ran the given commands:

$ git config --get branch.source.remote
origin
$ git config --get branch.source.merge
refs/heads/master

Putting these together,2 this tells Git that your branch source tracks your "remote-tracking branch", origin/master.

But now look at the output of git branch -a, which shows all the local and remote-tracking branch names in your repository. The remote-tracking names are listed under remotes/ ... and there is no remotes/origin/master. Presumably there was, at one time, but it's gone now.

Git is telling you that you can remove the tracking information with --unset-upstream. This will clear out both branch.source.origin and branch.source.merge, and stop the warning.

It seems fairly likely that what you want, though, is to switch from tracking origin/master, to tracking something else: probably origin/source, but maybe one of the octopress/ names.

You can do this with git branch --set-upstream-to,3 e.g.:

$ git branch --set-upstream-to=origin/source

(assuming you're still on branch "source", and that origin/source is the upstream you want—there is no way for me to tell which one, if any, you actually want, though).

(See also How do you make an existing Git branch track a remote branch?)

I think the way you got here is that when you first did a git clone, the thing you cloned-from had a branch master. You also had a branch master, which was set to track origin/master (this is a normal, standard setup for git). This meant you had branch.master.remote and branch.master.merge set, to origin and refs/heads/master. But then your origin remote changed its name from master to source. To match, I believe you also changed your local name from master to source. This changed the names of your settings, from branch.master.remote to branch.source.remote and from branch.master.merge to branch.source.merge ... but it left the old values, so branch.source.merge was now wrong.

It was at this point that the "upstream" linkage broke, but in Git versions older than 1.8.5, Git never noticed the broken setting. Now that you have 1.8.5, it's pointing this out.


That covers most of the questions, but not the "do I need to fix it" one. It's likely that you have been working around the broken-ness for years now, by doing git pull remote branch (e.g., git pull origin source). If you keep doing that, it will keep working around the problem—so, no, you don't need to fix it. If you like, you can use --unset-upstream to remove the upstream and stop the complaints, and not have local branch source marked as having any upstream at all.

The point of having an upstream is to make various operations more convenient. For instance, git fetch followed by git merge will generally "do the right thing" if the upstream is set correctly, and git status after git fetch will tell you whether your repo matches the upstream one, for that branch.

If you want the convenience, re-set the upstream.


1git pull uses git fetch, and as of Git 1.8.4, this (finally!) also updates the "remote-tracking branch" information. In older versions of Git, the updates did not get recorded in remote-tracking branches with git pull, only with git fetch. Since your Git must be at least version 1.8.5 this is not an issue for you.

2Well, this plus a configuration line I'm deliberately ignoring that is found under remote.origin.fetch. Git has to map the "merge" name to figure out that the full local name for the remote-branch is refs/remotes/origin/master. The mapping almost always works just like this, though, so it's predictable that master goes to origin/master.

3Or, with git config. If you just want to set the upstream to origin/source the only part that has to change is branch.source.merge, and git config branch.source.merge refs/heads/source would do it. But --set-upstream-to says what you want done, rather than making you go do it yourself manually, so that's a "better way".

How can I combine two commits into one commit?

You want to git rebase -i to perform an interactive rebase.

If you're currently on your "commit 1", and the commit you want to merge, "commit 2", is the previous commit, you can run git rebase -i HEAD~2, which will spawn an editor listing all the commits the rebase will traverse. You should see two lines starting with "pick". To proceed with squashing, change the first word of the second line from "pick" to "squash". Then save your file, and quit. Git will squash your first commit into your second last commit.

Note that this process rewrites the history of your branch. If you are pushing your code somewhere, you'll have to git push -f and anybody sharing your code will have to jump through some hoops to pull your changes.

Note that if the two commits in question aren't the last two commits on the branch, the process will be slightly different.

What is the printf format specifier for bool?

I prefer an answer from Best way to print the result of a bool as 'false' or 'true' in c?, just like

printf("%s\n", "false\0true"+6*x);
  • x == 0, "false\0true"+ 0" it means "false";
  • x == 1, "false\0true"+ 6" it means "true";

Implement specialization in ER diagram

So I assume your permissions table has a foreign key reference to admin_accounts table. If so because of referential integrity you will only be able to add permissions for account ids exsiting in the admin accounts table. Which also means that you wont be able to enter a user_account_id [assuming there are no duplicates!]

Easily measure elapsed time

They are they same because your doSomething function happens faster than the granularity of the timer. Try:

printf ("**MyProgram::before time= %ld\n", time(NULL));

for(i = 0; i < 1000; ++i) {
    doSomthing();
    doSomthingLong();
}

printf ("**MyProgram::after time= %ld\n", time(NULL));

How to add a set path only for that batch file executing?

That's right, but it doesn't change it permanently, but just for current command prompt, if you wanna to change it permanently you have to use for example this:

setx ENV_VAR_NAME "DESIRED_PATH" /m

This will change it permanently and yes you can overwrite it by another batch script.

Calculating moving average

In order to complement the answer of cantdutchthis and Rodrigo Remedio;

moving_fun <- function(x, w, FUN, ...) {
  # x: a double vector
  # w: the length of the window, i.e., the section of the vector selected to apply FUN
  # FUN: a function that takes a vector and return a summarize value, e.g., mean, sum, etc.
  # Given a double type vector apply a FUN over a moving window from left to the right, 
  #    when a window boundary is not a legal section, i.e. lower_bound and i (upper bound) 
  #    are not contained in the length of the vector, return a NA_real_
  if (w < 1) {
    stop("The length of the window 'w' must be greater than 0")
  }
  output <- x
  for (i in 1:length(x)) {
     # plus 1 because the index is inclusive with the upper_bound 'i'
    lower_bound <- i - w + 1
    if (lower_bound < 1) {
      output[i] <- NA_real_
    } else {
      output[i] <- FUN(x[lower_bound:i, ...])
    }
  }
  output
}

# example
v <- seq(1:10)

# compute a MA(2)
moving_fun(v, 2, mean)

# compute moving sum of two periods
moving_fun(v, 2, sum)

What is the "Illegal Instruction: 4" error and why does "-mmacosx-version-min=10.x" fix it?

I'm consciously writing this answer to an old question with this in mind, because the other answers didn't help me.

I got the Illegal Instruction: 4 while running the binary on the same system I had compiled it on, so -mmacosx-version-min didn't help.

I was using gcc in Code Blocks 16 on Mac OS X 10.11.

However, turning off all of Code Blocks' compiler flags for optimization worked. So look at all the flags Code Blocks set (right-click on the Project -> "Build Properties") and turn off all the flags you are sure you don't need, especially -s and the -Oflags for optimization. That did it for me.

data.frame rows to a list

If you want to completely abuse the data.frame (as I do) and like to keep the $ functionality, one way is to split you data.frame into one-line data.frames gathered in a list :

> df = data.frame(x=c('a','b','c'), y=3:1)
> df
  x y
1 a 3
2 b 2
3 c 1

# 'convert' into a list of data.frames
ldf = lapply(as.list(1:dim(df)[1]), function(x) df[x[1],])

> ldf
[[1]]
x y
1 a 3    
[[2]]
x y
2 b 2
[[3]]
x y
3 c 1

# and the 'coolest'
> ldf[[2]]$y
[1] 2

It is not only intellectual masturbation, but allows to 'transform' the data.frame into a list of its lines, keeping the $ indexation which can be useful for further use with lapply (assuming the function you pass to lapply uses this $ indexation)

Pandas column of lists, create a row for each list element

For those looking for a version of Roman Pekar's answer that avoids manual column naming:

column_to_explode = 'samples'
res = (df
       .set_index([x for x in df.columns if x != column_to_explode])[column_to_explode]
       .apply(pd.Series)
       .stack()
       .reset_index())
res = res.rename(columns={
          res.columns[-2]:'exploded_{}_index'.format(column_to_explode),
          res.columns[-1]: '{}_exploded'.format(column_to_explode)})

Sum all the elements java arraylist

I haven't tested it but it should work.

public double incassoMargherita()
{
    double sum = 0;
    for(int i = 0; i < m.size(); i++)
    {
        sum = sum + m.get(i);
    }
    return sum;
}

Slide right to left Android Animations

For sliding both activity (old and new) same direction:

left_in.xml

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="300"
    android:fromXDelta="-100%"
    android:toXDelta="0%"
    android:interpolator="@android:anim/decelerate_interpolator"
     />

right_in.xml

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="300"
    android:fromXDelta="100%"
    android:toXDelta="0%"
    android:interpolator="@android:anim/decelerate_interpolator"
     />

left_out.xml

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="300"
    android:fromXDelta="0%"
    android:interpolator="@android:anim/decelerate_interpolator"
    android:toXDelta="-100%" />

right_out.xml

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="300"
    android:fromXDelta="0%"
    android:interpolator="@android:anim/decelerate_interpolator"
    android:toXDelta="100%" />

startActivity transition:

overridePendingTransition(R.anim.right_in, R.anim.left_out);

onBackPressed transition:

overridePendingTransition(R.anim.left_in, R.anim.right_out);

Send PHP variable to javascript function

Your JavaScript would have to be defined within a PHP-parsed file.

For example, in index.php you could place

<?php
$time = time();
?>
<script>
    document.write(<?php echo $time; ?>);
</script>

How to use gitignore command in git

If you dont have a .gitignore file, first use:

touch .gitignore

then this command to add lines in your gitignore file:

echo 'application/cache' >> .gitignore

Be careful about new lines

How to convert all tables in database to one collation?

For phpMyAdmin I figured this out:

SELECT GROUP_CONCAT("ALTER TABLE ", TABLE_SCHEMA, '.', TABLE_NAME," CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;" SEPARATOR ' ') AS    OneSQLString
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA="yourtableschemaname"
AND TABLE_TYPE="BASE TABLE"

Just change yourtableschemaname and you're fine.

Reading NFC Tags with iPhone 6 / iOS 8

From digging into the iOS 8 docs that are available as of Sept 9th 3:30pm there is no mention of developer access to the NFC controller to perform any NFC operations; that includes reading tags, writing tags, pairing, payments, tag emulation... Given its an NXP controller the hardware has the capability to perform these features. They did mention a 3rd party app for the watch that allowed a hotel guest to open their room door with NFC. This is a classic use case for NFC and gives some indication that the NFC controller will be open to developers at some point. Remember, the watch is not supposed to be released until Q1 2015. So for now I'd say it's closed but will be open soon. Given the 'newness' of contactless payments for the general US consumer and the recent security breaches its not surprising Apple wants to keep this closed for a while.

Disclosure: Im the CEO of GoToTags, an NFC company with obvious vested interest in Apple opening up NFC to developers.

--- Correction & Update ---

The hotel app actually uses Bluetooth, not NFC. NFC is still often used for door unlocking, just not in this one example. NFC could be used if the watch has an open NFC controller.

I do know that Apple is aware of all of this and is discussing this with their top developers and stakeholders. There has already been massive negative push back on the lack of support for reading tags. As often the case in the past, I expect Apple to eventually open this up to developers for non-payment related functionality (reading tags, pairing). I do not think Apple will ever allow other wallets though. File sharing will likely be left to AirDrop as well.

--- Update on March 23rd 2016 ---

I am continually asked for updates about this topic, often with people referencing this post. With Apple releasing the iPhone SE, many are again asking why Apple has not supported tag reading yet. In summary Apple is more focused on Apple Pay succeeding than the other use cases for NFC for now. Apple could make a lot of money from Apple Pay, and has less to make from the other uses for NFC. Apple will likely open up NFC tag reading when they feel that consumer trust and security with NFC and Apple Pay is such that it wont put Apple Pay at risk. Further information here.

--- Update on May 24th 2017 ---

A developer in Greece has hacked the iPhone 6s to get it to read NFC tags via the NFC private frameworks; more info & video. While this isn't a long term solution, it provides some guidance on some outstanding question: Is there enough power in the iPhone's NFC controller to power an NFC tag? Looks like the answer is yes. From initial testing the range is a few cm, which isn't too bad. It might also be the power is tunable; this is being investigated at this time. The implications of this are significant. If the older model phones do have enough RF power for tag reading/writing, then when Apple does open up the SDK it means there will be 100Ms of iPhones that can read NFC tags, vs the case where only the new iPhones could.

How do I exit a foreach loop in C#?

Just use the statement:

break;

Difference between JSONObject and JSONArray

When a JSON start's with {} it is a ObjectJSON object and when it start's with [] it is an Array JOSN Array

An JSON array can consist of a/many objects and that is called an array of objects

How to write MySQL query where A contains ( "a" or "b" )

I've used most of the times the LIKE option and it works just fine. I just like to share one of my latest experiences where I used INSTR function. Regardless of the reasons that made me consider this options, what's important here is that the use is similar: instr(A, 'text 1') > 0 or instr(A, 'text 2') > 0 Another option could be: (instr(A, 'text 1') + instr(A, 'text 2')) > 0

I'd go with the LIKE '%text1%' OR LIKE '%text2%' option... if not hope this other option helps

Get a substring of a char*

Use char* strncpy(char* dest, char* src, int n) from <cstring>. In your case you will need to use the following code:

char* substr = malloc(4);
strncpy(substr, buff+10, 4);

Full documentation on the strncpy function here.

Bootstrap: How do I identify the Bootstrap version?

you will see your current bootstrap version in this "bootstrap.min.css/bootstrap.css" files, In the top section

finding first day of the month in python

This could be an alternative to Gustavo Eduardo Belduma's answer:

import datetime 
first_day_of_the_month = datetime.date.today().replace(day=1)

Render basic HTML view?

try this. it works for me.

app.configure(function(){

  .....

  // disable layout
  app.set("view options", {layout: false});

  // make a custom html template
  app.register('.html', {
    compile: function(str, options){
      return function(locals){
        return str;
      };
    }
  });
});

....

app.get('/', function(req, res){
  res.render("index.html");
});

Pass variables to AngularJS controller, best practice?

I'm not very advanced in AngularJS, but my solution would be to use a simple JS class for you cart (in the sense of coffee script) that extend Array.

The beauty of AngularJS is that you can pass you "model" object with ng-click like shown below.

I don't understand the advantage of using a factory, as I find it less pretty that a CoffeeScript class.

My solution could be transformed in a Service, for reusable purpose. But otherwise I don't see any advantage of using tools like factory or service.

class Basket extends Array
  constructor: ->

  add: (item) ->
    @push(item)

  remove: (item) ->
    index = @indexOf(item)
    @.splice(index, 1)

  contains: (item) ->
    @indexOf(item) isnt -1

  indexOf: (item) ->
    indexOf = -1
    @.forEach (stored_item, index) ->
      if (item.id is stored_item.id)
        indexOf = index
    return indexOf

Then you initialize this in your controller and create a function for that action:

 $scope.basket = new Basket()
 $scope.addItemToBasket = (item) ->
   $scope.basket.add(item)

Finally you set up a ng-click to an anchor, here you pass your object (retreived from the database as JSON object) to the function:

li ng-repeat="item in items"
  a href="#" ng-click="addItemToBasket(item)" 

Mongoose, Select a specific field with find

The _id field is always present unless you explicitly exclude it. Do so using the - syntax:

exports.someValue = function(req, res, next) {
    //query with mongoose
    var query = dbSchemas.SomeValue.find({}).select('name -_id');

    query.exec(function (err, someValue) {
        if (err) return next(err);
        res.send(someValue);
    });
};

Or explicitly via an object:

exports.someValue = function(req, res, next) {
    //query with mongoose
    var query = dbSchemas.SomeValue.find({}).select({ "name": 1, "_id": 0});

    query.exec(function (err, someValue) {
        if (err) return next(err);
        res.send(someValue);
    });
};

How can I open Java .class files in a human-readable way?

JAD and/or JADclipse Eclipse plugin, for sure.

How to access route, post, get etc. parameters in Zend Framework 2

If You have no access to plugin for instance outside of controller You can get params from servicelocator like this

//from POST
$foo = $this->serviceLocator->get('request')->getPost('foo'); 
//from GET
$foo = $this->serviceLocator->get('request')->getQuery()->foo;
//from route
$foo = $this->serviceLocator->get('application')->getMvcEvent()->getRouteMatch()->getParam('foo');

How can you test if an object has a specific property?

I ended up with the following function ...

function HasNoteProperty(
    [object]$testObject,
    [string]$propertyName
)
{
    $members = Get-Member -InputObject $testObject 
    if ($members -ne $null -and $members.count -gt 0) 
    { 
        foreach($member in $members) 
        { 
            if ( ($member.MemberType -eq "NoteProperty" )  -and `
                 ($member.Name       -eq $propertyName) ) 
            { 
                return $true 
            } 
        } 
        return $false 
    } 
    else 
    { 
        return $false; 
    }
}

Using $setValidity inside a Controller

This line:

myForm.file.$setValidity("myForm.file.$error.size", false);

Should be

$scope.myForm.file.$setValidity("size", false);

What's the difference setting Embed Interop Types true and false in Visual Studio?

I noticed that when it's set to false, I'm able to see the value of an item using the debugger. When it was set to true, I was getting an error - item.FullName.GetValue The embedded interop type 'FullName' does not contain a definition for 'QBFC11Lib.IItemInventoryRet' since it was not used in the compiled assembly. Consider casting to object or changing the 'Embed Interop Types' property to true.

Best Practice: Software Versioning

We follow a.b.c approach like:

increament 'a' if there is some major changes happened in application. Like we upgrade .NET 1.1 application to .NET 3.5

increament 'b' if there is some minor changes like any new CR or Enhancement is implemented.

increament 'c' if there is some defects fixes in the code.

How do you run a js file using npm scripts?

You should use npm run-script build or npm build <project_folder>. More info here: https://docs.npmjs.com/cli/build.

What does it mean by select 1 from table?

it does what it says - it will always return the integer 1. It's used to check whether a record matching your where clause exists.

Customizing Bootstrap CSS template

Since Pabluez's answer back in December, there is now a better way to customize Bootstrap.

Use: Bootswatch to generate your bootstrap.css

Bootswatch builds the normal Twitter Bootstrap from the latest version (whatever you install in the bootstrap directory), but also imports your customizations. This makes it easy to use the the latest version of Bootstrap, while maintaining custom CSS, without having to change anything about your HTML. You can simply sway boostrap.css files.

How to mute an html5 video player using jQuery

If you don't want to jQuery, here's the vanilla JavaScript:

///Mute
var video = document.getElementById("your-video-id");
video.muted= true;

//Unmute
var video = document.getElementById("your-video-id");
video.muted= false;

It will work for audio too, just put the element's id and it will work (and change the var name if you want, to 'media' or something suited for both audio/video as you like).

How to convert list data into json in java

Try like below with Gson Library.

Earlier Conversion List format were:

[Product [Id=1, City=Bengalore, Category=TV, Brand=Samsung, Name=Samsung LED, Type=LED, Size=32 inches, Price=33500.5, Stock=17.0], Product [Id=2, City=Bengalore, Category=TV, Brand=Samsung, Name=Samsung LED, Type=LED, Size=42 inches, Price=41850.0, Stock=9.0]]

and here the conversion source begins.

//** Note I have created the method toString() in Product class.

//Creating and initializing a java.util.List of Product objects
List<Product> productList = (List<Product>)productRepository.findAll();

//Creating a blank List of Gson library JsonObject
List<JsonObject> entities = new ArrayList<JsonObject>();

//Simply printing productList size
System.out.println("Size of productList is : " + productList.size());

//Creating a Iterator for productList
Iterator<Product> iterator = productList.iterator();

//Run while loop till Product Object exists.
while(iterator.hasNext()){

    //Creating a fresh Gson Object
    Gson gs = new Gson();

    //Converting our Product Object to JsonElement 
    //Object by passing the Product Object String value (iterator.next())
    JsonElement element = gs.fromJson (gs.toJson(iterator.next()), JsonElement.class);

    //Creating JsonObject from JsonElement
    JsonObject jsonObject = element.getAsJsonObject();

    //Collecting the JsonObject to List
    entities.add(jsonObject);

}

//Do what you want to do with Array of JsonObject
System.out.println(entities);

Converted Json Result is :

[{"Id":1,"City":"Bengalore","Category":"TV","Brand":"Samsung","Name":"Samsung LED","Type":"LED","Size":"32 inches","Price":33500.5,"Stock":17.0}, {"Id":2,"City":"Bengalore","Category":"TV","Brand":"Samsung","Name":"Samsung LED","Type":"LED","Size":"42 inches","Price":41850.0,"Stock":9.0}]

Hope this would help many guys!

Event binding on dynamically created elements?

Use the .on() method of jQuery http://api.jquery.com/on/ to attach event handlers to live element.

Also as of version 1.9 .live() method is removed.

Cross domain POST request is not sending cookie Ajax Jquery

Please note this doesn't solve the cookie sharing process, as in general this is bad practice.

You need to be using JSONP as your type:

From $.ajax documentation: Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation.

$.ajax(
    { 
      type: "POST",
      url: "http://example.com/api/getlist.json",
      dataType: 'jsonp',
      xhrFields: {
           withCredentials: true
      },
      crossDomain: true,
      beforeSend: function(xhr) {
            xhr.setRequestHeader("Cookie", "session=xxxyyyzzz");
      },
      success: function(){
           alert('success');
      },
      error: function (xhr) {
             alert(xhr.responseText);
      }
    }
);

Python memory leaks

Have a look at this article: Tracing python memory leaks

Also, note that the garbage collection module actually can have debug flags set. Look at the set_debug function. Additionally, look at this code by Gnibbler for determining the types of objects that have been created after a call.

A table name as a variable

You'll need to generate the SQL content dynamically:

declare @tablename varchar(50)

set @tablename = 'test'

declare @sql varchar(500)

set @sql = 'select * from ' + @tablename

exec (@sql)

How do I raise the same Exception with a custom message in Python?

Try below:

try:
    raise ValueError("Original message. ")
except Exception as err:
    message = 'My custom error message. '
    # Change the order below to "(message + str(err),)" if custom message is needed first. 
    err.args = (str(err) + message,)
    raise 

Output:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
      1 try:
----> 2     raise ValueError("Original message")
      3 except Exception as err:
      4     message = 'My custom error message.'
      5     err.args = (str(err) + ". " + message,)

ValueError: Original message. My custom error message.

No internet on Android emulator - why and how to fix?

Check your internet settings, firewalls and such may be blocking it, I know when I was working on it in college they were blocking the port number but I've never had any trouble on my home machines

Sorting 1 million 8-decimal-digit numbers with 1 MB of RAM

Suppose this task is possible. Just prior to output, there will be an in-memory representation of the million sorted numbers. How many different such representations are there? Since there may be repeated numbers we can't use nCr (choose), but there is an operation called multichoose that works on multisets.

  • There are 2.2e2436455 ways to choose a million numbers in range 0..99,999,999.
  • That requires 8,093,730 bits to represent every possible combination, or 1,011,717 bytes.

So theoretically it may be possible, if you can come up with a sane (enough) representation of the sorted list of numbers. For example, an insane representation might require a 10MB lookup table or thousands of lines of code.

However, if "1M RAM" means one million bytes, then clearly there is not enough space. The fact that 5% more memory makes it theoretically possible suggests to me that the representation will have to be VERY efficient and probably not sane.

In C#, should I use string.Empty or String.Empty or "" to intitialize a string?

string is synonym for System.String type, They are identical.

Values are also identical: string.Empty == String.Empty == ""

I would not use character constant "" in code, rather string.Empty or String.Empty - easier to see what programmer meant.

Between string and String I like lower case string more just because I used to work with Delphi for lot of years and Delphi style is lowercase string.

So, if I was your boss, you would be writing string.Empty

How to load assemblies in PowerShell?

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") worked for me.

converting json to string in python

There are other differences. For instance, {'time': datetime.now()} cannot be serialized to JSON, but can be converted to string. You should use one of these tools depending on the purpose (i.e. will the result later be decoded).

Creating a very simple linked list

The selected answer doesn't have an iterator; it is more basic, but perhaps not as useful.

Here is one with an iterator/enumerator. My implementation is based on Sedgewick's bag; see http://algs4.cs.princeton.edu/13stacks/Bag.java.html

void Main()
{
    var b = new Bag<string>();
    b.Add("bike");
    b.Add("erasmus");
    b.Add("kumquat");
    b.Add("beaver");
    b.Add("racecar");
    b.Add("barnacle");

    foreach (var thing in b)
    {
        Console.WriteLine(thing);
    }
}

// Define other methods and classes here

public class Bag<T> : IEnumerable<T>
{
    public Node<T> first;// first node in list

    public class Node<T>
    {
        public T item;
        public Node<T> next;

        public Node(T item)
        {
            this.item = item;
        }
    }


    public void Add(T item)
    {
        Node<T> oldFirst = first;
        first = new Node<T>(item);
        first.next = oldFirst;
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

    public IEnumerator<T> GetEnumerator()
    {
        return new BagEnumerator<T>(this);
    }

    public class BagEnumerator<V> : IEnumerator<T>
    {
        private Node<T> _head;
        private Bag<T> _bag;
        private Node<T> _curNode;


        public BagEnumerator(Bag<T> bag)
        {

            _bag = bag;
            _head = bag.first;
            _curNode = default(Node<T>);

        }

        public T Current
        {
            get { return _curNode.item; }
        }


        object IEnumerator.Current
        {
            get { return Current; }
        }

        public bool MoveNext()
        {
            if (_curNode == null)
            {
                _curNode = _head;
                if (_curNode == null)
                return false;
                return true;
            }
            if (_curNode.next == null)
            return false;
            else
            {
                _curNode = _curNode.next;
                return true;
            }

        }

        public void Reset()
        {
            _curNode = default(Node<T>); ;
        }


        public void Dispose()
        {
        }
    }
}

How to query as GROUP BY in django?

from django.db.models import Sum
Members.objects.annotate(total=Sum(designation))

first you need to import Sum then ..

Scroll to a div using jquery

Add this little function and use it as so: $('div').scrollTo(500);

jQuery.fn.extend(
{
  scrollTo : function(speed, easing)
  {
    return this.each(function()
    {
      var targetOffset = $(this).offset().top;
      $('html,body').animate({scrollTop: targetOffset}, speed, easing);
    });
  }
});

Why do I need to configure the SQL dialect of a data source?

The SQL dialect converts the HQL query which we write in our java or any other object oriented program to the specific database SQL.

For example in the java suppose I write List employees = session.createQuery("FROM Employee").list();

but when my dialect is <property name="hibernate.dialect"> org.hibernate.dialect.MySQLDialect

The HQL ("FROM Employee") gets converted to "SELECT * FROM EMPLOYEE" before hitting the MySQL database

Getting the minimum of two values in SQL

This works for up to 5 dates and handles nulls. Just couldn't get it to work as an Inline function.

CREATE FUNCTION dbo.MinDate(@Date1 datetime = Null,
                            @Date2 datetime = Null,
                            @Date3 datetime = Null,
                            @Date4 datetime = Null,
                            @Date5 datetime = Null)
RETURNS Datetime AS
BEGIN
--USAGE select dbo.MinDate('20120405',null,null,'20110305',null)
DECLARE @Output datetime;

WITH Datelist_CTE(DT)
AS (
        SELECT @Date1 AS DT WHERE @Date1 is not NULL UNION
        SELECT @Date2 AS DT WHERE @Date2 is not NULL UNION
        SELECT @Date3 AS DT WHERE @Date3 is not NULL UNION
        SELECT @Date4 AS DT WHERE @Date4 is not NULL UNION
        SELECT @Date5 AS DT WHERE @Date5 is not NULL
   )
Select @Output=Min(DT) FROM Datelist_CTE

RETURN @Output
END

HTML5 Canvas Resize (Downscale) Image High Quality?

context.scale(xScale, yScale)

<canvas id="c"></canvas>
<hr/>
<img id="i" />

<script>
var i = document.getElementById('i');

i.onload = function(){
    var width = this.naturalWidth,
        height = this.naturalHeight,
        canvas = document.getElementById('c'),
        ctx = canvas.getContext('2d');

    canvas.width = Math.floor(width / 2);
    canvas.height = Math.floor(height / 2);

    ctx.scale(0.5, 0.5);
    ctx.drawImage(this, 0, 0);
    ctx.rect(0,0,500,500);
    ctx.stroke();

    // restore original 1x1 scale
    ctx.scale(2, 2);
    ctx.rect(0,0,500,500);
    ctx.stroke();
};

i.src = 'https://static.md/b70a511140758c63f07b618da5137b5d.png';
</script>

Find an item in List by LINQ?

I used to use a Dictionary which is some sort of an indexed list which will give me exactly what I want when I want it.

Dictionary<string, int> margins = new Dictionary<string, int>();
margins.Add("left", 10);
margins.Add("right", 10);
margins.Add("top", 20);
margins.Add("bottom", 30);

Whenever I wish to access my margins values, for instance, I address my dictionary:

int xStartPos = margins["left"];
int xLimitPos = margins["right"];
int yStartPos = margins["top"];
int yLimitPos = margins["bottom"];

So, depending on what you're doing, a dictionary can be useful.

Convert object to JSON string in C#

I have used Newtonsoft JSON.NET (Documentation) It allows you to create a class / object, populate the fields, and serialize as JSON.

public class ReturnData 
{
    public int totalCount { get; set; }
    public List<ExceptionReport> reports { get; set; }  
}

public class ExceptionReport
{
    public int reportId { get; set; }
    public string message { get; set; }  
}


string json = JsonConvert.SerializeObject(myReturnData);

Send email with PHP from html form on submit with the same script

PHP script to connect to a SMTP server and send email on Windows 7

Sending an email from PHP in Windows is a bit of a minefield with gotchas and head scratching. I'll try to walk you through one instance where I got it to work on Windows 7 and PHP 5.2.3 under (IIS) Internet Information Services webserver.

I'm assuming you don't want to use any pre-built framework like CodeIgniter or Symfony which contains email sending capability. We'll be sending an email from a standalone PHP file. I acquired this code from under the codeigniter hood (under system/libraries) and modified it so you can just drop in this Email.php file and it should just work.

This should work with newer versions of PHP. But you never know.

Step 1, You need a username/password with an SMTP server:

I'm using the smtp server from smtp.ihostexchange.net which is already created and setup for me. If you don't have this you can't proceed. You should be able to use an email client like thunderbird, evolution, Microsoft Outlook, to specify your smtp server and then be able to send emails through there.

Step 2, Create your Hello World Email file:

I'm assuming you are using IIS. So create a file called index.php under C:\inetpub\wwwroot and put this code in there:

<?php

  include("Email.php");

  $c = new CI_Email();

  $c->from("[email protected]");
  $c->to("[email protected]");
  $c->subject("Celestial Temple");
  $c->message("Dominion reinforcements on the way.");
  $c->send();
  echo "done";
?>

You should be able to visit this index.php by navigating to localhost/index.php in a browser, it will spew errors because Email.php is missing. But make sure you can at least run it from the browser.

Step 3, Create a file called Email.php:

Create a new file called Email.php under C:\inetpub\wwwroot.

Copy/paste this PHP code into Email.php:

https://github.com/sentientmachine/standalone_php_script_send_email/blob/master/Email.php

Since there are many kinds of smtp servers, you will have to manually fiddle with the settings at the top of Email.php. I've set it up so it automatically works with smtp.ihostexchange.net, but your smtp server might be different.

For example:

  1. Set the smtp_port setting to the port of your smtp server.
  2. Set the smtp_crypto setting to what your smtp server needs.
  3. Set the $newline and $crlf so it's compatible with what your smtp server uses. If you pick wrong, the smtp server may ignore your request without error. I use \r\n, for you maybe \n is required.

The linked code is too long to paste as a stackoverflow answer, If you want to edit it, leave a comment in here or through github and I'll change it.

Step 4, make sure your php.ini has ssl extension enabled:

Find your PHP.ini file and uncomment the

;extension=php_openssl.dll

So it looks like:

extension=php_openssl.dll

Step 5, Run the index.php file you just made in a browser:

You should get the following output:

220 smtp.ihostexchange.net Microsoft ESMTP MAIL Service ready at 
Wed, 16 Apr 2014 15:43:58 -0400 250 2.6.0 
<[email protected]> Queued mail for delivery 
lang:email_sent

done

Step 6, check your email, and spam folder:

Visit the email account for [email protected] and you should have received an email. It should arrive within 5 or 10 seconds. If you does not, inspect the errors returned on the page. If that doesn't work, try mashing your face on the keyboard on google while chanting: "working at the grocery store isn't so bad."

How to get the error message from the error code returned by GetLastError()?

If you're using c# you can use this code:

using System.Runtime.InteropServices;

public static class WinErrors
{
    #region definitions
    [DllImport("kernel32.dll", SetLastError = true)]
    static extern IntPtr LocalFree(IntPtr hMem);

    [DllImport("kernel32.dll", SetLastError = true)]
    static extern int FormatMessage(FormatMessageFlags dwFlags, IntPtr lpSource, uint dwMessageId, uint dwLanguageId, ref IntPtr lpBuffer, uint nSize, IntPtr Arguments);

    [Flags]
    private enum FormatMessageFlags : uint
    {
        FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100,
        FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200,
        FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000,
        FORMAT_MESSAGE_ARGUMENT_ARRAY = 0x00002000,
        FORMAT_MESSAGE_FROM_HMODULE = 0x00000800,
        FORMAT_MESSAGE_FROM_STRING = 0x00000400,
    }
    #endregion

    /// <summary>
    /// Gets a user friendly string message for a system error code
    /// </summary>
    /// <param name="errorCode">System error code</param>
    /// <returns>Error string</returns>
    public static string GetSystemMessage(int errorCode)
    {
        try
        {
            IntPtr lpMsgBuf = IntPtr.Zero;

            int dwChars = FormatMessage(
                FormatMessageFlags.FORMAT_MESSAGE_ALLOCATE_BUFFER | FormatMessageFlags.FORMAT_MESSAGE_FROM_SYSTEM | FormatMessageFlags.FORMAT_MESSAGE_IGNORE_INSERTS,
                IntPtr.Zero,
                (uint) errorCode,
                0, // Default language
                ref lpMsgBuf,
                0,
                IntPtr.Zero);
            if (dwChars == 0)
            {
                // Handle the error.
                int le = Marshal.GetLastWin32Error();
                return "Unable to get error code string from System - Error " + le.ToString();
            }

            string sRet = Marshal.PtrToStringAnsi(lpMsgBuf);

            // Free the buffer.
            lpMsgBuf = LocalFree(lpMsgBuf);
            return sRet;
        }
        catch (Exception e)
        {
            return "Unable to get error code string from System -> " + e.ToString();
        }
    }
}

How to send data in request body with a GET when using jQuery $.ajax()

we all know generally that for sending the data according to the http standards we generally use POST request. But if you really want to use Get for sending the data in your scenario I would suggest you to use the query-string or query-parameters.

1.GET use of Query string as. {{url}}admin/recordings/some_id

here the some_id is mendatory parameter to send and can be used and req.params.some_id at server side.

2.GET use of query string as{{url}}admin/recordings?durationExact=34&isFavourite=true

here the durationExact ,isFavourite is optional strings to send and can be used and req.query.durationExact and req.query.isFavourite at server side.

3.GET Sending arrays {{url}}admin/recordings/sessions/?os["Windows","Linux","Macintosh"]

and you can access those array values at server side like this

let osValues = JSON.parse(req.query.os);
        if(osValues.length > 0)
        {
            for (let i=0; i<osValues.length; i++)
            {
                console.log(osValues[i])
                //do whatever you want to do here
            }
        }

How to disable spring security for particular url

As @M.Deinum already wrote the answer.

I tried with api /api/v1/signup. it will bypass the filter/custom filter but an additional request invoked by the browser for /favicon.ico, so, I add this also in web.ignoring() and it works for me.

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/api/v1/signup", "/favicon.ico");
}

Maybe this is not required for the above question.

How can I force a hard reload in Chrome for Android

Don't forget to make sure that the "Reduce data usage" setting is turned OFF, as it seems to download cached data (from Google servers?) even though your local cache is flushed.

Basic Ajax send/receive with node.js

  1. Your request should be to the server, NOT the server.js file which instantiates it. So, the request should look something like this: xmlhttp.open("GET","http://localhost:8001/", true); Also, you are trying to serve the front-end (index.html) AND serve AJAX requests at the same URI. To accomplish this, you are going to have to introduce logic to your server.js that will differentiate between your AJAX requests and a normal http access request. To do this, you'll want to either introduce GET/POST data (i.e. call http://localhost:8001/?getstring=true) or use a different path for your AJAX requests (i.e. call http://localhost:8001/getstring). On the server end then, you'll need to examine the request object to determine what to write on the response. For the latter option, you need to use the 'url' module to parse the request.

  2. You are correctly calling listen() but incorrectly writing the response. First of all, if you wish to serve index.html when navigating to http://localhost:8001/, you need to write the contents of the file to the response using response.write() or response.end(). First, you need to include fs=require('fs') to get access to the filesystem. Then, you need to actually serve the file.

  3. XMLHttpRequest needs a callback function specified if you use it asynchronously (third parameter = true, as you have done) AND want to do something with the response. The way you have it now, string will be undefined (or perhaps null), because that line will execute before the AJAX request is complete (i.e. the responseText is still empty). If you use it synchronously (third parameter = false), you can write inline code as you have done. This is not recommended as it locks the browser during the request. Asynchronous operation is usually used with the onreadystatechange function, which can handle the response once it is complete. You need to learn the basics of XMLHttpRequest. Start here.

Here is a simple implementation that incorporates all of the above:

server.js:

var http = require('http'),
      fs = require('fs'),
     url = require('url'),
 choices = ["hello world", "goodbye world"];

http.createServer(function(request, response){
    var path = url.parse(request.url).pathname;
    if(path=="/getstring"){
        console.log("request recieved");
        var string = choices[Math.floor(Math.random()*choices.length)];
        console.log("string '" + string + "' chosen");
        response.writeHead(200, {"Content-Type": "text/plain"});
        response.end(string);
        console.log("string sent");
    }else{
        fs.readFile('./index.html', function(err, file) {  
            if(err) {  
                // write an error response or nothing here  
                return;  
            }  
            response.writeHead(200, { 'Content-Type': 'text/html' });  
            response.end(file, "utf-8");  
        });
    }
}).listen(8001);
console.log("server initialized");

frontend (part of index.html):

function newGame()
{
   guessCnt=0;
   guess="";
   server();
   displayHash();
   displayGuessStr();
   displayGuessCnt();
}

function server()
{
   xmlhttp = new XMLHttpRequest();
   xmlhttp.open("GET","http://localhost:8001/getstring", true);
   xmlhttp.onreadystatechange=function(){
         if (xmlhttp.readyState==4 && xmlhttp.status==200){
           string=xmlhttp.responseText;
         }
   }
   xmlhttp.send();
}

You will need to be comfortable with AJAX. Use the mozilla learning center to learn about XMLHttpRequest. After you can use the basic XHR object, you will most likely want to use a good AJAX library instead of manually writing cross-browser AJAX requests (for example, in IE you'll need to use an ActiveXObject instead of XHR). The AJAX in jQuery is excellent, but if you don't need everything else jQuery offers, find a good AJAX library here: http://microjs.com/. You will also need to get comfy with the node.js docs, found here. Search http://google.com for some good node.js server and static file server tutorials. http://nodetuts.com is a good place to start.

UPDATE: I have changed response.sendHeader() to the new response.writeHead() in the code above !!!

Cannot hide status bar in iOS7

Try this simple method:

- (void)viewWillAppear:(BOOL)animated
{
[[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationNone];
}

- (void)viewWillDisappear:(BOOL)animated
{
[[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationNone];
}

RegEx for Javascript to allow only alphanumeric

I have string similar to Samsung Galaxy A10s 6.2-Inch (2GB,32GB ROM) Android 9.0, (13MP+2MP)+ 8MP Dual SIM 4000mAh 4G LTE Smartphone - Black (BF19)

Below is what i did:

string.replace(/[^a-zA-Z0-9 ,._-]/g, '').split(',').join('-').split(' ').join('-').toLowerCase()

Notice i allowed ,._- then use split() and join() to replace , to - and space to - respectively.

I ended up getting something like this: samsung-galaxy-a10s-6.2-inch-2gb-32gb-rom-android-9.0-13mp-2mp-8mp-dual-sim-4000mah-4g-lte-smartphone-black-bf19-20 which is what i wanted.

There might be a better solution but this is what i found working fine for me.

android image button

You just use an ImageButton and make the background whatever you want and set the icon as the src.

<ImageButton
    android:id="@+id/ImageButton01"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/album_icon"
    android:background="@drawable/round_button" />

enter image description here

To prevent a memory leak, the JDBC Driver has been forcibly unregistered

I see this issue come up a lot. Yes, Tomcat 7 does automatically deregister it, but it that REALLY taking control of your code and a good coding practice? Surely YOU want to know that you have all the correct code in place to close all your objects, shut down database connection pool threads, and get rid of all warnings. I certainly do.

This is how I do it.

Step 1: Register a Listener

web.xml

<listener>
    <listener-class>com.mysite.MySpecialListener</listener-class>
</listener>

Step 2: Implement the Listener

com.mysite.MySpecialListener.java

public class MySpecialListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        // On Application Startup, please…

        // Usually I'll make a singleton in here, set up my pool, etc.
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        // On Application Shutdown, please…

        // 1. Go fetch that DataSource
        Context initContext = new InitialContext();
        Context envContext  = (Context)initContext.lookup("java:/comp/env");
        DataSource datasource = (DataSource)envContext.lookup("jdbc/database");

        // 2. Deregister Driver
        try {
            java.sql.Driver mySqlDriver = DriverManager.getDriver("jdbc:mysql://localhost:3306/");
            DriverManager.deregisterDriver(mySqlDriver);
        } catch (SQLException ex) {
            logger.info("Could not deregister driver:".concat(ex.getMessage()));
        } 

        // 3. For added safety, remove the reference to dataSource for GC to enjoy.
        dataSource = null;
    }

}

Please feel free to comment and/or add...

ECMAScript 6 class destructor

Is there such a thing as destructors for ECMAScript 6?

No. EcmaScript 6 does not specify any garbage collection semantics at all[1], so there is nothing like a "destruction" either.

If I register some of my object's methods as event listeners in the constructor, I want to remove them when my object is deleted

A destructor wouldn't even help you here. It's the event listeners themselves that still reference your object, so it would not be able to get garbage-collected before they are unregistered.
What you are actually looking for is a method of registering listeners without marking them as live root objects. (Ask your local eventsource manufacturer for such a feature).

1): Well, there is a beginning with the specification of WeakMap and WeakSet objects. However, true weak references are still in the pipeline [1][2].

Change output format for MySQL command line results to CSV

How about using sed? It comes standard with most (all?) Linux OS.

sed 's/\t/<your_field_delimiter>/g'.

This example uses GNU sed (Linux). For POSIX sed (AIX/Solaris)I believe you would type a literal TAB instead of \t

Example (for CSV output):

#mysql mysql -B -e "select * from user" | while read; do sed 's/\t/,/g'; done

localhost,root,,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,,,,,0,0,0,0,,
localhost,bill,*2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,,,,,0,0,0,0,,
127.0.0.1,root,,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,,,,,0,0,0,0,,
::1,root,,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,,,,,0,0,0,0,,
%,jim,*2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,,,,,0,0,0,0,,

Reading text files using read.table

From ?read.table: The number of data columns is determined by looking at the first five lines of input (or the whole file if it has less than five lines), or from the length of col.names if it is specified and is longer. This could conceivably be wrong if fill or blank.lines.skip are true, so specify col.names if necessary.

So, perhaps your data file isn't clean. Being more specific will help the data import:

d = read.table("foobar.txt", 
               sep="\t", 
               col.names=c("id", "name"), 
               fill=FALSE, 
               strip.white=TRUE)

will specify exact columns and fill=FALSE will force a two column data frame.

Match two strings in one line with grep

grep -i -w 'string1\|string2' filename

This works for exact word match and matching case insensitive words ,for that -i is used

PHPMailer: SMTP Error: Could not connect to SMTP host

Followed code worked for me:

$mail = new PHPMailer(true);

$mail->isSMTP();// Set mailer to use SMTP
$mail->CharSet = "utf-8";// set charset to utf8
$mail->SMTPAuth = true;// Enable SMTP authentication
$mail->SMTPSecure = 'tls';// Enable TLS encryption, `ssl` also accepted

$mail->Host = 'smtp.gmail.com';// Specify main and backup SMTP servers
$mail->Port = 587;// TCP port to connect to
$mail->SMTPOptions = array(
    'ssl' => array(
        'verify_peer' => false,
        'verify_peer_name' => false,
        'allow_self_signed' => true
    )
);
$mail->isHTML(true);// Set email format to HTML

$mail->Username = 'Sender Email';// SMTP username
$mail->Password = 'Sender Email Password';// SMTP password

$mail->setFrom('[email protected]', 'John Smith');//Your application NAME and EMAIL
$mail->Subject = 'Test';//Message subject
$mail->MsgHTML('HTML code');// Message body
$mail->addAddress('User Email', 'User Name');// Target email


$mail->send();

Dynamic function name in javascript?

Dynamic methods of an object may be created using Object Literal Extensions provided by ECMAScript 2015 (ES6):

const postfixes = ['foo', 'bar'];

const mainObj = {};

const makeDynamic = (postfix) => {
  const newMethodName = 'instance: ' + postfix;
  const tempObj = {
    [newMethodName]() {
      console.log(`called method ${newMethodName}`);
    }
  }
  Object.assign(mainObj, tempObj);
  return mainObj[newMethodName]();
}

const processPostfixes = (postfixes) => { 
  for (const postfix of postfixes) {
    makeDynamic(postfix); 
  }
};

processPostfixes(postfixes);

console.log(mainObj);

The output of running the code above is:

"called method instance: foo"
"called method instance: bar"
Object {
  "instance: bar": [Function anonymous],
  "instance: foo": [Function anonymous]
}

Print a file's last modified date in Bash

For the line breaks i edited your code to get something with no line breaks.

#!/bin/bash
for i in /Users/anthonykiggundu/Sites/rku-it/*; do
   t=$(stat -f "%Sm"  -t "%Y-%m-%d %H:%M" "$i")
   echo $t : "${i##*/}"  # t only contains date last modified, then only filename 'grokked'- else $i alone is abs. path           
done

How to print / echo environment variables?

These need to go as different commands e.g.:

NAME=sam; echo "$NAME"
NAME=sam && echo "$NAME"

The expansion $NAME to empty string is done by the shell earlier, before running echo, so at the time the NAME variable is passed to the echo command's environment, the expansion is already done (to null string).

To get the same result in one command:

NAME=sam printenv NAME

Connecting to remote URL which requires authentication using Java

i did that this way you need to do this just copy paste it be happy

    HttpURLConnection urlConnection;
    String url;
 //   String data = json;
    String result = null;
    try {
        String username ="[email protected]";
        String password = "12345678";

        String auth =new String(username + ":" + password);
        byte[] data1 = auth.getBytes(UTF_8);
        String base64 = Base64.encodeToString(data1, Base64.NO_WRAP);
        //Connect
        urlConnection = (HttpURLConnection) ((new URL(urlBasePath).openConnection()));
        urlConnection.setDoOutput(true);
        urlConnection.setRequestProperty("Content-Type", "application/json");
        urlConnection.setRequestProperty("Authorization", "Basic "+base64);
        urlConnection.setRequestProperty("Accept", "application/json");
        urlConnection.setRequestMethod("POST");
        urlConnection.setConnectTimeout(10000);
        urlConnection.connect();
        JSONObject obj = new JSONObject();

        obj.put("MobileNumber", "+97333746934");
        obj.put("EmailAddress", "[email protected]");
        obj.put("FirstName", "Danish");
        obj.put("LastName", "Hussain");
        obj.put("Country", "BH");
        obj.put("Language", "EN");
        String data = obj.toString();
        //Write
        OutputStream outputStream = urlConnection.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
        writer.write(data);
        writer.close();
        outputStream.close();
        int responseCode=urlConnection.getResponseCode();
        if (responseCode == HttpsURLConnection.HTTP_OK) {
            //Read
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));

        String line = null;
        StringBuilder sb = new StringBuilder();

        while ((line = bufferedReader.readLine()) != null) {
            sb.append(line);
        }

        bufferedReader.close();
        result = sb.toString();

        }else {
        //    return new String("false : "+responseCode);
        new String("false : "+responseCode);
        }

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }

process.start() arguments

Very edge case, but I had to use a program that worked correctly only when I specified

StartInfo = {..., RedirectStandardOutput = true}

Not specifying it would result in an error. There was not even the need to read the output afterward.

Insert a background image in CSS (Twitter Bootstrap)

And if you can't repeat the background image (for esthetic reasons), then this handy JQuery plugin will stretch the background image to fit the window.

Backstretch http://srobbin.com/jquery-plugins/backstretch/

Works great...

~Cheers!

How connect Postgres to localhost server using pgAdmin on Ubuntu?

if you open the psql console in a terminal window, by typing

$ psql

you're super user username will be shown before the =#, for example:

elisechant=#$

That will be the user name you should use for localhost.

Eclipse does not start when I run the exe?

If its a Java version problem, you can edit the eclipse.ini file and assign the compatible version to the application through adding these lines:

windows example:

-vm
C:\jdk1.7.0_21\bin\javaw.exe 

for more information: https://wiki.eclipse.org/Eclipse.ini

PHP "php://input" vs $_POST

Simple example of how to use it

 <?php  
     if(!isset($_POST) || empty($_POST)) { 
     ?> 
        <form name="form1" method="post" action=""> 
          <input type="text" name="textfield"><br /> 
          <input type="submit" name="Submit" value="submit"> 
        </form> 
   <?php  
        } else { 
        $example = file_get_contents("php://input");
        echo $example;  }  
   ?>

Typing the Enter/Return key using Python and Selenium

import org.openqa.selenium.Keys

WebElement.sendKeys(Keys.RETURN);

The import statement is for Java. For other languages, it is maybe different. For example, in Python it is from selenium.webdriver.common.keys import Keys

convert a list of objects from one type to another using lambda expression

var target = origList.ConvertAll(x => (TargetType)x);

Add a prefix string to beginning of each line

If you have Perl:

perl -pe 's/^/PREFIX/' input.file

Javascript Iframe innerHTML

This solution works same as iFrame. I have created a PHP script that can get all the contents from the other website, and most important part is you can easily apply your custom jQuery to that external content. Please refer to the following script that can get all the contents from the other website and then you can apply your cusom jQuery/JS as well. This content can be used anywhere, inside any element or any page.

<div id='myframe'>

  <?php 
   /* 
    Use below function to display final HTML inside this div
   */

   //Display Frame
   echo displayFrame(); 
  ?>

</div>

<?php

/* 
  Function to display frame from another domain 
*/

function displayFrame()
{
  $webUrl = 'http://[external-web-domain.com]/';

  //Get HTML from the URL
  $content = file_get_contents($webUrl);

  //Add custom JS to returned HTML content
  $customJS = "
  <script>

      /* Here I am writing a sample jQuery to hide the navigation menu
         You can write your own jQuery for this content
      */
    //Hide Navigation bar
    jQuery(\".navbar\").hide();

  </script>";

  //Append Custom JS with HTML
  $html = $content . $customJS;

  //Return customized HTML
  return $html;
}

Using grep to search for hex strings in a file

We tried several things before arriving at an acceptable solution:

xxd -u /usr/bin/xxd | grep 'DF'
00017b0: 4010 8D05 0DFF FF0A 0300 53E3 0610 A003  @.........S.....


root# grep -ibH "df" /usr/bin/xxd
Binary file /usr/bin/xxd matches
xxd -u /usr/bin/xxd | grep -H 'DF'
(standard input):00017b0: 4010 8D05 0DFF FF0A 0300 53E3 0610 A003  @.........S.....

Then found we could get usable results with

xxd -u /usr/bin/xxd > /tmp/xxd.hex ; grep -H 'DF' /tmp/xxd

Note that using a simple search target like 'DF' will incorrectly match characters that span across byte boundaries, i.e.

xxd -u /usr/bin/xxd | grep 'DF'
00017b0: 4010 8D05 0DFF FF0A 0300 53E3 0610 A003  @.........S.....
--------------------^^

So we use an ORed regexp to search for ' DF' OR 'DF ' (the searchTarget preceded or followed by a space char).

The final result seems to be

xxd -u -ps -c 10000000000 DumpFile > DumpFile.hex
egrep ' DF|DF ' Dumpfile.hex

0001020: 0089 0424 8D95 D8F5 FFFF 89F0 E8DF F6FF  ...$............
-----------------------------------------^^
0001220: 0C24 E871 0B00 0083 F8FF 89C3 0F84 DF03  .$.q............
--------------------------------------------^^

Get ID of element that called a function

i also want this to happen , so just pass the id of the element in the called function and used in my js file :

function copy(i,n)
{
 var range = document.createRange();
range.selectNode(document.getElementById(i));
window.getSelection().removeAllRanges();
window.getSelection().addRange(range); 
document.execCommand('copy');
window.getSelection().removeAllRanges();
document.getElementById(n).value = "Copied";
}

window.location.href not working

if anyone faced problem even after using return false; . then use the below.

setTimeout(function(){document.location.href = "index.php"},500);

How to check the maximum number of allowed connections to an Oracle database?

Note: this only answers part of the question.

If you just want to know the maximum number of sessions allowed, then you can execute in sqlplus, as sysdba:

SQL> show parameter sessions

This gives you an output like:

    NAME                                 TYPE        VALUE
------------------------------------ ----------- ------------------------------
java_max_sessionspace_size           integer     0
java_soft_sessionspace_limit         integer     0
license_max_sessions                 integer     0
license_sessions_warning             integer     0
sessions                             integer     248
shared_server_sessions               integer

The sessions parameter is the one what you want.

How to determine whether a Pandas Column contains a particular value

Use

df[df['id']==x].index.tolist()

If x is present in id then it'll return the list of indices where it is present, else it gives an empty list.

How to convert 2D float numpy array to 2D int numpy array?

you can use np.int_:

>>> x = np.array([[1.0, 2.3], [1.3, 2.9]])
>>> x
array([[ 1. ,  2.3],
       [ 1.3,  2.9]])
>>> np.int_(x)
array([[1, 2],
       [1, 2]])

Python style - line continuation with strings?

I've gotten around this with

mystr = ' '.join(
        ["Why, hello there",
         "wonderful stackoverflow people!"])

in the past. It's not perfect, but it works nicely for very long strings that need to not have line breaks in them.

"Mixed content blocked" when running an HTTP AJAX operation in an HTTPS page

in my case, my localhost was http and my deployed version was https, so i used this script to add http-equiv meta tag only for https:

if (window.location.protocol.indexOf('https') == 0){
  var el = document.createElement('meta')
  el.setAttribute('http-equiv', 'Content-Security-Policy')
  el.setAttribute('content', 'upgrade-insecure-requests')
  document.head.append(el)
}

How can I take a screenshot/image of a website using Python?

You don't mention what environment you're running in, which makes a big difference because there isn't a pure Python web browser that's capable of rendering HTML.

But if you're using a Mac, I've used webkit2png with great success. If not, as others have pointed out there are plenty of options.

How to check if a string contains text from an array of substrings in JavaScript?

substringsArray.every(substring=>yourBigString.indexOf(substring) === -1)

For full support ;)

PHP code to convert a MySQL query to CSV

An update to @jrgns (with some slight syntax differences) solution.

$result = mysql_query('SELECT * FROM `some_table`'); 
if (!$result) die('Couldn\'t fetch records'); 
$num_fields = mysql_num_fields($result); 
$headers = array(); 
for ($i = 0; $i < $num_fields; $i++) 
{     
       $headers[] = mysql_field_name($result , $i); 
} 
$fp = fopen('php://output', 'w'); 
if ($fp && $result) 
{     
       header('Content-Type: text/csv');
       header('Content-Disposition: attachment; filename="export.csv"');
       header('Pragma: no-cache');    
       header('Expires: 0');
       fputcsv($fp, $headers); 
       while ($row = mysql_fetch_row($result)) 
       {
          fputcsv($fp, array_values($row)); 
       }
die; 
} 

Convert Int to String in Swift

let intAsString = 45.description     // "45"
let stringAsInt = Int("45")          // 45

Bootstrap 3 collapsed menu doesn't close on click

Though the solution posted earlier to change the menu item itself, like below, works when the menu is on a small device, it has a side effect when the menu is on full width and expanded, this can result in a horizontal scrollbar sliding over your menu items. The javascript solutions do not have this side-effect.

<li><a href="#one">One</a></li> to 
<li><a data-toggle="collapse" data-target=".navbar-collapse" href="#one">One</a></li>  

(sorry for answering like this, wanted to add a comment to that answer, but, seems I haven't sufficient credit to make remarks )

send mail to multiple receiver with HTML mailto

"There are no safe means of assigning multiple recipients to a single mailto: link via HTML. There are safe, non-HTML, ways of assigning multiple recipients from a mailto: link."

http://www.sightspecific.com/~mosh/www_faq/multrec.html

For a quick fix to your problem, change your ; to a comma , and eliminate the spaces between email addresses

<a href='mailto:[email protected],[email protected]'>Email Us</a>

Insert ellipsis (...) into HTML tag if content too wide

Pure CSS Multi-line Ellipsis for text content:

_x000D_
_x000D_
.container{_x000D_
    position: relative;  /* Essential */_x000D_
    background-color: #bbb;  /* Essential */_x000D_
    padding: 20px; /* Arbritrary */_x000D_
}_x000D_
.text {_x000D_
    overflow: hidden;  /* Essential */_x000D_
    /*text-overflow: ellipsis; Not needed */_x000D_
    line-height: 16px;  /* Essential */_x000D_
    max-height: 48px; /* Multiples of line-height */_x000D_
}_x000D_
.ellipsis {_x000D_
    position: absolute;/* Relies on relative container */_x000D_
    bottom: 20px; /* Matches container padding */_x000D_
    right: 20px; /* Matches container padding */_x000D_
    height: 16px; /* Matches line height */_x000D_
    width: 30px; /* Arbritrary */_x000D_
    background-color: inherit; /* Essential...or specify a color */_x000D_
    padding-left: 8px; /* Arbritrary */_x000D_
}
_x000D_
<div class="container">_x000D_
    <div class="text">_x000D_
        Lorem ipsum dolor sit amet, consectetur eu in adipiscing elit. Aliquam consectetur venenatis blandit. Praesent vehicula, libero non pretium vulputate, lacus arcu facilisis lectus, sed feugiat tellus nulla eu dolor. Nulla porta bibendum lectus quis euismod. Aliquam volutpat ultricies porttitor. Cras risus nisi, accumsan vel cursus ut, sollicitudin vitae dolor. Fusce scelerisque eleifend lectus in bibendum. Suspendisse lacinia egestas felis a volutpat. Aliquam volutpat ultricies porttitor. Cras risus nisi, accumsan vel cursus ut, sollicitudin vitae dolor. Fusce scelerisque eleifend lectus in bibendum. Suspendisse lacinia egestas felis a volutpat._x000D_
    </div>_x000D_
    <div class="ellipsis">...</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Please checkout the snippet for a live example.

Best way to use PHP to encrypt and decrypt passwords?

You should not encrypt passwords, instead you should hash them using an algorithm like bcrypt. This answer explains how to properly implement password hashing in PHP. Still, here is how you would encrypt/decrypt:

$key = 'password to (en/de)crypt';
$string = ' string to be encrypted '; // note the spaces

To Encrypt:

$iv = mcrypt_create_iv(
    mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC),
    MCRYPT_DEV_URANDOM
);

$encrypted = base64_encode(
    $iv .
    mcrypt_encrypt(
        MCRYPT_RIJNDAEL_128,
        hash('sha256', $key, true),
        $string,
        MCRYPT_MODE_CBC,
        $iv
    )
);

To Decrypt:

$data = base64_decode($encrypted);
$iv = substr($data, 0, mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC));

$decrypted = rtrim(
    mcrypt_decrypt(
        MCRYPT_RIJNDAEL_128,
        hash('sha256', $key, true),
        substr($data, mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC)),
        MCRYPT_MODE_CBC,
        $iv
    ),
    "\0"
);

Warning: The above example encrypts information, but it does not authenticate the ciphertext to prevent tampering. You should not rely on unauthenticated encryption for security, especially since the code as provided is vulnerable to padding oracle attacks.

See also:

Also, don't just use a "password" for an encryption key. Encryption keys are random strings.


Demo at 3v4l.org:

echo 'Encrypted:' . "\n";
var_dump($encrypted); // "m1DSXVlAKJnLm7k3WrVd51omGL/05JJrPluBonO9W+9ohkNuw8rWdJW6NeLNc688="

echo "\n";

echo 'Decrypted:' . "\n";
var_dump($decrypted); // " string to be encrypted "

Linux: is there a read or recv from socket with timeout?

You can use the setsockopt function to set a timeout on receive operations:

SO_RCVTIMEO

Sets the timeout value that specifies the maximum amount of time an input function waits until it completes. It accepts a timeval structure with the number of seconds and microseconds specifying the limit on how long to wait for an input operation to complete. If a receive operation has blocked for this much time without receiving additional data, it shall return with a partial count or errno set to [EAGAIN] or [EWOULDBLOCK] if no data is received. The default for this option is zero, which indicates that a receive operation shall not time out. This option takes a timeval structure. Note that not all implementations allow this option to be set.

// LINUX
struct timeval tv;
tv.tv_sec = timeout_in_seconds;
tv.tv_usec = 0;
setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof tv);

// WINDOWS
DWORD timeout = timeout_in_seconds * 1000;
setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout, sizeof timeout);

// MAC OS X (identical to Linux)
struct timeval tv;
tv.tv_sec = timeout_in_seconds;
tv.tv_usec = 0;
setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof tv);

Reportedly on Windows this should be done before calling bind. I have verified by experiment that it can be done either before or after bind on Linux and OS X.

What are pipe and tap methods in Angular tutorial?

You are right, the documentation lacks of those methods. However when I dug into rxjs repository, I found nice comments about tap (too long to paste here) and pipe operators:

  /**
   * Used to stitch together functional operators into a chain.
   * @method pipe
   * @return {Observable} the Observable result of all of the operators having
   * been called in the order they were passed in.
   *
   * @example
   *
   * import { map, filter, scan } from 'rxjs/operators';
   *
   * Rx.Observable.interval(1000)
   *   .pipe(
   *     filter(x => x % 2 === 0),
   *     map(x => x + x),
   *     scan((acc, x) => acc + x)
   *   )
   *   .subscribe(x => console.log(x))
   */

In brief:

Pipe: Used to stitch together functional operators into a chain. Before we could just do observable.filter().map().scan(), but since every RxJS operator is a standalone function rather than an Observable's method, we need pipe() to make a chain of those operators (see example above).

Tap: Can perform side effects with observed data but does not modify the stream in any way. Formerly called do(). You can think of it as if observable was an array over time, then tap() would be an equivalent to Array.forEach().

Opening PDF String in new window with javascript

//for pdf view

let pdfWindow = window.open("");
pdfWindow.document.write("<iframe width='100%' height='100%' src='data:application/pdf;base64," + data.data +"'></iframe>");

How to add a button dynamically in Android?

Button btn = new Button(this);
btn.setText("Submit");
LinearLayout linearLayout = (LinearLayout)findViewById(R.id.buttonlayout);
LayoutParams buttonlayout = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
linearLayout.addView(btn, buttonlayout);

Inner join with 3 tables in mysql

Almost correctly.. Look at the joins, you are referring the wrong fields

SELECT student.firstname,
       student.lastname,
       exam.name,
       exam.date,
       grade.grade
  FROM grade
 INNER JOIN student ON student.studentId = grade.fk_studentId
 INNER JOIN exam ON exam.examId = grade.fk_examId
 ORDER BY exam.date

Javascript equivalent of php's strtotime()?

_x000D_
_x000D_
var strdate = new Date('Tue Feb 07 2017 12:51:48 GMT+0200 (Türkiye Standart Saati)');_x000D_
var date = moment(strdate).format('DD.MM.YYYY');_x000D_
$("#result").text(date); //07.02.2017
_x000D_
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.js"></script>_x000D_
_x000D_
<div id="result"></div>
_x000D_
_x000D_
_x000D_

Temporarily change current working directory in bash to run a command

bash has a builtin

pushd SOME_PATH
run_stuff
...
...
popd 

Difference between application/x-javascript and text/javascript content types

mime-types starting with x- are not standardized. In case of javascript it's kind of outdated. Additional the second code snippet

<?Header('Content-Type: text/javascript');?>

requires short_open_tags to be enabled. you should avoid it.

<?php Header('Content-Type: text/javascript');?>

However, the completely correct mime-type for javascript is

application/javascript

http://www.iana.org/assignments/media-types/application/index.html

How to go to a specific element on page?

The standard technique in plugin form would look something like this:

(function($) {
    $.fn.goTo = function() {
        $('html, body').animate({
            scrollTop: $(this).offset().top + 'px'
        }, 'fast');
        return this; // for chaining...
    }
})(jQuery);

Then you could just say $('#div_element2').goTo(); to scroll to <div id="div_element2">. Options handling and configurability is left as an exercise for the reader.

What's an easy way to read random line from a file in Unix command line?

Single bash line:

sed -n $((1+$RANDOM%`wc -l test.txt | cut -f 1 -d ' '`))p test.txt

Slight problem: duplicate filename.

Free tool to Create/Edit PNG Images?

The GIMP (GNU Image Manipulation Program). It's free, open source and runs on Windows and Linux (and maybe Mac?).

SELECT INTO Variable in MySQL DECLARE causes syntax error?

SELECT c1, c2, c3, ... INTO @v1, @v2, @v3,... FROM table_name WHERE condition;

CMake does not find Visual C++ compiler

Here is the solution that worked for me:

  1. Open Visual Studio command prompt tool (as an administrator). On windows 10 it might be called 'Developer command prompt'.
  2. Navigate to where you have the CMake executable
  3. Run Cmake.exe
  4. Proceed as usual to select build and source folder
  5. Select the appropriate Visual Studio compiler and hit the configure button

Hopefully it should run without problems.

Return number of rows affected by UPDATE statements

You might need to collect the stats as you go, but @@ROWCOUNT captures this:

declare @Fish table (
Name varchar(32)
)

insert into @Fish values ('Cod')
insert into @Fish values ('Salmon')
insert into @Fish values ('Butterfish')
update @Fish set Name = 'LurpackFish' where Name = 'Butterfish'
select @@ROWCOUNT  --gives 1

update @Fish set Name = 'Dinner'
select @@ROWCOUNT -- gives 3

How to force input to only allow Alpha Letters?

The property event.key gave me an undefined value. Instead, I used event.keyCode:

function alphaOnly(event) {
  var key = event.keyCode;
  return ((key >= 65 && key <= 90) || key == 8);
};

Note that the value of 8 is for the backspace key.

How to redirect output of an already running process

See Redirecting Output from a Running Process.

Firstly I run the command cat > foo1 in one session and test that data from stdin is copied to the file. Then in another session I redirect the output.

Firstly find the PID of the process:

$ ps aux | grep cat
rjc 6760 0.0 0.0 1580 376 pts/5 S+ 15:31 0:00 cat

Now check the file handles it has open:

$ ls -l /proc/6760/fd
total 3
lrwx—— 1 rjc rjc 64 Feb 27 15:32 0 -> /dev/pts/5
l-wx—— 1 rjc rjc 64 Feb 27 15:32 1 -> /tmp/foo1
lrwx—— 1 rjc rjc 64 Feb 27 15:32 2 -> /dev/pts/5

Now run GDB:

$ gdb -p 6760 /bin/cat
GNU gdb 6.4.90-debian

[license stuff snipped]

Attaching to program: /bin/cat, process 6760

[snip other stuff that's not interesting now]

(gdb) p close(1)
$1 = 0
(gdb) p creat("/tmp/foo3", 0600)
$2 = 1
(gdb) q
The program is running. Quit anyway (and detach it)? (y or n) y
Detaching from program: /bin/cat, process 6760

The p command in GDB will print the value of an expression, an expression can be a function to call, it can be a system call… So I execute a close() system call and pass file handle 1, then I execute a creat() system call to open a new file. The result of the creat() was 1 which means that it replaced the previous file handle. If I wanted to use the same file for stdout and stderr or if I wanted to replace a file handle with some other number then I would need to call the dup2() system call to achieve that result.

For this example I chose to use creat() instead of open() because there are fewer parameter. The C macros for the flags are not usable from GDB (it doesn’t use C headers) so I would have to read header files to discover this – it’s not that hard to do so but would take more time. Note that 0600 is the octal permission for the owner having read/write access and the group and others having no access. It would also work to use 0 for that parameter and run chmod on the file later on.

After that I verify the result:

ls -l /proc/6760/fd/
total 3
lrwx—— 1 rjc rjc 64 2008-02-27 15:32 0 -> /dev/pts/5
l-wx—— 1 rjc rjc 64 2008-02-27 15:32 1 -> /tmp/foo3 <====
lrwx—— 1 rjc rjc 64 2008-02-27 15:32 2 -> /dev/pts/5

Typing more data in to cat results in the file /tmp/foo3 being appended to.

If you want to close the original session you need to close all file handles for it, open a new device that can be the controlling tty, and then call setsid().

How to find the size of a table in SQL?

I know that in SQL 2012 (may work in other versions) you can do the following:

  1. Right click on the database name in the Object Explorer.
  2. Select Reports > Standard Reports > Disk Usage by Top Tables.

That will give you a list of the top 1000 tables and then you can order it by data size etc.

MSSQL Error 'The underlying provider failed on Open'

You should see innerException to see what the inner cause of throwing of error is.

In my case, the original error was:

Unable to open the physical file "D:\Projects2\xCU\xCU\App_Data\xCUData_log.ldf". Operating system error 5: "5(Access is denied.)". An attempt to attach an auto-named database for file D:\Projects2\xCU\xCU\App_Data\xCUData.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.

which solved by giving full permission to current user for accessing related mdf and ldf files using files' properties.

Use of True, False, and None as return values in Python functions

In the case of your fictional getattr function, if the requested attribute always should be available but isn't then throw an error. If the attribute is optional then return None.

Could not load file or assembly 'Microsoft.Web.Infrastructure,

You need to download the ASP.NET MVC framework on the server hosting your application. It's a quick fix just download and install from here (This is the MVC 3 framework http://www.asp.net/mvc/mvc3), then boom you are good to go.

MySQL LEFT JOIN Multiple Conditions

Just move the extra condition into the JOIN ON criteria, this way the existence of b is not required to return a result

SELECT a.* FROM a 
    LEFT JOIN b ON a.group_id=b.group_id AND b.user_id!=$_SESSION{['user_id']} 
    WHERE a.keyword LIKE '%".$keyword."%' 
    GROUP BY group_id

How to tell if UIViewController's view is visible

For those of you looking for a Swift 2.2 version of the answer:

if self.isViewLoaded() && (self.view.window != nil) {
     // viewController is visible
}

and Swift 3:

if self.isViewLoaded && (self.view.window != nil) {
         // viewController is visible
}

Check if a string within a list contains a specific string with Linq

Try this:

bool matchFound = myList.Any(s => s.Contains("Mdd LH"));

The Any() will stop searching the moment it finds a match, so is quite efficient for this task.

Convert pandas.Series from dtype object to float, and errors to nans

In [30]: pd.Series([1,2,3,4,'.']).convert_objects(convert_numeric=True)
Out[30]: 
0     1
1     2
2     3
3     4
4   NaN
dtype: float64

Google Maps v3 - limit viewable area and zoom level

For some reason

if (strictBounds.contains(map.getCenter())) return;

didnt work for me (maybe a southern hemisphere issue). I had to change it to:

    function checkBounds() {
        var c = map.getCenter(),
            x = c.lng(),
            y = c.lat(),
            maxX = strictBounds.getNorthEast().lng(),
            maxY = strictBounds.getNorthEast().lat(),
            minX = strictBounds.getSouthWest().lng(),
            minY = strictBounds.getSouthWest().lat();

        if(x < minX || x > maxX || y < minY || y > maxY) {
            if (x < minX) x = minX;
            if (x > maxX) x = maxX;
            if (y < minY) y = minY;
            if (y > maxY) y = maxY;
            map.setCenter(new google.maps.LatLng(y, x));
        }
    }

Hope it will help someone.

Emulator: ERROR: x86 emulation currently requires hardware acceleration

I had the same issue. In my case I found two issues causing the problem

  1. I had Hyper-V running, I think if any Virtualization programs running you need to uninstall
  2. I was running under Standard Account / Not Administrator

multiple conditions for filter in spark data frames

You need to use filter

package dataframe

import org.apache.spark.sql.SparkSession
/**
 * @author [email protected]
 */
//

object DataFrameExample{
  //
  case class Employee(id: Integer, name: String, address: String, salary: Double, state: String,zip:Integer)
  //
  def main(args: Array[String]) {
    val spark =
      SparkSession.builder()
        .appName("DataFrame-Basic")
        .master("local[4]")
        .getOrCreate()

    import spark.implicits._

    // create a sequence of case class objects 

    // (we defined the case class above)

    val emp = Seq( 
    Employee(1, "vaquar khan", "111 algoinquin road chicago", 120000.00, "AZ",60173),
    Employee(2, "Firdos Pasha", "1300 algoinquin road chicago", 2500000.00, "IL",50112),
    Employee(3, "Zidan khan", "112 apt abcd timesqure NY", 50000.00, "NY",55490),
    Employee(4, "Anwars khan", "washington dc", 120000.00, "VA",33245),
    Employee(5, "Deepak sharma ", "rolling edows schumburg", 990090.00, "IL",60172),
    Employee(6, "afaq khan", "saeed colony Bhopal", 1000000.00, "AZ",60173)
    )

    val employee=spark.sparkContext.parallelize(emp, 4).toDF()

     employee.printSchema()

    employee.show()


    employee.select("state", "zip").show()

    println("*** use filter() to choose rows")

    employee.filter($"state".equalTo("IL")).show()

    println("*** multi contidtion in filer || ")

    employee.filter($"state".equalTo("IL") || $"state".equalTo("AZ")).show()

    println("*** multi contidtion in filer &&  ")

    employee.filter($"state".equalTo("AZ") && $"zip".equalTo("60173")).show()

  }
}

How to redirect the output of a PowerShell to a file during its execution

One possible solution, if your situation allows it:

  1. Rename MyScript.ps1 to TheRealMyScript.ps1
  2. Create a new MyScript.ps1 that looks like:

    .\TheRealMyScript.ps1 > output.txt

R: Print list to a text file

Format won't be completely the same, but it does write the data to a text file, and R will be able to reread it using dget when you want to retrieve it again as a list.

dput(mylist, "mylist.txt")

Relative instead of Absolute paths in Excel VBA

if current directory of the operating system is the path of the workbook you are using, Workbooks.Open FileName:= "TRICATEndurance Summary.html" would suffice. if you are making calculations with the path, you can refer to current directory as . and then \ to tell the file is in that dir, and in case you have to change the os's current directory to your workbook's path, you can use ChDrive and ChDir to do so.

ChDrive ThisWorkbook.Path
ChDir ThisWorkbook.Path
Workbooks.Open FileName:= ".\TRICATEndurance Summary.html"

Window.Open with PDF stream instead of PDF location

Note: I have verified this in the latest version of IE, and other browsers like Mozilla and Chrome and this works for me. Hope it works for others as well.

if (data == "" || data == undefined) {
    alert("Falied to open PDF.");
} else { //For IE using atob convert base64 encoded data to byte array
    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        var byteCharacters = atob(data);
        var byteNumbers = new Array(byteCharacters.length);
        for (var i = 0; i < byteCharacters.length; i++) {
            byteNumbers[i] = byteCharacters.charCodeAt(i);
        }
        var byteArray = new Uint8Array(byteNumbers);
        var blob = new Blob([byteArray], {
            type: 'application/pdf'
        });
        window.navigator.msSaveOrOpenBlob(blob, fileName);
    } else { // Directly use base 64 encoded data for rest browsers (not IE)
        var base64EncodedPDF = data;
        var dataURI = "data:application/pdf;base64," + base64EncodedPDF;
        window.open(dataURI, '_blank');
    }

}

How to get twitter bootstrap modal to close (after initial launch)

If you have few modal shown simultaneously you can specify target modal for in-modal button with attributes data-toggle and data-target:

<div class="modal fade in" id="sendMessageModal" tabindex="-1" role="dialog" aria-hidden="true">
      <div class="modal-dialog modal-sm">
           <div class="modal-content">
                <div class="modal-header text-center">
                     <h4 class="modal-title">Modal Title</h4>
                     <small>Modal Subtitle</small>
                </div>
                <div class="modal-body">
                     <p>Modal content text</p>
                </div>
                <div class="modal-footer">
                     <button type="button" class="btn btn-default pull-left" data-toggle="modal" data-target="#sendMessageModal">Close</button>
                     <button type="button" class="btn btn-danger" data-toggle="modal" data-target="#sendMessageModal">Send</button>
                </div>
           </div>
      </div>
 </div>

Somewhere outside the modal code you can have another toggle button:

<a href="index.html#" class="btn btn-default btn-xs" data-toggle="modal" data-target="#sendMessageModal">Resend Message</a>

User can't click in-modal toggle button while these button hidden and it correct works with option "modal" for attribute data-toggle. This scheme works automagicaly!

How do I convert a String to a BigInteger?

If you may want to convert plaintext (not just numbers) to a BigInteger you will run into an exception, if you just try to: new BigInteger("not a Number")

In this case you could do it like this way:

public  BigInteger stringToBigInteger(String string){
    byte[] asciiCharacters = string.getBytes(StandardCharsets.US_ASCII);
    StringBuilder asciiString = new StringBuilder();
    for(byte asciiCharacter:asciiCharacters){
        asciiString.append(Byte.toString(asciiCharacter));
    }
    BigInteger bigInteger = new BigInteger(asciiString.toString());
    return bigInteger;
}

StringUtils.isBlank() vs String.isEmpty()

StringUtils.isBlank() checks that each character of the string is a whitespace character (or that the string is empty or that it's null). This is totally different than just checking if the string is empty.

From the linked documentation:

Checks if a String is whitespace, empty ("") or null.

 StringUtils.isBlank(null)      = true
 StringUtils.isBlank("")        = true  
 StringUtils.isBlank(" ")       = true  
 StringUtils.isBlank("bob")     = false  
 StringUtils.isBlank("  bob  ") = false

For comparison StringUtils.isEmpty:

 StringUtils.isEmpty(null)      = true
 StringUtils.isEmpty("")        = true  
 StringUtils.isEmpty(" ")       = false  
 StringUtils.isEmpty("bob")     = false  
 StringUtils.isEmpty("  bob  ") = false

Warning: In java.lang.String.isBlank() and java.lang.String.isEmpty() work the same except they don't return true for null.

java.lang.String.isBlank() (since Java 11)

java.lang.String.isEmpty()

PHPExcel - creating multiple sheets by iteration

You can write different sheets as follows

$objPHPExcel = new PHPExcel();
$objPHPExcel->getProperties()->setCreator("creater");
$objPHPExcel->getProperties()->setLastModifiedBy("Middle field");
$objPHPExcel->getProperties()->setSubject("Subject");
$objWorkSheet = $objPHPExcel->createSheet();
$work_sheet_count=3;//number of sheets you want to create
$work_sheet=0;
while($work_sheet<=$work_sheet_count){ 
     if($work_sheet==0){
         $objWorkSheet->setTitle("Worksheet$work_sheet");
         $objPHPExcel->setActiveSheetIndex($work_sheet)->setCellValue('A1', 'SR No. In sheet 1')->getStyle('A1')->getFont()->setBold(true);
         $objPHPExcel->setActiveSheetIndex($work_sheet)->setCellValueByColumnAndRow($col++, $row++, $i++);//setting value by column and row indexes if needed
     }
     if($work_sheet==1){
         $objWorkSheet->setTitle("Worksheet$work_sheet");
         $objPHPExcel->setActiveSheetIndex($work_sheet)->setCellValue('A1', 'SR No. In sheet 2')->getStyle('A1')->getFont()->setBold(true);
         $objPHPExcel->setActiveSheetIndex($work_sheet)->setCellValueByColumnAndRow($col++, $row++, $i++);//setting value by column and row indexes if needed
     }
     if($work_sheet==2){
         $objWorkSheet = $objPHPExcel->createSheet($work_sheet_count);
         $objWorkSheet->setTitle("Worksheet$work_sheet");
         $objPHPExcel->setActiveSheetIndex($work_sheet)->setCellValue('A1', 'SR No. In sheet 3')->getStyle('A1')->getFont()->setBold(true);
         $objPHPExcel->setActiveSheetIndex($work_sheet)->setCellValueByColumnAndRow($col++, $row++, $i++);//setting value by column and row indexes if needed
     }
     $work_sheet++;
}

$filename='file-name'.'.xls'; //save our workbook as this file name
header('Content-Type: application/vnd.ms-excel'); //mime type
header('Content-Disposition: attachment;filename="'.$filename.'"'); //tell browser what's the file name
header('Cache-Control: max-age=0'); //no cach

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');

Javax.net.ssl.SSLHandshakeException: javax.net.ssl.SSLProtocolException: SSL handshake aborted: Failure in SSL library, usually a protocol error

I found the solution here in this link.

You just have to place below code in your Android application class. And that is enough. Don't need to do any changes in your Retrofit settings. It saved my day.

public class MyApplication extends Application {
@Override
public void onCreate() {
    super.onCreate();
    try {
      // Google Play will install latest OpenSSL 
      ProviderInstaller.installIfNeeded(getApplicationContext());
      SSLContext sslContext;
      sslContext = SSLContext.getInstance("TLSv1.2");
      sslContext.init(null, null, null);
      sslContext.createSSLEngine();
    } catch (GooglePlayServicesRepairableException | GooglePlayServicesNotAvailableException
        | NoSuchAlgorithmException | KeyManagementException e) {
        e.printStackTrace();
        }
    }
}

Hope this will be of help. Thank you.

Using a dictionary to select function to execute

Simplify, simplify, simplify:

def p1(args):
    whatever

def p2(more args):
    whatever

myDict = {
    "P1": p1,
    "P2": p2,
    ...
    "Pn": pn
}

def myMain(name):
    myDict[name]()

That's all you need.


You might consider the use of dict.get with a callable default if name refers to an invalid function—

def myMain(name):
    myDict.get(name, lambda: 'Invalid')()

(Picked this neat trick up from Martijn Pieters)

Corrupt jar file

It can be a typo int the MANIFEST.MF too, p.ex. Build-Date with two :

  Build-Date:: 2017-03-13 16:07:12

How does EL empty operator work in JSF?

From EL 2.2 specification (get the one below "Click here to download the spec for evaluation"):

1.10 Empty Operator - empty A

The empty operator is a prefix operator that can be used to determine if a value is null or empty.

To evaluate empty A

  • If A is null, return true
  • Otherwise, if A is the empty string, then return true
  • Otherwise, if A is an empty array, then return true
  • Otherwise, if A is an empty Map, return true
  • Otherwise, if A is an empty Collection, return true
  • Otherwise return false

So, considering the interfaces, it works on Collection and Map only. In your case, I think Collection is the best option. Or, if it's a Javabean-like object, then Map. Either way, under the covers, the isEmpty() method is used for the actual check. On interface methods which you can't or don't want to implement, you could throw UnsupportedOperationException.

Regular expression to match any character being repeated more than 10 times

. matches any character. Used in conjunction with the curly braces already mentioned:

$: cat > test
========
============================
oo
ooooooooooooooooooooooo


$: grep -E '(.)\1{10}' test
============================
ooooooooooooooooooooooo

Could not reliably determine the server's fully qualified domain name

  1. sudo vim /etc/apache2/httpd.conf
  2. Insert the following line at the httpd.conf: ServerName localhost
  3. Just restart the Apache: sudo /etc/init.d/apache2 restart

Cast received object to a List<object> or IEnumerable<object>

Have to join the fun...

    private void TestBench()
    {
        // An object to test
        string[] stringEnumerable = new string[] { "Easy", "as", "Pi" };

        ObjectListFromUnknown(stringEnumerable);
    }

    private void ObjectListFromUnknown(object o)
    {
        if (typeof(IEnumerable<object>).IsAssignableFrom(o.GetType()))
        {
            List<object> listO = ((IEnumerable<object>)o).ToList();
            // Test it
            foreach (var v in listO)
            {
                Console.WriteLine(v);
            }
        }
    }

Insert variable into Header Location PHP

There's nothing here explaining the use of multiple variables, so I'll chuck it in just incase someone needs it in the future.

You need to concatenate multiple variables:

header('Location: http://linkhere.com?var1='.$var1.'&var2='.$var2.'&var3'.$var3);

Violation of PRIMARY KEY constraint. Cannot insert duplicate key in object

Make sure if your table doesn't already have rows whose Primary Key values are same as the the Primary Key Id in your Query.