Programs & Examples On #Firebug1.5

Difference between h:button and h:commandButton

<h:button>

The <h:button> generates a HTML <input type="button">. The generated element uses JavaScript to navigate to the page given by the attribute outcome, using a HTTP GET request.

E.g.

<h:button value="GET button" outcome="otherpage" />

will generate

<input type="button" onclick="window.location.href='/contextpath/otherpage.xhtml'; return false;" value="GET button" />

Even though this ends up in a (bookmarkable) URL change in the browser address bar, this is not SEO-friendly. Searchbots won't follow the URL in the onclick. You'd better use a <h:outputLink> or <h:link> if SEO is important on the given URL. You could if necessary throw in some CSS on the generated HTML <a> element to make it to look like a button.

Do note that while you can put an EL expression referring a method in outcome attribute as below,

<h:button value="GET button" outcome="#{bean.getOutcome()}" />

it will not be invoked when you click the button. Instead, it is already invoked when the page containing the button is rendered for the sole purpose to obtain the navigation outcome to be embedded in the generated onclick code. If you ever attempted to use the action method syntax as in outcome="#{bean.action}", you would already be hinted by this mistake/misconception by facing a javax.el.ELException: Could not find property actionMethod in class com.example.Bean.

If you intend to invoke a method as result of a POST request, use <h:commandButton> instead, see below. Or if you intend to invoke a method as result of a GET request, head to Invoke JSF managed bean action on page load or if you also have GET request parameters via <f:param>, How do I process GET query string URL parameters in backing bean on page load?


<h:commandButton>

The <h:commandButton> generates a HTML <input type="submit"> button which submits by default the parent <h:form> using HTTP POST method and invokes the actions attached to action, actionListener and/or <f:ajax listener>, if any. The <h:form> is required.

E.g.

<h:form id="form">
    <h:commandButton id="button" value="POST button" action="otherpage" />
</h:form>

will generate

<form id="form" name="form" method="post" action="/contextpath/currentpage.xhtml" enctype="application/x-www-form-urlencoded">
    <input type="hidden" name="form" value="form" />
    <input type="submit" name="form:button" value="POST button" />
    <input type="hidden" name="javax.faces.ViewState" id="javax.faces.ViewState" value="...." autocomplete="off" />
</form>

Note that it thus submits to the current page (the form action URL will show up in the browser address bar). It will afterwards forward to the target page, without any change in the URL in the browser address bar. You could add ?faces-redirect=true parameter to the outcome value to trigger a redirect after POST (as per the Post-Redirect-Get pattern) so that the target URL becomes bookmarkable.

The <h:commandButton> is usually exclusively used to submit a POST form, not to perform page-to-page navigation. Normally, the action points to some business action, such as saving the form data in DB, which returns a String outcome.

<h:commandButton ... action="#{bean.save}" />

with

public String save() {
    // ...
    return "otherpage";
}

Returning null or void will bring you back to the same view. Returning an empty string also, but it would recreate any view scoped bean. These days, with modern JSF2 and <f:ajax>, more than often actions just return to the same view (thus, null or void) wherein the results are conditionally rendered by ajax.

public void save() {
    // ...
}

See also:

Batch script to delete files

Lets say you saved your software onto your desktop.
if you want to remove an entire folder like an uninstaller program you could use this.

cd C:\Users\User\Detsktop\
rd /s /q SOFTWARE

this will delete the entire folder called software and all of its files and subfolders

Make Sure You Delete The Correct Folder Cause This Does Not Have A Yes / No Option

How to trim a string to N chars in Javascript?

Copying Will's comment into an answer, because I found it useful:

var string = "this is a string";
var length = 20;
var trimmedString = string.length > length ? 
                    string.substring(0, length - 3) + "..." : 
                    string;

Thanks Will.

And a jsfiddle for anyone who cares https://jsfiddle.net/t354gw7e/ :)

How to display a range input slider vertically

Without changing the position to absolute, see below. This supports all recent browsers as well.

_x000D_
_x000D_
.vranger {_x000D_
  margin-top: 50px;_x000D_
   transform: rotate(270deg);_x000D_
  -moz-transform: rotate(270deg); /*do same for other browsers if required*/_x000D_
}
_x000D_
<input type="range" class="vranger"/>
_x000D_
_x000D_
_x000D_

for very old browsers, you can use -sand-transform: rotate(10deg); from CSS sandpaper

or use

prefix selector such as -ms-transform: rotate(270deg); for IE9

Submit button doesn't work

If you are not using any javascript/jquery for form validation, then a simple layout for your form would look like this.

within the body of your html document:

<form action="formHandler.php" name="yourForm" id="theForm" method="post">    
    <input type="text" name="fname" id="fname" />    
    <input type="submit" value="submit"/>
</form>

You need to ensure you have the submit button within the form tags, and an appropriate action assigned. Such as sending to a php file.

For a more direct answer, provide the code you are working with.

You may find the following of use: http://www.w3.org/TR/html401/interact/forms.html

How to add Python to Windows registry

I installed ArcGIS Pro 1.4 and it didn't register the Python 3.5.2 it installed which prevented me from installing any add-ons. I resolved this by using the "reg" command in an Administrator PowerShell session to manually create and populate the necessary registry keys/values (where Python is installed in C:\Python35):

reg add "HKLM\Software\Python\PythonCore\3.5\Help\Main Python Documentation" /reg:64 /ve /t REG_SZ /d "C:\Python35\Doc\Python352.chm"
reg add "HKLM\Software\Python\PythonCore\3.5\InstallPath" /reg:64 /ve /t REG_SZ /d "C:\Python35\"
reg add "HKLM\Software\Python\PythonCore\3.5\InstallPath\InstallGroup" /reg:64 /ve /t REG_SZ /d "Python 3.5"
reg add "HKLM\Software\Python\PythonCore\3.5\PythonPath" /reg:64 /ve /t REG_SZ /d "C:\Python35\Lib;C:\Python35\DLLs;C:\Python35\Lib\lib-tk"

I find this easier than using Registry Editor but that's solely a personal preference.

The same commands can be executed in CMD.EXE session if you prefer; just make sure you run it as Administrator.

List files with certain extensions with ls and grep

ls -R | findstr ".mp3"

ls -R => lists subdirectories recursively

How to delete a cookie?

Some of the other solutions might not work if you created the cookie manually.

Here's a quick way to delete a cookie:

document.cookie = 'COOKIE_NAME=; Max-Age=0; path=/; domain=' + location.host;

How to test an Oracle Stored Procedure with RefCursor return type?

I think this link will be enough for you. I found it when I was searching for the way to execute oracle procedures.

The link to the page

Short Description:

--cursor variable declaration 
variable Out_Ref_Cursor refcursor;
--execute procedure 
execute get_employees_name(IN_Variable,:Out_Ref_Cursor);
--display result referenced by ref cursor.
print Out_Ref_Cursor;

Plotting multiple lines, in different colors, with pandas dataframe

You can use this code to get your desire output

import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'color': ['red','red','red','blue','blue','blue'], 'x': [0,1,2,3,4,5],'y': [0,1,2,9,16,25]})
print df

  color  x   y
0   red  0   0
1   red  1   1
2   red  2   2
3  blue  3   9
4  blue  4  16
5  blue  5  25

To plot graph

a = df.iloc[[i for i in xrange(0,len(df)) if df['x'][i]==df['y'][i]]].plot(x='x',y='y',color = 'red')
df.iloc[[i for i in xrange(0,len(df)) if df['y'][i]== df['x'][i]**2]].plot(x='x',y='y',color = 'blue',ax=a)

plt.show()

Output The output result will look like this

How to pass a vector to a function?

found = binarySearch(first, last, search4, &random);

Notice the &.

Looping through the content of a file in Bash

Suppose you have this file:

$ cat /tmp/test.txt
Line 1
    Line 2 has leading space
Line 3 followed by blank line

Line 5 (follows a blank line) and has trailing space    
Line 6 has no ending CR

There are four elements that will alter the meaning of the file output read by many Bash solutions:

  1. The blank line 4;
  2. Leading or trailing spaces on two lines;
  3. Maintaining the meaning of individual lines (i.e., each line is a record);
  4. The line 6 not terminated with a CR.

If you want the text file line by line including blank lines and terminating lines without CR, you must use a while loop and you must have an alternate test for the final line.

Here are the methods that may change the file (in comparison to what cat returns):

1) Lose the last line and leading and trailing spaces:

$ while read -r p; do printf "%s\n" "'$p'"; done </tmp/test.txt
'Line 1'
'Line 2 has leading space'
'Line 3 followed by blank line'
''
'Line 5 (follows a blank line) and has trailing space'

(If you do while IFS= read -r p; do printf "%s\n" "'$p'"; done </tmp/test.txt instead, you preserve the leading and trailing spaces but still lose the last line if it is not terminated with CR)

2) Using process substitution with cat will reads the entire file in one gulp and loses the meaning of individual lines:

$ for p in "$(cat /tmp/test.txt)"; do printf "%s\n" "'$p'"; done
'Line 1
    Line 2 has leading space
Line 3 followed by blank line

Line 5 (follows a blank line) and has trailing space    
Line 6 has no ending CR'

(If you remove the " from $(cat /tmp/test.txt) you read the file word by word rather than one gulp. Also probably not what is intended...)


The most robust and simplest way to read a file line-by-line and preserve all spacing is:

$ while IFS= read -r line || [[ -n $line ]]; do printf "'%s'\n" "$line"; done </tmp/test.txt
'Line 1'
'    Line 2 has leading space'
'Line 3 followed by blank line'
''
'Line 5 (follows a blank line) and has trailing space    '
'Line 6 has no ending CR'

If you want to strip leading and trading spaces, remove the IFS= part:

$ while read -r line || [[ -n $line ]]; do printf "'%s'\n" "$line"; done </tmp/test.txt
'Line 1'
'Line 2 has leading space'
'Line 3 followed by blank line'
''
'Line 5 (follows a blank line) and has trailing space'
'Line 6 has no ending CR'

(A text file without a terminating \n, while fairly common, is considered broken under POSIX. If you can count on the trailing \n you do not need || [[ -n $line ]] in the while loop.)

More at the BASH FAQ

PHP Fatal error: Call to undefined function json_decode()

The module was install but symbolic link was not in /etc/php5/cli/conf.d

Most efficient way to append arrays in C#?

If you can make an approximation of the number of items that will be there at the end, use the overload of the List constuctor that takes count as a parameter. You will save some expensive List duplications. Otherwise you have to pay for it.

javax.xml.bind.UnmarshalException: unexpected element. Expected elements are (none)

When you generate a JAXB model from an XML Schema, global elements that correspond to named complex types will have that metadata captured as an @XmlElementDecl annotation on a create method in the ObjectFactory class. Since you are creating the JAXBContext on just the DocumentType class this metadata isn't being processed. If you generated your JAXB model from an XML Schema then you should create the JAXBContext on the generated package name or ObjectFactory class to ensure all the necessary metadata is processed.

Example solution:

JAXBContext jaxbContext = JAXBContext.newInstance(my.generatedschema.dir.ObjectFactory.class);
DocumentType documentType = ((JAXBElement<DocumentType>) jaxbContext.createUnmarshaller().unmarshal(inputStream)).getValue();

Displaying unicode symbols in HTML

I think this is a file problem, you simple saved your file in 1-byte encoding like latin-1. Google up your editor and how to set files to utf-8.

I wonder why there are editors that don't default to utf-8.

Spring Data: "delete by" is supported?

2 ways:-

1st one Custom Query

@Modifying
@Query("delete from User where firstName = :firstName")
void deleteUsersByFirstName(@Param("firstName") String firstName);

2nd one JPA Query by method

List<User> deleteByLastname(String lastname);

When you go with query by method (2nd way) it will first do a get call

select * from user where last_name = :firstName

Then it will load it in a List Then it will call delete id one by one

delete from user where id = 18
delete from user where id = 19

First fetch list of object, then for loop to delete id one by one

But, the 1st option (custom query),

It's just a single query It will delete wherever the value exists.

Go through this link too https://www.baeldung.com/spring-data-jpa-deleteby

How to limit the number of dropzone.js files uploaded?

Dropzone.options.dpzSingleFile = {
    paramName: "file", // The name that will be used to transfer the file
    maxFiles: 1,
    init: function() {
        this.on("maxfilesexceeded", function(file) {
            this.removeAllFiles();
            this.addFile(file);
        });
    }
};

Hidden Features of Xcode

  • To "set next statement", just drag the red instruction pointer to the next line to execute. (source)

How to get only numeric column values?

SELECT column1 FROM table WHERE column1 not like '%[0-9]%'

Removing the '^' did it for me. I'm looking at a varchar field and when I included the ^ it excluded all of my non-numerics which is exactly what I didn't want. So, by removing ^ I only got non-numeric values back.

How do you use Intent.FLAG_ACTIVITY_CLEAR_TOP to clear the Activity Stack?

Though this question already has sufficient answers, I thought somebody would want to know why this flag works in this peculiar manner, This is what I found in Android documentation

The currently running instance of activity B in the above example will either receive the new intent you are starting here in its onNewIntent() method, or be itself finished and restarted with the new intent.

If it has declared its launch mode to be "multiple" (the default) and you have not set FLAG_ACTIVITY_SINGLE_TOP in the same intent, then it will be finished and re-created; for all other launch modes or if FLAG_ACTIVITY_SINGLE_TOP is set then this Intent will be delivered to the current instance's onNewIntent().


So, Either,
1. Change the launchMode of the Activity A to something else from standard (ie. singleTask or something). Then your flag FLAG_ACTIVITY_CLEAR_TOP will not restart your Activity A.

or,

2. Use Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP as your flag. Then it will work the way you desire.

How to generate a number of most distinctive colors in R?

You can also try the randomcoloR package:

library(randomcoloR)
n <- 20
palette <- distinctColorPalette(n)

You can see that a set of highly distinct colors are chosen when visualizing in a pie chart (as suggested by other answers here):

pie(rep(1, n), col=palette)

enter image description here

Shown in a pie chart with 50 colors:

n <- 50
palette <- distinctColorPalette(n)
pie(rep(1, n), col=palette)

enter image description here

MongoDB: How to find the exact version of installed MongoDB

Sometimes you need to see version of mongodb after making a connection from your project/application/code. In this case you can follow like this:

 mongoose.connect(
    encodeURI(DB_URL), {
      keepAlive: true
    },
    (err) => {
      if (err) {
        console.log(err)
      }else{
           const con = new mongoose.mongo.Admin(mongoose.connection.db)
              con.buildInfo( (err, db) => {
              if(err){
                throw err
              }
             // see the db version
             console.log(db.version)
            })
      }
    }
  )

Hope this will be helpful for someone.

Change label text using JavaScript

Using .innerText should work.

document.getElementById('lbltipAddedComment').innerText = 'your tip has been submitted!';

Linq Select Group By

This will give you sequence of anonymous objects, containing date string and two properties with average price:

var query = from p in PriceLogList
            group p by p.LogDateTime.ToString("MMM yyyy") into g
            select new { 
               LogDate = g.Key,
               AvgGoldPrice = (int)g.Average(x => x.GoldPrice), 
               AvgSilverPrice = (int)g.Average(x => x.SilverPrice)
            };

If you need to get list of PriceLog objects:

var query = from p in PriceLogList
            group p by p.LogDateTime.ToString("MMM yyyy") into g
            select new PriceLog { 
               LogDateTime = DateTime.Parse(g.Key),
               GoldPrice = (int)g.Average(x => x.GoldPrice), 
               SilverPrice = (int)g.Average(x => x.SilverPrice)
            };

Regex Explanation ^.*$

  • ^ matches position just before the first character of the string
  • $ matches position just after the last character of the string
  • . matches a single character. Does not matter what character it is, except newline
  • * matches preceding match zero or more times

So, ^.*$ means - match, from beginning to end, any character that appears zero or more times. Basically, that means - match everything from start to end of the string. This regex pattern is not very useful.

Let's take a regex pattern that may be a bit useful. Let's say I have two strings The bat of Matt Jones and Matthew's last name is Jones. The pattern ^Matt.*Jones$ will match Matthew's last name is Jones. Why? The pattern says - the string should start with Matt and end with Jones and there can be zero or more characters (any characters) in between them.

Feel free to use an online tool like https://regex101.com/ to test out regex patterns and strings.

Multiline for WPF TextBox

Also, if, like me, you add controls directly in XAML (not using the editor), you might get frustrated that it won't stretch to the available height, even after setting those two properties.

To make the TextBox stretch, set the Height="Auto".

UPDATE:

In retrospect, I think this must have been necessary thanks to a default style for TextBoxes specifying the height to some standard for the application somewhere in the App resources. It may be worthwhile checking this if this helped you.

Hibernate - A collection with cascade=”all-delete-orphan” was no longer referenced by the owning entity instance

I ran into this when updating an entity with a JSON post request. The error occurred when I updated the entity without data about the children, even when there were none. Adding

"children": [],

to the request body solved the problem.

jQuery .css("margin-top", value) not updating in IE 8 (Standards mode)

The correct format for IE8 is:

  $("#ActionBox").css({ 'margin-top': '10px' });  

with this work.

React Native add bold or italics to single words in <Text> field

You could just nest the Text components with the required style. The style will be applied along with already defined style in the first Text component.

Example:

 <Text style={styles.paragraph}>
   Trouble singing in. <Text style={{fontWeight: "bold"}}> Resolve</Text>
 </Text>

How to run a shell script on a Unix console or Mac terminal?

If you want the script to run in the current shell (e.g. you want it to be able to affect your directory or environment) you should say:

. /path/to/script.sh

or

source /path/to/script.sh

Note that /path/to/script.sh can be relative, for instance . bin/script.sh runs the script.sh in the bin directory under the current directory.

Reading Excel files from C#

Late to the party, but I'm a fan of LinqToExcel

JavaScript string encryption and decryption?

Use SimpleCrypto

Using encrypt() and decrypt()

To use SimpleCrypto, first create a SimpleCrypto instance with a secret key (password). Secret key parameter MUST be defined when creating a SimpleCrypto instance.

To encrypt and decrypt data, simply use encrypt() and decrypt() function from an instance. This will use AES-CBC encryption algorithm.

var _secretKey = "some-unique-key";

var simpleCrypto = new SimpleCrypto(_secretKey);

var plainText = "Hello World!";
var chiperText = simpleCrypto.encrypt(plainText);
console.log("Encryption process...");
console.log("Plain Text    : " + plainText);
console.log("Cipher Text   : " + cipherText);
var decipherText = simpleCrypto.decrypt(cipherText);
console.log("... and then decryption...");
console.log("Decipher Text : " + decipherText);
console.log("... done.");

Webpack "OTS parsing error" loading fonts

TL;DR Use absolute paths to your assets (including your complete hostname) by setting your output.publicPath to e.g. "http://example.com/assets/".

The problem

The problem is the way that URLs are resolved by Chrome when they're parsed from a dynamically loaded CSS blob.

When you load the page, the browser loads your Webpack bundle entry JavaScript file, which (when you're using the style-loader) also contains a Base64 encoded copy of your CSS, which gets loaded into the page.

Screenshot of embedded CSS in Chrome DevTools This is what it looks like in Chrome DevTools

That's fine for all the images or fonts which are encoded into the CSS as data URIs (i.e. the content of the file is embedded in the CSS), but for assets referenced by URL, the browser has to find and fetch the file.

Now by default the file-loader (which url-loader delegates to for large files) will use relative URLs to reference assets - and that's the problem!

Relative URLs generated by Webpack These are the URLs generated by file-loader by default - relative URLs

When you use relative URLs, Chrome will resolve them relative to the containing CSS file. Ordinarily that's fine, but in this case the containing file is at blob://... and any relative URLs are referenced the same way. The end result is that Chrome attempts to load them from the parent HTML file, and ends up trying to parse the HTML file as the content of the font, which obviously won't work.

The Solution

Force the file-loader to use absolute paths including the protocol ("http" or "https").

Change your webpack config to include something equivalent to:

{
  output: {
    publicPath: "http://localhost:8080/", // Development Server
    // publicPath: "http://example.com/", // Production Server
  }
}

Now the URLs that it generates will look like this:

enter image description here Absolute URLs!

These URLs will be correctly parsed by Chrome and every other browser.

Using extract-text-webpack-plugin

It's worth noting that if you're extracting your CSS to a separate file, you won't have this problem because your CSS will be in a proper file and URLs will be correctly resolved.

How do I print the key-value pairs of a dictionary in python

A little intro to dictionary

d={'a':'apple','b':'ball'}
d.keys()  # displays all keys in list
['a','b']
d.values() # displays your values in list
['apple','ball']
d.items() # displays your pair tuple of key and value
[('a','apple'),('b','ball')

Print keys,values method one

for x in d.keys():
    print x +" => " + d[x]

Another method

for key,value in d.items():
    print key + " => " + value

You can get keys using iter

>>> list(iter(d))
['a', 'b']

You can get value of key of dictionary using get(key, [value]):

d.get('a')
'apple'

If key is not present in dictionary,when default value given, will return value.

d.get('c', 'Cat')
'Cat'

Pie chart with jQuery

A few others that have not been mentioned:

For mini pies, lines and bars, Peity is brilliant, simple, tiny, fast, uses really elegant markup.

I'm not sure of it's relationship with Flot (given its name), but Flotr2 is pretty good, certainly does better pies than Flot.

Bluff produces nice-looking line graphs, but I had a bit of trouble with its pies.

Not what I was after, but another commercial product (much like Highcharts) is TeeChart.

Convert generic list to dataset in C#

You could create an extension method to add all property values through reflection:

public static DataSet ToDataSet<T>(this IList<T> list)
{
    Type elementType = typeof(T);
    DataSet ds = new DataSet();
    DataTable t = new DataTable();
    ds.Tables.Add(t);

    //add a column to table for each public property on T
    foreach(var propInfo in elementType.GetProperties())
    {
        t.Columns.Add(propInfo.Name, propInfo.PropertyType);
    }

    //go through each property on T and add each value to the table
    foreach(T item in list)
    {
        DataRow row = t.NewRow();
        foreach(var propInfo in elementType.GetProperties())
        {
            row[propInfo.Name] = propInfo.GetValue(item, null);
        }
    }

    return ds;
}

Finding second occurrence of a substring in a string in Java

I hope I'm not late to the party.. Here is my answer. I like using Pattern/Matcher because it uses regex which should be more efficient. Yet, I think this answer could be enhanced:

    Matcher matcher = Pattern.compile("is").matcher("I think there is a smarter solution, isn't there?");
    int numOfOcurrences = 2;
    for(int i = 0; i < numOfOcurrences; i++) matcher.find();
    System.out.println("Index: " + matcher.start());

How to convert JSON string to array

this my solution: json string $columns_validation = string(1736) "[{"colId":"N_ni","hide":true,"aggFunc":null,"width":136,"pivotIndex":null,"pinned":null,"rowGroupIndex":null},{"colId":"J_2_fait","hide":true,"aggFunc":null,"width":67,"pivotIndex":null,"pinned":null,"rowGroupIndex":null}]"

so i use json_decode twice like that :

$js_column_validation = json_decode($columns_validation);
$js_column_validation = json_decode($js_column_validation); 

var_dump($js_column_validation);

and the result is :

 array(15) { [0]=> object(stdClass)#23 (7) { ["colId"]=> string(4) "N_ni" ["hide"]=> bool(true) ["aggFunc"]=> NULL ["width"]=> int(136) ["pivotIndex"]=> NULL ["pinned"]=> NULL ["rowGroupIndex"]=> NULL } [1]=> object(stdClass)#2130 (7) { ["colId"]=> string(8) "J_2_fait" ["hide"]=> bool(true) ["aggFunc"]=> NULL ["width"]=> int(67) ["pivotIndex"]=> NULL ["pinned"]=> NULL ["rowGroupIndex"]=> NULL }

Formula to determine brightness of RGB color

Below is the only CORRECT algorithm for converting sRGB images, as used in browsers etc., to grayscale.

It is necessary to apply an inverse of the gamma function for the color space before calculating the inner product. Then you apply the gamma function to the reduced value. Failure to incorporate the gamma function can result in errors of up to 20%.

For typical computer stuff, the color space is sRGB. The right numbers for sRGB are approx. 0.21, 0.72, 0.07. Gamma for sRGB is a composite function that approximates exponentiation by 1/(2.2). Here is the whole thing in C++.

// sRGB luminance(Y) values
const double rY = 0.212655;
const double gY = 0.715158;
const double bY = 0.072187;

// Inverse of sRGB "gamma" function. (approx 2.2)
double inv_gam_sRGB(int ic) {
    double c = ic/255.0;
    if ( c <= 0.04045 )
        return c/12.92;
    else 
        return pow(((c+0.055)/(1.055)),2.4);
}

// sRGB "gamma" function (approx 2.2)
int gam_sRGB(double v) {
    if(v<=0.0031308)
        v *= 12.92;
    else 
        v = 1.055*pow(v,1.0/2.4)-0.055;
    return int(v*255+0.5); // This is correct in C++. Other languages may not
                           // require +0.5
}

// GRAY VALUE ("brightness")
int gray(int r, int g, int b) {
    return gam_sRGB(
            rY*inv_gam_sRGB(r) +
            gY*inv_gam_sRGB(g) +
            bY*inv_gam_sRGB(b)
    );
}

How does it work - requestLocationUpdates() + LocationRequest/Listener

I use this one:

LocationManager.requestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener)

For example, using a 1s interval:

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,0,this);

the time is in milliseconds, the distance is in meters.

This automatically calls:

public void onLocationChanged(Location location) {
    //Code here, location.getAccuracy(), location.getLongitude() etc...
}

I also had these included in the script but didnt actually use them:

public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}

In short:

public class GPSClass implements LocationListener {

    public void onLocationChanged(Location location) {
        // Called when a new location is found by the network location provider.
        Log.i("Message: ","Location changed, " + location.getAccuracy() + " , " + location.getLatitude()+ "," + location.getLongitude());
    }

    public void onStatusChanged(String provider, int status, Bundle extras) {}
    public void onProviderEnabled(String provider) {}
    public void onProviderDisabled(String provider) {}

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,0,this);
    }
}

What is the best way to connect and use a sqlite database from C#

Mono comes with a wrapper, use theirs!

https://github.com/mono/mono/tree/master/mcs/class/Mono.Data.Sqlite/Mono.Data.Sqlite_2.0 gives code to wrap the actual SQLite dll ( http://www.sqlite.org/sqlite-shell-win32-x86-3071300.zip found on the download page http://www.sqlite.org/download.html/ ) in a .net friendly way. It works on Linux or Windows.

This seems the thinnest of all worlds, minimizing your dependence on third party libraries. If I had to do this project from scratch, this is the way I would do it.

Live video streaming using Java?

JMF was abandoned. VLC is more up to date and it reads everything. https://stackoverflow.com/a/5160010

I think vlc beats every other software out there yet, or at least the ones that I know...

What does the 'u' symbol mean in front of string values?

The 'u' in front of the string values means the string is a Unicode string. Unicode is a way to represent more characters than normal ASCII can manage. The fact that you're seeing the u means you're on Python 2 - strings are Unicode by default on Python 3, but on Python 2, the u in front distinguishes Unicode strings. The rest of this answer will focus on Python 2.

You can create a Unicode string multiple ways:

>>> u'foo'
u'foo'
>>> unicode('foo') # Python 2 only
u'foo'

But the real reason is to represent something like this (translation here):

>>> val = u'???????????? ? ?????????????'
>>> val
u'\u041e\u0437\u043d\u0430\u043a\u043e\u043c\u044c\u0442\u0435\u0441\u044c \u0441 \u0434\u043e\u043a\u0443\u043c\u0435\u043d\u0442\u0430\u0446\u0438\u0435\u0439'
>>> print val
???????????? ? ?????????????

For the most part, Unicode and non-Unicode strings are interoperable on Python 2.

There are other symbols you will see, such as the "raw" symbol r for telling a string not to interpret backslashes. This is extremely useful for writing regular expressions.

>>> 'foo\"'
'foo"'
>>> r'foo\"'
'foo\\"'

Unicode and non-Unicode strings can be equal on Python 2:

>>> bird1 = unicode('unladen swallow')
>>> bird2 = 'unladen swallow'
>>> bird1 == bird2
True

but not on Python 3:

>>> x = u'asdf' # Python 3
>>> y = b'asdf' # b indicates bytestring
>>> x == y
False

Kotlin: How to get and set a text to TextView in Android using Kotlin?

findViewById(R.id.android_text) does not need typecasting.

Laravel 5 PDOException Could Not Find Driver

Same thing happend to me after upgrading distro.

Running sudo apt-get install php7.0-mysql fixed it for me.

Reading a registry key in C#

string InstallPath = (string)Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\MyApplication\AppPath", "Installed", null);    
if (InstallPath != null)
{
    // Do stuff
}

That code should get your value. You'll need to be

using Microsoft.Win32;

for that to work though.

Suppress/ print without b' prefix for bytes in Python 3

If the bytes use an appropriate character encoding already; you could print them directly:

sys.stdout.buffer.write(data)

or

nwritten = os.write(sys.stdout.fileno(), data)  # NOTE: it may write less than len(data) bytes

<select> HTML element with height

I've used a few CSS hacks and targeted Chrome/Safari/Firefox/IE individually, as each browser renders selects a bit differently. I've tested on all browsers except IE.

For Safari/Chrome, set the height and line-height you want for your <select />.

For Firefox, we're going to kill Firefox's default padding and border, then set our own. Set padding to whatever you like.

For IE 8+, just like Chrome, we've set the height and line-height properties. These two media queries can be combined. But I kept it separate for demo purposes. So you can see what I'm doing.

Please note, for the height/line-height property to work in Chrome/Safari OSX, you must set the background to a custom value. I changed the color in my example.

Here's a jsFiddle of the below: http://jsfiddle.net/URgCB/4/

For the non-hack route, why not use a custom select plug-in via jQuery? Check out this: http://codepen.io/wallaceerick/pen/ctsCz

HTML:

<select>
    <option>Here's one option</option>
    <option>here's another option</option>
</select>

CSS:

@media screen and (-webkit-min-device-pixel-ratio:0) {  /*safari and chrome*/
    select {
        height:30px;
        line-height:30px;
        background:#f4f4f4;
    } 
}
select::-moz-focus-inner { /*Remove button padding in FF*/ 
    border: 0;
    padding: 0;
}
@-moz-document url-prefix() { /* targets Firefox only */
    select {
        padding: 15px 0!important;
    }
}        
@media screen\0 { /* IE Hacks: targets IE 8, 9 and 10 */        
    select {
        height:30px;
        line-height:30px;
    }     
}

How to get height of entire document with JavaScript?

You can even use this:

var B = document.body,
    H = document.documentElement,
    height

if (typeof document.height !== 'undefined') {
    height = document.height // For webkit browsers
} else {
    height = Math.max( B.scrollHeight, B.offsetHeight,H.clientHeight, H.scrollHeight, H.offsetHeight );
}

or in a more jQuery way (since as you said jQuery doesn't lie) :)

Math.max($(document).height(), $(window).height())

Laravel Eloquent groupBy() AND also return count of each group

Thanks Antonio,

I've just added the lists command at the end so it will only return one array with key and count:

Laravel 4

$user_info = DB::table('usermetas')
             ->select('browser', DB::raw('count(*) as total'))
             ->groupBy('browser')
             ->lists('total','browser');

Laravel 5.1

$user_info = DB::table('usermetas')
             ->select('browser', DB::raw('count(*) as total'))
             ->groupBy('browser')
             ->lists('total','browser')->all();

Laravel 5.2+

$user_info = DB::table('usermetas')
             ->select('browser', DB::raw('count(*) as total'))
             ->groupBy('browser')
             ->pluck('total','browser')->all();

jQuery duplicate DIV into another DIV

You'll want to use the clone() method in order to get a deep copy of the element:

$(function(){
  var $button = $('.button').clone();
  $('.package').html($button);
});

Full demo: http://jsfiddle.net/3rXjx/

From the jQuery docs:

The .clone() method performs a deep copy of the set of matched elements, meaning that it copies the matched elements as well as all of their descendant elements and text nodes. When used in conjunction with one of the insertion methods, .clone() is a convenient way to duplicate elements on a page.

Displaying tooltip on mouse hover of a text

I would also like to add something here that if you load desired form that contain tooltip controll before the program's run then tool tip control on that form will not work as described below...

    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        objfrmmain = new Frm_Main();
        Showtop();//this is procedure in program.cs to load an other form, so if that contain's tool tip control then it will not work
        Application.Run(objfrmmain);


    }

so I solved this problem by puting following code in Fram_main_load event procedure like this

    private void Frm_Main_Load(object sender, EventArgs e)
    {
        Program.Showtop();
    }

Node.js Generate html

You can use jsdom

const jsdom = require("jsdom");
const { JSDOM } = jsdom;
const { document } = (new JSDOM(`...`)).window;

or, take a look at cheerio, it may more suitable in your case.

How do I handle a click anywhere in the page, even when a certain element stops the propagation?

You could use jQuery to add an event listener on the document DOM.

_x000D_
_x000D_
    $(document).on("click", function () {_x000D_
        console.log('clicked');_x000D_
    });
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Break when a value changes using the Visual Studio debugger

Right click on the breakpoint works fine for me (though mostly I am using it for conditional breakpoints on specific variable values. Even breaking on expressions involving a thread name works which is very useful if you're trying to spot threading issues).

How to enable production mode?

To enable production mode in angular 6.X.X Just go to environment file

Like this path

Your path: project>\src\environments\environment.ts

Change production: false from :

export const environment = {
  production: false
};

To

export const environment = {
  production: true
};

enter image description here

Get POST data in C#/ASP.NET

Try using:

string ap = c.Request["AP"];

That reads from the cookies, form, query string or server variables.

Alternatively:

string ap = c.Request.Form["AP"];

to just read from the form's data.

Proper way to handle multiple forms on one page in Django

A method for future reference is something like this. bannedphraseform is the first form and expectedphraseform is the second. If the first one is hit, the second one is skipped (which is a reasonable assumption in this case):

if request.method == 'POST':
    bannedphraseform = BannedPhraseForm(request.POST, prefix='banned')
    if bannedphraseform.is_valid():
        bannedphraseform.save()
else:
    bannedphraseform = BannedPhraseForm(prefix='banned')

if request.method == 'POST' and not bannedphraseform.is_valid():
    expectedphraseform = ExpectedPhraseForm(request.POST, prefix='expected')
    bannedphraseform = BannedPhraseForm(prefix='banned')
    if expectedphraseform.is_valid():
        expectedphraseform.save()

else:
    expectedphraseform = ExpectedPhraseForm(prefix='expected')

Open file with associated application

This is an old thread but just in case anyone comes across it like I did. pi.FileName needs to be set to the file name (and possibly full path to file ) of the executable you want to use to open your file. The below code works for me to open a video file with VLC.

var path = files[currentIndex].fileName;
var pi = new ProcessStartInfo(path)
{
    Arguments = Path.GetFileName(path),
    UseShellExecute = true,
    WorkingDirectory = Path.GetDirectoryName(path),
    FileName = "C:\\Program Files (x86)\\VideoLAN\\VLC\\vlc.exe",
    Verb = "OPEN"
};
Process.Start(pi)

Tigran's answer works but will use windows' default application to open your file, so using ProcessStartInfo may be useful if you want to open the file with an application that is not the default.

Converting a string to an integer on Android

The much simpler method is to use the decode method of Integer so for example:

int helloInt = Integer.decode(hello);

Git with SSH on Windows

you are using a smart quote instead of " here:

git.exe clone -v “ssh://
                ^^^ 

Make sure you use the plain-old-double-quote.

Printing reverse of any String without using any predefined function?

public class StringReverse {

    public static void main(String[] args) {
        String s= (args[0]);
        for (int i =s.length()-1; i >= 0; i--) {            
               System.out.print(s.charAt(i));    
        }
    } 
}

Prints the reversed string of the input.

How to update maven repository in Eclipse?

In newer versions of Eclipse that use the M2E plugin it is:

Right-click on your project(s) --> Maven --> Update Project...

In the following dialog is a checkbox for forcing the update ("Force Update of Snapshots/Releases")

MySQL selecting yesterday's date

Last or next date, week, month & year calculation. It might be helpful for anyone.

Current Date:

select curdate();

Yesterday:

select subdate(curdate(), 1)

Tomorrow:

select adddate(curdate(), 1)

Last 1 week:

select between subdate(curdate(), 7) and subdate(curdate(), 1)

Next 1 week:

between adddate(curdate(), 7) and adddate(curdate(), 1)

Last 1 month:

between subdate(curdate(), 30) and subdate(curdate(), 1)

Next 1 month:

between adddate(curdate(), 30) and adddate(curdate(), 1)

Current month:

subdate(curdate(),day(curdate())-1) and last_day(curdate());

Last 1 year:

between subdate(curdate(), 365) and subdate(curdate(), 1)

Next 1 year:

between adddate(curdate(), 365) and adddate(curdate(), 1)

Nested objects in javascript, best practices

If you know the settings in advance you can define it in a single statement:

var defaultsettings = {
                        ajaxsettings : { "ak1" : "v1", "ak2" : "v2", etc. },
                        uisettings : { "ui1" : "v1", "ui22" : "v2", etc }
                      };

If you don't know the values in advance you can just define the top level object and then add properties:

var defaultsettings = { };
defaultsettings["ajaxsettings"] = {};
defaultsettings["ajaxsettings"]["somekey"] = "some value";

Or half-way between the two, define the top level with nested empty objects as properties and then add properties to those nested objects:

var defaultsettings = {
                        ajaxsettings : {  },
                        uisettings : {  }
                      };

defaultsettings["ajaxsettings"]["somekey"] = "some value";
defaultsettings["uisettings"]["somekey"] = "some value";

You can nest as deep as you like using the above techniques, and anywhere that you have a string literal in the square brackets you can use a variable:

var keyname = "ajaxsettings";
var defaultsettings = {};
defaultsettings[keyname] = {};
defaultsettings[keyname]["some key"] = "some value";

Note that you can not use variables for key names in the { } literal syntax.

Setting PayPal return URL and making it auto return?

I think that the idea of setting the Auto Return values as described above by Kevin is a bit strange!

Say, for example, that you have a number of websites that use the same PayPal account to handle your payments, or say that you have a number of sections in one website that perform different purchasing tasks, and require different return-addresses when the payment is completed. If I put a button on my page as described above in the 'Sample form using PHP for direct payments' section, you can see that there is a line there:

input type="hidden" name="return" value="https://www.yoursite.com/checkout_complete.php"

where you set the individual return value. Why does it have to be set generally, in the profile section as well?!?!

Also, because you can only set one value in the Profile Section, it means (AFAIK) that you cannot use the Auto Return on a site with multiple actions.

Comments please??

How to install a .ipa file into my iPhone?

You need to install the provisioning profile (drag and drop it into iTunes). Then drag and drop the .ipa. Ensure you device is set to sync apps, and try again.

How to overwrite styling in Twitter Bootstrap

Came across this late, but I think it could use another answer.

If you're using sass, you can actually change the variables before you import bootstrap. http://twitter.github.com/bootstrap/customize.html#variables

Change any of them, such as:

$bodyBackground: red;
@import "bootstrap";

Alternatively if there isn't a variable available for what you want to change, you can override the styles or add your own.

Sass:

@import "bootstrap";

/* override anything manually, like rounded buttons */
.btn {
  border-radius: 0;
}

Also see this: Proper SCSS Asset Structure in Rails

Getting rid of bullet points from <ul>

In a chrome, you can use

ul {
 list-style: none;
}

Get single listView SelectedItem

For a shopping cart situation here's what I recommend. I'm gonna break it down into it's simplest form.

Assuming we start with this(a list view with 2 colums, 2 buttons, and a label): starting

First things first, removing the items, to do that we'll enter our remove button:

private void button2_Click(object sender, EventArgs e)
{
    listView1.Items.Remove(listView1.SelectedItems[0]);
    label1.Text = updateCartTotal().ToString();
}

Now the second line is updating our labels total using the next function i'll post to addup all the total of column 2 in the listview:

private decimal updateCartTotal()
{
    decimal runningTotal = 0;
    foreach(ListViewItem l in listView1.Items)
    {
        runningTotal += Convert.ToDecimal(l.SubItems[1].Text);
    }
    return runningTotal;
}

You don't have to use decimal like I did, you can use float or int if you don't have decimals. So let's break it down. We use a for loop to total all the items in the column 2(SubItems[1].Text). Add that to a decimal we declared prior to the foreach loop to keep a total. If you want to do tax you can do something like:

return runningTotal * 1.15;

or whatever your tax rate is.

Long and short of it, using this function you can retotal your listview by just calling the function. You can change the labels text like I demo'd prior if that's what you're after.

if, elif, else statement issues in Bash

You have some syntax issues with your script. Here is a fixed version:

#!/bin/bash

if [ "$seconds" -eq 0 ]; then
   timezone_string="Z"
elif [ "$seconds" -gt 0 ]; then
   timezone_string=$(printf "%02d:%02d" $((seconds/3600)) $(((seconds / 60) % 60)))
else
   echo "Unknown parameter"
fi

Click outside menu to close in jquery

The answer is right, but it will add a listener that will be triggered every time a click occurs on your page. To avoid that, you can add the listener for just one time :

$('a#menu-link').on('click', function(e) {
    e.preventDefault();
    e.stopPropagation();

    $('#menu').toggleClass('open');

    $(document).one('click', function closeMenu (e){
        if($('#menu').has(e.target).length === 0){
            $('#menu').removeClass('open');
        } else {
            $(document).one('click', closeMenu);
        }
    });
});

Edit: if you want to avoid the stopPropagation() on the initial button you can use this

var $menu = $('#menu');

$('a#menu-link').on('click', function(e) {
    e.preventDefault();

    if (!$menu.hasClass('active')) {
        $menu.addClass('active');

        $(document).one('click', function closeTooltip(e) {
            if ($menu.has(e.target).length === 0 && $('a#menu-link').has(e.target).length === 0) {
                $menu.removeClass('active');
            } else if ($menu.hasClass('active')) {
                $(document).one('click', closeTooltip);
            }
        });
    } else {
        $menu.removeClass('active');
    }
});

setting content between div tags using javascript

If the number of your messages is limited then the following may help. I used jQuery for the following example, but it works with plain js too.

The innerHtml property did not work for me. So I experimented with ...

    <div id=successAndErrorMessages-1>100% OK</div>
    <div id=successAndErrorMessages-2>This is an error mssg!</div>

and toggled one of the two on/off ...

 $("#successAndErrorMessages-1").css('display', 'none')
 $("#successAndErrorMessages-2").css('display', '')

For some reason I had to fiddle around with the ordering before it worked in all types of browsers.

Spring Boot Rest Controller how to return different HTTP status codes?

Try this code:

@RequestMapping(value = "/validate", method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<ErrorBean> validateUser(@QueryParam("jsonInput") final String jsonInput) {
    int numberHTTPDesired = 400;
    ErrorBean responseBean = new ErrorBean();
    responseBean.setError("ERROR");
    responseBean.setMensaje("Error in validation!");

    return new ResponseEntity<ErrorBean>(responseBean, HttpStatus.valueOf(numberHTTPDesired));
}

Cygwin Make bash command not found

I faced the same problem too. Look up to the left side, and select (full). (Make), (gcc) and many others will appear. You will be able to chose the search bar to find them easily.

Clear screen in shell

An easier way to clear a screen while in python is to use Ctrl + L though it works for the shell as well as other programs.

Pipenv: Command Not Found

I tried this:

python -m pipenv # for python2

python3 -m pipenv # for python3

Hope this can help you.

How do I fix this "TypeError: 'str' object is not callable" error?

this part :

"Your new price is: $"(float(price)

asks python to call this string:

"Your new price is: $"

just like you would a function: function( some_args) which will ALWAYS trigger the error:

TypeError: 'str' object is not callable

Label python data points on plot

I had a similar issue and ended up with this:

enter image description here

For me this has the advantage that data and annotation are not overlapping.

from matplotlib import pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111)

A = -0.75, -0.25, 0, 0.25, 0.5, 0.75, 1.0
B = 0.73, 0.97, 1.0, 0.97, 0.88, 0.73, 0.54

plt.plot(A,B)

# annotations at the side (ordered by B values)
x0,x1=ax.get_xlim()
y0,y1=ax.get_ylim()
for ii, ind in enumerate(np.argsort(B)):
    x = A[ind]
    y = B[ind]
    xPos = x1 + .02 * (x1 - x0)
    yPos = y0 + ii * (y1 - y0)/(len(B) - 1)
    ax.annotate('',#label,
          xy=(x, y), xycoords='data',
          xytext=(xPos, yPos), textcoords='data',
          arrowprops=dict(
                          connectionstyle="arc3,rad=0.",
                          shrinkA=0, shrinkB=10,
                          arrowstyle= '-|>', ls= '-', linewidth=2
                          ),
          va='bottom', ha='left', zorder=19
          )
    ax.text(xPos + .01 * (x1 - x0), yPos,
            '({:.2f}, {:.2f})'.format(x,y),
            transform=ax.transData, va='center')

plt.grid()
plt.show()

Using the text argument in .annotate ended up with unfavorable text positions. Drawing lines between a legend and the data points is a mess, as the location of the legend is hard to address.

Determine what attributes were changed in Rails after_save callback?

You just add an accessor who define what you change

class Post < AR::Base
  attr_reader :what_changed

  before_filter :what_changed?

  def what_changed?
    @what_changed = changes || []
  end

  after_filter :action_on_changes

  def action_on_changes
    @what_changed.each do |change|
      p change
    end
  end
end

Configure Log4net to write to multiple files

These answers were helpful, but I wanted to share my answer with both the app.config part and the c# code part, so there is less guessing for the next person.

<log4net>
  <appender name="SomeName" type="log4net.Appender.RollingFileAppender">
    <file value="c:/Console.txt" />
    <appendToFile value="true" />
    <rollingStyle value="Composite" />
    <datePattern value="yyyyMMdd" />
    <maxSizeRollBackups value="10" />
    <maximumFileSize value="1MB" />
  </appender>
  <appender name="Summary" type="log4net.Appender.FileAppender">
    <file value="SummaryFile.log" />
    <appendToFile value="true" />
  </appender>
  <root>
    <level value="ALL" />
    <appender-ref ref="SomeName" />
  </root>
  <logger additivity="false" name="Summary">
    <level value="DEBUG"/>
    <appender-ref ref="Summary" />
  </logger>
</log4net>

Then in code:

ILog Log = LogManager.GetLogger("SomeName");
ILog SummaryLog = LogManager.GetLogger("Summary");
Log.DebugFormat("Processing");
SummaryLog.DebugFormat("Processing2"));

Here c:/Console.txt will contain "Processing" ... and \SummaryFile.log will contain "Processing2"

how to add <script>alert('test');</script> inside a text box?

is you want fix XSS on input element? you can encode string before output to input field

PHP:

$str = htmlentities($str);

C#:

str = WebUtility.HtmlEncode(str);

after that output value direct to input field:

<input type="text" value="<?php echo $str" />

Coerce multiple columns to factors at once

Here is an option using dplyr. The %<>% operator from magrittr update the lhs object with the resulting value.

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

data %<>%
       mutate_each_(funs(factor(.)),cols)
str(data)
#'data.frame':  4 obs. of  10 variables:
# $ A: Factor w/ 4 levels "23","24","26",..: 1 2 3 4
# $ B: int  15 13 39 16
# $ C: Factor w/ 4 levels "3","5","18","37": 2 1 3 4
# $ D: Factor w/ 4 levels "2","6","28","38": 3 1 4 2
# $ E: int  14 4 22 20
# $ F: int  7 19 36 27
# $ G: int  35 40 21 10
# $ H: Factor w/ 4 levels "11","29","32",..: 1 4 3 2
# $ I: int  17 1 9 25
# $ J: int  12 30 8 33

Or if we are using data.table, either use a for loop with set

setDT(data)
for(j in cols){
  set(data, i=NULL, j=j, value=factor(data[[j]]))
}

Or we can specify the 'cols' in .SDcols and assign (:=) the rhs to 'cols'

setDT(data)[, (cols):= lapply(.SD, factor), .SDcols=cols]

How to debug Javascript with IE 8

I was hoping to add this as a comment to Marcus Westin's reply, but I can't find a link - maybe I need more reputation?


Anyway, thanks, I found this code snippet useful for quick debugging in IE. I have made some quick tweaks to fix a problem that stopped it working for me, also to scroll down automatically and use fixed positioning so it will appear in the viewport. Here's my version in case anyone finds it useful:

myLog = function() {

    var _div = null;

    this.toJson = function(obj) {

        if (typeof window.uneval == 'function') { return uneval(obj); }
        if (typeof obj == 'object') {
            if (!obj) { return 'null'; }
            var list = [];
            if (obj instanceof Array) {
                    for (var i=0;i < obj.length;i++) { list.push(this.toJson(obj[i])); }
                    return '[' + list.join(',') + ']';
            } else {
                    for (var prop in obj) { list.push('"' + prop + '":' + this.toJson(obj[prop])); }
                    return '{' + list.join(',') + '}';
            }
        } else if (typeof obj == 'string') {
            return '"' + obj.replace(/(["'])/g, '\\$1') + '"';
        } else {
            return new String(obj);
        }

    };

    this.createDiv = function() {

        myLog._div = document.body.appendChild(document.createElement('div'));

        var props = {
            position:'fixed', top:'10px', right:'10px', background:'#333', border:'5px solid #333', 
            color: 'white', width: '400px', height: '300px', overflow: 'auto', fontFamily: 'courier new',
            fontSize: '11px', whiteSpace: 'nowrap'
        }

        for (var key in props) { myLog._div.style[key] = props[key]; }

    };


    if (!myLog._div) { this.createDiv(); }

    var logEntry = document.createElement('span');

    for (var i=0; i < arguments.length; i++) {
        logEntry.innerHTML += this.toJson(arguments[i]) + '<br />';
    }

    logEntry.innerHTML += '<br />';

    myLog._div.appendChild(logEntry);

    // Scroll automatically to the bottom
    myLog._div.scrollTop = myLog._div.scrollHeight;

}

Jquery Hide table rows

$('inputFile').parent().parent().children('td > label').hide();

can help you navigate two levels up ( to TD, to TR ) moving two levels back down ( all TD's in that TR and their LABEL tags ), applying the hide() function there.

if you want to stay at the TR level and hide them:

$('inputFile').parent().parent().hide();

… is sufficient.

you can navigate very easily through the elements using the jquery selectors.

parent is documented here: http://api.jquery.com/parent/

hide is documented here: http://api.jquery.com/hide/

How to make the corners of a button round?

create shape.xml in drawable folder

like shape.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
  <stroke android:width="2dp"
    android:color="#FFFFFF"/>
  <gradient 
    android:angle="225"
    android:startColor="#DD2ECCFA"
    android:endColor="#DD000000"/>
<corners
    android:bottomLeftRadius="7dp"
    android:bottomRightRadius="7dp"
    android:topLeftRadius="7dp"
   android:topRightRadius="7dp" />
</shape>

and in myactivity.xml

you can use

<Button
    android:id="@+id/btn_Shap"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" 
    android:text="@string/Shape"
    android:background="@drawable/shape"/>

Given a URL to a text file, what is the simplest way to read the contents of the text file?

I'm a newbie to Python and the offhand comment about Python 3 in the accepted solution was confusing. For posterity, the code to do this in Python 3 is

import urllib.request
data = urllib.request.urlopen(target_url)

for line in data:
    ...

or alternatively

from urllib.request import urlopen
data = urlopen(target_url)

Note that just import urllib does not work.

Group by with multiple columns using lambda

Further to aduchis answer above - if you then need to filter based on those group by keys, you can define a class to wrap the many keys.

return customers.GroupBy(a => new CustomerGroupingKey(a.Country, a.Gender))
                .Where(a => a.Key.Country == "Ireland" && a.Key.Gender == "M")
                .SelectMany(a => a)
                .ToList();

Where CustomerGroupingKey takes the group keys:

    private class CustomerGroupingKey
    {
        public CustomerGroupingKey(string country, string gender)
        {
            Country = country;
            Gender = gender;
        }

        public string Country { get; }

        public string Gender { get; }
    }

Could you explain STA and MTA?

The COM threading model is called an "apartment" model, where the execution context of initialized COM objects is associated with either a single thread (Single Thread Apartment) or many threads (Multi Thread Apartment). In this model, a COM object, once initialized in an apartment, is part of that apartment for the duration of its runtime.

The STA model is used for COM objects that are not thread safe. That means they do not handle their own synchronization. A common use of this is a UI component. So if another thread needs to interact with the object (such as pushing a button in a form) then the message is marshalled onto the STA thread. The windows forms message pumping system is an example of this.

If the COM object can handle its own synchronization then the MTA model can be used where multiple threads are allowed to interact with the object without marshalled calls.

Unable instantiate android.gms.maps.MapFragment

Please read carefully

If everything is woking same as google code then please check manifest file in my case i added geo key and map key that's why exception occurs,

Note - do not add two keys in manifest file remove map key

meta-data
        android:name="com.google.android.maps.v2.API_KEY"
        android:value="@string/google_maps_key"/>

add this code.

 <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="@string/auto_location"/>

 <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version"/>

Making LaTeX tables smaller?

http://en.wikibooks.org/wiki/LaTeX/Tables#Resize_tables talks about two ways to do this.

I used:

\scalebox{0.7}{
  \begin{tabular}
    ...
  \end{tabular}
}

Newline character in StringBuilder

StringBuilder sb = new StringBuilder();

You can use sb.AppendLine() or sb.Append(Environment.NewLine);

What is the most efficient way to get first and last line of a text file?

w=open(file.txt, 'r')
print ('first line is : ',w.readline())
for line in w:  
    x= line
print ('last line is : ',x)
w.close()

The for loop runs through the lines and x gets the last line on the final iteration.

How to apply filters to *ngFor?

I was finding somethig for make a filter passing an Object, then i can use it like multi-filter: Multi filter example

i did this Beauty Solution:

filter.pipe.ts

import { PipeTransform, Pipe } from '@angular/core';

@Pipe({
  name: 'filterx',
  pure: false
})
export class FilterPipe implements PipeTransform {
 transform(items: any, filter: any, isAnd: boolean): any {
  let filterx=JSON.parse(JSON.stringify(filter));
  for (var prop in filterx) {
    if (Object.prototype.hasOwnProperty.call(filterx, prop)) {
       if(filterx[prop]=='')
       {
         delete filterx[prop];
       }
    }
 }
if (!items || !filterx) {
  return items;
}

return items.filter(function(obj) {
  return Object.keys(filterx).every(function(c) {
    return obj[c].toLowerCase().indexOf(filterx[c].toLowerCase()) !== -1
  });
  });
  }
}

component.ts

slotFilter:any={start:'',practitionerCodeDisplay:'',practitionerName:''};

componet.html

             <tr>
                <th class="text-center">  <input type="text" [(ngModel)]="slotFilter.start"></th>
                <th class="text-center"><input type="text" [(ngModel)]="slotFilter.practitionerCodeDisplay"></th>
                <th class="text-left"><input type="text" [(ngModel)]="slotFilter.practitionerName"></th>
                <th></th>
              </tr>


 <tbody *ngFor="let item of practionerRoleList | filterx: slotFilter">...

Start index for iterating Python list

Why are people using list slicing (slow because it copies to a new list), importing a library function, or trying to rotate an array for this?

Use a normal for-loop with range(start, stop, step) (where start and step are optional arguments).

For example, looping through an array starting at index 1:

for i in range(1, len(arr)):
    print(arr[i])

Is there an easy way to check the .NET Framework version?

Little large, but looks like it is up-to-date to Microsoft oddities:

    public static class Versions
    {
        static Version 
            _NET;

        static SortedList<String,Version>
            _NETInstalled;

#if NET40
#else
        public static bool VersionTry(String S, out Version V)
        {
            try
            { 
                V=new Version(S); 
                return true;
            }
            catch
            {
                V=null;
                return false;
            }
        }
#endif
        const string _NetFrameWorkKey = "SOFTWARE\\Microsoft\\NET Framework Setup\\NDP";
        static void FillNetInstalled()
        {
            if (_NETInstalled == null)
            {
                _NETInstalled = new SortedList<String, Version>(StringComparer.InvariantCultureIgnoreCase);
                RegistryKey
                    frmks = Registry.LocalMachine.OpenSubKey(_NetFrameWorkKey);
                string[]
                    names = frmks.GetSubKeyNames();
                foreach (string name in names)
                {
                    if (name.StartsWith("v", StringComparison.InvariantCultureIgnoreCase) && name.Length > 1)
                    {
                        string
                            f, vs;
                        Version
                            v;
                        vs = name.Substring(1);
                        if (vs.IndexOf('.') < 0)
                            vs += ".0";
#if NET40
                        if (Version.TryParse(vs, out v))
#else
                        if (VersionTry(vs, out v))
#endif
                        {
                            f = String.Format("{0}.{1}", v.Major, v.Minor);
#if NET40
                            if (Version.TryParse((string)frmks.OpenSubKey(name).GetValue("Version"), out v))
#else
                            if (VersionTry((string)frmks.OpenSubKey(name).GetValue("Version"), out v))
#endif
                            {
                                if (!_NETInstalled.ContainsKey(f) || v.CompareTo(_NETInstalled[f]) > 0)
                                    _NETInstalled[f] = v;
                            }
                            else
                            { // parse variants
                                Version
                                    best = null;
                                if (_NETInstalled.ContainsKey(f))
                                    best = _NETInstalled[f];
                                string[]
                                    varieties = frmks.OpenSubKey(name).GetSubKeyNames();
                                foreach (string variety in varieties)
#if NET40
                                    if (Version.TryParse((string)frmks.OpenSubKey(name + '\\' + variety).GetValue("Version"), out v))
#else
                                    if (VersionTry((string)frmks.OpenSubKey(name + '\\' + variety).GetValue("Version"), out v))
#endif
                                    {
                                        if (best == null || v.CompareTo(best) > 0)
                                        {
                                            _NETInstalled[f] = v;
                                            best = v;
                                        }
                                        vs = f + '.' + variety;
                                        if (!_NETInstalled.ContainsKey(vs) || v.CompareTo(_NETInstalled[vs]) > 0)
                                            _NETInstalled[vs] = v;
                                    }
                            }
                        }
                    }
                }
            }
        } // static void FillNetInstalled()

        public static Version NETInstalled
        {
            get
            {
                FillNetInstalled();
                return _NETInstalled[_NETInstalled.Keys[_NETInstalled.Count-1]];
            }
        } // NETInstalled

        public static Version NET
        {
            get
            {
                FillNetInstalled();
                string
                    clr = String.Format("{0}.{1}", Environment.Version.Major, Environment.Version.Minor);
                Version
                    found = _NETInstalled[_NETInstalled.Keys[_NETInstalled.Count-1]];
                if(_NETInstalled.ContainsKey(clr))
                    return _NETInstalled[clr];

                for (int i = _NETInstalled.Count - 1; i >= 0; i--)
                    if (_NETInstalled.Keys[i].CompareTo(clr) < 0)
                        return found;
                    else
                        found = _NETInstalled[_NETInstalled.Keys[i]];
                return found;
            }
        } // NET
    }

Redirect in Spring MVC

It is possible to define a urlBasedViewResolver in your properties file:

excel.(class)=fi.utu.seurantaraporttisuodatin.service.Raportti  
index.(class)=org.springframework.web.servlet.view.urlBasedView  
index.viewClass =org.springframework.web.servlet.view.JstlView  
index.prefix = /WEB-INF/jsp/  
index.suffix =.jsp

Basic authentication with fetch?

You can also use btoa instead of base64.encode().

headers.set('Authorization', 'Basic ' + btoa(username + ":" + password));

Change color of bootstrap navbar on hover link?

This should be enough:

.nav.navbar-nav li a:hover {
  color: red;
}

What do I use on linux to make a python program executable

Putting these lines at the starting of the code will tell your operating systems to look up the binary program needed for the execution of the python script i.e it is the python interpreter.

So it depends on your operating system where it keeps the python interpreter. As I have Ubuntu as operating system it keeps the python interpreter in /usr/bin/python so I have to write this line at the starting of my python script;

#!/usr/bin/python

After completing and saving your code

  1. Start your command terminal

  2. Make sure the script lies in your present working directory

  3. Type chmod +x script_name.py

  4. Now you can start the script by clicking the script. An alert box will appear; press "Run" or "Run in Terminal" in the alert box; or, at the terminal prompt, type ./script_name.py

Java - removing first character of a string

You can use the substring method of the String class that takes only the beginning index and returns the substring that begins with the character at the specified index and extending to the end of the string.

String str = "Jamaica";
str = str.substring(1);

How to programmatically determine the current checked out Git branch

Here's my solution, suitable for use in a PS1, or for automatically labeling a release

If you are checked out at a branch, you get the branch name.

If you are in a just init'd git project, you just get '@'

If you are headless, you get a nice human name relative to some branch or tag, with an '@' preceding the name.

If you are headless and not an ancestor of some branch or tag you just get the short SHA1.

function we_are_in_git_work_tree {
    git rev-parse --is-inside-work-tree &> /dev/null
}

function parse_git_branch {
    if we_are_in_git_work_tree
    then
    local BR=$(git rev-parse --symbolic-full-name --abbrev-ref HEAD 2> /dev/null)
    if [ "$BR" == HEAD ]
    then
        local NM=$(git name-rev --name-only HEAD 2> /dev/null)
        if [ "$NM" != undefined ]
        then echo -n "@$NM"
        else git rev-parse --short HEAD 2> /dev/null
        fi
    else
        echo -n $BR
    fi
    fi
}

You can remove the if we_are_in_git_work_tree bit if you like; I just use it in another function in my PS1 which you can view in full here: PS1 line with git current branch and colors

Execute method on startup in Spring

What we have done was extending org.springframework.web.context.ContextLoaderListener to print something when the context starts.

public class ContextLoaderListener extends org.springframework.web.context.ContextLoaderListener
{
    private static final Logger logger = LoggerFactory.getLogger( ContextLoaderListener.class );

    public ContextLoaderListener()
    {
        logger.info( "Starting application..." );
    }
}

Configure the subclass then in web.xml:

<listener>
    <listener-class>
        com.mycomp.myapp.web.context.ContextLoaderListener
    </listener-class>
</listener>

"Multiple definition", "first defined here" errors

I am adding this A because I got caught with a bizarre version of this which really had me scratching my head for about a hour until I spotted the root cause. My load was failing because of multiple repeats of this format

<path>/linit.o:(.rodata1.libs+0x50): multiple definition of `lua_lib_BASE'
<path>/linit.o:(.rodata1.libs+0x50): first defined here

I turned out to be a bug in my Makefile magic where I had a list of C files and using vpath etc., so the compiles would pick them up from the correct directory in hierarchy. However one C file was repeated in the list, at the end of one line and the start of the next so the gcc load generated by the make had the .o file twice on the command line. Durrrrh. The multiple definitions were from multiple occurances of the same file. The linker ignored duplicates apart from static initialisers!

Difference between map and collect in Ruby?

I've been told they are the same.

Actually they are documented in the same place under ruby-doc.org:

http://www.ruby-doc.org/core/classes/Array.html#M000249

  • ary.collect {|item| block } ? new_ary
  • ary.map {|item| block } ? new_ary
  • ary.collect ? an_enumerator
  • ary.map ? an_enumerator

Invokes block once for each element of self. Creates a new array containing the values returned by the block. See also Enumerable#collect.
If no block is given, an enumerator is returned instead.

a = [ "a", "b", "c", "d" ]
a.collect {|x| x + "!" }   #=> ["a!", "b!", "c!", "d!"]
a                          #=> ["a", "b", "c", "d"]

How to fix Uncaught InvalidValueError: setPosition: not a LatLng or LatLngLiteral: in property lat: not a number?

You're probably passing null value if you're loading the coordinates dynamically, set a check before you call the map loader ie: if(mapCords){loadMap}

Best way to check for nullable bool in a condition expression (if ...)

Just think of bool? as having 3 values, then things get easier:

if (someNullableBool == true)     // only if true
if (someNullableBool == false)    // only if false
if (someNullableBool == null)     // only if null

Is it good practice to use the xor operator for boolean checks?

if((boolean1 && !boolean2) || (boolean2 && !boolean1)) 
{ 
  //do it 
} 

IMHO this code could be simplified:

if(boolean1 != boolean2) 
{ 
  //do it 
} 

Indent multiple lines quickly in vi

To indent every line in a file type, Esc and then G=gg.

How do I open a URL from C++?

Create a function and copy the code using winsock which is mentioned already by Software_Developer.

For Instance:

#ifdef _WIN32

// this is required only for windows

if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0)
{

  //...

}

#endif

winsock code here

#ifdef _WIN32

WSACleanup();

#endif

How can I debug what is causing a connection refused or a connection time out?

Use a packet analyzer to intercept the packets to/from somewhere.com. Studying those packets should tell you what is going on.

Time-outs or connections refused could mean that the remote host is too busy.

From Now() to Current_timestamp in Postgresql

Use an interval instead of an integer:

SELECT *
FROM table
WHERE auth_user.lastactivity > CURRENT_TIMESTAMP - INTERVAL '100 days'

Vue.js - How to properly watch for nested data

I used deep:true, but found the old and new value in the watched function was the same always. As an alternative to previous solutions I tried this, which will check any change in the whole object by transforming it to a string:

created() {
    this.$watch(
        () => JSON.stringify(this.object),
            (newValue, oldValue) => {
                //do your stuff                
            }
    );
},

"Unable to locate tools.jar" when running ant

  1. Try to check it once more according to this tutorial: http://vietpad.sourceforge.net/javaonwindows.html

  2. Try to reboot your system.

  3. If nothing, try to run "cmd" and type there "java", does it print anything?

Input placeholders for Internet Explorer

Simple like this:

$(function() {
    ...

    var element = $("#selecter")
    if(element.val() === element.attr("placeholder"){

        element.text("").select().blur();
    }

    ...
});

How to open new browser window on button click event?

You can use some code like this, you can adjust a height and width as per your need

    protected void button_Click(object sender, EventArgs e)
    {
        // open a pop up window at the center of the page.
        ScriptManager.RegisterStartupScript(this, typeof(string), "OPEN_WINDOW", "var Mleft = (screen.width/2)-(760/2);var Mtop = (screen.height/2)-(700/2);window.open( 'your_page.aspx', null, 'height=700,width=760,status=yes,toolbar=no,scrollbars=yes,menubar=no,location=no,top=\'+Mtop+\', left=\'+Mleft+\'' );", true);
    }

Print specific part of webpage

I made this jQuery extension to print the HTML of the element selected: $('#div2').print();

$.fn.extend({
    print: function() {
        var frameName = 'printIframe';
        var doc = window.frames[frameName];
        if (!doc) {
            $('<iframe>').hide().attr('name', frameName).appendTo(document.body);
            doc = window.frames[frameName];
        }
        doc.document.body.innerHTML = this.html();
        doc.window.print();
        return this;
    }
});

See it in action here.

addEventListener vs onclick

Using inline handlers is incompatible with Content Security Policy so the addEventListener approach is more secure from that point of view. Of course you can enable the inline handlers with unsafe-inline but, as the name suggests, it's not safe as it brings back the whole hordes of JavaScript exploits that CSP prevents.

get keys of json-object in JavaScript

[What you have is just an object, not a "json-object". JSON is a textual notation. What you've quoted is JavaScript code using an array initializer and an object initializer (aka, "object literal syntax").]

If you can rely on having ECMAScript5 features available, you can use the Object.keys function to get an array of the keys (property names) in an object. All modern browsers have Object.keys (including IE9+).

Object.keys(jsonData).forEach(function(key) {
    var value = jsonData[key];
    // ...
});

The rest of this answer was written in 2011. In today's world, A) You don't need to polyfill this unless you need to support IE8 or earlier (!), and B) If you did, you wouldn't do it with a one-off you wrote yourself or grabbed from an SO answer (and probably shouldn't have in 2011, either). You'd use a curated polyfill, possibly from es5-shim or via a transpiler like Babel that can be configured to include polyfills (which may come from es5-shim).

Here's the rest of the answer from 2011:

Note that older browsers won't have it. If not, this is one of the ones you can supply yourself:

if (typeof Object.keys !== "function") {
    (function() {
        var hasOwn = Object.prototype.hasOwnProperty;
        Object.keys = Object_keys;
        function Object_keys(obj) {
            var keys = [], name;
            for (name in obj) {
                if (hasOwn.call(obj, name)) {
                    keys.push(name);
                }
            }
            return keys;
        }
    })();
}

That uses a for..in loop (more info here) to loop through all of the property names the object has, and uses Object.prototype.hasOwnProperty to check that the property is owned directly by the object rather than being inherited.

(I could have done it without the self-executing function, but I prefer my functions to have names, and to be compatible with IE you can't use named function expressions [well, not without great care]. So the self-executing function is there to avoid having the function declaration create a global symbol.)

R: rJava package install failing

Wouldn't

apt-get install r-cran-rjava

have been easier? You could have asked me at useR! :)

What is the difference between a candidate key and a primary key?

Primary key -> Any column or set of columns that can uniquely identify a record in the table is a primary key. (There can be only one Primary key in the table)

Candidate key -> Any column or set of columns that are candidate to become primary key are Candidate key. (There can be one or more candidate key(s) in the table, if there is only one candidate key, it can be chosen as Primary key)

MySQL DAYOFWEEK() - my week begins with monday

You can easily use the MODE argument:

MySQL :: MySQL 5.5 Reference Manual :: 12.7 Date and Time Functions

If the mode argument is omitted, the value of the default_week_format system variable is used:

MySQL :: MySQL 5.1 Reference Manual :: 5.1.4 Server System Variables

How to create EditText with cross(x) button at end of it?

    <EditText
    android:id="@+id/idSearchEditText"
    android:layout_width="match_parent"
    android:layout_height="@dimen/dimen_40dp"
    android:drawableStart="@android:drawable/ic_menu_search"
    android:drawablePadding="8dp"
    android:ellipsize="start"
    android:gravity="center_vertical"
    android:hint="Search"
    android:imeOptions="actionSearch"
    android:inputType="text"
    android:paddingStart="16dp"
    android:paddingEnd="8dp"
/>

EditText mSearchEditText = findViewById(R.id.idSearchEditText);
mSearchEditText.addTextChangedListener(this);
mSearchEditText.setOnTouchListener(this);


@Override
public void afterTextChanged(Editable aEditable) {
    int clearIcon = android.R.drawable.ic_notification_clear_all;
    int searchIcon = android.R.drawable.ic_menu_search;
    if (aEditable == null || TextUtils.isEmpty(aEditable.toString())) {
        clearIcon = 0;
        searchIcon = android.R.drawable.ic_menu_search;
    } else {
        clearIcon = android.R.drawable.ic_notification_clear_all;
        searchIcon = 0;
    }
    Drawable leftDrawable =  null;
    if (searchIcon != 0) {
        leftDrawable = getResources().getDrawable(searchIcon);
    }
    Drawable rightDrawable = null;
    if (clearIcon != 0) {
        rightDrawable = getResources().getDrawable(clearIcon);
    }

    mSearchEditText.setCompoundDrawablesWithIntrinsicBounds(leftDrawable, null, rightDrawable, null);
}


@Override
public boolean onTouch(View aView, MotionEvent aEvent) {
    if (aEvent.getAction() == MotionEvent.ACTION_UP){
        if (aEvent.getX() > ( mSearchEditText.getWidth() - 
         mSearchEditText.getCompoundPaddingEnd())){
            mSearchEditText.setText("");
        }
    }
    return false;
}

JS jQuery - check if value is in array

As to your bonus question, try if (jQuery.inArray(jQuery("input:first").val(), ar) < 0)

How to get the number of characters in a std::string?

std::string str("a string");
std::cout << str.size() << std::endl;

What does the Java assert keyword do, and when should it be used?

Basically, "assert true" will pass and "assert false" will fail. Let's looks at how this will work:

public static void main(String[] args)
{
    String s1 = "Hello";
    assert checkInteger(s1);
}

private static boolean checkInteger(String s)
{
    try {
        Integer.parseInt(s);
        return true;
    }
    catch(Exception e)
    {
        return false;
    }
}

How do I skip a header from CSV files in Spark?

Use the filter() method in PySpark by filtering out the first column name to remove the header:

# Read file (change format for other file formats)
contentRDD = sc.textfile(<filepath>)

# Filter out first column of the header
filterDD = contentRDD.filter(lambda l: not l.startswith(<first column name>)

# Check your result
for i in filterDD.take(5) : print (i)

Get only the date in timestamp in mysql

$date= new DateTime($row['your_date']) ;  
echo $date->format('Y-m-d');

How do I set environment variables from Java?

You can pass parameters into your initial java process with -D:

java -cp <classpath> -Dkey1=value -Dkey2=value ...

How to update each dependency in package.json to the latest version?

I found another solution for recent version of NPM. What I want to do is to replace all the "*" dependencies with the explicit lastest version number. None of the methods discussed has worked for me.

What I did:

  1. Replace all "*" with "^0.0.0"
  2. Run npm-check-updates -u

Everything in package.json now is updated to the last version.

Re-ordering factor levels in data frame

Assuming your dataframe is mydf:

mydf$task <- factor(mydf$task, levels = c("up", "down", "left", "right", "front", "back"))

Understanding PrimeFaces process/update and JSF f:ajax execute/render attributes

If you have a hard time remembering the default values (I know I have...) here's a short extract from BalusC's answer:

Component    | Submit          | Refresh
------------ | --------------- | --------------
f:ajax       | execute="@this" | render="@none"
p:ajax       | process="@this" | update="@none"
p:commandXXX | process="@form" | update="@none"

Can I use a min-height for table, tr or td?

Simply use the css entry of min-height to one of the cells of your table row. Works on old browsers too.

.rowNumberColumn {
    background-color: #e6e6e6;
    min-height: 22;
}

<table width="100%" cellspacing="0" class="htmlgrid-table">
    <tr id="tr_0">
            <td width="3%" align="center" class="readOnlyCell rowNumberColumn">1</td>
            <td align="left" width="40%" id="td_0_0" class="readOnlyCell gContentSection">411978430-Intimate:Ruby:Small</td>

HTML5 Email Validation

The input type=email page of the www.w3.org site notes that an email address is any string which matches the following regular expression:

/^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/

Use the required attribute and a pattern attribute to require the value to match the regex pattern.

<input
    type="text"
    pattern="/^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/"
    required
>

How to find/identify large commits in git history?

You should use BFG Repo-Cleaner.

According to the website:

The BFG is a simpler, faster alternative to git-filter-branch for cleansing bad data out of your Git repository history:

  • Removing Crazy Big Files
  • Removing Passwords, Credentials & other Private data

The classic procedure for reducing the size of a repository would be:

git clone --mirror git://example.com/some-big-repo.git
java -jar bfg.jar --strip-biggest-blobs 500 some-big-repo.git
cd some-big-repo.git
git reflog expire --expire=now --all
git gc --prune=now --aggressive
git push

Move column by name to front of table in pandas

We can use ix to reorder by passing a list:

In [27]:
# get a list of columns
cols = list(df)
# move the column to head of list using index, pop and insert
cols.insert(0, cols.pop(cols.index('Mid')))
cols
Out[27]:
['Mid', 'Net', 'Upper', 'Lower', 'Zsore']
In [28]:
# use ix to reorder
df = df.ix[:, cols]
df
Out[28]:
                      Mid Net  Upper   Lower  Zsore
Answer_option                                      
More_than_once_a_day    2  0%  0.22%  -0.12%     65
Once_a_day              3  0%  0.32%  -0.19%     45
Several_times_a_week    4  2%  2.45%   1.10%     78
Once_a_week             6  1%  1.63%  -0.40%     65

Another method is to take a reference to the column and reinsert it at the front:

In [39]:
mid = df['Mid']
df.drop(labels=['Mid'], axis=1,inplace = True)
df.insert(0, 'Mid', mid)
df
Out[39]:
                      Mid Net  Upper   Lower  Zsore
Answer_option                                      
More_than_once_a_day    2  0%  0.22%  -0.12%     65
Once_a_day              3  0%  0.32%  -0.19%     45
Several_times_a_week    4  2%  2.45%   1.10%     78
Once_a_week             6  1%  1.63%  -0.40%     65

You can also use loc to achieve the same result as ix will be deprecated in a future version of pandas from 0.20.0 onwards:

df = df.loc[:, cols]

Angular2 dynamic change CSS property

Angular 6 + Alyle UI

With Alyle UI you can change the styles dynamically

Here a demo stackblitz

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    CommonModule,
    FormsModule,
    HttpClientModule,
    BrowserAnimationsModule,
    AlyleUIModule.forRoot(
      {
        name: 'myTheme',
        primary: {
          default: '#00bcd4'
        },
        accent: {
          default: '#ff4081'
        },
        scheme: 'myCustomScheme', // myCustomScheme from colorSchemes
        lightGreen: '#8bc34a',
        colorSchemes: {
          light: {
            myColor: 'teal',
          },
          dark: {
            myColor: '#FF923D'
          },
          myCustomScheme: {
            background: {
              primary: '#dde4e6',
            },
            text: {
              default: '#fff'
            },
            myColor: '#C362FF'
          }
        }
      }
    ),
    LyCommonModule, // for bg, color, raised and others
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Html

<div [className]="classes.card">dynamic style</div>
<p color="myColor">myColor</p>
<p bg="myColor">myColor</p>

For change Style

import { Component } from '@angular/core';
import { LyTheme } from '@alyle/ui';

@Component({ ... })
export class AppComponent  {
  classes = {
    card: this.theme.setStyle(
      'card', // key
      () => (
        // style
        `background-color: ${this.theme.palette.myColor};` +
        `position: relative;` +
        `margin: 1em;` +
        `text-align: center;`
         ...
      )
    )
  }
  constructor(
    public theme: LyTheme
  ) { }

  changeScheme() {
    const scheme = this.theme.palette.scheme === 'light' ?
    'dark' : this.theme.palette.scheme === 'dark' ?
    'myCustomScheme' : 'light';
    this.theme.setScheme(scheme);
  }
}

Github Repository

Update built-in vim on Mac OS X

A note to romainl's answer: aliases don't work together with sudo because only the first word is checked on aliases. To change this add another alias to your .profile / .bashrc:

alias sudo='sudo '

With this change sudo vim will behave as expected!

iOS Swift - Get the Current Local Time and Date Timestamp

If you code for iOS 13.0 or later and want a timestamp, then you can use:

let currentDate = NSDate.now

How can I render a list select box (dropdown) with bootstrap?

Ben's code requires the parent div to have the form-group class (I was using btn-group), this is a slightly different version which just searches for the closest div and may even be a bit faster.

$(".dropdown-menu li a").click(function(){
    var selText = $(this).text();
    $(this).closest('div').find('button[data-toggle="dropdown"]').html(selText + ' <span class="caret"></span>');
});

Fundamental difference between Hashing and Encryption algorithms

Cryptography deals with numbers and strings. Basically every digital thing in the entire universe are numbers. When I say numbers, its 0 & 1. You know what they are, binary. The images you see on screen, the music that you listen through your earphone, everything are binaries. But our ears and eyes will not understand binaries right? Only brain could understand that, and even if it could understand binaries, it can’t enjoy binaries. So we convert the binaries to human understandable formats such as mp3,jpg,etc. Let’s term the process as Encoding. It’s two way process and can be easily decoded back to its original form.

Hashing

Hashing is another cryptography technique in which a data once converted to some other form can never be recovered back. In Layman’s term, there is no process called de-hashing. There are many hash functions to do the job such as sha-512, md5 and so on.

If the original value cannot be recovered, then where do we use this? Passwords! When you set up a password for your mobile or PC, a hash of your password is created and stored in a secure place. When you make a login attempt next time, the entered string is again hashed with the same algorithm (hash function) and the output is matched with the stored value. If it’s the same, you get logged in. Otherwise you are thrown out.

Credits: wikimedia By applying hash to the password, we can ensure that an attacker will never get our password even if he steal the stored password file. The attacker will have the hash of the password. He can probably find a list of most commonly used passwords and apply sha-512 to each of it and compare it with the value in his hand. It is called the dictionary attack. But how long would he do this? If your password is random enough, do you think this method of cracking would work? All the passwords in the databases of Facebook, Google and Amazon are hashed, or at least they are supposed to be hashed.

Then there is Encryption

Encryption lies in between hashing and encoding. Encoding is a two way process and should not be used to provide security. Encryption is also a two way process, but original data can be retrieved if and only if the encryption key is known. If you don’t know how encryption works, don’t worry, we will discuss the basics here. That would be enough to understand the basics of SSL. So, there are two types of Encryption namely Symmetric and Asymmetric encryption.

Symmetric Key Encryption

I am trying to keep things as simple as I could. So, let’s understand the symmetric encryption by means of a shift algorithm. This algorithm is used to encrypt alphabets by shifting the letters to either left or right. Let’s take a string CRYPTO and consider a number +3. Then, the encrypted format of CRYPTO will be FUBSWR. That means each letter is shifted to right by 3 places. Here, the word CRYPTO is called Plaintext, the output FUBSWR is called the Ciphertext, the value +3 is called the Encryption key (symmetric key) and the whole process is a cipher. This is one of the oldest and basic symmetric key encryption algorithm and its first usage was reported during the time of Julius Caesar. So, it was named after him and it is the famous Caesar Cipher. Anyone who knows the encryption key and can apply the reverse of Caesar’s algorithm and retrieve the original Plaintext. Hence it is called a Symmetric Encryption.

Asymmetric Key Encryption

We know that, in Symmetric encryption same key is used for both encryption and decryption. Once that key is stolen, all the data is gone. That’s a huge risk and we need more complex technique. In 1976, Whitfield Diffie and Martin Hellman first published the concept of Asymmetric encryption and the algorithm was known as Diffie–Hellman key exchange. Then in 1978, Ron Rivest, Adi Shamir and Leonard Adleman of MIT published the RSA algorithm. These can be considered as the foundation of Asymmetric cryptography.

As compared to Symmetric encryption, in Asymmetric encryption, there will be two keys instead of one. One is called the Public key, and the other one is the Private key. Theoretically, during initiation we can generate the Public-Private key pair to our machine. Private key should be kept in a safe place and it should never be shared with anyone. Public key, as the name indicates, can be shared with anyone who wish to send encrypted text to you. Now, those who have your public key can encrypt the secret data with it. If the key pair were generated using RSA algorithm, then they should use the same algorithm while encrypting the data. Usually the algorithm will be specified in the public key. The encrypted data can only be decrypted with the private key which is owned by you.

Source: SSL/TLS for dummies part 1 : Ciphersuite, Hashing,Encryption | WST (https://www.wst.space/ssl-part1-ciphersuite-hashing-encryption/)

Setting environment variables on OS X

Any of the Bash startup files -- ~/.bashrc, ~/.bash_profile, ~/.profile. There's also some sort of weird file named ~/.MacOSX/environment.plist for environment variables in GUI applications.

Element-wise addition of 2 lists?

a_list = []
b_list = []
for i in range(1,100):
    a_list.append(random.randint(1,100))

for i in range(1,100):
    a_list.append(random.randint(101,200))
[sum(x) for x in zip(a_list , b_list )]

Node.js ES6 classes with require

Using Classes in Node -

Here we are requiring the ReadWrite module and calling a makeObject(), which returns the object of the ReadWrite class. Which we are using to call the methods. index.js

const ReadWrite = require('./ReadWrite').makeObject();
const express = require('express');
const app = express();

class Start {
  constructor() {
    const server = app.listen(8081),
     host = server.address().address,
     port = server.address().port
    console.log("Example app listening at http://%s:%s", host, port);
    console.log('Running');

  }

  async route(req, res, next) {
    const result = await ReadWrite.readWrite();
    res.send(result);
  }
}

const obj1 = new Start();
app.get('/', obj1.route);
module.exports = Start;

ReadWrite.js

Here we making a makeObject method, which makes sure that a object is returned, only if a object is not available.

class ReadWrite {
    constructor() {
        console.log('Read Write'); 
        this.x;   
    }
    static makeObject() {        
        if (!this.x) {
            this.x = new ReadWrite();
        }
        return this.x;
    }
    read(){
    return "read"
    }

    write(){
        return "write"
    }


    async readWrite() {
        try {
            const obj = ReadWrite.makeObject();
            const result = await Promise.all([ obj.read(), obj.write()])
            console.log(result);
            check();
            return result
        }
        catch(err) {
            console.log(err);

        }
    }
}
module.exports = ReadWrite;

For more explanation go to https://medium.com/@nynptel/node-js-boiler-plate-code-using-singleton-classes-5b479e513f74

Detect when browser receives file download

I just had this exact same problem. My solution was to use temporary files since I was generating a bunch of temporary files already. The form is submitted with:

var microBox = {
    show : function(content) {
        $(document.body).append('<div id="microBox_overlay"></div><div id="microBox_window"><div id="microBox_frame"><div id="microBox">' +
        content + '</div></div></div>');
        return $('#microBox_overlay');
    },

    close : function() {
        $('#microBox_overlay').remove();
        $('#microBox_window').remove();
    }
};

$.fn.bgForm = function(content, callback) {
    // Create an iframe as target of form submit
    var id = 'bgForm' + (new Date().getTime());
    var $iframe = $('<iframe id="' + id + '" name="' + id + '" style="display: none;" src="about:blank"></iframe>')
        .appendTo(document.body);
    var $form = this;
    // Submittal to an iframe target prevents page refresh
    $form.attr('target', id);
    // The first load event is called when about:blank is loaded
    $iframe.one('load', function() {
        // Attach listener to load events that occur after successful form submittal
        $iframe.load(function() {
            microBox.close();
            if (typeof(callback) == 'function') {
                var iframe = $iframe[0];
                var doc = iframe.contentWindow.document;
                var data = doc.body.innerHTML;
                callback(data);
            }
        });
    });

    this.submit(function() {
        microBox.show(content);
    });

    return this;
};

$('#myForm').bgForm('Please wait...');

At the end of the script that generates the file I have:

header('Refresh: 0;url=fetch.php?token=' . $token);
echo '<html></html>';

This will cause the load event on the iframe to be fired. Then the wait message is closed and the file download will then start. Tested on IE7 and Firefox.

How to open an existing project in Eclipse?

If it's a maven project, go to file>import>maven project >existing maven project, then browse for the folder that contains the project, select folder then click finish. That worked for me

How do I change tab size in Vim?

UPDATE

If you are working in a particular project I highly recommend using editorconfig.

It lets you define an .editorconfig file at the root of your repository defining the indentation you want to use for each file type across your repository.

For example:

root = true

[*.css]
charset = utf-8
indent_style = space
indent_size = 4

[*.js]
charset = utf-8
indent_style = space
indent_size = 2

There is a vim plugin that automatically configures vim according to the config file for file you open.

On top of that the .editorconfig file is automatically supported on many other IDEs and editors so it is the best option for collaborating between users with different environments.

ORIGINAL ANSWER

If you need to change sizes often and you don't want to bind this to a specific file type you can have predefined commands on your .vimrc file to quickly switch preferences:

nmap <leader>t :set expandtab tabstop=4 shiftwidth=4 softtabstop=4<CR>
nmap <leader>m :set expandtab tabstop=2 shiftwidth=2 softtabstop=2<CR>

This maps two different sets of sizes to keys \t and \m. You can rebind this to whatever keys you want.

Check if a file exists or not in Windows PowerShell?

Test-Path may give odd answer. E.g. "Test-Path c:\temp\ -PathType leaf" gives false, but "Test-Path c:\temp* -PathType leaf" gives true. Sad :(

Create controller for partial view in ASP.NET MVC

You don't need a controller and when using .Net 5 (MVC 6) you can render the partial view async

@await Html.PartialAsync("_LoginPartial")

or

@{await Html.RenderPartialAsync("PartialName");}

or if you are using .net core 2.1 > you can just use:

<partial name="Shared/_ProductPartial.cshtml"
         for="Product" />

Difference between pre-increment and post-increment in a loop?

Pre-increment ++i increments the value of i and evaluates to the new incremented value.

int i = 3;
int preIncrementResult = ++i;
Assert( preIncrementResult == 4 );
Assert( i == 4 );

Post-increment i++ increments the value of i and evaluates to the original non-incremented value.

int i = 3;
int postIncrementResult = i++;
Assert( postIncrementtResult == 3 );
Assert( i == 4 );

In C++, the pre-increment is usually preferred where you can use either.

This is because if you use post-increment, it can require the compiler to have to generate code that creates an extra temporary variable. This is because both the previous and new values of the variable being incremented need to be held somewhere because they may be needed elsewhere in the expression being evaluated.

So, in C++ at least, there can be a performance difference which guides your choice of which to use.

This is mainly only a problem when the variable being incremented is a user defined type with an overridden ++ operator. For primitive types (int, etc) there's no performance difference. But, it's worth sticking to the pre-increment operator as a guideline unless the post-increment operator is definitely what's required.

There's some more discussion here.

In C++ if you're using STL, then you may be using for loops with iterators. These mainly have overridden ++ operators, so sticking to pre-increment is a good idea. Compilers get smarter all the time though, and newer ones may be able to perform optimizations that mean there's no performance difference - especially if the type being incremented is defined inline in header file (as STL implementations often are) so that the compiler can see how the method is implemented and can then know what optimizations are safe to perform. Even so, it's probably still worth sticking to pre-increment because loops get executed lots of times and this means a small performance penalty could soon get amplified.


In other languages such as C# where the ++ operator can't be overloaded there is no performance difference. Used in a loop to advance the loop variable, the pre and post increment operators are equivalent.

Correction: overloading ++ in C# is allowed. It seems though, that compared to C++, in C# you cannot overload the pre and post versions independently. So, I would assume that if the result of calling ++ in C# is not assigned to a variable or used as part of a complex expression, then the compiler would reduce the pre and post versions of ++ down to code that performs equivalently.

Nodejs send file in response

You need use Stream to send file (archive) in a response, what is more you have to use appropriate Content-type in your response header.

There is an example function that do it:

const fs = require('fs');

// Where fileName is name of the file and response is Node.js Reponse. 
responseFile = (fileName, response) => {
  const filePath =  "/path/to/archive.rar" // or any file format

  // Check if file specified by the filePath exists 
  fs.exists(filePath, function(exists){
      if (exists) {     
        // Content-type is very interesting part that guarantee that
        // Web browser will handle response in an appropriate manner.
        response.writeHead(200, {
          "Content-Type": "application/octet-stream",
          "Content-Disposition": "attachment; filename=" + fileName
        });
        fs.createReadStream(filePath).pipe(response);
      } else {
        response.writeHead(400, {"Content-Type": "text/plain"});
        response.end("ERROR File does not exist");
      }
    });
  }
}

The purpose of the Content-Type field is to describe the data contained in the body fully enough that the receiving user agent can pick an appropriate agent or mechanism to present the data to the user, or otherwise deal with the data in an appropriate manner.

"application/octet-stream" is defined as "arbitrary binary data" in RFC 2046, purpose of this content-type is to be saved to disk - it is what you really need.

"filename=[name of file]" specifies name of file which will be downloaded.

For more information please see this stackoverflow topic.

Send string to stdin

Solution

You want to (1) create stdout output in one process (like echo '…') and (2) redirect that output to stdin input of another process but (3) without the use of the bash pipe mechanism. Here's a solution that matches all three conditions:

/my/bash/script < <(echo 'This string will be sent to stdin.')

The < is normal input redirection for stdin. The <(…) is bash process substitution. Roughly it creates a /dev/fd/… file with the output of the substituting command and passes that filename in place of the <(…), resulting here for example in script < /dev/fd/123. For details, see this answer.

Comparison with other solutions

  • A one-line heredoc sent to stdin script <<< 'string' only allows to send static strings, not the output of other commands.

  • Process substitution alone, such as in diff <(ls /bin) <(ls /usr/bin), does not send anything to stdin. Instead, the process output is saved into a file, and its path is passed as a command line argument. For the above example, this is equivalent to diff /dev/fd/10 /dev/fd/11, a command where diff receives no input from stdin.

Use cases

I like that, unlike the pipe mechanism, the < <(…) mechanism allows to put the command first and all input after it, as is the standard for input from command line options.

However, beyond commandline aesthetics, there are some cases where a pipe mechanism cannot be used. For example, when a certain command has to be provided as argument to another command, such as in this example with sshpass.

Recursive Lock (Mutex) vs Non-Recursive Lock (Mutex)

The right mental model for using mutexes: The mutex protects an invariant.

Why are you sure that this is really right mental model for using mutexes? I think right model is protecting data but not invariants.

The problem of protecting invariants presents even in single-threaded applications and has nothing common with multi-threading and mutexes.

Furthermore, if you need to protect invariants, you still may use binary semaphore wich is never recursive.

How to send a pdf file directly to the printer using JavaScript?

<?php

$browser_ver = get_browser(null,true);
//echo $browser_ver['browser'];

if($browser_ver['browser'] == 'IE') {
?>

<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>pdf print test</title>
<style>
    html { height:100%; }
</style>
<script>
    function printIt(id) {
        var pdf = document.getElementById("samplePDF");
        pdf.click();
        pdf.setActive();
        pdf.focus();
        pdf.print();
    }
</script>
</head>

<body style="margin:0; height:100%;">

<embed id="samplePDF" type="application/pdf" src="/pdfs/2010/dash_fdm350.pdf" width="100%" height="100%" />
<button onClick="printIt('samplePDF')">Print</button>


</body>
</html>

<?php
} else {
?>
<HTML>
<script Language="javascript">

function printfile(id) { 
    window.frames[id].focus();
    window.frames[id].print();
} 

</script>
<BODY marginheight="0" marginwidth="0">

<iframe src="/pdfs/2010/dash_fdm350.pdf" id="objAdobePrint" name="objAdobePrint" height="95%" width="100%" frameborder=0></iframe><br>

<input type="button" value="Print" onclick="javascript:printfile('objAdobePrint');">

</BODY>
</HTML>
<?php
}
?>

Font Awesome icon inside text input element

<HTML>
<head>
<style>
.inp1{
color:#2E64FE;
width:350px;
height:35px;
border:solid;
font-size:20px;
text-align:left;
}
</style>
</head>

<body>

<div class="inp1">          
<a href="#" class=""><i class="fa fa-search"></i></a>
</div>

Getting the last revision number in SVN?

Just svn info in BASH will give you all details

RESULT:
Path: .
URL: 
Repository Root: 
Repository UUID: 
Revision: 54
Node Kind: directory
Schedule: normal
Last Changed Author: 
Last Changed Rev: 54
Last Changed Date: 

You will get the REVISION from this

MySQL DROP all tables, ignoring foreign keys

One-step solution without copying returned value from SQL Select query using procedure.

SET FOREIGN_KEY_CHECKS = 0

SET @TABLES = NULL;
SELECT GROUP_CONCAT('`', table_schema, '`.`', table_name,'`') INTO @TABLES FROM information_schema.tables 
  WHERE table_schema = 'databaseName';

SET @TABLES = CONCAT('DROP TABLE IF EXISTS ', @TABLES);

PREPARE stmt FROM @TABLES;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET FOREIGN_KEY_CHECKS = 1

PHP Checking if the current date is before or after a set date

if( strtotime($database_date) > strtotime('now') ) {
...

shared global variables in C

In the header file write it with extern. And at the global scope of one of the c files declare it without extern.

How to get the browser language using JavaScript

The "JavaScript" way:

var lang = navigator.language || navigator.userLanguage; //no ?s necessary

Really you should be doing language detection on the server, but if it's absolutely necessary to know/use via JavaScript, it can be gotten.

Multiple Inheritance in C#

Multiple inheritance is one of those things that generally causes more problems than it solves. In C++ it fits the pattern of giving you enough rope to hang yourself, but Java and C# have chosen to go the safer route of not giving you the option. The biggest problem is what to do if you inherit multiple classes that have a method with the same signature that the inheritee doesn't implement. Which class's method should it choose? Or should that not compile? There is generally another way to implement most things that doesn't rely on multiple inheritance.

Simple way to count character occurrences in a string

You can look at sorting the string -- treat it as a char array -- and then do a modified binary search which counts occurrences? But I agree with @tofutim that traversing it is the most efficient -- O(N) versus O(N * logN) + O(logN)

DataTables warning: Requested unknown parameter '0' from the data source for row '0'

If you're using knockout.bindings.dataTables.js then you can edit the file and replace this line

dataTable.fnAddData(unwrappedItems);

with

if (unwrappedItems.length > 0) {
    dataTable.fnAddData(unwrappedItems);
}

This has help me and i hope will help you.

How to change the background color of a UIButton while it's highlighted?

if you won't override just set two action touchDown touchUpInside

Find most frequent value in SQL column

Try something like:

SELECT       `column`
    FROM     `your_table`
    GROUP BY `column`
    ORDER BY COUNT(*) DESC
    LIMIT    1;

Create a hexadecimal colour based on a string with JavaScript

Just porting over the Java from Compute hex color code for an arbitrary string to Javascript:

function hashCode(str) { // java String#hashCode
    var hash = 0;
    for (var i = 0; i < str.length; i++) {
       hash = str.charCodeAt(i) + ((hash << 5) - hash);
    }
    return hash;
} 

function intToRGB(i){
    var c = (i & 0x00FFFFFF)
        .toString(16)
        .toUpperCase();

    return "00000".substring(0, 6 - c.length) + c;
}

To convert you would do:

intToRGB(hashCode(your_string))

Rails 4 - Strong Parameters - Nested Objects

I found this suggestion useful in my case:

  def product_params
    params.require(:product).permit(:name).tap do |whitelisted|
      whitelisted[:data] = params[:product][:data]
    end
  end

Check this link of Xavier's comment on github.

This approach whitelists the entire params[:measurement][:groundtruth] object.

Using the original questions attributes:

  def product_params
    params.require(:measurement).permit(:name, :groundtruth).tap do |whitelisted|
      whitelisted[:groundtruth] = params[:measurement][:groundtruth]
    end
  end

How to get day of the month?

It is simplified a lot in version Java 8. I have given some util methods below.

To get the day of the month in the format of int for the given day, month, and year.

    public static int findDay(final int month, final int day, final int year) {
        // System.out.println(LocalDate.of(year, month, day).getDayOfMonth());
        return LocalDate.of(year, month, day).getDayOfMonth();
    }

To get current day of the month in the format of int.

    public static int findDay(final int month, final int day, final int year) {
        // System.out.println(LocalDate.now(ZoneId.of("Asia/Kolkata")).getDayOfMonth());
        return LocalDate.now(ZoneId.of("Asia/Kolkata")).getDayOfMonth();
    }

To get the day of the week in the format of String for the given day, month, and year.

    public static String findDay(final int month, final int day, final int year) {
        // System.out.println(LocalDate.of(year, month, day).getDayOfWeek());
        return LocalDate.of(year, month, day).getDayOfWeek().toString();
    }

To get current day of the week in the format of String.

    public static String findDay(final int month, final int day, final int year) {
        // System.out.println(LocalDate.now(ZoneId.of("Asia/Kolkata"))..getDayOfWeek());
        return LocalDate.now(ZoneId.of("Asia/Kolkata")).getDayOfWeek().toString();
    }

IIS7 Cache-Control

The F5 Refresh has the semantic of "please reload the current HTML AND its direct dependancies". Hence you should expect to see any imgs, css and js resource directly referenced by the HTML also being refetched. Of course a 304 is an acceptable response to this but F5 refresh implies that the browser will make the request rather than rely on fresh cache content.

Instead try simply navigating somewhere else and then navigating back.

You can force the refresh, past a 304, by holding ctrl while pressing f5 in most browsers.

How to use multiprocessing pool.map with multiple arguments?

From python 3.4.4, you can use multiprocessing.get_context() to obtain a context object to use multiple start methods:

import multiprocessing as mp

def foo(q, h, w):
    q.put(h + ' ' + w)
    print(h + ' ' + w)

if __name__ == '__main__':
    ctx = mp.get_context('spawn')
    q = ctx.Queue()
    p = ctx.Process(target=foo, args=(q,'hello', 'world'))
    p.start()
    print(q.get())
    p.join()

Or you just simply replace

pool.map(harvester(text,case),case, 1)

by:

pool.apply_async(harvester(text,case),case, 1)

require_once :failed to open stream: no such file or directory

this will work as well

 require_once(realpath($_SERVER["DOCUMENT_ROOT"]) .'/mysite/php/includes/dbconn.inc');

How to format numbers?

Due to the bugs found by JasperV — good points! — I have rewritten my old code. I guess I only ever used this for positive values with two decimal places.

Depending on what you are trying to achieve, you may want rounding or not, so here are two versions split across that divide.

First up, with rounding.

I've introduced the toFixed() method as it better handles rounding to specific decimal places accurately and is well support. It does slow things down however.

This version still detaches the decimal, but using a different method than before. The w|0 part removes the decimal. For more information on that, this is a good answer. This then leaves the remaining integer, stores it in k and then subtracts it again from the original number, leaving the decimal by itself.

Also, if we're to take negative numbers into account, we need to while loop (skipping three digits) until we hit b. This has been calculated to be 1 when dealing with negative numbers to avoid putting something like -,100.00

The rest of the loop is the same as before.

function formatThousandsWithRounding(n, dp){
  var w = n.toFixed(dp), k = w|0, b = n < 0 ? 1 : 0,
      u = Math.abs(w-k), d = (''+u.toFixed(dp)).substr(2, dp),
      s = ''+k, i = s.length, r = '';
  while ( (i-=3) > b ) { r = ',' + s.substr(i, 3) + r; }
  return s.substr(0, i + 3) + r + (d ? '.'+d: '');
};

In the snippet below you can edit the numbers to test yourself.

_x000D_
_x000D_
function formatThousandsWithRounding(n, dp){_x000D_
  var w = n.toFixed(dp), k = w|0, b = n < 0 ? 1 : 0,_x000D_
      u = Math.abs(w-k), d = (''+u.toFixed(dp)).substr(2, dp),_x000D_
      s = ''+k, i = s.length, r = '';_x000D_
  while ( (i-=3) > b ) { r = ',' + s.substr(i, 3) + r; }_x000D_
  return s.substr(0, i + 3) + r + (d ? '.'+d: '');_x000D_
};_x000D_
_x000D_
var dp;_x000D_
var createInput = function(v){_x000D_
  var inp = jQuery('<input class="input" />').val(v);_x000D_
  var eql = jQuery('<span>&nbsp;=&nbsp;</span>');_x000D_
  var out = jQuery('<div class="output" />').css('display', 'inline-block');_x000D_
  var row = jQuery('<div class="row" />');_x000D_
  row.append(inp).append(eql).append(out);_x000D_
  inp.keyup(function(){_x000D_
    out.text(formatThousandsWithRounding(Number(inp.val()), Number(dp.val())));_x000D_
  });_x000D_
  inp.keyup();_x000D_
  jQuery('body').append(row);_x000D_
  return inp;_x000D_
};_x000D_
_x000D_
jQuery(function(){_x000D_
  var numbers = [_x000D_
    0, 99.999, -1000, -1000000, 1000000.42, -1000000.57, -1000000.999_x000D_
  ], inputs = $();_x000D_
  dp = jQuery('#dp');_x000D_
  for ( var i=0; i<numbers.length; i++ ) {_x000D_
    inputs = inputs.add(createInput(numbers[i]));_x000D_
  }_x000D_
  dp.on('input change', function(){_x000D_
    inputs.keyup();_x000D_
  });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input id="dp" type="range" min="0" max="5" step="1" value="2" title="number of decimal places?" />
_x000D_
_x000D_
_x000D_

Now the other version, without rounding.

This takes a different route and attempts to avoid mathematical calculation (as this can introduce rounding, or rounding errors). If you don't want rounding, then you are only dealing with things as a string i.e. 1000.999 converted to two decimal places will only ever be 1000.99 and not 1001.00.

This method avoids using .split() and RegExp() however, both of which are very slow in comparison. And whilst I learned something new from Michael's answer about toLocaleString, I also was surprised to learn that it is — by quite a way — the slowest method out of them all (at least in Firefox and Chrome; Mac OSX).

Using lastIndexOf() we find the possibly existent decimal point, and from there everything else is pretty much the same. Save for the padding with extra 0s where needed. This code is limited to 5 decimal places. Out of my test this was the faster method.

var formatThousandsNoRounding = function(n, dp){
  var e = '', s = e+n, l = s.length, b = n < 0 ? 1 : 0,
      i = s.lastIndexOf('.'), j = i == -1 ? l : i,
      r = e, d = s.substr(j+1, dp);
  while ( (j-=3) > b ) { r = ',' + s.substr(j, 3) + r; }
  return s.substr(0, j + 3) + r + 
    (dp ? '.' + d + ( d.length < dp ? 
        ('00000').substr(0, dp - d.length):e):e);
};

_x000D_
_x000D_
var formatThousandsNoRounding = function(n, dp){_x000D_
  var e = '', s = e+n, l = s.length, b = n < 0 ? 1 : 0,_x000D_
      i = s.lastIndexOf('.'), j = i == -1 ? l : i,_x000D_
      r = e, d = s.substr(j+1, dp);_x000D_
  while ( (j-=3) > b ) { r = ',' + s.substr(j, 3) + r; }_x000D_
  return s.substr(0, j + 3) + r + _x000D_
   (dp ? '.' + d + ( d.length < dp ? _x000D_
     ('00000').substr(0, dp - d.length):e):e);_x000D_
};_x000D_
_x000D_
var dp;_x000D_
var createInput = function(v){_x000D_
  var inp = jQuery('<input class="input" />').val(v);_x000D_
  var eql = jQuery('<span>&nbsp;=&nbsp;</span>');_x000D_
  var out = jQuery('<div class="output" />').css('display', 'inline-block');_x000D_
  var row = jQuery('<div class="row" />');_x000D_
  row.append(inp).append(eql).append(out);_x000D_
  inp.keyup(function(){_x000D_
    out.text(formatThousandsNoRounding(Number(inp.val()), Number(dp.val())));_x000D_
  });_x000D_
  inp.keyup();_x000D_
  jQuery('body').append(row);_x000D_
  return inp;_x000D_
};_x000D_
_x000D_
jQuery(function(){_x000D_
  var numbers = [_x000D_
    0, 99.999, -1000, -1000000, 1000000.42, -1000000.57, -1000000.999_x000D_
  ], inputs = $();_x000D_
  dp = jQuery('#dp');_x000D_
  for ( var i=0; i<numbers.length; i++ ) {_x000D_
    inputs = inputs.add(createInput(numbers[i]));_x000D_
  }_x000D_
  dp.on('input change', function(){_x000D_
    inputs.keyup();_x000D_
  });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input id="dp" type="range" min="0" max="5" step="1" value="2" title="number of decimal places?" />
_x000D_
_x000D_
_x000D_

I'll update with an in-page snippet demo shortly, but for now here is a fiddle:

https://jsfiddle.net/bv2ort0a/2/



Old Method

Why use RegExp for this? — don't use a hammer when a toothpick will do i.e. use string manipulation:

var formatThousands = function(n, dp){
  var s = ''+(Math.floor(n)), d = n % 1, i = s.length, r = '';
  while ( (i -= 3) > 0 ) { r = ',' + s.substr(i, 3) + r; }
  return s.substr(0, i + 3) + r + 
    (d ? '.' + Math.round(d * Math.pow(10, dp || 2)) : '');
};

walk through

formatThousands( 1000000.42 );

First strip off decimal:

s = '1000000', d = ~ 0.42

Work backwards from the end of the string:

',' + '000'
',' + '000' + ',000'

Finalise by adding the leftover prefix and the decimal suffix (with rounding to dp no. decimal points):

'1' + ',000,000' + '.42'

fiddlesticks

http://jsfiddle.net/XC3sS/

Grab a segment of an array in Java without creating a new array on heap

One option would be to pass the whole array and the start and end indices, and iterate between those instead of iterating over the whole array passed.

void method1(byte[] array) {
    method2(array,4,5);
}
void method2(byte[] smallarray,int start,int end) {
    for ( int i = start; i <= end; i++ ) {
        ....
    }
}

Gradle build without tests

The accepted answer is the correct one.

OTOH, the way I previously solved this was to add the following to all projects:

test.onlyIf { ! Boolean.getBoolean('skip.tests') }

Run the build with -Dskip.tests=true and all test tasks will be skipped.

How to change the link color in a specific class for a div CSS

I think you want to put a, in front of a:link (a, a:link) in your CSS file. The only way I could get rid of that awful default blue link color. I'm not sure if this was necessary for earlier version of the browsers we have, because it's supposed to work without a

How do I fix a .NET windows application crashing at startup with Exception code: 0xE0434352?

So.. I had noticed in event viewer that this crash corresponded to a "System.IO.FileNotFoundException" error.

So I fired ProcMon and noticed that one of the program dlls was failing to load vcruntime140. So I simply installed vs15 redist and it worked.

Oracle: is there a tool to trace queries, like Profiler for sql server?

I found an easy solution

Step1. connect to DB with an admin user using PLSQL or sqldeveloper or any other query interface

Step2. run the script bellow; in the S.SQL_TEXT column, you will see the executed queries

SELECT            
 S.LAST_ACTIVE_TIME,     
 S.MODULE,
 S.SQL_FULLTEXT, 
 S.SQL_PROFILE,
 S.EXECUTIONS,
 S.LAST_LOAD_TIME,
 S.PARSING_USER_ID,
 S.SERVICE                                                                       
FROM
 SYS.V_$SQL S, 
 SYS.ALL_USERS U
WHERE
 S.PARSING_USER_ID=U.USER_ID 
 AND UPPER(U.USERNAME) IN ('oracle user name here')   
ORDER BY TO_DATE(S.LAST_LOAD_TIME, 'YYYY-MM-DD/HH24:MI:SS') desc;

The only issue with this is that I can't find a way to show the input parameters values(for function calls), but at least we can see what is ran in Oracle and the order of it without using a specific tool.

unix diff side-to-side results?

You should have sdiff for side-by-side merge of file differences. Take a read of man sdiff for the full story.

How to clear APC cache entries?

You can use the PHP function apc_clear_cache.

Calling apc_clear_cache() will clear the system cache and calling apc_clear_cache('user') will clear the user cache.

difference between @size(max = value ) and @min(value) @max(value)

From the documentation I get the impression that in your example it would be intended to use:

@Range(min= SEQ_MIN_VALUE, max= SEQ_MAX_VALUE)

Checks whether the annotated value lies between (inclusive) the specified minimum and maximum. Supported data types:

BigDecimal, BigInteger, CharSequence, byte, short, int, long and the respective wrappers of the primitive types

Android ImageView Animation

One way - split you image into N rotating it slightly every time. I'd say 5 is enough. then create something like this in drawable

<animation-list   android:id="@+id/handimation" android:oneshot="false" 
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/progress1" android:duration="150" />
    <item android:drawable="@drawable/progress2" android:duration="150" />
    <item android:drawable="@drawable/progress3" android:duration="150" />
 </animation-list> 

code start

progress.setVisibility(View.VISIBLE);
AnimationDrawable frameAnimation = (AnimationDrawable)progress.getDrawable();
frameAnimation.setCallback(progress);
frameAnimation.setVisible(true, true);

code stop

AnimationDrawable frameAnimation = (AnimationDrawable)progress.getDrawable();
frameAnimation.stop();
frameAnimation.setCallback(null);
frameAnimation = null;
progress.setVisibility(View.GONE);

more here

How do I format {{$timestamp}} as MM/DD/YYYY in Postman?

Any future date in JavaScript (postman test uses JavaScript) can be retrieved as:

var dateNow = new Date();  
var twoWeeksFutureDate = new Date(dateNow.setDate(dateNow.getDate() + 14)).toISOString();

postman.setEnvironmentVariable("future-date", twoWeeksFutureDate);

How to compare each item in a list with the rest, only once?

Use itertools.combinations(mylist, 2)

mylist = range(5)
for x,y in itertools.combinations(mylist, 2):
    print x,y

0 1
0 2
0 3
0 4
1 2
1 3
1 4
2 3
2 4
3 4

How do I directly modify a Google Chrome Extension File? (.CRX)

If you have installed the Portable version of Chrome, or have it installed in a custom directory - the extensions won't be available in directory referenced in above answers.

Try right-clicking on Chrome's shortcut & Check the "Target" directory. From there, navigate to one directory above and you should be able to see the User Data folder and then can use the answers mentioned above

C# error: Use of unassigned local variable

The compiler doesn't know that Environment.Exit() does not return. Why not just "return" from Main()?

How can I truncate a string to the first 20 words in PHP?

use explode() .

Example from the docs.

// Example 1
$pizza  = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2

note that explode has a limit function. So you could do something like

$message = implode(" ", explode(" ", $long_message, 20));

HTML <sup /> tag affecting line height, how to make it consistent?

I prefer the solution suggested here, as exemplified by this jsfiddle:

CSS:

sup, sub {
  vertical-align: baseline;
  position: relative;
  top: -0.2em;
}

sub {
  top: 0.2em;
}

HTML:

<span>The following equation is perhaps the most well known of all: </span><span id="box">E<sub>a</sub> = mc<sup>2</sup></span><span>.  And it gives an opportunity to try out a superscript and even throw in a superfluous subscript!  I'm sure that Einstein would be pleased.</span>.

The beauty of this solution is that you can tailor the vertical positioning of the superscript and subscript, to avoid any clashes with the line above or below... in the above, just increase or decrease the 0.2em to suit your requirements.

Get source JARs from Maven repository

If a project creates a jar of the project sources and deploys it to a maven repository, then you'll find it :)

Just FYI, sources artifacts are generally created by the maven-source-plugin. This plugin can bundle the main or test sources of a project into a jar archive and, as explained in Configuring Source Plugin:

(...) The generated jar file will be named by the value of the finalName plus "-sources" if it is the main sources. Otherwise, it would be finalName plus "-test-sources" if it is the test sources.

The additional text was given to describe an artifact ("-sources" or "-test-sources" here) is called a classifier.

To declare a dependency on an artifact that uses a classifier, simply add the <classifier> element. For example:

<dependency>
  <groupId>org.hibernate</groupId>
  <artifactId>hibernate</artifactId>
  <version>3.2.7.ga</version>
  <classifier>sources</classifier>
</dependency>

Note that you generally don't do this, most IDEs provide support to download sources (and/or JavaDoc) from the main artifact without declaring explicitly a dependency on them.

Finally, also note that some repository search engines allow searching for artifacts using the classifier (at least Nexus does with the advanced search). See this search for example.

ImportError: No module named 'django.core.urlresolvers'

use this one:

from django.urls import reverse

How do you overcome the svn 'out of date' error?

Are you moving it using svn mv, or just mv? I think using just mv may cause this issue.

Evenly space multiple views within a container view

Very quick Interface Builder solution:

For any number of views to be evenly spaced within a superview, simply give each an "Align Center X to superview" constraint for horizontal layout, or "Align Center Y superview" for vertical layout, and set the Multiplier to be N:p (NOTE: some have had better luck with p:N - see below)

where

N = total number of views, and

p = position of the view including spaces

First position is 1, then a space, making the next position 3, so p becomes a series [1,3,5,7,9,...]. Works for any number of views.

So, if you have 3 views to space out, it looks like this:

Illustration of how to evenly spread views in IB

EDIT Note: The choice of N:p or p:N depends on the relation order of your alignment constraint. If "First Item" is Superview.Center, you may use p:N, while if Superview.Center is "Second Item", you may use N:p. If in doubt, just try both out... :-)

How can I zoom an HTML element in Firefox and Opera?

Try this code, this’ll work:

-moz-transform: scale(2);

You can refer to this.

CUDA incompatible with my gcc version

For CUDA 6.5 (and apparently 7.0 and 7.5), I've created a version of the gcc 4.8.5 RPM package (under Fedora Core 30) that allows that version of gcc to be install alongside your system's current GCC.

You can find all of that information here.

"CSV file does not exist" for a filename with embedded quotes

Being on jupyter notebook it works for me including the relative path only. For example:

df = pd.read_csv ('file.csv')

But, for example, in vscode I have to put the complete path:

df = pd.read_csv ('/home/code/file.csv')

MySQL LIKE IN()?

This would be correct:

SELECT * FROM table WHERE field regexp concat_ws("|",(
"111",
"222",
"333"
));

How to get all values from python enum class?

To use Enum with any type of value, try this:
Updated with some improvements... Thanks @Jeff, by your tip!

from enum import Enum

class Color(Enum):
    RED = 1
    GREEN = 'GREEN'
    BLUE = ('blue', '#0000ff')

    @staticmethod
    def list():
        return list(map(lambda c: c.value, Color))

print(Color.list())

As result:

[1, 'GREEN', ('blue', '#0000ff')]

How to compare values which may both be null in T-SQL

Along the same lines as @Eric's answer, but without using a 'NULL' symbol.

(Field1 = Field2) OR (ISNULL(Field1, Field2) IS NULL)

This will be true only if both values are non-NULL, and equal each other, or both values are NULL