Programs & Examples On #Inline code

Source code that is written into the body of a program, in the same or different language as/than the host language.

Are there inline functions in java?

Java does not provide a way to manually suggest that a method should be inlined. As @notnoop says in the comments, the inlining is typically done by the JVM at execution time.

What is the "assert" function?

Take a look at

assert() example program in C++

Many compilers offer an assert() macro. The assert() macro returns TRUE if its parameter evaluates TRUE and takes some kind of action if it evaluates FALSE. Many compilers will abort the program on an assert() that fails; others will throw an exception

One powerful feature of the assert() macro is that the preprocessor collapses it into no code at all if DEBUG is not defined. It is a great help during development, and when the final product ships there is no performance penalty nor increase in the size of the executable version of the program.

Eg

#include <stdio.h>
#include <assert.h>

void analyze (char *, int);

int main(void)
{
   char *string = "ABC";
   int length = 3;

   analyze(string, length);
   printf("The string %s is not null or empty, "
          "and has length %d \n", string, length);
}

void analyze(char *string, int length)
{
   assert(string != NULL);     /* cannot be NULL */
   assert(*string != '\0');    /* cannot be empty */
   assert(length > 0);         /* must be positive */
}

/****************  Output should be similar to  ******************
The string ABC is not null or empty, and has length 3

How do you set, clear, and toggle a single bit?

Try one of these functions in the C language to change n bit:

char bitfield;

// Start at 0th position

void chang_n_bit(int n, int value)
{
    bitfield = (bitfield | (1 << n)) & (~( (1 << n) ^ (value << n) ));
}

Or

void chang_n_bit(int n, int value)
{
    bitfield = (bitfield | (1 << n)) & ((value << n) | ((~0) ^ (1 << n)));
}

Or

void chang_n_bit(int n, int value)
{
    if(value)
        bitfield |= 1 << n;
    else
        bitfield &= ~0 ^ (1 << n);
}

char get_n_bit(int n)
{
    return (bitfield & (1 << n)) ? 1 : 0;
}

JPA entity without id

I know that JPA entities must have primary key but I can't change database structure due to reasons beyond my control.

More precisely, a JPA entity must have some Id defined. But a JPA Id does not necessarily have to be mapped on the table primary key (and JPA can somehow deal with a table without a primary key or unique constraint).

Is it possible to create JPA (Hibernate) entities that will be work with database structure like this?

If you have a column or a set of columns in the table that makes a unique value, you can use this unique set of columns as your Id in JPA.

If your table has no unique columns at all, you can use all of the columns as the Id.

And if your table has some id but your entity doesn't, make it an Embeddable.

Calling one Bash script from another Script passing it arguments with quotes and spaces

I found following program works for me

test1.sh 
a=xxx
test2.sh $a

in test2.sh you use $1 to refer variable a in test1.sh

echo $1

The output would be xxx

Generate Row Serial Numbers in SQL Query

Using Common Table Expression (CTE)

WITH CTE AS(
    SELECT ROW_NUMBER() OVER(ORDER BY CustomerId) AS RowNumber,
    Customers.*
    FROM Customers
)
SELECT * FROM CTE

Longer object length is not a multiple of shorter object length?

Yes, this is something that you should worry about. Check the length of your objects with nrow(). R can auto-replicate objects so that they're the same length if they differ, which means you might be performing operations on mismatched data.

In this case you have an obvious flaw in that your subtracting aggregated data from raw data. These will definitely be of different lengths. I suggest that you merge them as time series (using the dates), then locf(), then do your subtraction. Otherwise merge them by truncating the original dates to the same interval as the aggregated series. Just be very careful that you don't drop observations.

Lastly, as some general advice as you get started: look at the result of your computations to see if they make sense. You might even pull them into a spreadsheet and replicate the results.

Iterate over the lines of a string

I'm not sure what you mean by "then again by the parser". After the splitting has been done, there's no further traversal of the string, only a traversal of the list of split strings. This will probably actually be the fastest way to accomplish this, so long as the size of your string isn't absolutely huge. The fact that python uses immutable strings means that you must always create a new string, so this has to be done at some point anyway.

If your string is very large, the disadvantage is in memory usage: you'll have the original string and a list of split strings in memory at the same time, doubling the memory required. An iterator approach can save you this, building a string as needed, though it still pays the "splitting" penalty. However, if your string is that large, you generally want to avoid even the unsplit string being in memory. It would be better just to read the string from a file, which already allows you to iterate through it as lines.

However if you do have a huge string in memory already, one approach would be to use StringIO, which presents a file-like interface to a string, including allowing iterating by line (internally using .find to find the next newline). You then get:

import StringIO
s = StringIO.StringIO(myString)
for line in s:
    do_something_with(line)

IntelliJ IDEA generating serialVersionUID

Another way to generate the serialVersionUID is to use >Analyze >Run Inspection by Name from the context menu ( or the keyboard short cut, which is ctrl+alt+shift+i by default) and then type "Serializable class without 'serialVersionUID'" (or simply type "serialVersionUID" and the type ahead function will find it for you.

Idea >Analyze >Run Inspection by Name You will then get a context menu where you can choose where to run the inspections on (e.g. all from a specific module, whole project, one file, ...)

With this approach you don't even have to set the general inspection rules to anything.

How to draw a line in android

You can make a drawable like circle, line, rectangle etc through shapes in xml as follow:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="line" >

    <solid android:color="#00000000" />

    <stroke
        android:width="2dp"
        android:color="#808080" />

</shape>

How do I get video durations with YouTube API version 3?

You will have to make a call to the YouTube data API's video resource after you make the search call. You can put up to 50 video IDs in a search, so you won't have to call it for each element.

https://developers.google.com/youtube/v3/docs/videos/list

You'll want to set part=contentDetails, because the duration is there.

For example, the following call:

https://www.googleapis.com/youtube/v3/videos?id=9bZkp7q19f0&part=contentDetails&key={YOUR_API_KEY}

Gives this result:

{
 "kind": "youtube#videoListResponse",
 "etag": "\"XlbeM5oNbUofJuiuGi6IkumnZR8/ny1S4th-ku477VARrY_U4tIqcTw\"",
 "items": [
  {

   "id": "9bZkp7q19f0",
   "kind": "youtube#video",
   "etag": "\"XlbeM5oNbUofJuiuGi6IkumnZR8/HN8ILnw-DBXyCcTsc7JG0z51BGg\"",
   "contentDetails": {
    "duration": "PT4M13S",
    "dimension": "2d",
    "definition": "hd",
    "caption": "false",
    "licensedContent": true,
    "regionRestriction": {
     "blocked": [
      "DE"
     ]
    }
   }
  }
 ]
}

The time is formatted as an ISO 8601 string. PT stands for Time Duration, 4M is 4 minutes, and 13S is 13 seconds.

How to get address of a pointer in c/c++?

&a gives address of a - &p gives address of p.

int * * p_to_p = &p;

How can I compile and run c# program without using visual studio?

There are different ways for this:

1.Building C# Applications Using csc.exe

While it is true that you might never decide to build a large-scale application using nothing but the C# command-line compiler, it is important to understand the basics of how to compile your code files by hand.

2.Building .NET Applications Using Notepad++

Another simple text editor I’d like to quickly point out is the freely downloadable Notepad++ application. This tool can be obtained from http://notepad-plus.sourceforge.net. Unlike the primitive Windows Notepad application, Notepad++ allows you to author code in a variety of languages and supports

3.Building .NET Applications Using SharpDevelop

As you might agree, authoring C# code with Notepad++ is a step in the right direction, compared to Notepad. However, these tools do not provide rich IntelliSense capabilities for C# code, designers for building graphical user interfaces, project templates, or database manipulation utilities. To address such needs, allow me to introduce the next .NET development option: SharpDevelop (also known as "#Develop").You can download it from http://www.sharpdevelop.com.

org.hibernate.MappingException: Could not determine type for: java.util.List, at table: College, for columns: [org.hibernate.mapping.Column(students)]

Adding the @ElementCollection to the List field solved this issue:

    @Column
    @ElementCollection(targetClass=Integer.class)
    private List<Integer> countries;

Can I delete a git commit but keep the changes?

I think you are looking for this

git reset --soft HEAD~1

It undoes the most recent commit whilst keeping the changes made in that commit to staging.

Java int to String - Integer.toString(i) vs new Integer(i).toString()

Simple way is just concatenate "" with integer:

int i = 100;

String s = "" + i;

now s will have 100 as string value.

How can I get device ID for Admob

Another easiest way to show test ads is to use test device id for banner to show admob test ads for all devices. "ca-app-pub-3940256099942544/6300978111" . This admob test ads id was noted in the admob tutorial of google: link. This is the quote from the above link: enter image description here

  • This is the test device id for interstitial "ca-app-pub-3940256099942544/1033173712" . This also was used in interstitial tutorial

Easiest way to split a string on newlines in .NET?

Examples here are great and helped me with a current "challenge" to split RSA-keys to be presented in a more readable way. Based on Steve Coopers solution:

    string Splitstring(string txt, int n = 120, string AddBefore = "", string AddAfterExtra = "")
    {
        //Spit each string into a n-line length list of strings
        var Lines = Enumerable.Range(0, txt.Length / n).Select(i => txt.Substring(i * n, n)).ToList();
        
        //Check if there are any characters left after split, if so add the rest
        if(txt.Length > ((txt.Length / n)*n) )
            Lines.Add(txt.Substring((txt.Length/n)*n));

        //Create return text, with extras
        string txtReturn = "";
        foreach (string Line in Lines)
            txtReturn += AddBefore + Line + AddAfterExtra +  Environment.NewLine;
        return txtReturn;
    }

Presenting a RSA-key with 33 chars width and quotes are then simply

Console.WriteLine(Splitstring(RSAPubKey, 33, "\"", "\""));

Output:

Output of Splitstring();

Hopefully someone find it usefull...

How to create a JPA query with LEFT OUTER JOIN

Normally the ON clause comes from the mapping's join columns, but the JPA 2.1 draft allows for additional conditions in a new ON clause.

See,

http://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Basic_JPA_Development/Querying/JPQL#ON

How to import .py file from another directory?

You can add to the system-path at runtime:

import sys
sys.path.insert(0, 'path/to/your/py_file')

import py_file

This is by far the easiest way to do it.

How do I use the lines of a file as arguments of a command?

command `< file`

will pass file contents to the command on stdin, but will strip newlines, meaning you couldn't iterate over each line individually. For that you could write a script with a 'for' loop:

for line in `cat input_file`; do some_command "$line"; done

Or (the multi-line variant):

for line in `cat input_file`
do
    some_command "$line"
done

Or (multi-line variant with $() instead of ``):

for line in $(cat input_file)
do
    some_command "$line"
done

References:

  1. For loop syntax: https://www.cyberciti.biz/faq/bash-for-loop/

String parsing in Java with delimiter tab "\t" using split

I just had the same question and noticed the answer in some kind of tutorial. In general you need to use the second form of the split method, using the

split(regex, limit)

Here is the full tutorial http://www.rgagnon.com/javadetails/java-0438.html

If you set some negative number for the limit parameter you will get empty strings in the array where the actual values are missing. To use this your initial string should have two copies of the delimiter i.e. you should have \t\t where the values are missing.

Hope this helps :)

Printing a java map Map<String, Object> - How?

There is a get method in HashMap:

for (String keys : objectSet.keySet())  
{
   System.out.println(keys + ":"+ objectSet.get(keys));
}

How can I use the apply() function for a single column?

Given a sample dataframe df as:

a,b
1,2
2,3
3,4
4,5

what you want is:

df['a'] = df['a'].apply(lambda x: x + 1)

that returns:

   a  b
0  2  2
1  3  3
2  4  4
3  5  5

Python dictionary get multiple values

If the fallback keys are not too many you can do something like this

value = my_dict.get('first_key') or my_dict.get('second_key')

How to log SQL statements in Spring Boot?

Please use:

logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type=TRACE
spring.jpa.show-sql=true

Convert Linq Query Result to Dictionary

Try the following

Dictionary<int, DateTime> existingItems = 
    (from ObjType ot in TableObj).ToDictionary(x => x.Key);

Or the fully fledged type inferenced version

var existingItems = TableObj.ToDictionary(x => x.Key);

possible EventEmitter memory leak detected

I prefer to hunt down and fix problems instead of suppressing logs whenever possible. After a couple days of observing this issue in my app, I realized I was setting listeners on the req.socket in an Express middleware to catch socket io errors that kept popping up. At some point, I learned that that was not necessary, but I kept the listeners around anyway. I just removed them and the error you are experiencing went away. I verified it was the cause by running requests to my server with and without the following middleware:

socketEventsHandler(req, res, next) {
        req.socket.on("error", function(err) {
            console.error('------REQ ERROR')
            console.error(err.stack)
        });
        res.socket.on("error", function(err) {
            console.error('------RES ERROR')
            console.error(err.stack)
        });
        next();
    }

Removing that middleware stopped the warning you are seeing. I would look around your code and try to find anywhere you may be setting up listeners that you don't need.

Entity framework self referencing loop detected

Self-referencing as example

public class Employee {
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public int ManagerId { get; set; }
    public virtual Employee Manager { get; set; }

    public virtual ICollection<Employee> Employees { get; set; }

    public Employee() {
        Employees = new HashSet<Employee>();
    }
}
HasMany(e => e.Employees)
    .WithRequired(e => e.Manager)
    .HasForeignKey(e => e.ManagerId)
    .WillCascadeOnDelete(false);

How to convert a list of numbers to jsonarray in Python

Use the json module to produce JSON output:

import json

with open(outputfilename, 'wb') as outfile:
    json.dump(row, outfile)

This writes the JSON result directly to the file (replacing any previous content if the file already existed).

If you need the JSON result string in Python itself, use json.dumps() (added s, for 'string'):

json_string = json.dumps(row)

The L is just Python syntax for a long integer value; the json library knows how to handle those values, no L will be written.

Demo string output:

>>> import json
>>> row = [1L,[0.1,0.2],[[1234L,1],[134L,2]]]
>>> json.dumps(row)
'[1, [0.1, 0.2], [[1234, 1], [134, 2]]]'

jQuery preventDefault() not triggered

Update

And there's your problem - you do have to click event handlers for some a elements. In this case, the order in which you attach the handlers matters since they'll be fired in that order.

Here's a working fiddle that shows the behaviour you want.

This should be your code:

$(document).ready(function(){


    $('#tabs div.tab').hide();
    $('#tabs div.tab:first').show();
    $('#tabs ul li:first').addClass('active');

    $("div.subtab_left li.notebook a").click(function(e) {
        e.stopImmediatePropagation();
        alert("asdasdad");
        return false;
    });

    $('#tabs ul li a').click(function(){
        alert("Handling link click");
        $('#tabs ul li').removeClass('active');
        $(this).parent().addClass('active');
        var currentTab = $(this).attr('href');
        $('#tabs div.tab').hide();
        $(currentTab).show();
        return false;
    });

});

Note that the order of attaching the handlers has been exchanged and e.stopImmediatePropagation() is used to stop the other click handler from firing while return false is used to stop the default behaviour of following the link (as well as stopping the bubbling of the event. You may find that you need to use only e.stopPropagation).

Play around with this, if you remove the e.stopImmediatePropagation() you'll find that the second click handler's alert will fire after the first alert. Removing the return false will have no effect on this behaviour but will cause links to be followed by the browser.

Note

A better fix might be to ensure that the selectors return completely different sets of elements so there is no overlap but this might not always be possible in which case the solution described above might be one way to consider.


  1. I don't see why your first code snippet would not work. What's the default action that you're seeing that you want to stop?

    If you've attached other event handlers to the link, you should look into event.stopPropagation() and event.stopImmediatePropagation() instead. Note that return false is equivalent to calling both event.preventDefault and event.stopPropagation()ref

  2. In your second code snippet, e is not defined. So an error would thrown at e.preventDefault() and the next lines never execute. In other words

    $("div.subtab_left li.notebook a").click(function() {
        e.preventDefault();
        alert("asdasdad");
        return false;   
    });
    

    should be

    //note the e declared in the function parameters now
    $("div.subtab_left li.notebook a").click(function(e) {
        e.preventDefault();
        alert("asdasdad");
        return false;   
    });
    

Here's a working example showing that this code indeed does work and that return false is not really required if you only want to stop the following of a link.

In CSS Flexbox, why are there no "justify-items" and "justify-self" properties?

I know this doesn't use flexbox, but for the simple use-case of three items (one at left, one at center, one at right), this can be accomplished easily using display: grid on the parent, grid-area: 1/1/1/1; on the children, and justify-self for positioning of those children.

_x000D_
_x000D_
<div style="border: 1px solid red; display: grid; width: 100px; height: 25px;">_x000D_
  <div style="border: 1px solid blue; width: 25px; grid-area: 1/1/1/1; justify-self: left;"></div>_x000D_
  <div style="border: 1px solid blue; width: 25px; grid-area: 1/1/1/1; justify-self: center;"></div>_x000D_
  <div style="border: 1px solid blue; width: 25px; grid-area: 1/1/1/1; justify-self: right;"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Convert java.util.Date to java.time.LocalDate

public static LocalDate Date2LocalDate(Date date) {
        return LocalDate.parse(date.toString(), DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy"))

this format is from Date#tostring

    public String toString() {
        // "EEE MMM dd HH:mm:ss zzz yyyy";
        BaseCalendar.Date date = normalize();
        StringBuilder sb = new StringBuilder(28);
        int index = date.getDayOfWeek();
        if (index == BaseCalendar.SUNDAY) {
            index = 8;
        }
        convertToAbbr(sb, wtb[index]).append(' ');                        // EEE
        convertToAbbr(sb, wtb[date.getMonth() - 1 + 2 + 7]).append(' ');  // MMM
        CalendarUtils.sprintf0d(sb, date.getDayOfMonth(), 2).append(' '); // dd

        CalendarUtils.sprintf0d(sb, date.getHours(), 2).append(':');   // HH
        CalendarUtils.sprintf0d(sb, date.getMinutes(), 2).append(':'); // mm
        CalendarUtils.sprintf0d(sb, date.getSeconds(), 2).append(' '); // ss
        TimeZone zi = date.getZone();
        if (zi != null) {
            sb.append(zi.getDisplayName(date.isDaylightTime(), TimeZone.SHORT, Locale.US)); // zzz
        } else {
            sb.append("GMT");
        }
        sb.append(' ').append(date.getYear());  // yyyy
        return sb.toString();
    }

Targeting both 32bit and 64bit with Visual Studio in same solution/project

If you use Custom Actions written in .NET as part of your MSI installer then you have another problem.

The 'shim' that runs these custom actions is always 32bit then your custom action will run 32bit as well, despite what target you specify.

More info & some ninja moves to get around (basically change the MSI to use the 64 bit version of this shim)

Building an MSI in Visual Studio 2005/2008 to work on a SharePoint 64

64-bit Managed Custom Actions with Visual Studio

Git: How configure KDiff3 as merge tool and diff tool

(When trying to find out how to use kdiff3 from WSL git I ended up here and got the final pieces, so I'll post my solution for anyone else also stumbling in here while trying to find that answer)

How to use kdiff3 as diff/merge tool for WSL git

With Windows update 1903 it is a lot easier; just use wslpath and there is no need to share TMP from Windows to WSL since the Windows side now has access to the WSL filesystem via \wsl$:

[merge]
    renormalize = true
    guitool = kdiff3
[diff]
    tool = kdiff3
[difftool]
    prompt = false
[difftool "kdiff3"]
    # Unix style paths must be converted to windows path style
    cmd = kdiff3.exe \"`wslpath -w $LOCAL`\" \"`wslpath -w $REMOTE`\"
    trustExitCode = false
[mergetool]
    keepBackup = false
    prompt = false
[mergetool "kdiff3"]
    path = kdiff3.exe
    trustExitCode = false

Before Windows update 1903

Steps for using kdiff3 installed on Windows 10 as diff/merge tool for git in WSL:

  1. Add the kdiff3 installation directory to the Windows Path.
  2. Add TMP to the WSLENV Windows environment variable (WSLENV=TMP/up). The TMP dir will be used by git for temporary files, like previous revisions of files, so the path must be on the windows filesystem for this to work.
  3. Set TMPDIR to TMP in .bashrc:
# If TMP is passed via WSLENV then use it as TMPDIR
[[ ! -z "$WSLENV" && ! -z "$TMP" ]] && export TMPDIR=$TMP
  1. Convert unix-path to windows-path when calling kdiff3. Sample of my .gitconfig:
[merge]
    renormalize = true
    guitool = kdiff3
[diff]
    tool = kdiff3
[difftool]
    prompt = false
[difftool "kdiff3"]
    #path = kdiff3.exe
    # Unix style paths must be converted to windows path style by changing '/mnt/c/' or '/c/' to 'c:/'
    cmd = kdiff3.exe \"`echo $LOCAL | sed 's_^\\(/mnt\\)\\?/\\([a-z]\\)/_\\2:/_'`\" \"`echo $REMOTE | sed 's_^\\(/mnt\\)\\?/\\([a-z]\\)/_\\2:/_'`\"
    trustExitCode = false
[mergetool]
    keepBackup = false
    prompt = false
[mergetool "kdiff3"]
    path = kdiff3.exe
    trustExitCode = false

AWS S3: how do I see how much disk space is using

s3cmd can show you this by running s3cmd du, optionally passing the bucket name as an argument.

C# An established connection was aborted by the software in your host machine

This problem appear if two software use same port for connecting to the server
try to close the port by cmd according to your operating system
then reboot your Android studio or your Eclipse or your Software.

Xcode 6 iPhone Simulator Application Support location

In Swift 4 or Swift 5 you can use NSHomeDirectory().

The easiest way in Xcode 10 (or Xcode 11) is to pause your app (like when it hits a breakpoint) and run this line in the debugger console:

po NSHomeDirectory()

po stands for print object and prints most things

What is the best way to paginate results in SQL Server

Incredibly, no other answer has mentioned the fastest way to do pagination in all SQL Server versions. Offsets can be terribly slow for large page numbers as is benchmarked here. There is an entirely different, much faster way to perform pagination in SQL. This is often called the "seek method" or "keyset pagination" as described in this blog post here.

SELECT TOP 10 first_name, last_name, score, COUNT(*) OVER()
FROM players
WHERE (score < @previousScore)
   OR (score = @previousScore AND player_id < @previousPlayerId)
ORDER BY score DESC, player_id DESC

The "seek predicate"

The @previousScore and @previousPlayerId values are the respective values of the last record from the previous page. This allows you to fetch the "next" page. If the ORDER BY direction is ASC, simply use > instead.

With the above method, you cannot immediately jump to page 4 without having first fetched the previous 40 records. But often, you do not want to jump that far anyway. Instead, you get a much faster query that might be able to fetch data in constant time, depending on your indexing. Plus, your pages remain "stable", no matter if the underlying data changes (e.g. on page 1, while you're on page 4).

This is the best way to implement pagination when lazy loading more data in web applications, for instance.

Note, the "seek method" is also called keyset pagination.

Total records before pagination

The COUNT(*) OVER() window function will help you count the number of total records "before pagination". If you're using SQL Server 2000, you will have to resort to two queries for the COUNT(*).

Why is HttpContext.Current null?

In IIS7 with integrated mode, Current is not available in Application_Start. There is a similar thread here.

CSS Disabled scrolling

I use iFrame to insert the content from another page and CSS mentioned above is NOT working as expected. I have to use the parameter scrolling="no" even if I use HTML 5 Doctype

Increment value in mysql update query

Why don't you let PHP do the job?

"UPDATE member_profile SET points= ' ". ($points+1) ." '  WHERE user_id = '".$userid."'"

Android Get Current timestamp?

This code is Kotlin version. I have another idea to add a random shuffle integer in last digit for giving variance epoch time.

Kotlin version

val randomVariance = (0..100).shuffled().first()
val currentEpoch = (System.currentTimeMilis()/1000) + randomVariance

val deltaEpoch = oldEpoch - currentEpoch

I think it will be better using this kode then depend on android version 26 or more

Javascript: How to check if a string is empty?

if (value == "") {
  // it is empty
}

IntelliJ, can't start simple web application: Unable to ping server at localhost:1099

For those who encounter this when you just recently updated IntelliJ (In my case 2019.2).

I am using JBoss server so i tried to run standalone.bat in the command line and I saw the real issue on the console.

It can be different to yours, but in my case I saw:

failure description: "WFLYSRV0137: No deployment content with

And on that error I was able to fix this by removing the items (war or ear) inside the <deployments/> node in my standalone.xml

Hope this helps for those using JBoss+IntelliJ

Gaussian fit for Python

Explanation

You need good starting values such that the curve_fit function converges at "good" values. I can not really say why your fit did not converge (even though the definition of your mean is strange - check below) but I will give you a strategy that works for non-normalized Gaussian-functions like your one.

Example

The estimated parameters should be close to the final values (use the weighted arithmetic mean - divide by the sum of all values):

import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import numpy as np

x = np.arange(10)
y = np.array([0, 1, 2, 3, 4, 5, 4, 3, 2, 1])

# weighted arithmetic mean (corrected - check the section below)
mean = sum(x * y) / sum(y)
sigma = np.sqrt(sum(y * (x - mean)**2) / sum(y))

def Gauss(x, a, x0, sigma):
    return a * np.exp(-(x - x0)**2 / (2 * sigma**2))

popt,pcov = curve_fit(Gauss, x, y, p0=[max(y), mean, sigma])

plt.plot(x, y, 'b+:', label='data')
plt.plot(x, Gauss(x, *popt), 'r-', label='fit')
plt.legend()
plt.title('Fig. 3 - Fit for Time Constant')
plt.xlabel('Time (s)')
plt.ylabel('Voltage (V)')
plt.show()

I personally prefer using numpy.

Comment on the definition of the mean (including Developer's answer)

Since the reviewers did not like my edit on #Developer's code, I will explain for what case I would suggest an improved code. The mean of developer does not correspond to one of the normal definitions of the mean.

Your definition returns:

>>> sum(x * y)
125

Developer's definition returns:

>>> sum(x * y) / len(x)
12.5 #for Python 3.x

The weighted arithmetic mean:

>>> sum(x * y) / sum(y)
5.0

Similarly you can compare the definitions of standard deviation (sigma). Compare with the figure of the resulting fit:

Resulting fit

Comment for Python 2.x users

In Python 2.x you should additionally use the new division to not run into weird results or convert the the numbers before the division explicitly:

from __future__ import division

or e.g.

sum(x * y) * 1. / sum(y)

Python import csv to list

Unfortunately I find none of the existing answers particularly satisfying.

Here is a straightforward and complete Python 3 solution, using the csv module.

import csv

with open('../resources/temp_in.csv', newline='') as f:
    reader = csv.reader(f, skipinitialspace=True)
    rows = list(reader)

print(rows)

Notice the skipinitialspace=True argument. This is necessary since, unfortunately, OP's CSV contains whitespace after each comma.

Output:

[['This is the first line', 'Line1'], ['This is the second line', 'Line2'], ['This is the third line', 'Line3']]

How to use bootstrap datepicker

I believe you have to reference bootstrap.js before bootstrap-datepicker.js

Is there an XSL "contains" directive?

From Zvon.org XSLT Reference:

XPath function: boolean contains (string, string) 

Hope this helps.

Python: Find in list

Finding the first occurrence

There's a recipe for that in itertools:

def first_true(iterable, default=False, pred=None):
    """Returns the first true value in the iterable.

    If no true value is found, returns *default*

    If *pred* is not None, returns the first item
    for which pred(item) is true.

    """
    # first_true([a,b,c], x) --> a or b or c or x
    # first_true([a,b], x, f) --> a if f(a) else b if f(b) else x
    return next(filter(pred, iterable), default)

For example, the following code finds the first odd number in a list:

>>> first_true([2,3,4,5], None, lambda x: x%2==1)
3  

How to enable Logger.debug() in Log4j

If you are coming here because you are using Apache commons logging with log4j and log4j isn't working as you expect then check that you actually have a log4j.jar in your run-time classpath. That one had me puzzled for a little while. I have now configured the runner in my dev environment to include -Dlog4j.debug in the Java command line so I can always see that Log4j is being initialized correctly

IE 8: background-size fix

I use the filter solution above, for ie8. However.. In order to solve the freezing links problem , do also the following:

background: no-repeat center center fixed\0/; /* IE8 HACK */

This has solved the frozen links problem for me.

How to get relative path of a file in visual studio?

In Visual Studio please click 'Folder.ico' file in the Solution Explorer pane. Then you will see Properties pane. Change 'Copy to Output Directory' behavior to 'Copy if newer'. This will make Visual Studio copy the file to the output bin directory.

Now to get the file path using relative path just type:

string pathToIcoFile = AppDomain.CurrentDomain.BaseDirectory + "//FolderIcon//Folder.ico";

Hope that helped.

How to set up Android emulator proxy settings

-http-proxy on Android Emulator

On Run Configuration> Android Application > App > Target > Additional Emulator Command Line Options: -http-proxy http://xx.xxx.xx.xx:8080

Sql Query to list all views in an SQL Server 2005 database

This is old, but I thought I'd put this out anyway since I couldn't find a query that would give me ALL the SQL code from EVERY view I had out there. So here it is:

  SELECT SM.definition
  FROM sys.sql_modules SM
  INNER JOIN sys.Objects SO ON SM.Object_id = SO.Object_id
  WHERE SO.type = 'v'

How do I run Selenium in Xvfb?

This is the setup I use:

Before running the tests, execute:

export DISPLAY=:99
/etc/init.d/xvfb start

And after the tests:

/etc/init.d/xvfb stop

The init.d file I use looks like this:

#!/bin/bash

XVFB=/usr/bin/Xvfb
XVFBARGS="$DISPLAY -ac -screen 0 1024x768x16"
PIDFILE=${HOME}/xvfb_${DISPLAY:1}.pid
case "$1" in
  start)
    echo -n "Starting virtual X frame buffer: Xvfb"
    /sbin/start-stop-daemon --start --quiet --pidfile $PIDFILE --make-pidfile --background --exec $XVFB -- $XVFBARGS
    echo "."
    ;;
  stop)
    echo -n "Stopping virtual X frame buffer: Xvfb"
    /sbin/start-stop-daemon --stop --quiet --pidfile $PIDFILE
    echo "."
    ;;
  restart)
    $0 stop
    $0 start
    ;;
  *)
  echo "Usage: /etc/init.d/xvfb {start|stop|restart}"
  exit 1
esac
exit 0

How to resolve the "EVP_DecryptFInal_ex: bad decrypt" during file decryption

I think the Key and IV used for encryption using command line and decryption using your program are not same.

Please note that when you use the "-k" (different from "-K"), the input given is considered as a password from which the key is derived. Generally in this case, there is no need for the "-iv" option as both key and password will be derived from the input given with "-k" option.

It is not clear from your question, how you are ensuring that the Key and IV are same between encryption and decryption.

In my suggestion, better use "-K" and "-iv" option to explicitly specify the Key and IV during encryption and use the same for decryption. If you need to use "-k", then use the "-p" option to print the key and iv used for encryption and use the same in your decryption program.

More details can be obtained at https://www.openssl.org/docs/manmaster/apps/enc.html

Greater than less than, python

Check to make sure that both score and array[x] are numerical types. You might be comparing an integer to a string...which is heartbreakingly possible in Python 2.x.

>>> 2 < "2"
True
>>> 2 > "2"
False
>>> 2 == "2"
False

Edit

Further explanation: How does Python compare string and int?

Iterating over arrays in Python 3

The for loop iterates over the elements of the array, not its indexes. Suppose you have a list ar = [2, 4, 6]:

When you iterate over it with for i in ar: the values of i will be 2, 4 and 6. So, when you try to access ar[i] for the first value, it might work (as the last position of the list is 2, a[2] equals 6), but not for the latter values, as a[4] does not exist.

If you intend to use indexes anyhow, try using for index, value in enumerate(ar):, then theSum = theSum + ar[index] should work just fine.

ImportError: No module named xlsxwriter

Even if it looks like the module is installed, as far as Python is concerned it isn't since it throws that exception.

Try installing the module again using one of the installation methods shown in the XlsxWriter docs and look out for any installation errors.

If there are none then run a sample program like the following:

import xlsxwriter

workbook = xlsxwriter.Workbook('hello.xlsx')
worksheet = workbook.add_worksheet()

worksheet.write('A1', 'Hello world')

workbook.close()

CSS: stretching background image to 100% width and height of screen?

The VH unit can be used to fill the background of the viewport, aka the browser window.

(height:100vh;)

html{
    height:100%;
    }
.body {
     background: url(image.jpg) no-repeat center top; 
     background-size: cover; 
     height:100vh;     
}

How can I apply a border only inside a table?

Add the border to each cell with this:

table > tbody > tr > td { border: 1px solid rgba(255, 255, 255, 0.1); }

Remove the top border from all the cells in the first row:

table > tbody > tr:first-child > td { border-top: 0; }

Remove the left border from the cells in the first column:

table > tbody > tr > td:first-child { border-left: 0; }

Remove the right border from the cells in the last column:

table > tbody > tr > td:last-child { border-right: 0; }

Remove the bottom border from the cells in the last row:

table > tbody > tr:last-child > td { border-bottom: 0; }

http://jsfiddle.net/hzru0ytx/

Jquery: how to trigger click event on pressing enter key

Are you trying to mimic a click on a button when the enter key is pressed? If so you may need to use the trigger syntax.

Try changing

$('input[name = butAssignProd]').click();

to

$('input[name = butAssignProd]').trigger("click");

If this isn't the problem then try taking a second look at your key capture syntax by looking at the solutions in this post: jQuery Event Keypress: Which key was pressed?

Calling a php function by onclick event

In Your HTML

<input type="button" name="Release" onclick="hello();" value="Click to Release" />

In Your JavaScript

<script type="text/javascript">
    function hello(){
        alert('Your message here');
    }
</script>

If you need to run PHP in JavaScript You need to use JQuery Ajax Function

<script type="text/javascript">
function hello(){
    $.ajax(
{     
 type:    'post',
 url:     'folder/my_php_file.php',
 data:    '&id=' + $('#id').val() + '&name=' +     $('#name').val(),
 dataType: 'json',
 //alert(data);
 success: function(data) 
 {
  //alert(data);
 }   
});
}
</script>

Now in your my_php_file.php file

<?php 
    echo 'hello';
?>

Good Luck !!!!!

What is the difference between server side cookie and client side cookie?

  1. Yes you can create cookies that can only be read on the server-side. These are called "HTTP Only" -cookies, as explained in other answers already

  2. No, there is no way (I know of) to create "cookies" that can be read only on the client-side. Cookies are meant to facilitate client-server communication.

  3. BUT, if you want something LIKE "client-only-cookies" there is a simple answer: Use "Local Storage".

Local Storage is actually syntactically simpler to use than cookies. A good simple summary of cookies vs. local storage can be found at:

https://courses.cs.washington.edu/courses/cse154/12au/lectures/slides/lecture21-client-storage.shtml#slide8

A point: You might use cookies created in JavaScript to store GUI-related things you only need on the client-side. BUT the cookie is sent to the server for EVERY request made, it becomes part of the http-request headers thus making the request contain more data and thus slower to send.

If your page has 50 resources like images and css-files and scripts then the cookie is (typically) sent with each request. More on this in Does every web request send the browser cookies?

Local storage does not have those data-transfer related disadvantages, it sends no data. It is great.

Count occurrences of a char in a string using Bash

awk is very cool, but why not keep it simple?

num=$(echo $var | grep -o "," | wc -l)

How to conditional format based on multiple specific text in Excel

Suppose your "Don't Check" list is on Sheet2 in cells A1:A100, say, and your current client IDs are in Sheet1 in Column A.

What you would do is:

  1. Select the whole data table you want conditionally formatted in Sheet1
  2. Click Conditional Formatting > New Rule > Use a Formula to determine which cells to format
  3. In the formula bar, type in =ISNUMBER(MATCH($A1,Sheet2!$A$1:$A$100,0)) and select how you want those rows formatted

And that should do the trick.

Differences between ConstraintLayout and RelativeLayout

Following are the differences/advantages:

  1. Constraint Layout has dual power of both Relative Layout as well as Linear layout: Set relative positions of views ( like Relative layout ) and also set weights for dynamic UI (which was only possible in Linear Layout).

  2. A very powerful use is grouping of elements by forming a chain. This way we can form a group of views which as a whole can be placed in a desired way without adding another layer of hierarchy just to form another group of views.

  3. In addition to weights, we can apply horizontal and vertical bias which is nothing but the percentage of displacement from the centre. ( bias of 0.5 means centrally aligned. Any value less or more means corresponding movement in the respective direction ) .

  4. Another very important feature is that it respects and provides the functionality to handle the GONE views so that layouts do not break if some view is set to GONE through java code. More can be found here: https://developer.android.com/reference/android/support/constraint/ConstraintLayout.html#VisibilityBehavior

  5. Provides power of automatic constraint applying by the use of Blue print and Visual Editor tool which makes it easy to design a page.

All these features lead to flattening of the view hierarchy which improves performance and also helps in making responsive and dynamic UI which can more easily adapt to different screen size and density.

Here is the best place to learn quickly: https://codelabs.developers.google.com/codelabs/constraint-layout/#0

CMAKE_MAKE_PROGRAM not found

I had the exact same problem when I tried to compile OpenCV with Qt Creator (MinGW) to build the .a static library files.

For those that installed Qt 5.2.1 for Windows 32-bit (MinGW 4.8, OpenGL, 634 MB), this problem can be fixed if you add the following to the system's environment variable Path:

C:\Qt\Qt5.2.0\Tools\mingw48_32\bin

How do I prevent a form from being resized by the user?

You can remove the UI to control this with:

frmYour.MinimizeBox = False
frmYour.MaximizeBox = False

How to create enum like type in TypeScript?

This is now part of the language. See TypeScriptLang.org > Basic Types > enum for the documentation on this. An excerpt from the documentation on how to use these enums:

enum Color {Red, Green, Blue};
var c: Color = Color.Green;

Or with manual backing numbers:

enum Color {Red = 1, Green = 2, Blue = 4};
var c: Color = Color.Green;

You can also go back to the enum name by using for example Color[2].

Here's an example of how this all goes together:

module myModule {
    export enum Color {Red, Green, Blue};

    export class MyClass {
        myColor: Color;

        constructor() {
            console.log(this.myColor);
            this.myColor = Color.Blue;
            console.log(this.myColor);
            console.log(Color[this.myColor]);
        }
    }
}

var foo = new myModule.MyClass();

This will log:

undefined  
2  
Blue

Because, at the time of writing this, the Typescript Playground will generate this code:

var myModule;
(function (myModule) {
    (function (Color) {
        Color[Color["Red"] = 0] = "Red";
        Color[Color["Green"] = 1] = "Green";
        Color[Color["Blue"] = 2] = "Blue";
    })(myModule.Color || (myModule.Color = {}));
    var Color = myModule.Color;
    ;
    var MyClass = (function () {
        function MyClass() {
            console.log(this.myColor);
            this.myColor = Color.Blue;
            console.log(this.myColor);
            console.log(Color[this.myColor]);
        }
        return MyClass;
    })();
    myModule.MyClass = MyClass;
})(myModule || (myModule = {}));
var foo = new myModule.MyClass();

Joining two lists together

targetList = list1.Concat(list2).ToList();

It's working fine I think so. As previously said, Concat returns a new sequence and while converting the result to List, it does the job perfectly. Implicit conversions may fail sometimes when using the AddRange method.

Send mail via Gmail with PowerShell V2's Send-MailMessage

I am really new to PowerShell, and I was searching about gmailing from PowerShell. I took what you folks did in previous answers, and modified it a bit and have come up with a script which will check for attachments before adding them, and also to take an array of recipients.

## Send-Gmail.ps1 - Send a gmail message
## By Rodney Fisk - [email protected]
## 2 / 13 / 2011

# Get command line arguments to fill in the fields
# Must be the first statement in the script
param(
    [Parameter(Mandatory = $true,
               Position = 0,
               ValueFromPipelineByPropertyName = $true)]
    [Alias('From')] # This is the name of the parameter e.g. -From [email protected]
    [String]$EmailFrom, # This is the value [Don't forget the comma at the end!]

    [Parameter(Mandatory = $true,
               Position = 1,
               ValueFromPipelineByPropertyName = $true)]
    [Alias('To')]
    [String[]]$Arry_EmailTo,

    [Parameter(Mandatory = $true,
               Position = 2,
               ValueFromPipelineByPropertyName = $true)]
    [Alias('Subj')]
    [String]$EmailSubj,

    [Parameter(Mandatory = $true,
               Position = 3,
               ValueFromPipelineByPropertyName = $true)]
    [Alias('Body')]
    [String]$EmailBody,

    [Parameter(Mandatory = $false,
               Position = 4,
               ValueFromPipelineByPropertyName = $true)]
    [Alias('Attachment')]
    [String[]]$Arry_EmailAttachments
)

# From Christian @ stackoverflow.com
$SMTPServer = "smtp.gmail.com"
$SMTPClient = New-Object Net.Mail.SMTPClient($SmtpServer, 587)
$SMTPClient.EnableSSL = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("GMAIL_USERNAME", "GMAIL_PASSWORD");

# From Core @ stackoverflow.com
$emailMessage = New-Object System.Net.Mail.MailMessage
$emailMessage.From = $EmailFrom
foreach ($recipient in $Arry_EmailTo)
{
    $emailMessage.To.Add($recipient)
}
$emailMessage.Subject = $EmailSubj
$emailMessage.Body = $EmailBody
# Do we have any attachments?
# If yes, then add them, if not, do nothing
if ($Arry_EmailAttachments.Count -ne $NULL)
{
    $emailMessage.Attachments.Add()
}
$SMTPClient.Send($emailMessage)

Of course, change the GMAIL_USERNAME and GMAIL_PASSWORD values to your particular user and password.

Check if a varchar is a number (TSQL)

Damien_The_Unbeliever noted that his was only good for digits

Wade73 added a bit to handle decimal points

neizan made an additional tweak as did notwhereuareat

Unfortunately, none appear to handle negative values and they appear to have issues with a comma in the value...

Here's my tweak to pick up negative values and those with commas

declare @MyTable table(MyVar nvarchar(10));
insert into @MyTable (MyVar) 
values 
(N'1234')
, (N'000005')
, (N'1,000')
, (N'293.8457')
, (N'x')
, (N'+')
, (N'293.8457.')
, (N'......')
, (N'.')
, (N'-375.4')
, (N'-00003')
, (N'-2,000')
, (N'3-3')
, (N'3000-')
;

-- This shows that Neizan's answer allows "." to slip through.
select * from (
select 
    MyVar
    , case when MyVar not like N'%[^0-9.]%' then 1 else 0 end as IsNumber 
from 
    @MyTable
) t order by IsNumber;

-- Notice the addition of "and MyVar not like '.'".
select * from (
select 
    MyVar
    , case when MyVar not like N'%[^0-9.]%' and MyVar not like N'%.%.%' and MyVar not like '.' then 1 else 0 end as IsNumber 
from 
    @MyTable
) t 
order by IsNumber;

--Trying to tweak for negative values and the comma
--Modified when comparison
select * from (
select 
    MyVar
    , case 
        when MyVar not like N'%[^0-9.,-]%' and MyVar not like '.' and isnumeric(MyVar) = 1 then 1
        else 0 
    end as IsNumber 
from 
    @MyTable
) t 
order by IsNumber;

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

Trying to work through Roman Pekar's solution step-by-step to understand it better, I came up with my own solution, which uses melt to avoid some of the confusing stacking and index resetting. I can't say that it's obviously a clearer solution though:

items_as_cols = df.apply(lambda x: pd.Series(x['samples']), axis=1)
# Keep original df index as a column so it's retained after melt
items_as_cols['orig_index'] = items_as_cols.index

melted_items = pd.melt(items_as_cols, id_vars='orig_index', 
                       var_name='sample_num', value_name='sample')
melted_items.set_index('orig_index', inplace=True)

df.merge(melted_items, left_index=True, right_index=True)

Output (obviously we can drop the original samples column now):

                 samples  subject  trial_num sample_num  sample
0    [1.84, 1.05, -0.66]        1          1          0    1.84
0    [1.84, 1.05, -0.66]        1          1          1    1.05
0    [1.84, 1.05, -0.66]        1          1          2   -0.66
1    [-0.24, -0.9, 0.65]        1          2          0   -0.24
1    [-0.24, -0.9, 0.65]        1          2          1   -0.90
1    [-0.24, -0.9, 0.65]        1          2          2    0.65
2    [1.15, -0.87, -1.1]        1          3          0    1.15
2    [1.15, -0.87, -1.1]        1          3          1   -0.87
2    [1.15, -0.87, -1.1]        1          3          2   -1.10
3   [-0.8, -0.62, -0.68]        2          1          0   -0.80
3   [-0.8, -0.62, -0.68]        2          1          1   -0.62
3   [-0.8, -0.62, -0.68]        2          1          2   -0.68
4    [0.91, -0.47, 1.43]        2          2          0    0.91
4    [0.91, -0.47, 1.43]        2          2          1   -0.47
4    [0.91, -0.47, 1.43]        2          2          2    1.43
5  [-1.14, -0.24, -0.91]        2          3          0   -1.14
5  [-1.14, -0.24, -0.91]        2          3          1   -0.24
5  [-1.14, -0.24, -0.91]        2          3          2   -0.91

How to insert a file in MySQL database?

File size by MySQL type:

  • TINYBLOB 255 bytes = 0.000255 Mb
  • BLOB 65535 bytes = 0.0655 Mb
  • MEDIUMBLOB 16777215 bytes = 16.78 Mb
  • LONGBLOB 4294967295 bytes = 4294.97 Mb = 4.295 Gb

How can I select an element by name with jQuery?

You can use any attribute as selector with [attribute_name=value].

$('td[name=tcol1]').hide();

Mailx send html message

EMAILCC=" -c [email protected],[email protected]"
TURNO_EMAIL="[email protected]"

mailx $EMAILCC -s "$(echo "Status: Control Aplicactivo \nContent-Type: text/html")" $TURNO_EMAIL < tmp.tmp

Apache SSL Configuration Error (SSL Connection Error)

I encounter this problem, because I have <VirtualHost> defined both in httpd.conf and httpd-ssl.conf.

in httpd.conf, it's defined as

<VirtualHost localhost>

in httpd-ssl.conf, it's defined as

<VirtualHost _default_:443>

The following change solved this problem, add :80 in httpd.conf

<VirtualHost localhost:80>

ES6 class variable alternatives

In your example:

class MyClass {
    const MY_CONST = 'string';
    constructor(){
        this.MY_CONST;
    }
}

Because of MY_CONST is primitive https://developer.mozilla.org/en-US/docs/Glossary/Primitive we can just do:

class MyClass {
    static get MY_CONST() {
        return 'string';
    }
    get MY_CONST() {
        return this.constructor.MY_CONST;
    }
    constructor() {
        alert(this.MY_CONST === this.constructor.MY_CONST);
    }
}
alert(MyClass.MY_CONST);
new MyClass

// alert: string ; true

But if MY_CONST is reference type like static get MY_CONST() {return ['string'];} alert output is string, false. In such case delete operator can do the trick:

class MyClass {
    static get MY_CONST() {
        delete MyClass.MY_CONST;
        return MyClass.MY_CONST = 'string';
    }
    get MY_CONST() {
        return this.constructor.MY_CONST;
    }
    constructor() {
        alert(this.MY_CONST === this.constructor.MY_CONST);
    }
}
alert(MyClass.MY_CONST);
new MyClass

// alert: string ; true

And finally for class variable not const:

class MyClass {
    static get MY_CONST() {
        delete MyClass.MY_CONST;
        return MyClass.MY_CONST = 'string';
    }
    static set U_YIN_YANG(value) {
      delete MyClass.MY_CONST;
      MyClass.MY_CONST = value;
    }
    get MY_CONST() {
        return this.constructor.MY_CONST;
    }
    set MY_CONST(value) {
        this.constructor.MY_CONST = value;
    }
    constructor() {
        alert(this.MY_CONST === this.constructor.MY_CONST);
    }
}
alert(MyClass.MY_CONST);
new MyClass
// alert: string, true
MyClass.MY_CONST = ['string, 42']
alert(MyClass.MY_CONST);
new MyClass
// alert: string, 42 ; true

Copy rows from one table to another, ignoring duplicates

I realize this is old, but I got here from google and after reviewing the accepted answer I did my own statement and it worked for me hope someone will find it useful:

    INSERT IGNORE INTO destTable SELECT id, field2,field3... FROM origTable

Edit: This works on MySQL I did not test on MSSQL

What does the [Flags] Enum Attribute mean in C#?

In extension to the accepted answer, in C#7 the enum flags can be written using binary literals:

[Flags]
public enum MyColors
{
    None   = 0b0000,
    Yellow = 0b0001,
    Green  = 0b0010,
    Red    = 0b0100,
    Blue   = 0b1000
}

I think this representation makes it clear how the flags work under the covers.

How to display a PDF via Android web browser without "downloading" first

public class MainActivity extends AppCompatActivity {

    Button button;

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

        button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openURL("http://docs.google.com/viewer?url=" + " your pdf link ");
            }
        });
    }

    private void openURL(String s) {
        Uri uri = Uri.parse(s);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(uri,"text/html");
        startActivity(intent);
    }
}

Can't use modulus on doubles?

Use fmod() from <cmath>. If you do not want to include the C header file:

template<typename T, typename U>
constexpr double dmod (T x, U mod)
{
    return !mod ? x : x - mod * static_cast<long long>(x / mod);
}

//Usage:
double z = dmod<double, unsigned int>(14.3, 4);
double z = dmod<long, float>(14, 4.6);
//This also works:
double z = dmod(14.7, 0.3);
double z = dmod(14.7, 0);
double z = dmod(0, 0.3f);
double z = dmod(myFirstVariable, someOtherVariable);

HTML5 Video Autoplay not working correctly

Chrome does not allow autoplay if the video is not muted. Try using this:

<video width="440px" loop="true" autoplay="autoplay" controls muted>
  <source src="http://www.tuscorlloyds.com/CorporateVideo.mp4" type="video/mp4" />
  <source src="http://www.tuscorlloyds.com/CorporateVideo.ogv" type="video/ogv" />
  <source src="http://www.tuscorlloyds.com/CorporateVideo.webm" type="video/webm" />
</video>

How can I embed a YouTube video on GitHub wiki pages?

I created https://yt-embed.herokuapp.com/ to simplify this. The usage is direct, from the examples above:

[![Everything Is AWESOME](https://yt-embed.herokuapp.com/embed?v=StTqXEQ2l-Y)](https://www.youtube.com/watch?v=StTqXEQ2l-Y "Everything Is AWESOME")

Will result in: example of usage of yt-embed

Just make a call to: https://yt-embed.herokuapp.com/embed?v=[video_id] as the image instead of https://img.youtube.com/vi/.

What is the purpose of "&&" in a shell command?

&& strings commands together. Successive commands only execute if preceding ones succeed.

Similarly, || will allow the successive command to execute if the preceding fails.

See Bash Shell Programming.

What is the difference between a symbolic link and a hard link?

I just found an easy way to understand hard links in a common scenario, software install.

One day I downloaded a software to folder Downloads for install. After I did sudo make install, some executables were cped to local bin folder. Here, cp creates hard link. I was happy with the software but soon realized that Downloads isn't a good place in the long run. So I mved the software folder to source directory. Well, I can still run the software as before without worrying about any target link things, like in Windows. This means hard link finds inode directly and other files around.

Why are arrays of references illegal?

References are not objects. They don't have storage of their own, they just reference existing objects. For this reason it doesn't make sense to have arrays of references.

If you want a light-weight object that references another object then you can use a pointer. You will only be able to use a struct with a reference member as objects in arrays if you provide explicit initialization for all the reference members for all struct instances. References cannot be default initalized.

Edit: As jia3ep notes, in the standard section on declarations there is an explicit prohibition on arrays of references.

Only mkdir if it does not exist

Use mkdir's -p option, but note that it has another effect as well.

 -p      Create intermediate directories as required.  If this option is not specified, the full path prefix of each oper-
         and must already exist.  On the other hand, with this option specified, no error will be reported if a directory
         given as an operand already exists.  Intermediate directories are created with permission bits of rwxrwxrwx
         (0777) as modified by the current umask, plus write and search permission for the owner.

XAMPP - Apache could not start - Attempting to start Apache service

when i run xampp control panel normal:

enter image description here

I had been run

I can’t start apache So, I will run it with administrator:

enter image description here

I can run apache

How to check for file lock?

No, unfortunately, and if you think about it, that information would be worthless anyway since the file could become locked the very next second (read: short timespan).

Why specifically do you need to know if the file is locked anyway? Knowing that might give us some other way of giving you good advice.

If your code would look like this:

if not locked then
    open and update file

Then between the two lines, another process could easily lock the file, giving you the same problem you were trying to avoid to begin with: exceptions.

Expand a div to fill the remaining width

A slightly different implementation,

Two div panels(content+extra), side by side, content panel expands if extra panel is not present.

jsfiddle: http://jsfiddle.net/qLTMf/1722/

How to get child element by index in Jquery?

If you know the child element you're interested in is the first:

 $('.second').children().first();

Or to find by index:

 var index = 0
 $('.second').children().eq(index);

VBA - how to conditionally skip a for loop iteration

You can use a kind of continue by using a nested Do ... Loop While False:

'This sample will output 1 and 3 only

Dim i As Integer

For i = 1 To 3: Do

    If i = 2 Then Exit Do 'Exit Do is the Continue

    Debug.Print i

Loop While False: Next i

Get Excel sheet name and use as variable in macro

in a Visual Basic Macro you would use

pName = ActiveWorkbook.Path      ' the path of the currently active file
wbName = ActiveWorkbook.Name     ' the file name of the currently active file
shtName = ActiveSheet.Name       ' the name of the currently selected worksheet

The first sheet in a workbook can be referenced by

ActiveWorkbook.Worksheets(1)

so after deleting the [Report] tab you would use

ActiveWorkbook.Worksheets("Report").Delete
shtName = ActiveWorkbook.Worksheets(1).Name

to "work on that sheet later on" you can create a range object like

Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(shtName).[A1]

and continue working on MySheet(rowNum, colNum) etc. ...

shortcut creation of a range object without defining shtName:

Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(1).[A1]

String.equals() with multiple conditions (and one action on result)

Pattern p = Pattern.compile("tom"); //the regular-expression pattern
Matcher m = p.matcher("(bob)(tom)(harry)"); //The data to find matches with

while (m.find()) {
    //do something???
}   

Use regex to find a match maybe?

Or create an array

 String[] a = new String[]{
        "tom",
        "bob",
        "harry"
 };

 if(a.contains(stringtomatch)){
     //do something
 }

Should I test private methods or only public ones?

I understand the point of view where private methods are considered as implementations details and then don't have to be tested. And I would stick with this rule if we had to develop outside of the object only. But us, are we some kind of restricted developers who are developing only outside of objects, calling only their public methods? Or are we actually also developing that object? As we are not bound to program outside objects, we will probably have to call those private methods into new public ones we are developing. Wouldn't it be great to know that the private method resist against all odds?

I know some people could answer that if we are developing another public method into that object then this one should be tested and that's it (the private method could carry on living without test). But this is also true for any public methods of an object: when developing a web app, all the public methods of an object are called from controllers methods and hence could be considered as implementation details for controllers.

So why are we unit testing objects? Because it is really difficult, not to say impossible to be sure that we are testing the controllers' methods with the appropriate input which will trigger all the branches of the underlying code. In other words, the higher we are in the stack, the more difficult it is to test all the behaviour. And so is the same for private methods.

To me the frontier between private and public methods is a psychologic criteria when it comes to tests. Criteria which matters more to me are:

  • is the method called more than once from different places?
  • is the method sophisticated enough to require tests?

__FILE__ macro shows full path

Here is the solution that uses compile-time calculation:

constexpr auto* getFileName(const char* const path)
{
    const auto* startPosition = path;
    for (const auto* currentCharacter = path;*currentCharacter != '\0'; ++currentCharacter)
    {
        if (*currentCharacter == '\\' || *currentCharacter == '/')
        {
            startPosition = currentCharacter;
        }
    }

    if (startPosition != path)
    {
        ++startPosition;
    }

    return startPosition;
}

std::cout << getFileName(__FILE__);

How to get row from R data.frame

Try:

> d <- data.frame(a=1:3, b=4:6, c=7:9)

> d
  a b c
1 1 4 7
2 2 5 8
3 3 6 9

> d[1, ]
  a b c
1 1 4 7

> d[1, ]['a']
  a
1 1

How to pass arguments to a Dockerfile?

You are looking for --build-arg and the ARG instruction. These are new as of Docker 1.9. Check out https://docs.docker.com/engine/reference/builder/#arg. This will allow you to add ARG arg to the Dockerfile and then build with docker build --build-arg arg=2.3 ..

Case insensitive 'in'

I would make a wrapper so you can be non-invasive. Minimally, for example...:

class CaseInsensitively(object):
    def __init__(self, s):
        self.__s = s.lower()
    def __hash__(self):
        return hash(self.__s)
    def __eq__(self, other):
        # ensure proper comparison between instances of this class
        try:
           other = other.__s
        except (TypeError, AttributeError):
          try:
             other = other.lower()
          except:
             pass
        return self.__s == other

Now, if CaseInsensitively('MICHAEL89') in whatever: should behave as required (whether the right-hand side is a list, dict, or set). (It may require more effort to achieve similar results for string inclusion, avoid warnings in some cases involving unicode, etc).

Pass a datetime from javascript to c# (Controller)

Try to use toISOString(). It returns string in ISO8601 format.

GET method

javascript

$.get('/example/doGet?date=' + new Date().toISOString(), function (result) {
    console.log(result);
});

c#

[HttpGet]
public JsonResult DoGet(DateTime date)
{
    return Json(date.ToString(), JsonRequestBehavior.AllowGet);
}

POST method

javascript

$.post('/example/do', { date: date.toISOString() }, function (result) {
    console.log(result);
});

c#

[HttpPost]
public JsonResult Do(DateTime date)
{
     return Json(date.ToString());
}

How to split a string into an array of characters in Python?

If you wish to read only access to the string you can use array notation directly.

Python 2.7.6 (default, Mar 22 2014, 22:59:38) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> t = 'my string'
>>> t[1]
'y'

Could be useful for testing without using regexp. Does the string contain an ending newline?

>>> t[-1] == '\n'
False
>>> t = 'my string\n'
>>> t[-1] == '\n'
True

How to check what user php is running as?

<?php echo exec('whoami'); ?>

Convert integer into its character equivalent, where 0 => a, 1 => b, etc

A simple answer would be (26 characters):

String.fromCharCode(97+n);

If space is precious you could do the following (20 characters):

(10+n).toString(36);

Think about what you could do with all those extra bytes!

How this works is you convert the number to base 36, so you have the following characters:

0123456789abcdefghijklmnopqrstuvwxyz
^         ^
n        n+10

By offsetting by 10 the characters start at a instead of 0.

Not entirely sure about how fast running the two different examples client-side would compare though.

How do I write good/correct package __init__.py files

Your __init__.py should have a docstring.

Although all the functionality is implemented in modules and subpackages, your package docstring is the place to document where to start. For example, consider the python email package. The package documentation is an introduction describing the purpose, background, and how the various components within the package work together. If you automatically generate documentation from docstrings using sphinx or another package, the package docstring is exactly the right place to describe such an introduction.

For any other content, see the excellent answers by firecrow and Alex Martelli.

How do I query using fields inside the new PostgreSQL JSON datatype?

Postgres 9.2

I quote Andrew Dunstan on the pgsql-hackers list:

At some stage there will possibly be some json-processing (as opposed to json-producing) functions, but not in 9.2.

Doesn't prevent him from providing an example implementation in PLV8 that should solve your problem.

Postgres 9.3

Offers an arsenal of new functions and operators to add "json-processing".

The answer to the original question in Postgres 9.3:

SELECT *
FROM   json_array_elements(
  '[{"name": "Toby", "occupation": "Software Engineer"},
    {"name": "Zaphod", "occupation": "Galactic President"} ]'
  ) AS elem
WHERE elem->>'name' = 'Toby';

Advanced example:

For bigger tables you may want to add an expression index to increase performance:

Postgres 9.4

Adds jsonb (b for "binary", values are stored as native Postgres types) and yet more functionality for both types. In addition to expression indexes mentioned above, jsonb also supports GIN, btree and hash indexes, GIN being the most potent of these.

The manual goes as far as suggesting:

In general, most applications should prefer to store JSON data as jsonb, unless there are quite specialized needs, such as legacy assumptions about ordering of object keys.

Bold emphasis mine.

Performance benefits from general improvements to GIN indexes.

Postgres 9.5

Complete jsonb functions and operators. Add more functions to manipulate jsonb in place and for display.

How to convert JTextField to String and String to JTextField?

how to convert JTextField to string and string to JTextField in java

If you mean how to get and set String from jTextField then you can use following methods:

String str = jTextField.getText() // get string from jtextfield

and

jTextField.setText(str)  // set string to jtextfield
//or
new JTextField(str)     // set string to jtextfield

You should check JavaDoc for JTextField

SimpleXml to string

You can use ->child to get a child element named child.

This element will contain the text of the child element.

But if you try var_dump() on that variable, you will see it is not actually a PHP string.

The easiest way around this is to perform a strval(xml->child); That will convert it to an actual PHP string.

This is useful when debugging when looping your XML and using var_dump() to check the result.

So $s = strval($xml->child);.

Laravel Query Builder where max id

Just like the docs say

DB::table('orders')->max('id');

process.waitFor() never returns

Also from Java doc:

java.lang

Class Process

Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, and even deadlock.

Fail to clear the buffer of input stream (which pipes to the output stream of subprocess) from Process may lead to a subprocess blocking.

Try this:

Process process = Runtime.getRuntime().exec("tasklist");
BufferedReader reader =
new BufferedReader(new InputStreamReader(process.getInputStream()));
while ((reader.readLine()) != null) {}
process.waitFor();

What does the term "Tuple" Mean in Relational Databases?

Tuple is used to refer to a row in a relational database model. But tuple has little bit difference with row.

Git: Could not resolve host github.com error while cloning remote repository in git

This solve the issue

git config --global --unset http.proxy

or https

git config --global --unset https.proxy

What does <value optimized out> mean in gdb?

From https://idlebox.net/2010/apidocs/gdb-7.0.zip/gdb_9.html

The values of arguments that were not saved in their stack frames are shown as `value optimized out'.

Im guessing you compiled with -O(somevalue) and are accessing variables a,b,c in a function where optimization has occurred.

Initialize a string variable in Python: "" or None?

empty_string = ""

if not empty_string:

    print "Empty string is not set"

=>Empty string is not set

if empty_string is not None:
    print "Empty string is not None"

=>Empty string is not None

Can I use multiple versions of jQuery on the same page?

Yes, it's doable due to jQuery's noconflict mode. http://blog.nemikor.com/2009/10/03/using-multiple-versions-of-jquery/

<!-- load jQuery 1.1.3 -->
<script type="text/javascript" src="http://example.com/jquery-1.1.3.js"></script>
<script type="text/javascript">
var jQuery_1_1_3 = $.noConflict(true);
</script>

<!-- load jQuery 1.3.2 -->
<script type="text/javascript" src="http://example.com/jquery-1.3.2.js"></script>
<script type="text/javascript">
var jQuery_1_3_2 = $.noConflict(true);
</script>

Then, instead of $('#selector').function();, you'd do jQuery_1_3_2('#selector').function(); or jQuery_1_1_3('#selector').function();.

How do you create a read-only user in PostgreSQL?

The not straightforward way of doing it would be granting select on each table of the database:

postgres=# grant select on db_name.table_name to read_only_user;

You could automate that by generating your grant statements from the database metadata.

(13: Permission denied) while connecting to upstream:[nginx]

I have solved my problem by running my Nginx as the user I'm currently logged in with, mulagala.

By default the user as nginx is defined at the very top section of the nginx.conf file as seen below;

user nginx; # Default Nginx user

Change nginx to the name of your current user - here, mulagala.

user mulagala; # Custom Nginx user (as username of the current logged in user)

However, this may not address the actual problem and may actually have casual side effect(s).

For an effective solution, please refer to Joseph Barbere's solution.

Using custom std::set comparator

1. Modern C++20 solution

auto cmp = [](int a, int b) { return ... };
std::set<int, decltype(cmp)> s;

We use lambda function as comparator. As usual, comparator should return boolean value, indicating whether the element passed as first argument is considered to go before the second in the specific strict weak ordering it defines.

Online demo

2. Modern C++11 solution

auto cmp = [](int a, int b) { return ... };
std::set<int, decltype(cmp)> s(cmp);

Before C++20 we need to pass lambda as argument to set constructor

Online demo

3. Similar to first solution, but with function instead of lambda

Make comparator as usual boolean function

bool cmp(int a, int b) {
    return ...;
}

Then use it, either this way:

std::set<int, decltype(cmp)*> s(cmp);

Online demo

or this way:

std::set<int, decltype(&cmp)> s(&cmp);

Online demo

4. Old solution using struct with () operator

struct cmp {
    bool operator() (int a, int b) const {
        return ...
    }
};

// ...
// later
std::set<int, cmp> s;

Online demo

5. Alternative solution: create struct from boolean function

Take boolean function

bool cmp(int a, int b) {
    return ...;
}

And make struct from it using std::integral_constant

#include <type_traits>
using Cmp = std::integral_constant<decltype(&cmp), &cmp>;

Finally, use the struct as comparator

std::set<X, Cmp> set;

Online demo

How do you use variables in a simple PostgreSQL script?

I had to do something like this

CREATE OR REPLACE FUNCTION MYFUNC()
RETURNS VOID AS $$
DO
$do$
BEGIN
DECLARE
 myvar int;
 ...
END
$do$
$$ LANGUAGE SQL;

Prevent browser caching of AJAX call result

Personally I feel that the query string method is more reliable than trying to set headers on the server - there's no guarantee that a proxy or browser won't just cache it anyway (some browsers are worse than others - naming no names).

I usually use Math.random() but I don't see anything wrong with using the date (you shouldn't be doing AJAX requests fast enough to get the same value twice).

Android WSDL/SOAP service client

private static  final  String NAMESPACE = "http://tempuri.org/";
private static  final String URL = "http://example.com/CRM/Service.svc";
private static  final  String SOAP_ACTION = "http://tempuri.org/Login";
private static  final String METHOD_NAME = "Login";


//calling web services method

String loginresult=callService(username,password,usertype);


//calling webservices
String callService(String a1,String b1,Integer c1) throws Exception {

            Boolean flag=true;
            do
            {
                try{
                    System.out.println(flag);

                SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

                PropertyInfo pa1 = new PropertyInfo();
                pa1.setName("Username");
                pa1.setValue(a1.toString());

                PropertyInfo pb1 = new PropertyInfo();
                pb1.setName("Password");
                pb1.setValue(b1.toString());

                PropertyInfo pc1 = new PropertyInfo();
                pc1.setName("UserType");
                pc1.setValue(c1);
                System.out.println(c1+"this is integer****s");




                System.out.println("new");
                request.addProperty(pa1);
                request.addProperty(pb1);
                request.addProperty(pc1);



                System.out.println("new2");
                SoapSerializationEnvelope envelope = new    SoapSerializationEnvelope(SoapEnvelope.VER11);
                envelope.dotNet = true;
                System.out.println("new3");
                envelope.setOutputSoapObject(request);
                HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
                androidHttpTransport.setXmlVersionTag("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
                System.out.println("new4");
                try{
                androidHttpTransport.call(SOAP_ACTION, envelope);
                }
                catch(Exception e)
                {

                    System.out.println(e+"   this is exception");
                }
                System.out.println("new5");
                SoapObject response = (SoapObject)envelope.bodyIn;

                result = response.getProperty(0).toString(); 

                flag=false;
                System.out.println(flag);
                }catch (Exception e) {
                // TODO: handle exception
                    flag=false;
            }
            }
            while(flag);
            return result;

        }  
///

Difference between PCDATA and CDATA in DTD

The very main difference between PCDATA and CDATA is

PCDATA - Basically used for ELEMENTS while

CDATA - Used for Attributes of XML i.e ATTLIST

How to declare array of zeros in python (or an array of a certain size)

You can multiply a list by an integer n to repeat the list n times:

buckets = [0] * 100

Disable html5 video autoplay

just use preload="none" in your video tag and video will stop autoplay when the page is loading.

Convert dictionary to list collection in C#

If you want to pass the Dictionary keys collection into one method argument.

List<string> lstKeys = Dict.Keys;
Methodname(lstKeys);
-------------------
void MethodName(List<String> lstkeys)
{
    `enter code here`
    //Do ur task
}

What does the 'static' keyword do in a class?

The static keyword means that something (a field, method or nested class) is related to the type rather than any particular instance of the type. So for example, one calls Math.sin(...) without any instance of the Math class, and indeed you can't create an instance of the Math class.

For more information, see the relevant bit of Oracle's Java Tutorial.


Sidenote

Java unfortunately allows you to access static members as if they were instance members, e.g.

// Bad code!
Thread.currentThread().sleep(5000);
someOtherThread.sleep(5000);

That makes it look as if sleep is an instance method, but it's actually a static method - it always makes the current thread sleep. It's better practice to make this clear in the calling code:

// Clearer
Thread.sleep(5000);

Oracle JDBC intermittent Connection Issue

Note that the suggested solution of using /dev/urandom did work the first time for me but didn't work always after that.

DBA at my firm switched of 'SQL* net banners' and that fixed it permanently for me with or without the above.

I don't know what 'SQL* net banners' are, but am hoping by putting this information here that if you have(are) a DBA he(you) would know what to do.

What is the difference between CHARACTER VARYING and VARCHAR in PostgreSQL?

Varying is an alias for varchar, so no difference, see documentation :)

The notations varchar(n) and char(n) are aliases for character varying(n) and character(n), respectively. character without length specifier is equivalent to character(1). If character varying is used without length specifier, the type accepts strings of any size. The latter is a PostgreSQL extension.

System not declared in scope?

You need to add:

 #include <cstdlib>

in order for the compiler to see the prototype for system().

How can we programmatically detect which iOS version is device running on?

To get more specific version number information with major and minor versions separated:

NSString* versionString = [UIDevice currentDevice].systemVersion;
NSArray* vN = [versionString componentsSeparatedByString:@"."];

The array vN will contain the major and minor versions as strings, but if you want to do comparisons, version numbers should be stored as numbers (ints). You can add this code to store them in the C-array* versionNumbers:

int versionNumbers[vN.count];
for (int i = 0; i < sizeof(versionNumbers)/sizeof(versionNumbers[0]); i++)
    versionNumbers[i] = [[vN objectAtIndex:i] integerValue];

* C-arrays used here for more concise syntax.

Difference between array_push() and $array[] =

explain: 1.the first one declare the variable in array.

2.the second array_push method is used to push the string in the array variable.

3.finally it will print the result.

4.the second method is directly store the string in the array.

5.the data is printed in the array values in using print_r method.

this two are same

How to navigate to a section of a page

Main page

<a href="/sample.htm#page1">page1</a>
<a href="/sample.htm#page2">page2</a>

sample pages

<div id='page1'><a name="page1"></a></div>
<div id='page2'><a name="page2"></a></div>

Differentiate between function overloading and function overriding

Function overloading is same name function but different arguments. Function over riding means same name function and same as arguments

Reading a text file in MATLAB line by line

If you really want to process your file line by line, a solution might be to use fgetl:

  1. Open the data file with fopen
  2. Read the next line into a character array using fgetl
  3. Retreive the data you need using sscanf on the character array you just read
  4. Perform any relevant test
  5. Output what you want to another file
  6. Back to point 2 if you haven't reached the end of your file.

Unlike the previous answer, this is not very much in the style of Matlab but it might be more efficient on very large files.

Hope this will help.

Passing data to a jQuery UI Dialog

You could do it like this:

  • mark the <a> with a class, say "cancel"
  • set up the dialog by acting on all elements with class="cancel":

    $('a.cancel').click(function() { 
      var a = this; 
      $('#myDialog').dialog({
        buttons: {
          "Yes": function() {
             window.location = a.href; 
          }
        }
      }); 
      return false;
    });
    

(plus your other options)

The key points here are:

  • make it as unobtrusive as possible
  • if all you need is the URL, you already have it in the href.

However, I recommend that you make this a POST instead of a GET, since a cancel action has side effects and thus doesn't comply with GET semantics...

Changing iframe src with Javascript

change onselect to onchange in inputs and use

calendar.src = loc

_x000D_
_x000D_
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">_x000D_
<html xmlns="http://www.w3.org/1999/xhtml">_x000D_
_x000D_
<head>_x000D_
  <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />_x000D_
  <title>Untitled 1</title>_x000D_
_x000D_
  <script>_x000D_
  function go(loc) {_x000D_
    calendar.src = loc;_x000D_
  }_x000D_
  </script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <iframe id="calendar" src="about:blank" width="1000" height="450" frameborder="0" scrolling="no"></iframe>_x000D_
_x000D_
  <form method="post">_x000D_
    <input name="calendarSelection" type="radio" onchange="go('https://calendar.zoho.com/embed/9a6054c98fd2ad4047021cff76fee38773c34a35234fa42d426b9510864356a68cabcad57cbbb1a0?title=Kevin_Calendar&type=1&l=en&tz=America/Los_Angeles&sh=[0,0]&v=1')" />Day_x000D_
    <input name="calendarSelection" type="radio" onchange="go('https://calendar.zoho.com/embed/9a6054c98fd2ad4047021cff76fee38773c34a35234fa42d426b9510864356a68cabcad57cbbb1a0?title=Kevin_Calendar&type=1&l=en&tz=America/Los_Angeles&sh=[0,0]&v=1')" />Week_x000D_
    <input name="calendarSelection" type="radio" onchange="go('https://calendar.zoho.com/embed/9a6054c98fd2ad4047021cff76fee38773c34a35234fa42d426b9510864356a68cabcad57cbbb1a0?title=Kevin_Calendar&type=1&l=en&tz=America/Los_Angeles&sh=[0,0]&v=1')" />Month_x000D_
  </form>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Indent multiple lines quickly in vi

As well as the offered solutions, I like to do things a paragraph at a time with >}

How do we count rows using older versions of Hibernate (~2009)?

Here is what official hibernate docs tell us about this:

You can count the number of query results without returning them:

( (Integer) session.createQuery("select count(*) from ....").iterate().next() ).intValue()

However, it doesn't always return Integer instance, so it is better to use java.lang.Number for safety.

How to set alignment center in TextBox in ASP.NET?

Add the css styling text-align: center to the control.

Ideally you would do this through a css class assigned to the control, but if you must do it directly, here is an example:

<asp:TextBox ID="myTextBox" runat="server" style="text-align: center"></asp:TextBox>

bower command not found

Alternatively, you can use npx which comes along with the npm > 5.6.

npx bower install

Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger

You can use the following maven dependency in your pom file. Otherwise, you can download the following two jars from net and add it to your build path.

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.6.4</version>
</dependency>

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.6.4</version>
</dependency>

This is copied from my working project. First make sure it is working in your project. Then you can change the versions to use any other(versions) compatible jars.

For AggCat, you can refer the POM file of the sample java application.

https://github.com/IntuitDeveloperRelations/IPP_Sample_Code/blob/master/CustomerAccountData/Java/AggCatSampleApplication/pom.xml

Thanks

bad operand types for binary operator "&" java

You have to be more precise, using parentheses, otherwise Java will not use the order of operands that you want it to use.

if ((a[0] & 1 == 0) && (a[1] & 1== 0) && (a[2] & 1== 0)){

Becomes

if (((a[0] & 1) == 0) && ((a[1] & 1) == 0) && ((a[2] & 1) == 0)){

How can I set response header on express.js assets

Short Answer:

  • res.setHeaders - calls the native Node.js method

  • res.set - sets headers

  • res.headers - an alias to res.set

IE7 Z-Index Layering Issues

http://www.vancelucas.com/blog/fixing-ie7-z-index-issues-with-jquery/

$(function() {
var zIndexNumber = 1000;
$('div').each(function() {
    $(this).css('zIndex', zIndexNumber);
    zIndexNumber -= 10;
});
});

How to programmatically get iOS status bar height

EDIT The iOS 11 way to work out where to put the top of your view content is UIView's safeAreaLayoutGuide See UIView Documentation.

DEPRECATED ANSWER If you're targeting iOS 7+, The documentation for UIViewController advises that the viewController's topLayoutGuide property gives you the bottom of the status bar, or the bottom of the navigation bar, if it's also visible. That may be of use, and is certainly less hack than many of the previous solutions.

Where IN clause in LINQ

This will translate to a where in clause in Linq to SQL...

var myInClause = new string[] {"One", "Two", "Three"};

var results = from x in MyTable
              where myInClause.Contains(x.SomeColumn)
              select x;
// OR
var results = MyTable.Where(x => myInClause.Contains(x.SomeColumn));

In the case of your query, you could do something like this...

var results = from states in _objectdatasource.StateList()
              where listofcountrycodes.Contains(states.CountryCode)
              select new State
              {
                  StateName = states.StateName
              };
// OR
var results = _objectdatasource.StateList()
                  .Where(s => listofcountrycodes.Contains(s.CountryCode))
                  .Select(s => new State { StateName = s.StateName});

How to show multiline text in a table cell

You want to use the CSS white-space:pre applied to the appropriate <td>. To do this to all table cells, for example:

td { white-space:pre }

Alternatively, if you can change your markup, you can use a <pre> tag around your content. By default web browsers use their user-agent stylesheet to apply the same white-space:pre rule to this element.

The PRE element tells visual user agents that the enclosed text is "preformatted". When handling preformatted text, visual user agents:

  • May leave white space intact.
  • May render text with a fixed-pitch font.
  • May disable automatic word wrap.
  • Must not disable bidirectional processing.

Init array of structs in Go

You can have it this way:

It is important to mind the commas after each struct item or set of items.

earnings := []LineItemsType{

        LineItemsType{

            TypeName: "Earnings",

            Totals: 0.0,

            HasTotal: true,

            items: []LineItems{

                LineItems{

                    name: "Basic Pay",

                    amount: 100.0,
                },

                LineItems{

                    name: "Commuter Allowance",

                    amount: 100.0,
                },
            },
        },
        LineItemsType{

            TypeName: "Earnings",

            Totals: 0.0,

            HasTotal: true,

            items: []LineItems{

                LineItems{

                    name: "Basic Pay",

                    amount: 100.0,
                },

                LineItems{

                    name: "Commuter Allowance",

                    amount: 100.0,
                },
            },
        },
    }

Create local maven repository

Set up a simple repository using a web server with its default configuration. The key is the directory structure. The documentation does not mention it explicitly, but it is the same structure as a local repository.

To set up an internal repository just requires that you have a place to put it, and then start copying required artifacts there using the same layout as in a remote repository such as repo.maven.apache.org. Source

Add a file to your repository like this:

mvn install:install-file \
  -Dfile=YOUR_JAR.jar -DgroupId=YOUR_GROUP_ID 
  -DartifactId=YOUR_ARTIFACT_ID -Dversion=YOUR_VERSION \
  -Dpackaging=jar \
  -DlocalRepositoryPath=/var/www/html/mavenRepository

If your domain is example.com and the root directory of the web server is located at /var/www/html/, then maven can find "YOUR_JAR.jar" if configured with <url>http://example.com/mavenRepository</url>.

What is the best IDE for PHP?

There is a new guy in town, PhpStorm from JetBrains. You use it and I bet you will forget all the other editors. It's bit pricey though, unfortunately.

Project with path ':mypath' could not be found in root project 'myproject'

I got similar error after deleting a subproject, removed

"*compile project(path: ':MySubProject', configuration: 'android-endpoints')*"

in build.gradle (dependencies) under Gradle Scripts

byte array to pdf

Usually this happens if something is wrong with the byte array.

File.WriteAllBytes("filename.PDF", Byte[]);

This creates a new file, writes the specified byte array to the file, and then closes the file. If the target file already exists, it is overwritten.

Asynchronous implementation of this is also available.

public static System.Threading.Tasks.Task WriteAllBytesAsync 
(string path, byte[] bytes, System.Threading.CancellationToken cancellationToken = null);

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

Another difference is that POST generally requires two HTTP operations, whereas GET only requires one.

Edit: I should clarify--for common programming patterns. Generally responding to a POST with a straight up HTML web page is a questionable design for a variety of reasons, one of which is the annoying "you must resubmit this form, do you wish to do so?" on pressing the back button.

How can I properly use a PDO object for a parameterized SELECT query

You can use the bindParam or bindValue methods to help prepare your statement. It makes things more clear on first sight instead of doing $check->execute(array(':name' => $name)); Especially if you are binding multiple values/variables.

Check the clear, easy to read example below:

$q = $db->prepare("SELECT id FROM table WHERE forename = :forename and surname = :surname LIMIT 1");
$q->bindValue(':forename', 'Joe');
$q->bindValue(':surname',  'Bloggs');
$q->execute();

if ($q->rowCount() > 0){
    $check = $q->fetch(PDO::FETCH_ASSOC);
    $row_id = $check['id'];
    // do something
}

If you are expecting multiple rows remove the LIMIT 1 and change the fetch method into fetchAll:

$q = $db->prepare("SELECT id FROM table WHERE forename = :forename and surname = :surname");// removed limit 1
$q->bindValue(':forename', 'Joe');
$q->bindValue(':surname',  'Bloggs');
$q->execute();

if ($q->rowCount() > 0){
    $check = $q->fetchAll(PDO::FETCH_ASSOC);
    //$check will now hold an array of returned rows. 
    //let's say we need the second result, i.e. index of 1
    $row_id = $check[1]['id']; 
    // do something
}

How To change the column order of An Existing Table in SQL Server 2008

I tried this and dont see any way of doing it.

here is my approach for it.

  1. Right click on table and Script table for Create and have this on one of the SQL Query window,
  2. EXEC sp_rename 'Employee', 'Employee1' -- Original table name is Employee
  3. Execute the Employee create script, make sure you arrange the columns in the way you need.
  4. INSERT INTO TABLE2 SELECT * FROM TABLE1. -- Insert into Employee select Name, Company from Employee1
  5. DROP table Employee1.

How to add jQuery to an HTML page?

You need to wrap this in script tags:

<script type='text/javascript'> ... your code ... </script>

That being said, it's important WHEN you execute this code. If you put this in the page BEFORE the HTML elements that it is hooking into then the script will run BEFORE the HTML is actually rendered in the page, so it will fail.

It is common practice to wrap this type of code in a "document ready" block, like so:

<script type='text/javascript'>
$(document).ready(function() {

... your code...

}}
</script>

This ensures that the entire page has rendered in the browser BEFORE your code is executed. It is also a best practice to put the code in the <head> section of your page.

When to use If-else if-else over switch statements and vice versa

This depends very much on the specific case. Preferably, I think one should use the switch over the if-else if there are many nested if-elses.

The question is how much is many?

Yesterday I was asking myself the same question:

public enum ProgramType {
    NEW, OLD
}

if (progType == OLD) {
    // ...
} else if (progType == NEW) {
    // ...
}

if (progType == OLD) {
    // ...
} else {
    // ...
}

switch (progType) {
case OLD:
    // ...
    break;
case NEW:
    // ...
    break;
default:
    break;
}

In this case, the 1st if has an unnecessary second test. The 2nd feels a little bad because it hides the NEW.

I ended up choosing the switch because it just reads better.

Coerce multiple columns to factors at once

Choose some columns to coerce to factors:

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

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

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

Check the result:

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

python numpy/scipy curve fitting

I suggest you to start with simple polynomial fit, scipy.optimize.curve_fit tries to fit a function f that you must know to a set of points.

This is a simple 3 degree polynomial fit using numpy.polyfit and poly1d, the first performs a least squares polynomial fit and the second calculates the new points:

import numpy as np
import matplotlib.pyplot as plt

points = np.array([(1, 1), (2, 4), (3, 1), (9, 3)])
# get x and y vectors
x = points[:,0]
y = points[:,1]

# calculate polynomial
z = np.polyfit(x, y, 3)
f = np.poly1d(z)

# calculate new x's and y's
x_new = np.linspace(x[0], x[-1], 50)
y_new = f(x_new)

plt.plot(x,y,'o', x_new, y_new)
plt.xlim([x[0]-1, x[-1] + 1 ])
plt.show()

enter image description here

AngularJs $http.post() does not send data

I had the same problem in express .. to resolve you have to use bodyparser to parse json objects before sending http requests ..

app.use(bodyParser.json());

Setting the height of a SELECT in IE

you can use a combination of font-size and line-height to force it to go larger, but obviously only in the situations where you need the font larger too

edit:

Example -> http://www.bse.co.nz EDIT: (this link is no longer relevant)

the select next to the big search box has the following css rules:

#navigation #search .locationDrop {
    font-size:2em;
    line-height:27px;
    display:block;
    float:left;
    height:27px;
    width:200px;
}

What does this symbol mean in IntelliJ? (red circle on bottom-left corner of file name, with 'J' in it)

Actually this can happens because of two reason.

  1. Your project not getting/ Updating your dependencies. Go to your terminal and enter mvn clean install. Or right click on pom.xml and click Add as Mevan Project.

  2. Check your jdk has set properly to the project.

Need to ZIP an entire directory using Node.js

Adm-zip has problems just compressing an existing archive https://github.com/cthackers/adm-zip/issues/64 as well as corruption with compressing binary files.

I've also ran into compression corruption issues with node-zip https://github.com/daraosn/node-zip/issues/4

node-archiver is the only one that seems to work well to compress but it doesn't have any uncompress functionality.

How to programmatically set the SSLContext of a JAX-WS client?

This is how I solved it based on this post with some minor tweaks. This solution does not require creation of any additional classes.

SSLContext sc = SSLContext.getInstance("SSLv3");

KeyManagerFactory kmf =
    KeyManagerFactory.getInstance( KeyManagerFactory.getDefaultAlgorithm() );

KeyStore ks = KeyStore.getInstance( KeyStore.getDefaultType() );
ks.load(new FileInputStream( certPath ), certPasswd.toCharArray() );

kmf.init( ks, certPasswd.toCharArray() );

sc.init( kmf.getKeyManagers(), null, null );

((BindingProvider) webservicePort).getRequestContext()
    .put(
        "com.sun.xml.internal.ws.transport.https.client.SSLSocketFactory",
        sc.getSocketFactory() );

How to convert std::string to LPCSTR?

The easiest way to convert a std::string to a LPWSTR is in my opinion:

  1. Convert the std::string to a std::vector<wchar_t>
  2. Take the address of the first wchar_t in the vector.

std::vector<wchar_t> has a templated ctor which will take two iterators, such as the std::string.begin() and .end() iterators. This will convert each char to a wchar_t, though. That's only valid if the std::string contains ASCII or Latin-1, due to the way Unicode values resemble Latin-1 values. If it contains CP1252 or characters from any other encoding, it's more complicated. You'll then need to convert the characters.

Create PDF with Java

Following are few libraries to create PDF with Java:

  1. iText
  2. Apache PDFBox
  3. BFO

I have used iText for genarating PDF's with a little bit of pain in the past.

Or you can try using FOP: FOP is an XSL formatter written in Java. It is used in conjunction with an XSLT transformation engine to format XML documents into PDF.

Including JavaScript class definition from another file in Node.js

I just want to point out that most of the answers here don't work, I am new to NodeJS and IDK if throughout time the "module.exports.yourClass" method changed, or if people just entered the wrong answer.

// MyClass

module.exports.Ninja = class Ninja{
    test(){
        console.log('TESTING 1... 2... 3...');
    };
}
//Using MyClass in seprate File


const ninjaFw = require('./NinjaFw');

let ninja = new ninjaFw.Ninja();
ninja.test();

  • This is the method I am currently using. I like this syntax, becuase module.exports sits on the same line as the class declaration and that cleans the code up a little imo. The other way you can do it is like this:
//  Ninja Framework File


class Ninja{
    test(){
        console.log('TESTING 1... 2... 3...');
    };
}


module.exports.Ninja = Ninja;

  • Two different syntax but, in the end, the same result. Just a matter of syntax anesthetics.

CSS Circle with border

_x000D_
_x000D_
.circle {_x000D_
    background-color:#fff;_x000D_
    border:1px solid red;    _x000D_
    height:100px;_x000D_
    border-radius:50%;_x000D_
    -moz-border-radius:50%;_x000D_
    -webkit-border-radius:50%;_x000D_
    width:100px;_x000D_
}
_x000D_
<div class="circle"></div>
_x000D_
_x000D_
_x000D_

getDate with Jquery Datepicker

Instead of parsing day, month and year you can specify date formats directly using datepicker's formatDate function. In my example I am using "yy-mm-dd", but you can use any format of your choice.

$("#datepicker").datepicker({
    dateFormat: 'yy-mm-dd',
    inline: true,
    minDate: new Date(2010, 1 - 1, 1),
    maxDate: new Date(2010, 12 - 1, 31),
    altField: '#datepicker_value',
    onSelect: function(){
        var fullDate = $.datepicker.formatDate("yy-mm-dd", $(this).datepicker('getDate'));
        var str_output = "<h1><center><img src=\"/images/a" + fullDate +".png\"></center></h1><br/><br>";
        $('#page_output').html(str_output);
    }
});

Set margins in a LinearLayout programmatically

Here a single line Solution:

((LinearLayout.LayoutParams) yourLinearLayout.getLayoutParams()).marginToAdd = ((int)(Resources.getSystem().getDisplayMetrics().density * yourDPValue));

Setting graph figure size

Write it as a one-liner:

figure('position', [0, 0, 200, 500])  % create new figure with specified size  

enter image description here

How to set entire application in portrait mode only?

You can do this for your entire application without having to make all your activities extend a common base class.

The trick is first to make sure you include an Application subclass in your project. In its onCreate(), called when your app first starts up, you register an ActivityLifecycleCallbacks object (API level 14+) to receive notifications of activity lifecycle events.

This gives you the opportunity to execute your own code whenever any activity in your app is started (or stopped, or resumed, or whatever). At this point you can call setRequestedOrientation() on the newly created activity.

class MyApp extends Application {

    @Override
    public void onCreate() {
        super.onCreate();  

        // register to be informed of activities starting up
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {

            @Override
            public void onActivityCreated(Activity activity, 
                                          Bundle savedInstanceState) {

                // new activity created; force its orientation to portrait
                activity.setRequestedOrientation(
                    ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

            }

            ....

        });

    }
}

Why can't I enter a string in Scanner(System.in), when calling nextLine()-method?

Scanner's buffer full when we take a input string through scan.nextLine(); so it skips the input next time . So solution is that we can create a new object of Scanner , the name of the object can be same as previous object......

Could not establish trust relationship for SSL/TLS secure channel -- SOAP

The very simple "catch all" solution is this:

System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

The solution from sebastian-castaldi is a bit more detailed.

CSS vertical-align: text-bottom;

if your text doesn't spill over two rows then you can do line-height: ; in your CSS, the more line-height you give, the lower on the container it will hold.

Java: Check if command line arguments are null

If you don't pass any argument then even in that case args gets initialized but without any item/element. Try the following one, you will get the same effect:

 
public static void main(String[] args) throws InterruptedException {
        String [] dummy= new String [] {};
        if(dummy[0] == null)
        {
            System.out.println("Proper Usage is: java program filename");
            System.exit(0);
        }

    }

Parse XML using JavaScript

The following will parse an XML string into an XML document in all major browsers, including Internet Explorer 6. Once you have that, you can use the usual DOM traversal methods/properties such as childNodes and getElementsByTagName() to get the nodes you want.

var parseXml;
if (typeof window.DOMParser != "undefined") {
    parseXml = function(xmlStr) {
        return ( new window.DOMParser() ).parseFromString(xmlStr, "text/xml");
    };
} else if (typeof window.ActiveXObject != "undefined" &&
       new window.ActiveXObject("Microsoft.XMLDOM")) {
    parseXml = function(xmlStr) {
        var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = "false";
        xmlDoc.loadXML(xmlStr);
        return xmlDoc;
    };
} else {
    throw new Error("No XML parser found");
}

Example usage:

var xml = parseXml("<foo>Stuff</foo>");
alert(xml.documentElement.nodeName);

Which I got from https://stackoverflow.com/a/8412989/1232175.

How to force deletion of a python object?

In general, to make sure something happens no matter what, you use

from exceptions import NameError

try:
    f = open(x)
except ErrorType as e:
    pass # handle the error
finally:
    try:
        f.close()
    except NameError: pass

finally blocks will be run whether or not there is an error in the try block, and whether or not there is an error in any error handling that takes place in except blocks. If you don't handle an exception that is raised, it will still be raised after the finally block is excecuted.

The general way to make sure a file is closed is to use a "context manager".

http://docs.python.org/reference/datamodel.html#context-managers

with open(x) as f:
    # do stuff

This will automatically close f.

For your question #2, bar gets closed on immediately when it's reference count reaches zero, so on del foo if there are no other references.

Objects are NOT created by __init__, they're created by __new__.

http://docs.python.org/reference/datamodel.html#object.new

When you do foo = Foo() two things are actually happening, first a new object is being created, __new__, then it is being initialized, __init__. So there is no way you could possibly call del foo before both those steps have taken place. However, if there is an error in __init__, __del__ will still be called because the object was actually already created in __new__.

Edit: Corrected when deletion happens if a reference count decreases to zero.

"document.getElementByClass is not a function"

I tried

Document.getElementsByClassName('option0')

Which resulted in the error: Uncaught TypeError: Document.getElementsByClass is not a function

After that I tried:

document.getElementsByClassName('option0')

And it works!

"Object doesn't support this property or method" error in IE11

This unfortunately breaks other things. Here is the fix I found on another site that seemed to work for me:

I'd say leave the X-UA-Compatible as "IE=8" and add the following code to the bottom of your master page:

<script language="javascript">
    /* IE11 Fix for SP2010 */
    if (typeof(UserAgentInfo) != 'undefined' && !window.addEventListener) 
    {
        UserAgentInfo.strBrowser=1; 
    } 
</script>

This fixes a bug in core.js which incorrectly calculates that sets UserAgentInfo.strBrowse=3 for IE11 and thus supporting addEventListener. I'm not entirely sure on the details other than that but the combination of keeping IE=8 and using this script is working for me. Fingers crossed until I find the next IE11/SharePoint "bug"!

Export DataTable to Excel with Open Xml SDK in c#

You can have a look at my library here. Under the documentation section, you will find how to import a data table.

You just have to write

using (var doc = new SpreadsheetDocument(@"C:\OpenXmlPackaging.xlsx")) {
    Worksheet sheet1 = doc.Worksheets.Add("My Sheet");
    sheet1.ImportDataTable(ds.Tables[0], "A1", true);
}

Hope it helps!

How to open existing project in Eclipse

Try File > New > Project... > Android Project From Existing Code. Don't copy your project from pc into workspace, copy it elsewhere and let the eclipse copy it into workspace by menu commands above and checking copy in existing workspace.

Checking for an empty field with MySQL

check this code for the problem:

$sql = "SELECT * FROM tablename WHERE condition";

$res = mysql_query($sql);

while ($row = mysql_fetch_assoc($res)) {

    foreach($row as $key => $field) {  

        echo "<br>";

        if(empty($row[$key])){

            echo $key." : empty field :"."<br>"; 

        }else{

        echo $key." =" . $field."<br>";     

        }
    }
}

Only detect click event on pseudo-element

My answer will work for anyone wanting to click a definitive area of the page. This worked for me on my absolutely-positioned :after

Thanks to this article, I realized (with jQuery) I can use e.pageY and e.pageX instead of worrying about e.offsetY/X and e.clientY/X issue between browsers.

Through my trial and error, I started to use the clientX and clientY mouse coordinates in the jQuery event object. These coordinates gave me the X and Y offset of the mouse relative to the top-left corner of the browser's view port. As I was reading the jQuery 1.4 Reference Guide by Karl Swedberg and Jonathan Chaffer, however, I saw that they often referred to the pageX and pageY coordinates. After checking the updated jQuery documentation, I saw that these were the coordinates standardized by jQuery; and, I saw that they gave me the X and Y offset of the mouse relative to the entire document (not just the view port).

I liked this event.pageY idea because it would always be the same, as it was relative to the document. I can compare it to my :after's parent element using offset(), which returns its X and Y also relative to the document.

Therefore, I can come up with a range of "clickable" region on the entire page that never changes.


Here's my demo on codepen.


or if too lazy for codepen, here's the JS:

* I only cared about the Y values for my example.

var box = $('.box');
// clickable range - never changes
var max = box.offset().top + box.outerHeight();
var min = max - 30; // 30 is the height of the :after

var checkRange = function(y) {
  return (y >= min && y <= max);
}

box.click(function(e){
  if ( checkRange(e.pageY) ) {
    // do click action
    box.toggleClass('toggle');
  }
});

How to programmatically set style attribute in a view

At runtime, you know what style you want your button to have. So beforehand, in xml in the layout folder, you can have all ready to go buttons with the styles you need. So in the layout folder, you might have a file named: button_style_1.xml. The contents of that file might look like:

<?xml version="1.0" encoding="utf-8"?>
<Button
    android:id="@+id/styleOneButton"
    style="@style/FirstStyle" />

If you are working with fragments, then in onCreateView you inflate that button, like:

Button firstStyleBtn = (Button) inflater.inflate(R.layout.button_style_1, container, false);

where container is the ViewGroup container associated with the onCreateView method you override when creating your fragment.

Need two more such buttons? You create them like this:

Button secondFirstStyleBtn = (Button) inflater.inflate(R.layout.button_style_1, container, false);
Button thirdFirstStyleBtn = (Button) inflater.inflate(R.layout.button_style_1, container, false);

You can customize those buttons:

secondFirstStyleBtn.setText("My Second");
thirdFirstStyleBtn.setText("My Third");

Then you add your customized, stylized buttons to the layout container you also inflated in the onCreateView method:

_stylizedButtonsContainer = (LinearLayout) rootView.findViewById(R.id.stylizedButtonsContainer);

_stylizedButtonsContainer.addView(firstStyleBtn);
_stylizedButtonsContainer.addView(secondFirstStyleBtn);
_stylizedButtonsContainer.addView(thirdFirstStyleBtn);

And that's how you can dynamically work with stylized buttons.

How to generate the "create table" sql statement for an existing table in postgreSQL

If you want to do this for various tables at once, you meed to use the -t switch multiple times (took me a while to figure out why comma separated list wasn't working). Also, can be useful to send results to an outfile or pipe to a postgres server on another machine

pg_dump -t table1 -t table2 database_name --schema-only > dump.sql

pg_dump -t table1 -t table2 database_name --schema-only | psql -h server_name database_name

Visual Studio 2008 Product Key in Registry?

I found the product key for Visual Studio 2008 Professional under a slightly different key:

HKLM\SOFTWARE\Wow6432Node\Microsoft\MSDN\8.0\Registration\PIDKEY

it was listed without the dashes as stated above.

How can I divide one column of a data frame through another?

Hadley Wickham

dplyr

packages is always a saver in case of data wrangling. To add the desired division as a third variable I would use mutate()

d <- mutate(d, new = min / count2.freq)

JSONDecodeError: Expecting value: line 1 column 1 (char 0)

There may be embedded 0's, even after calling decode(). Use replace():

import json
struct = {}
try:
    response_json = response_json.decode('utf-8').replace('\0', '')
    struct = json.loads(response_json)
except:
    print('bad json: ', response_json)
return struct

How can I add a PHP page to WordPress?

You can name your file "newpage.php" - put it in your theme directory in wp-content. You can make it a page template (see http://codex.wordpress.org/Pages...) or you can include it in one of the PHP files in your theme, such as header.php or single.php.

Even better, create a child theme and put it in there, so you leave your theme code alone, and it's easier to update.

http://codex.wordpress.org/Pages#Creating_Your_Own_Page_Templates

Java reflection: how to get field value from an object, not knowing its class

public abstract class Refl {
    /** Use: Refl.<TargetClass>get(myObject,"x.y[0].z"); */
    public static<T> T get(Object obj, String fieldPath) {
        return (T) getValue(obj, fieldPath);
    }
    public static Object getValue(Object obj, String fieldPath) {
        String[] fieldNames = fieldPath.split("[\\.\\[\\]]");
        String success = "";
        Object res = obj;
        for (String fieldName : fieldNames) {
            if (fieldName.isEmpty()) continue;
            int index = toIndex(fieldName);
            if (index >= 0) {
                try {
                    res = ((Object[])res)[index];
                } catch (ClassCastException cce) {
                    throw new RuntimeException("cannot cast "+res.getClass()+" object "+res+" to array, path:"+success, cce);
                } catch (IndexOutOfBoundsException iobe) {
                    throw new RuntimeException("bad index "+index+", array size "+((Object[])res).length +" object "+res +", path:"+success, iobe);
                }
            } else {
                Field field = getField(res.getClass(), fieldName);
                field.setAccessible(true);
                try {
                    res = field.get(res);
                } catch (Exception ee) {
                    throw new RuntimeException("cannot get value of ["+fieldName+"] from "+res.getClass()+" object "+res +", path:"+success, ee);
                }
            }
            success += fieldName + ".";
        }
        return res;
    }

    public static Field getField(Class<?> clazz, String fieldName) {
        Class<?> tmpClass = clazz;
        do {
            try {
                Field f = tmpClass.getDeclaredField(fieldName);
                return f;
            } catch (NoSuchFieldException e) {
                tmpClass = tmpClass.getSuperclass();
            }
        } while (tmpClass != null);

        throw new RuntimeException("Field '" + fieldName + "' not found in class " + clazz);
    }

    private static int toIndex(String s) {
        int res = -1;
        if (s != null && s.length() > 0 && Character.isDigit(s.charAt(0))) {
            try {
                res = Integer.parseInt(s);
                if (res < 0) {
                    res = -1;
                }
            } catch (Throwable t) {
                res = -1;
            }
        }
        return res;
    }
}

It supports fetching fields and array items, e.g.:

System.out.println(""+Refl.getValue(b,"x.q[0].z.y"));

there is no difference between dots and braces, they are just delimiters, and empty field names are ignored:

System.out.println(""+Refl.getValue(b,"x.q[0].z.y[value]"));
System.out.println(""+Refl.getValue(b,"x.q.1.y.z.value"));
System.out.println(""+Refl.getValue(b,"x[q.1]y]z[value"));

CSS Float: Floating an image to the left of the text

_x000D_
_x000D_
.post-container{_x000D_
    margin: 20px 20px 0 0;  _x000D_
    border:5px solid #333;_x000D_
    width:600px;_x000D_
    overflow:hidden;_x000D_
}_x000D_
_x000D_
.post-thumb img {_x000D_
    float: left;_x000D_
    clear:left;_x000D_
    width:50px;_x000D_
    height:50px;_x000D_
    border:1px solid red;_x000D_
}_x000D_
_x000D_
.post-title {_x000D_
     float:left;   _x000D_
    margin-left:10px;_x000D_
}_x000D_
_x000D_
.post-content {_x000D_
    float:right;_x000D_
}
_x000D_
<div class="post-container">                _x000D_
   <div class="post-thumb"><img src="thumb.jpg" /></div>_x000D_
   <div class="post-title">Post title</div>_x000D_
   <div class="post-content"><p>post description description description etc etc etc</p></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

jsFiddle

PHP check if file is an image

The getimagesize() should be the most definite way of working out whether the file is an image:

if(@is_array(getimagesize($mediapath))){
    $image = true;
} else {
    $image = false;
}

because this is a sample getimagesize() output:

Array (
[0] => 800
[1] => 450
[2] => 2
[3] => width="800" height="450"
[bits] => 8
[channels] => 3
[mime] => image/jpeg)

What does PermGen actually stand for?

PermGen is used by the JVM to hold loaded classes. You can increase it using:

-XX:MaxPermSize=384m

if you're using the Sun JVM or OpenJDK.

So if you get an OutOfMemoryException: PermGen you need to either make PermGen bigger or you might be having class loader problems.

Is it possible to change the package name of an Android app on Google Play?

No, you cannot change package name unless you're okay with publishing it as a new app in Play Store:

Once you publish your application under its manifest package name, this is the unique identity of the application forever more. Switching to a different name results in an entirely new application, one that can’t be installed as an update to the existing application. Android manual confirms it as well here:

Caution: Once you publish your application, you cannot change the package name. The package name defines your application's identity, so if you change it, then it is considered to be a different application and users of the previous version cannot update to the new version. If you're okay with publishing new version of your app as a completely new entity, you can do it of course - just remove old app from Play Store (if you want) and publish new one, with different package name.