Programs & Examples On #Nested if

This tag refers to a code structure in which multiple if-statements are placed in a "nested" form (i.e. one if-statement is contained within another).

ssh "permissions are too open" error

Type this command to resolve your issue.

chmod 600 ~/.ssh/id_rsa

Bringing a subview to be in front of all other views

In c#, View.BringSubviewToFront(childView); YourView.Layer.ZPosition = 1; both should work.

There was no endpoint listening at (url) that could accept the message

If you are using custom binding, please make sure that you are putting the same name for both custom binding (Server and Client)in config files

<bindings>
<customBinding>
 <binding name="BufferedHttpServerNoAuth" closeTimeout="00:10:00" openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00">
          <gzipMessageEncoding innerMessageEncoding="textMessageEncoding" MaxArrayLength="10485760" MaxBytesPerRead="31457280" MaxStringContentLength="102400000" />
          <httpsTransport hostNameComparisonMode="StrongWildcard" manualAddressing="False" maxReceivedMessageSize="31457280" authenticationScheme="Anonymous" bypassProxyOnLocal="True" realm="" useDefaultWebProxy="False" />
</binding>
</customBinding>
</bindings>

the binding name "BufferedHttpServerNoAuth" should be same in both.

Hope this would help someone

Before and After Suite execution hook in jUnit 4.x

The only way I think then to get the functionality you want would be to do something like

import junit.framework.Test;  
import junit.framework.TestResult;  
import junit.framework.TestSuite;  

public class AllTests {  
    public static Test suite() {  
        TestSuite suite = new TestSuite("TestEverything");  
        //$JUnit-BEGIN$  
        suite.addTestSuite(TestOne.class);  
        suite.addTestSuite(TestTwo.class);  
        suite.addTestSuite(TestThree.class);  
        //$JUnit-END$  
     }  

     public static void main(String[] args)  
     {  
        AllTests test = new AllTests();  
        Test testCase = test.suite();  
        TestResult result = new TestResult();  
        setUp();  
        testCase.run(result);  
        tearDown();  
     }  
     public void setUp() {}  
     public void tearDown() {}  
} 

I use something like this in eclipse, so I'm not sure how portable it is outside of that environment

How to add /usr/local/bin in $PATH on Mac

I tend to find this neat

sudo mkdir -p /etc/paths.d   # was optional in my case
echo /usr/local/git/bin  | sudo tee /etc/paths.d/mypath1

NULL vs nullptr (Why was it replaced?)

Here is Bjarne Stroustrup's wordings,

In C++, the definition of NULL is 0, so there is only an aesthetic difference. I prefer to avoid macros, so I use 0. Another problem with NULL is that people sometimes mistakenly believe that it is different from 0 and/or not an integer. In pre-standard code, NULL was/is sometimes defined to something unsuitable and therefore had/has to be avoided. That's less common these days.

If you have to name the null pointer, call it nullptr; that's what it's called in C++11. Then, "nullptr" will be a keyword.

How to plot all the columns of a data frame in R

With lattice:

library(lattice)

df <- data.frame(time = 1:10,
                 a = cumsum(rnorm(10)),
                 b = cumsum(rnorm(10)),
                 c = cumsum(rnorm(10)))

form <- as.formula(paste(paste(names(df)[- 1],  collapse = ' + '),  
                         'time',  sep = '~'))

xyplot(form,  data = df,  type = 'b',  outer = TRUE)

Remove lines that contain certain string

You could simply not include the line into the new file instead of doing replace.

for line in infile :
     if 'bad' not in line and 'naughty' not in line:
            newopen.write(line)

Eclipse: Set maximum line length for auto formatting?

In preferences Java -> Code Style -> Formatter, edit the profile. Under the Line Wrapping tab is the primary option for line width (Maximum line width:). In the Comments tab you have a separate option Maximum line width for comments:, which will also need to be changed to affect comment wrapping.

You will need to make your own profile to make these changes in if you using one of the [Built-in] ones. Just click "New..." on the formatter preferences page.

Java Multiple Inheritance

  1. Define interfaces for defining the capabilities. You can define multiple interfaces for multiple capabilities. These capabilities can be implemented by specific Animal or Bird.
  2. Use inheritance to establish relationships among classes by sharing non-static and non-public data/methods.
  3. Use Decorator_pattern to add capabilities dynamically. This will allow you to reduce number of inheritance classes & combinations.

Have a look at below example for better understanding

When to Use the Decorator Pattern?

Is it possible to ignore one single specific line with Pylint?

import config.logging_settings # pylint: disable=W0611

That was simple and is specific for that line.

You can and should use the more readable form:

import config.logging_settings # pylint: disable=unused-import

How to select all textareas and textboxes using jQuery?

$("**:**input[type=text], :input[type='textarea']").css({width: '90%'});

SQL: Alias Column Name for Use in CASE Statement

@OMG Ponies - One of my reasons of not using the following code

SELECT t.col1 as a, 
     CASE WHEN t.col1 = 'test' THEN 'yes' END as value 
FROM TABLE t;

can be that the t.col1 is not an actual column in the table. For example, it can be a value from a XML column like

Select XMLColumnName.value('(XMLPathOfTag)[1]', 'varchar(max)') 
as XMLTagAlias from Table

Taking multiple inputs from user in python

The best way to practice by using a single liner,
Syntax:

list(map(inputType, input("Enter").split(",")))

Taking multiple integer inputs:

   list(map(int, input('Enter: ').split(',')))

enter image description here

Taking multiple Float inputs:

list(map(float, input('Enter: ').split(',')))

enter image description here

Taking multiple String inputs:

list(map(str, input('Enter: ').split(',')))

enter image description here

how to get list of port which are in use on the server

nmap is a useful tool for this kind of thing

Fragment onCreateView and onActivityCreated called twice

The two upvoted answers here show solutions for an Activity with navigation mode NAVIGATION_MODE_TABS, but I had the same issue with a NAVIGATION_MODE_LIST. It caused my Fragments to inexplicably lose their state when the screen orientation changed, which was really annoying. Thankfully, due to their helpful code I managed to figure it out.

Basically, when using a list navigation, ``onNavigationItemSelected()is automatically called when your activity is created/re-created, whether you like it or not. To prevent your Fragment'sonCreateView()from being called twice, this initial automatic call toonNavigationItemSelected()should check whether the Fragment is already in existence inside your Activity. If it is, return immediately, because there is nothing to do; if it isn't, then simply construct the Fragment and add it to the Activity like you normally would. Performing this check prevents your Fragment from needlessly being created again, which is what causesonCreateView()` to be called twice!

See my onNavigationItemSelected() implementation below.

public class MyActivity extends FragmentActivity implements ActionBar.OnNavigationListener
{
    private static final String STATE_SELECTED_NAVIGATION_ITEM = "selected_navigation_item";

    private boolean mIsUserInitiatedNavItemSelection;

    // ... constructor code, etc.

    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState)
    {
        super.onRestoreInstanceState(savedInstanceState);

        if (savedInstanceState.containsKey(STATE_SELECTED_NAVIGATION_ITEM))
        {
            getActionBar().setSelectedNavigationItem(savedInstanceState.getInt(STATE_SELECTED_NAVIGATION_ITEM));
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState)
    {
        outState.putInt(STATE_SELECTED_NAVIGATION_ITEM, getActionBar().getSelectedNavigationIndex());

        super.onSaveInstanceState(outState);
    }

    @Override
    public boolean onNavigationItemSelected(int position, long id)
    {    
        Fragment fragment;
        switch (position)
        {
            // ... choose and construct fragment here
        }

        // is this the automatic (non-user initiated) call to onNavigationItemSelected()
        // that occurs when the activity is created/re-created?
        if (!mIsUserInitiatedNavItemSelection)
        {
            // all subsequent calls to onNavigationItemSelected() won't be automatic
            mIsUserInitiatedNavItemSelection = true;

            // has the same fragment already replaced the container and assumed its id?
            Fragment existingFragment = getSupportFragmentManager().findFragmentById(R.id.container);
            if (existingFragment != null && existingFragment.getClass().equals(fragment.getClass()))
            {
                return true; //nothing to do, because the fragment is already there 
            }
        }

        getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment).commit();
        return true;
    }
}

I borrowed inspiration for this solution from here.

SQL Server Text type vs. varchar data type

In SQL server 2005 new datatypes were introduced: varchar(max) and nvarchar(max) They have the advantages of the old text type: they can contain op to 2GB of data, but they also have most of the advantages of varchar and nvarchar. Among these advantages are the ability to use string manipulation functions such as substring().

Also, varchar(max) is stored in the table's (disk/memory) space while the size is below 8Kb. Only when you place more data in the field, it's is stored out of the table's space. Data stored in the table's space is (usually) retrieved quicker.

In short, never use Text, as there is a better alternative: (n)varchar(max). And only use varchar(max) when a regular varchar is not big enough, ie if you expect teh string that you're going to store will exceed 8000 characters.

As was noted, you can use SUBSTRING on the TEXT datatype,but only as long the TEXT fields contains less than 8000 characters.

Nginx no-www to www and www to no-www

If you are having trouble getting this working, you may need to add the IP address of your server. For example:

server {
listen XXX.XXX.XXX.XXX:80;
listen XXX.XXX.XXX.XXX:443 ssl;
ssl_certificate /var/www/example.com/web/ssl/example.com.crt;
ssl_certificate_key /var/www/example.com/web/ssl/example.com.key;
server_name www.example.com;
return 301 $scheme://example.com$request_uri;
}

where XXX.XXX.XXX.XXX is the IP address (obviously).

Note: ssl crt and key location must be defined to properly redirect https requests

Don't forget to restart nginx after making the changes:

service nginx restart

Convert List(of object) to List(of string)

List<string> myList Str = myList.Select(x=>x.Value).OfType<string>().ToList();

Use "Select" to select a particular column

MySQL - Trigger for updating same table after insert

On the last entry; this is another trick:

SELECT AUTO_INCREMENT FROM information_schema.tables WHERE table_schema = ... and table_name = ...

Creating .pem file for APNS?

Development Phase:

Step 1: Create Certificate .pem from Certificate .p12
openssl pkcs12 -clcerts -nokeys -out apns-dev-cert.pem -in apns-dev-cert.p12

Step 2: Create Key .pem from Key .p12
openssl pkcs12 -nocerts -out apns-dev-key.pem -in apns-dev-key.p12

Step 3 (Optional): If you want to remove pass phrase asked in second step
openssl rsa -in apns-dev-key.pem -out apns-dev-key-noenc.pem

Step 4: Now we have to merge the Key .pem and Certificate .pem to get Development .pem needed for Push Notifications in Development Phase of App.

If 3rd step was performed, run:
cat apns-dev-cert.pem apns-dev-key-noenc.pem > apns-dev.pem

If 3rd step was not performed, run:
cat apns-dev-cert.pem apns-dev-key.pem > apns-dev.pem

Step 5: Check certificate validity and connectivity to APNS

If 3rd step was performed, run:
openssl s_client -connect gateway.sandbox.push.apple.com:2195 -cert apns-dev-cert.pem -key apns-dev-key-noenc.pem

If 3rd step was not performed, run:
openssl s_client -connect gateway.sandbox.push.apple.com:2195 -cert apns-dev-cert.pem -key apns-dev-key.pem

Production Phase:

Step 1: Create Certificate .pem from Certificate .p12
openssl pkcs12 -clcerts -nokeys -out apns-pro-cert.pem -in apns-pro-cert.p12

Step 2: Create Key .pem from Key .p12
openssl pkcs12 -nocerts -out apns-pro-key.pem -in apns-pro-key.p12

Step 3 (Optional): If you want to remove pass phrase asked in second step
openssl rsa -in apns-pro-key.pem -out apns-pro-key-noenc.pem

Step 4: Now we have to merge the Key .pem and Certificate .pem to get Production .pem needed for Push Notifications in Production Phase of App.

If 3rd step was performed, run:
cat apns-pro-cert.pem apns-pro-key-noenc.pem > apns-pro.pem

If 3rd step was not performed, run:
cat apns-pro-cert.pem apns-pro-key.pem > apns-pro.pem

Step 5: Check certificate validity and connectivity to APNS.

If 3rd step was performed, run:
openssl s_client -connect gateway.push.apple.com:2195 -cert apns-pro-cert.pem -key apns-pro-key-noenc.pem

If 3rd step was not performed, run:
openssl s_client -connect gateway.push.apple.com:2195 -cert apns-pro-cert.pem -key apns-pro-key.pem

Implementing two interfaces in a class with same method. Which interface method is overridden?

This was marked as a duplicate to this question https://stackoverflow.com/questions/24401064/understanding-and-solving-the-diamond-problems-in-java

You need Java 8 to get a multiple inheritance problem, but it is still not a diamon problem as such.

interface A {
    default void hi() { System.out.println("A"); }
}

interface B {
    default void hi() { System.out.println("B"); }
}

class AB implements A, B { // won't compile
}

new AB().hi(); // won't compile.

As JB Nizet comments you can fix this my overriding.

class AB implements A, B {
    public void hi() { A.super.hi(); }
}

However, you don't have a problem with

interface D extends A { }

interface E extends A { }

interface F extends A {
    default void hi() { System.out.println("F"); }
}

class DE implement D, E { }

new DE().hi(); // prints A

class DEF implement D, E, F { }

new DEF().hi(); // prints F as it is closer in the heirarchy than A.

Downloading a large file using curl

<?php
set_time_limit(0);
//This is the file where we save the    information
$fp = fopen (dirname(__FILE__) . '/localfile.tmp', 'w+');
//Here is the file we are downloading, replace spaces with %20
$ch = curl_init(str_replace(" ","%20",$url));
curl_setopt($ch, CURLOPT_TIMEOUT, 50);
// write curl response to file
curl_setopt($ch, CURLOPT_FILE, $fp); 
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
// get curl response
curl_exec($ch); 
curl_close($ch);
fclose($fp);
?>

JSON Parse File Path

var request = new XMLHttpRequest();
request.open("GET","<path_to_file>", false);
request.send(null);
var jsonData = JSON.parse(request.responseText);

This code worked for me.

There are No resources that can be added or removed from the server

For this you need to update your Project Facets setting.

Project (right click) -> Properties -> Project Facets from left navigation.

If it is not open...click on the link, Check the Dynamic Web Module Check Box and select the respective version (Probably 2.4). Click on Apply Button and then Click on OK.

enter image description here

How to calculate the bounding box for a given lat/lng location?

Illustration of @Jan Philip Matuschek excellent explanation.(Please up-vote his answer, not this; I am adding this as I took a little time in understanding the original answer)

The bounding box technique of optimizing of finding nearest neighbors would need to derive the minimum and maximum latitude,longitude pairs, for a point P at distance d . All points that fall outside these are definitely at a distance greater than d from the point. One thing to note here is the calculation of latitude of intersection as is highlighted in Jan Philip Matuschek explanation. The latitude of intersection is not at the latitude of point P but slightly offset from it. This is a often missed but important part in determining the correct minimum and maximum bounding longitude for point P for the distance d.This is also useful in verification.

The haversine distance between (latitude of intersection,longitude high) to (latitude,longitude) of P is equal to distance d.

Python gist here https://gist.github.com/alexcpn/f95ae83a7ee0293a5225

enter image description here

Truncating long strings with CSS: feasible yet?

If you're OK with a JavaScript solution, there's a jQuery plug-in to do this in a cross-browser fashion - see http://azgtech.wordpress.com/2009/07/26/text-overflow-ellipsis-for-firefox-via-jquery/

Labels for radio buttons in rails form

Using true/false as the value will have the field pre-filled if the model passed to the form has this attribute already filled:

= f.radio_button(:public?, true)
= f.label(:public?, "yes", value: true)
= f.radio_button(:public?, false)
= f.label(:public?, "no", value: false)

How can I SELECT rows with MAX(Column value), DISTINCT by another column in SQL?

Try this

select * from mytable a join
(select home, max(datetime) datetime
from mytable
group by home) b
 on a.home = b.home and a.datetime = b.datetime

Regards K

Where can I find Android source code online?

gitweb will allow you to browse through the code (and changes) via a browser.

http://git.or.cz/gitwiki/Gitweb

(Don't know if someone has already setup a public gitweb for Android, but it's probably not too hard.)

How can I create an object and add attributes to it?

These solutions are very helpful during testing. Building on everyone else's answers I do this in Python 2.7.9 (without staticmethod I get a TypeError (unbound method...):

In [11]: auth = type('', (), {})
In [12]: auth.func = staticmethod(lambda i: i * 2)
In [13]: auth.func(2)
Out[13]: 4

Installing OpenCV 2.4.3 in Visual C++ 2010 Express

1. Installing OpenCV 2.4.3

First, get OpenCV 2.4.3 from sourceforge.net. Its a self-extracting so just double click to start the installation. Install it in a directory, say C:\.

OpenCV self-extractor

Wait until all files get extracted. It will create a new directory C:\opencv which contains OpenCV header files, libraries, code samples, etc.

Now you need to add the directory C:\opencv\build\x86\vc10\bin to your system PATH. This directory contains OpenCV DLLs required for running your code.

Open Control PanelSystemAdvanced system settingsAdvanced Tab → Environment variables...

enter image description here

On the System Variables section, select Path (1), Edit (2), and type C:\opencv\build\x86\vc10\bin; (3), then click Ok.

On some computers, you may need to restart your computer for the system to recognize the environment path variables.

This will completes the OpenCV 2.4.3 installation on your computer.


2. Create a new project and set up Visual C++

Open Visual C++ and select FileNewProject...Visual C++Empty Project. Give a name for your project (e.g: cvtest) and set the project location (e.g: c:\projects).

New project dialog

Click Ok. Visual C++ will create an empty project.

VC++ empty project

Make sure that "Debug" is selected in the solution configuration combobox. Right-click cvtest and select PropertiesVC++ Directories.

Project property dialog

Select Include Directories to add a new entry and type C:\opencv\build\include.

Include directories dialog

Click Ok to close the dialog.

Back to the Property dialog, select Library Directories to add a new entry and type C:\opencv\build\x86\vc10\lib.

Library directories dialog

Click Ok to close the dialog.

Back to the property dialog, select LinkerInputAdditional Dependencies to add new entries. On the popup dialog, type the files below:

opencv_calib3d243d.lib
opencv_contrib243d.lib
opencv_core243d.lib
opencv_features2d243d.lib
opencv_flann243d.lib
opencv_gpu243d.lib
opencv_haartraining_engined.lib
opencv_highgui243d.lib
opencv_imgproc243d.lib
opencv_legacy243d.lib
opencv_ml243d.lib
opencv_nonfree243d.lib
opencv_objdetect243d.lib
opencv_photo243d.lib
opencv_stitching243d.lib
opencv_ts243d.lib
opencv_video243d.lib
opencv_videostab243d.lib

Note that the filenames end with "d" (for "debug"). Also note that if you have installed another version of OpenCV (say 2.4.9) these filenames will end with 249d instead of 243d (opencv_core249d.lib..etc).

enter image description here

Click Ok to close the dialog. Click Ok on the project properties dialog to save all settings.

NOTE:

These steps will configure Visual C++ for the "Debug" solution. For "Release" solution (optional), you need to repeat adding the OpenCV directories and in Additional Dependencies section, use:

opencv_core243.lib
opencv_imgproc243.lib
...

instead of:

opencv_core243d.lib
opencv_imgproc243d.lib
...

You've done setting up Visual C++, now is the time to write the real code. Right click your project and select AddNew Item...Visual C++C++ File.

Add new source file

Name your file (e.g: loadimg.cpp) and click Ok. Type the code below in the editor:

#include <opencv2/highgui/highgui.hpp>
#include <iostream>

using namespace cv;
using namespace std;

int main()
{
    Mat im = imread("c:/full/path/to/lena.jpg");
    if (im.empty()) 
    {
        cout << "Cannot load image!" << endl;
        return -1;
    }
    imshow("Image", im);
    waitKey(0);
}

The code above will load c:\full\path\to\lena.jpg and display the image. You can use any image you like, just make sure the path to the image is correct.

Type F5 to compile the code, and it will display the image in a nice window.

First OpenCV program

And that is your first OpenCV program!


3. Where to go from here?

Now that your OpenCV environment is ready, what's next?

  1. Go to the samples dir → c:\opencv\samples\cpp.
  2. Read and compile some code.
  3. Write your own code.

selecting from multi-index pandas

Understanding how to access multi-indexed pandas DataFrame can help you with all kinds of task like that.

Copy paste this in your code to generate example:

# hierarchical indices and columns
index = pd.MultiIndex.from_product([[2013, 2014], [1, 2]],
                                   names=['year', 'visit'])
columns = pd.MultiIndex.from_product([['Bob', 'Guido', 'Sue'], ['HR', 'Temp']],
                                     names=['subject', 'type'])

# mock some data
data = np.round(np.random.randn(4, 6), 1)
data[:, ::2] *= 10
data += 37

# create the DataFrame
health_data = pd.DataFrame(data, index=index, columns=columns)
health_data

Will give you table like this:

enter image description here

Standard access by column

health_data['Bob']
type       HR   Temp
year visit      
2013    1   22.0    38.6
        2   52.0    38.3
2014    1   30.0    38.9
        2   31.0    37.3


health_data['Bob']['HR']
year  visit
2013  1        22.0
      2        52.0
2014  1        30.0
      2        31.0
Name: HR, dtype: float64

# filtering by column/subcolumn - your case:
health_data['Bob']['HR']==22
year  visit
2013  1         True
      2        False
2014  1        False
      2        False

health_data['Bob']['HR'][2013]    
visit
1    22.0
2    52.0
Name: HR, dtype: float64

health_data['Bob']['HR'][2013][1]
22.0

Access by row

health_data.loc[2013]
subject Bob Guido   Sue
type    HR  Temp    HR  Temp    HR  Temp
visit                       
1   22.0    38.6    40.0    38.9    53.0    37.5
2   52.0    38.3    42.0    34.6    30.0    37.7

health_data.loc[2013,1] 
subject  type
Bob      HR      22.0
         Temp    38.6
Guido    HR      40.0
         Temp    38.9
Sue      HR      53.0
         Temp    37.5
Name: (2013, 1), dtype: float64

health_data.loc[2013,1]['Bob']
type
HR      22.0
Temp    38.6
Name: (2013, 1), dtype: float64

health_data.loc[2013,1]['Bob']['HR']
22.0

Slicing multi-index

idx=pd.IndexSlice
health_data.loc[idx[:,1], idx[:,'HR']]
    subject Bob Guido   Sue
type    HR  HR  HR
year    visit           
2013    1   22.0    40.0    53.0
2014    1   30.0    52.0    45.0

How do I execute a stored procedure in a SQL Agent job?

As Marc says, you run it exactly like you would from the command line. See Creating SQL Server Agent Jobs on MSDN.

CSS3 animate border color

If you need the transition to run infinitely, try the below example:

_x000D_
_x000D_
#box {_x000D_
  position: relative;_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  background-color: gray;_x000D_
  border: 5px solid black;_x000D_
  display: block;_x000D_
}_x000D_
_x000D_
#box:hover {_x000D_
  border-color: red;_x000D_
  animation-name: flash_border;_x000D_
  animation-duration: 2s;_x000D_
  animation-timing-function: linear;_x000D_
  animation-iteration-count: infinite;_x000D_
  -webkit-animation-name: flash_border;_x000D_
  -webkit-animation-duration: 2s;_x000D_
  -webkit-animation-timing-function: linear;_x000D_
  -webkit-animation-iteration-count: infinite;_x000D_
  -moz-animation-name: flash_border;_x000D_
  -moz-animation-duration: 2s;_x000D_
  -moz-animation-timing-function: linear;_x000D_
  -moz-animation-iteration-count: infinite;_x000D_
}_x000D_
_x000D_
@keyframes flash_border {_x000D_
  0% {_x000D_
    border-color: red;_x000D_
  }_x000D_
  50% {_x000D_
    border-color: black;_x000D_
  }_x000D_
  100% {_x000D_
    border-color: red;_x000D_
  }_x000D_
}_x000D_
_x000D_
@-webkit-keyframes flash_border {_x000D_
  0% {_x000D_
    border-color: red;_x000D_
  }_x000D_
  50% {_x000D_
    border-color: black;_x000D_
  }_x000D_
  100% {_x000D_
    border-color: red;_x000D_
  }_x000D_
}_x000D_
_x000D_
@-moz-keyframes flash_border {_x000D_
  0% {_x000D_
    border-color: red;_x000D_
  }_x000D_
  50% {_x000D_
    border-color: black;_x000D_
  }_x000D_
  100% {_x000D_
    border-color: red;_x000D_
  }_x000D_
}
_x000D_
<div id="box">roll over me</div>
_x000D_
_x000D_
_x000D_

Rails ActiveRecord date between

You could use below gem to find the records between dates,

This gem quite easy to use and more clear By star am using this gem and the API more clear and documentation also well explained.

Post.between_times(Time.zone.now - 3.hours,  # all posts in last 3 hours
                  Time.zone.now)

Here you could pass our field also Post.by_month("January", field: :updated_at)

Please see the documentation and try it.

no such file to load -- rubygems (LoadError)

If you have several ruby installed, it might be sufficient just to remove one of them, on MacosX with extra ports install, remove the ports ruby installation with:

sudo port -f uninstall ruby

ReportViewer Client Print Control "Unable to load client print control"?

Found a Fix:

  1. First ensure that printing is working from Report Manager (open a report in Report Manager and print from there).

  2. If it works go to Step 3, if you received the same error you need to install the following patches on the Report Server.

  3. Download and install the following update:

Pandas read_csv low_memory and dtype options

I had a similar issue with a ~400MB file. Setting low_memory=False did the trick for me. Do the simple things first,I would check that your dataframe isn't bigger than your system memory, reboot, clear the RAM before proceeding. If you're still running into errors, its worth making sure your .csv file is ok, take a quick look in Excel and make sure there's no obvious corruption. Broken original data can wreak havoc...

How to improve performance of ngRepeat over a huge dataset (angular.js)?

for large data set and multiple value drop down it is better to use ng-options rather than ng-repeat.

ng-repeat is slow because it loops over all coming values but ng-options simply display to the select option.

ng-options='state.StateCode as state.StateName for state in States'>

much much faster than

<option ng-repeat="state in States" value="{{state.StateCode}}">
    {{state.StateName }}
</option>

How do I get the color from a hexadecimal color code using .NET?

If you don't want to use the ColorTranslator, you can do it in easily:

string colorcode = "#FFFFFF00";
int argb = Int32.Parse(colorcode.Replace("#", ""), NumberStyles.HexNumber);
Color clr = Color.FromArgb(argb);

The colorcode is just the hexadecimal representation of the ARGB value.

EDIT

If you need to use 4 values instead of a single integer, you can use this (combining several comments):

string colorcode = "#FFFFFF00";    
colorcode = colorcode.TrimStart('#');

Color col; // from System.Drawing or System.Windows.Media
if (colorcode.Length == 6)
    col = Color.FromArgb(255, // hardcoded opaque
                int.Parse(colorcode.Substring(0,2), NumberStyles.HexNumber),
                int.Parse(colorcode.Substring(2,2), NumberStyles.HexNumber),
                int.Parse(colorcode.Substring(4,2), NumberStyles.HexNumber));
else // assuming length of 8
    col = Color.FromArgb(
                int.Parse(colorcode.Substring(0, 2), NumberStyles.HexNumber),
                int.Parse(colorcode.Substring(2, 2), NumberStyles.HexNumber),
                int.Parse(colorcode.Substring(4, 2), NumberStyles.HexNumber),
                int.Parse(colorcode.Substring(6, 2), NumberStyles.HexNumber));

Note 1: NumberStyles is in System.Globalization.
Note 2: please provide your own error checking (colorcode should be a hexadecimal value of either 6 or 8 characters)

Android Webview - Completely Clear the Cache

This should clear your applications cache which should be where your webview cache is

File dir = getActivity().getCacheDir();

if (dir != null && dir.isDirectory()) {
    try {
        File[] children = dir.listFiles();
        if (children.length > 0) {
            for (int i = 0; i < children.length; i++) {
                File[] temp = children[i].listFiles();
                for (int x = 0; x < temp.length; x++) {
                    temp[x].delete();
                }
            }
        }
    } catch (Exception e) {
        Log.e("Cache", "failed cache clean");
    }
}

How to create Python egg file

You are reading the wrong documentation. You want this: https://setuptools.readthedocs.io/en/latest/setuptools.html#develop-deploy-the-project-source-in-development-mode

  1. Creating setup.py is covered in the distutils documentation in Python's standard library documentation here. The main difference (for python eggs) is you import setup from setuptools, not distutils.

  2. Yep. That should be right.

  3. I don't think so. pyc files can be version and platform dependent. You might be able to open the egg (they should just be zip files) and delete .py files leaving .pyc files, but it wouldn't be recommended.

  4. I'm not sure. That might be “Development Mode”. Or are you looking for some “py2exe” or “py2app” mode?

How can I comment a single line in XML?

It is the same as the HTML or JavaScript block comments:

<!-- The to-be-commented XML block goes here. -->

How to get the client IP address in PHP

$_SERVER['REMOTE_ADDR'] may not actually contain real client IP addresses, as it will give you a proxy address for clients connected through a proxy, for example. That may well be what you really want, though, depending what your doing with the IPs. Someone's private RFC1918 address may not do you any good if you're say, trying to see where your traffic is originating from, or remembering what IP the user last connected from, where the public IP of the proxy or NAT gateway might be the more appropriate to store.

There are several HTTP headers like X-Forwarded-For which may or may not be set by various proxies. The problem is that those are merely HTTP headers which can be set by anyone. There's no guarantee about their content. $_SERVER['REMOTE_ADDR'] is the actual physical IP address that the web server received the connection from and that the response will be sent to. Anything else is just arbitrary and voluntary information. There's only one scenario in which you can trust this information: you are controlling the proxy that sets this header. Meaning only if you know 100% where and how the header was set should you heed it for anything of importance.

Having said that, here's some sample code:

if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
    $ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
    $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
    $ip = $_SERVER['REMOTE_ADDR'];
}

Editor's note: Using the above code has security implications. The client can set all HTTP header information (ie. $_SERVER['HTTP_...) to any arbitrary value it wants. As such it's far more reliable to use $_SERVER['REMOTE_ADDR'], as this cannot be set by the user.

From: http://roshanbh.com.np/2007/12/getting-real-ip-address-in-php.html

How can I pass POST parameters in a URL?

You can make a link perform an Ajax post request when it's clicked.

In jQuery:

$('a').click(function(e) {
    var $this = $(this);
    e.preventDefault();
    $.post('url', {'user': 'something', 'foo': 'bar'}, function() {
        window.location = $this.attr('href');
    });
});

You could also make the link submit a POST form with JavaScript:

<form action="url" method="post">
    <input type="hidden" name="user" value="something" />
    <a href="#">CLick</a>
</form>

<script>
    $('a').click(function(e) {
        e.preventDefault();
        $(this).parents('form').submit();
    });
</script>

How to define an enumerated type (enum) in C?

It's worth mentioning that in C++ you can use "enum" to define a new type without needing a typedef statement.

enum Strategy {RANDOM, IMMEDIATE, SEARCH};
...
Strategy myStrategy = IMMEDIATE;

I find this approach a lot more friendly.

[edit - clarified C++ status - I had this in originally, then removed it!]

Creating a class object in c++

Example example;

Here example is an object on the stack.

Example* example=new Example();

This could be broken into:

Example* example;
....
example=new Example();

Here the first statement creates a variable example which is a "pointer to Example". When the constructor is called, memory is allocated for it on the heap (dynamic allocation). It is the programmer's responsibility to free this memory when it is no longer needed. (C++ does not have garbage collection like java).

How to update value of a key in dictionary in c#?

Dictionary is a key value pair. Catch Key by

dic["cat"] 

and assign its value like

dic["cat"] = 5

Remove items from one list in another

You can use Except:

List<car> list1 = GetTheList();
List<car> list2 = GetSomeOtherList();
List<car> result = list2.Except(list1).ToList();

You probably don't even need those temporary variables:

List<car> result = GetSomeOtherList().Except(GetTheList()).ToList();

Note that Except does not modify either list - it creates a new list with the result.

How to solve error: "Clock skew detected"?

Simply go to the directory where the troubling file is, type touch * without quotes in the console, and you should be good.

how to convert binary string to decimal?

function binaryToDecimal(string) {
    let decimal = +0;
    let bits = +1;
    for(let i = 0; i < string.length; i++) {
        let currNum = +(string[string.length - i - 1]);
        if(currNum === 1) {
            decimal += bits;
        }
        bits *= 2;
    }
    console.log(decimal);
}

Setting Windows PATH for Postgres tools

In order to connect my git bash to the postgreSQL, I had to add at least 4 environment variables to the windows. Git, Node.js, System 32 and postgreSQL. This is what I set as the value for the Path variable: C:\Windows\System32;C:\Program Files\Git\cmd;C:\Program Files\nodejs;C:\Program Files\PostgreSQL\12\bin; and It works perfectly.

How to open a workbook specifying its path

Workbooks.open("E:\sarath\PTMetrics\20131004\D8 L538-L550 16MY\D8 L538-L550_16MY_Powertrain Metrics_20131002.xlsm")

Or, in a more structured way...

Sub openwb()
    Dim sPath As String, sFile As String
    Dim wb As Workbook

    sPath = "E:\sarath\PTMetrics\20131004\D8 L538-L550 16MY\"
    sFile = sPath & "D8 L538-L550_16MY_Powertrain Metrics_20131002.xlsm"

    Set wb = Workbooks.Open(sFile)
End Sub

Angular js init ng-model from default values

You can also use within your HTML code: ng-init="card.description = 12345"

It is not recommended by Angular, and as mentioned above you should use exclusively your controller.

But it works :)

Fragment transaction animation: slide in and slide out

Have the same problem with white screen during transition from one fragment to another. Have navigation and animations set in action in navigation.xml.

enter image description here

Background in all fragments the same but white blank screen. So i set navOptions in fragment during executing transition

          //Transition options
        val options = navOptions {
            anim {
                enter = R.anim.slide_in_right
                exit = R.anim.slide_out_left
                popEnter = R.anim.slide_in_left
                popExit = R.anim.slide_out_right
            }
        }

.......................

  this.findNavController().navigate(SampleFragmentDirections.actionSampleFragmentToChartFragment(it),
                    options)

It worked for me. No white screen between transistion. Magic )

Python nonlocal statement

A google search for "python nonlocal" turned up the Proposal, PEP 3104, which fully describes the syntax and reasoning behind the statement. in short, it works in exactly the same way as the global statement, except that it is used to refer to variables that are neither global nor local to the function.

Here's a brief example of what you can do with this. The counter generator can be rewritten to use this so that it looks more like the idioms of languages with closures.

def make_counter():
    count = 0
    def counter():
        nonlocal count
        count += 1
        return count
    return counter

Obviously, you could write this as a generator, like:

def counter_generator():
    count = 0
    while True:
        count += 1
        yield count

But while this is perfectly idiomatic python, it seems that the first version would be a bit more obvious for beginners. Properly using generators, by calling the returned function, is a common point of confusion. The first version explicitly returns a function.

How do I run a Java program from the command line on Windows?

Now (with JDK 9 onwards), you can just use java to get that executed. In order to execute "Hello.java" containing the main, one can use: java Hello.java

You do not need to compile using separately using javac anymore.

Compile error: package javax.servlet does not exist

This is what solved the problem for me:

<dependency>
    <groupId>javax.servlet.jsp</groupId>
    <artifactId>jsp-api</artifactId>
    <version>2.2</version>
    <scope>provided</scope>
</dependency>

How do I encode URI parameter values?

I wrote my own, it's short, super simple, and you can copy it if you like: http://www.dmurph.com/2011/01/java-uri-encoder/

'No JUnit tests found' in Eclipse

I was using @RunWith(Parameterized.class) but missed to add the @Parameters annotation in the public static parameters method. After adding the annotation it worked.

how to display full stored procedure code?

\ef <function_name> in psql. It will give the whole function with editable text.

No connection could be made because the target machine actively refused it (PHP / WAMP)

Kindly check is your mysql-service is running.

for windows user: check the services - mysql service

for Linux user: Check the mysql service/demon is running (services mysql status)

Thanks & Regards Jaiswar Vipin Kumar R

The import org.junit cannot be resolved

If you are using eclipse and working on a maven project, then also the above steps work.

Right-click on your root folder.

Properties -> Java Build Path -> Libraries -> Add Library -> JUnit -> Junit 3/4

Step By Step Instructions here

Which browser has the best support for HTML 5 currently?

i think right now is Firefox 3.6.2, but when internet explorer 9 launched, it will support HTML5

Converting Object to JSON and JSON to Object in PHP, (library like Gson for Java)

for more extendability for large scale apps use oop style with encapsulated fields.

Simple way :-

  class Fruit implements JsonSerializable {

        private $type = 'Apple', $lastEaten = null;

        public function __construct() {
            $this->lastEaten = new DateTime();
        }

        public function jsonSerialize() {
            return [
                'category' => $this->type,
                'EatenTime' => $this->lastEaten->format(DateTime::ISO8601)
            ];
        }
    }

echo json_encode(new Fruit()); //which outputs:

{"category":"Apple","EatenTime":"2013-01-31T11:17:07-0500"}

Real Gson on PHP :-

  1. http://jmsyst.com/libs/serializer
  2. http://symfony.com/doc/current/components/serializer.html
  3. http://framework.zend.com/manual/current/en/modules/zend.serializer.html
  4. http://fractal.thephpleague.com/ - serialize only

How do I fix a "Performance counter registry hive consistency" when installing SQL Server R2 Express?

Well guys, the solution to the problem is the following:

  1. click in: Start
  2. write the word: ejecut
  3. After, write: regedit
  4. Open the directory: HKEY_LOCAL_MACHINE
  5. SOFTWARE
  6. Microsoft
  7. Windows NT
  8. CurrentVersion
  9. Perflib
  10. Check the following things:

1) Folder 00A: 2) Counter: the last number 3) Help: the last number

   Folder Perflib:
   Last Counter: 00A folder´s Counter 
   Last Help: 00A folder´s Help

Ready, verify the same number in both. success

Generating unique random numbers (integers) between 0 and 'x'

Here’s another algorithm for ensuring the numbers are unique:

  1. generate an array of all the numbers from 0 to x
  2. shuffle the array so the elements are in random order
  3. pick the first n

Compared to the method of generating random numbers until you get a unique one, this method uses more memory, but it has a more stable running time – the results are guaranteed to be found in finite time. This method works better if the upper limit is relatively low or if the amount to take is relatively high.

My answer uses the Lodash library for simplicity, but you could also implement the algorithm described above without that library.

// assuming _ is the Lodash library

// generates `amount` numbers from 0 to `upperLimit` inclusive
function uniqueRandomInts(upperLimit, amount) {
    var possibleNumbers = _.range(upperLimit + 1);
    var shuffled = _.shuffle(possibleNumbers);
    return shuffled.slice(0, amount);
}

Error 1046 No database Selected, how to resolve?

You need to tell MySQL which database to use:

USE database_name;

before you create a table.

In case the database does not exist, you need to create it as:

CREATE DATABASE database_name;

followed by:

USE database_name;

How to retrieve the current value of an oracle sequence without increment it?

select MY_SEQ_NAME.currval from DUAL;

Keep in mind that it only works if you ran select MY_SEQ_NAME.nextval from DUAL; in the current sessions.

How to make a .NET Windows Service start right after the installation?

To start it right after installation, I generate a batch file with installutil followed by sc start

It's not ideal, but it works....

Send POST data using XMLHttpRequest

var xhr = new XMLHttpRequest();
xhr.open('POST', 'somewhere', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onload = function () {
    // do something to response
    console.log(this.responseText);
};
xhr.send('user=person&pwd=password&organization=place&requiredkey=key');

Or if you can count on browser support you could use FormData:

var data = new FormData();
data.append('user', 'person');
data.append('pwd', 'password');
data.append('organization', 'place');
data.append('requiredkey', 'key');

var xhr = new XMLHttpRequest();
xhr.open('POST', 'somewhere', true);
xhr.onload = function () {
    // do something to response
    console.log(this.responseText);
};
xhr.send(data);

jQuery find parent form

As of HTML5 browsers one can use inputElement.form - the value of the attribute must be an id of a <form> element in the same document. More info on MDN.

Is it possible to iterate through JSONArray?

You can use the opt(int) method and use a classical for loop.

How to convert a file to utf-8 in Python?

You can use the codecs module, like this:

import codecs
BLOCKSIZE = 1048576 # or some other, desired size in bytes
with codecs.open(sourceFileName, "r", "your-source-encoding") as sourceFile:
    with codecs.open(targetFileName, "w", "utf-8") as targetFile:
        while True:
            contents = sourceFile.read(BLOCKSIZE)
            if not contents:
                break
            targetFile.write(contents)

EDIT: added BLOCKSIZE parameter to control file chunk size.

How can I convert an MDB (Access) file to MySQL (or plain SQL file)?

If you have access to a linux box with mdbtools installed, you can use this Bash shell script (save as mdbconvert.sh):

#!/bin/bash

TABLES=$(mdb-tables -1 $1)

MUSER="root"
MPASS="yourpassword"
MDB="$2"

MYSQL=$(which mysql)

for t in $TABLES
do
    $MYSQL -u $MUSER -p$MPASS $MDB -e "DROP TABLE IF EXISTS $t"
done

mdb-schema $1 mysql | $MYSQL -u $MUSER -p$MPASS $MDB

for t in $TABLES
do
    mdb-export -D '%Y-%m-%d %H:%M:%S' -I mysql $1 $t | $MYSQL -u $MUSER -p$MPASS $MDB
done

To invoke it simply call it like this:

./mdbconvert.sh accessfile.mdb mysqldatabasename

It will import all tables and all data.

How to check if a string starts with one of several prefixes?

No one mentioned Stream so far, so here it is:

if (Stream.of("Mon", "Tues", "Wed", "Thurs", "Fri").anyMatch(s -> newStr4.startsWith(s)))

The module was expected to contain an assembly manifest

I found another strange reason and i thought maybe another developer confused as me. I did run install.bat that created to install my service in developer Command Prompt of VS2010 but my service generated in VS2012. it was going to this error and drives me to crazy but i try VS2012 Developer Command Prompt tools and everything gone to be OK. I don't no why but my problem was solved. so you can test it and if anyone know reason of that please share with us. Thanks.

How can I check which version of Angular I'm using?

You can also check it by inspecting the elements on the page:

  1. press F12 to open Browser's developer tools.

  2. Inspect an Element.

  3. Expand Body

  4. You will see the version of Angular, like the following:

ng-version="4.3.6"

Printing a char with printf

%d prints an integer: it will print the ascii representation of your character. What you need is %c:

printf("%c", ch);

printf("%d", '\0'); prints the ascii representation of '\0', which is 0 (by escaping 0 you tell the compiler to use the ascii value 0.

printf("%d", sizeof('\n')); prints 4 because a character literal is an int, in C, and not a char.

Xcode 6 Storyboard the wrong size?

I had this issue in xcode 6 and there is a way to resolve the resize conflicts. If you select your view, at the bottom you will see an icon that looks like |-Δ-|. If you click on it, you're project will resize for different devices.

Git status shows files as changed even though contents are the same

The Git FAQ has an answer that might be relevant, although I've never come across this before:

Why does git diff sometimes list a file that has no changes?

git diff and other git operations is optimized so it does not even look at files whose status (size, modification time etc) on disk and in git's index are different. This makes git diff extremely fast for small changes. If the file has been touched somehow, git diff has to look at the content of and compare it which is a much slower operation even when there is in fact no change. git diff lists the files as a reminder that it is not used optimally. Running git status will not only show status, but will also update the index with status for unchanged files disk making subsequent operations, not only diff, much faster. A typical case that causes many files to be listed by diff is running mass editing commands like perl -pi -e '...'.

What does git status show for you?

Assembly - JG/JNLE/JL/JNGE after CMP

When you do a cmp a,b, the flags are set as if you had calculated a - b.

Then the jmp-type instructions check those flags to see if the jump should be made.

In other words, the first block of code you have (with my comments added):

cmp al,dl     ; set flags based on the comparison
jg label1     ; then jump based on the flags

would jump to label1 if and only if al was greater than dl.

You're probably better off thinking of it as al > dl but the two choices you have there are mathematically equivalent:

al > dl
al - dl > dl - dl (subtract dl from both sides)
al - dl > 0       (cancel the terms on the right hand side)

You need to be careful when using jg inasmuch as it assumes your values were signed. So, if you compare the bytes 101 (101 in two's complement) with 200 (-56 in two's complement), the former will actually be greater. If that's not what was desired, you should use the equivalent unsigned comparison.

See here for more detail on jump selection, reproduced below for completeness. First the ones where signed-ness is not appropriate:

+--------+------------------------------+-------------+--------------------+
|Instr   | Description                  | signed-ness | Flags              |
+--------+------------------------------+-------------+--------------------+
| JO     | Jump if overflow             |             | OF = 1             |
+--------+------------------------------+-------------+--------------------+
| JNO    | Jump if not overflow         |             | OF = 0             |
+--------+------------------------------+-------------+--------------------+
| JS     | Jump if sign                 |             | SF = 1             |
+--------+------------------------------+-------------+--------------------+
| JNS    | Jump if not sign             |             | SF = 0             |
+--------+------------------------------+-------------+--------------------+
| JE/    | Jump if equal                |             | ZF = 1             |
| JZ     | Jump if zero                 |             |                    |
+--------+------------------------------+-------------+--------------------+
| JNE/   | Jump if not equal            |             | ZF = 0             |
| JNZ    | Jump if not zero             |             |                    |
+--------+------------------------------+-------------+--------------------+
| JP/    | Jump if parity               |             | PF = 1             |
| JPE    | Jump if parity even          |             |                    |
+--------+------------------------------+-------------+--------------------+
| JNP/   | Jump if no parity            |             | PF = 0             |
| JPO    | Jump if parity odd           |             |                    |
+--------+------------------------------+-------------+--------------------+
| JCXZ/  | Jump if CX is zero           |             | CX = 0             |
| JECXZ  | Jump if ECX is zero          |             | ECX = 0            |
+--------+------------------------------+-------------+--------------------+

Then the unsigned ones:

+--------+------------------------------+-------------+--------------------+
|Instr   | Description                  | signed-ness | Flags              |
+--------+------------------------------+-------------+--------------------+
| JB/    | Jump if below                | unsigned    | CF = 1             |
| JNAE/  | Jump if not above or equal   |             |                    |
| JC     | Jump if carry                |             |                    |
+--------+------------------------------+-------------+--------------------+
| JNB/   | Jump if not below            | unsigned    | CF = 0             |
| JAE/   | Jump if above or equal       |             |                    |
| JNC    | Jump if not carry            |             |                    |
+--------+------------------------------+-------------+--------------------+
| JBE/   | Jump if below or equal       | unsigned    | CF = 1 or ZF = 1   |
| JNA    | Jump if not above            |             |                    |
+--------+------------------------------+-------------+--------------------+
| JA/    | Jump if above                | unsigned    | CF = 0 and ZF = 0  |
| JNBE   | Jump if not below or equal   |             |                    |
+--------+------------------------------+-------------+--------------------+

And, finally, the signed ones:

+--------+------------------------------+-------------+--------------------+
|Instr   | Description                  | signed-ness | Flags              |
+--------+------------------------------+-------------+--------------------+
| JL/    | Jump if less                 | signed      | SF <> OF           |
| JNGE   | Jump if not greater or equal |             |                    |
+--------+------------------------------+-------------+--------------------+
| JGE/   | Jump if greater or equal     | signed      | SF = OF            |
| JNL    | Jump if not less             |             |                    |
+--------+------------------------------+-------------+--------------------+
| JLE/   | Jump if less or equal        | signed      | ZF = 1 or SF <> OF |
| JNG    | Jump if not greater          |             |                    |
+--------+------------------------------+-------------+--------------------+
| JG/    | Jump if greater              | signed      | ZF = 0 and SF = OF |
| JNLE   | Jump if not less or equal    |             |                    |
+--------+------------------------------+-------------+--------------------+

Passing std::string by Value or Reference

I believe the normal answer is that it should be passed by value if you need to make a copy of it in your function. Pass it by const reference otherwise.

Here is a good discussion: http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/

Syntax for if/else condition in SCSS mixin

You could default the parameter to null or false.
This way, it would be shorter to test if a value has been passed as parameter.

@mixin clearfix($width: null) {

  @if not ($width) {

    // if width is not passed, or empty do this

  } @else {

    display: inline-block;
    width: $width;

  }
}

MySQL: is a SELECT statement case sensitive?

Marc B's answer is mostly correct.

If you are using a nonbinary string (CHAR, VARCHAR, TEXT), comparisons are case-insensitive, per the default collation.

If you are using a binary string (BINARY, VARBINARY, BLOB), comparisons are case-sensitive, so you'll need to use LOWER as described in other answers.

If you are not using the default collation and you are using a nonbinary string, case sensitivity is decided by the chosen collation.

Source: https://dev.mysql.com/doc/refman/8.0/en/case-sensitivity.html. Read closely. Some others have mistaken it to say that comparisons are necessarily case-sensitive or insensitive. This is not the case.

Objective-C - Remove last character from string

The documentation is your friend, NSString supports a call substringWithRange that can shorten the string that you have an return the shortened String. You cannot modify an instance of NSString it is immutable. If you have an NSMutableString is has a method called deleteCharactersInRange that can modify the string in place

...
NSRange r;
r.location = 0;
r.size = [mutable length]-1;
NSString* shorted = [stringValue substringWithRange:r];
...

How to set java_home on Windows 7?

Windows 7

  1. Go to Control Panel\All Control Panel Items\User Accounts using Explorer (not Internet Explorer!)

    or

    • click on the Start button

      start

    • click on your picture

      clickOnPhoto

  2. Change my environment variables

    Change my environment variables

  3. New...

    new

    (if you don't have enough permissions to add it in the System variables section, add it to the User variables section)

  4. Add JAVA_HOME as Variable name and the JDK location as Variable value > OK

    edit system variable ok

Test:

  • open a new console (cmd)
  • type set JAVA_HOME
    • expected output: JAVA_HOME=C:\Program Files\Java\jdk1.8.0_60

Android Error [Attempt to invoke virtual method 'void android.app.ActionBar' on a null object reference]

Whenever such an error occurs. Try to check Following Things

  1. Check what kind of Activity is being used, is it a simple android.app Activity or an AppCompatActivity or an ActionBarActivity and so on.

  2. Check if your activity type which is extended falls under the compat category

example android.app based Activity/Fragment are non appCompat types, whereas android.support.v4.app.Fragment or android.support.v4.app.ActivityCompat are appCompat based

if it falls under appCompat we use getSupportActionBar() else for android.app types we can use getActionBar()

  1. Check the theme applied to the activity in question in the manifest file

example: In the manifest file if theme applied is say android:theme="@android:style/Theme.Holo.Dialog" getActionBar() will work

but if theme applied for the activity in the manifest is as follows android:theme="@style/Theme.AppCompat.Light" then you have to use getSupportActionBar()

Define the selected option with the old input in Laravel / Blade

Instead of using Input class you can also use old() helper to make this even shorter.

<option {{ old('name') == $key ? "selected" : "" }} value="{{ $value }}">

SQL/mysql - Select distinct/UNIQUE but return all columns?

It can be done by inner query

$query = "SELECT * 
            FROM (SELECT field
                FROM table
                ORDER BY id DESC) as rows               
            GROUP BY field";

Deleting a local branch with Git

You probably have Test_Branch checked out, and you may not delete it while it is your current branch. Check out a different branch, and then try deleting Test_Branch.

Why powershell does not run Angular commands?

Remove ng.ps1 from the directory C:\Users\%username%\AppData\Roaming\npm\ then try clearing the npm cache at C:\Users\%username%\AppData\Roaming\npm-cache\

Calling a Function defined inside another function in Javascript

You are not calling the function inner, just defining it.

function outer() { 
    function inner() {
        alert("hi");
    }

    inner(); //Call the inner function

}

What causes java.lang.IncompatibleClassChangeError?

Documenting another scenario after burning way too much time.

Make sure you don't have a dependency jar that has a class with an EJB annotation on it.

We had a common jar file that had an @local annotation. That class was later moved out of that common project and into our main ejb jar project. Our ejb jar and our common jar are both bundled within an ear. The version of our common jar dependency was not updated. Thus 2 classes trying to be something with incompatible changes.

Clear the value of bootstrap-datepicker

You can use this syntax to reset your bootstrap datepicker

$('#datepicker').datepicker('update','');

reference http://bootstrap-datepicker.readthedocs.org/en/latest/methods.html#update

How is using "<%=request.getContextPath()%>" better than "../"

request.getContextPath()- returns root path of your application, while ../ - returns parent directory of a file.

You use request.getContextPath(), as it will always points to root of your application. If you were to move your jsp file from one directory to another, nothing needs to be changed. Now, consider the second approach. If you were to move your jsp files from one folder to another, you'd have to make changes at every location where you are referring your files.

Also, better approach of using request.getContextPath() will be to set 'request.getContextPath()' in a variable and use that variable for referring your path.

<c:set var="context" value="${pageContext.request.contextPath}" />
<script src="${context}/themes/js/jquery.js"></script>

PS- This is the one reason I can figure out. Don't know if there is any more significance to it.

Removing "http://" from a string

Something like this ought to do:

$url = preg_replace("|^.+?://|", "", $url); 

Removes everything up to and including the ://

How do I show multiple recaptchas on a single page?

Simple and straightforward:

1) Create your recaptcha fields normally with this:

<div class="g-recaptcha" data-sitekey="YOUR_KEY_HERE"></div>

2) Load the script with this:

<script src="https://www.google.com/recaptcha/api.js?onload=CaptchaCallback&render=explicit" async defer></script>

3) Now call this to iterate over the fields and create the recaptchas:

<script type="text/javascript">
  var CaptchaCallback = function() {
    jQuery('.g-recaptcha').each(function(index, el) {
        grecaptcha.render(el, {
            'sitekey' : jQuery(el).attr('data-sitekey')
            ,'theme' : jQuery(el).attr('data-theme')
            ,'size' : jQuery(el).attr('data-size')
            ,'tabindex' : jQuery(el).attr('data-tabindex')
            ,'callback' : jQuery(el).attr('data-callback')
            ,'expired-callback' : jQuery(el).attr('data-expired-callback')
            ,'error-callback' : jQuery(el).attr('data-error-callback')
        });
    });
  };
</script>

Download image from the site in .NET/C#

There is no need to involve any image classes, you can simply call WebClient.DownloadFile:

string localFilename = @"c:\localpath\tofile.jpg";
using(WebClient client = new WebClient())
{
    client.DownloadFile("http://www.example.com/image.jpg", localFilename);
}

Update
Since you will want to check whether the file exists and download the file if it does, it's better to do this within the same request. So here is a method that will do that:

private static void DownloadRemoteImageFile(string uri, string fileName)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();

    // Check that the remote file was found. The ContentType
    // check is performed since a request for a non-existent
    // image file might be redirected to a 404-page, which would
    // yield the StatusCode "OK", even though the image was not
    // found.
    if ((response.StatusCode == HttpStatusCode.OK || 
        response.StatusCode == HttpStatusCode.Moved || 
        response.StatusCode == HttpStatusCode.Redirect) &&
        response.ContentType.StartsWith("image",StringComparison.OrdinalIgnoreCase))
    {

        // if the remote file was found, download oit
        using (Stream inputStream = response.GetResponseStream())
        using (Stream outputStream = File.OpenWrite(fileName))
        {
            byte[] buffer = new byte[4096];
            int bytesRead;
            do
            {
                bytesRead = inputStream.Read(buffer, 0, buffer.Length);
                outputStream.Write(buffer, 0, bytesRead);
            } while (bytesRead != 0);
        }
    }
}

In brief, it makes a request for the file, verifies that the response code is one of OK, Moved or Redirect and also that the ContentType is an image. If those conditions are true, the file is downloaded.

Cannot connect to the Docker daemon at unix:/var/run/docker.sock. Is the docker daemon running?

I just hit this after doing a fresh install of DOCKER from the main docs. The problem for me was that immediately after the install, the service is not running.

These commands will help you to make sure docker is up and running for your run command to find it:

$ sudo service --status-all 
$ sudo service docker start
$ sudo service docker start

Error: Cannot pull with rebase: You have unstaged changes

If you want to automatically stash your changes and unstash them for every rebase, you can do this:

git config --global rebase.autoStash true

How can I render inline JavaScript with Jade / Pug?

Use the :javascript filter. This will generate a script tag and escape the script contents as CDATA:

!!! 5
html(lang="en")
  head
    title "Test"
    :javascript
      if (10 == 10) {
        alert("working")
      }
  body

VB.NET: Clear DataGridView

1) create button named it Clear.Inside insert tfhe following code datagridviewer.DataSource=nothing

2) In your search button begin your code by the following statement

datagridviewer.DataSource = DataSet.table

Nb:instead of table put the real name of your table ex: datagridviewer.DataSource = DataSet.client

How to check if element is visible after scrolling?

An example based off of this answer to check if an element is 75% visible (i.e. less than 25% of it is off of the screen).

function isScrolledIntoView(el) {
  // check for 75% visible
  var percentVisible = 0.75;
  var elemTop = el.getBoundingClientRect().top;
  var elemBottom = el.getBoundingClientRect().bottom;
  var elemHeight = el.getBoundingClientRect().height;
  var overhang = elemHeight * (1 - percentVisible);

  var isVisible = (elemTop >= -overhang) && (elemBottom <= window.innerHeight + overhang);
  return isVisible;
}

Platform.runLater and Task in JavaFX

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

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

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

Execution sequence of Group By, Having and Where clause in SQL Server?

Having Clause may come prior/before the group by clause.

Example: select * FROM test_std; ROLL_NO SNAME DOB TEACH


     1 John       27-AUG-18 Wills     
     2 Knit       27-AUG-18 Prestion  
     3 Perl       27-AUG-18 Wills     
     4 Ohrm       27-AUG-18 Woods     
     5 Smith      27-AUG-18 Charmy    
     6 Jony       27-AUG-18 Wills     
       Warner     20-NOV-18 Wills     
       Marsh      12-NOV-18 Langer    
       FINCH      18-OCT-18 Langer    

9 rows selected.

select teach, count() count from test_std having count() > 1 group by TEACH ;

TEACH COUNT


Langer 2 Wills 4

Folder structure for a Node.js project

More example from my project architecture you can see here:

+-- Dockerfile
+-- README.md
+-- config
¦   +-- production.json
+-- package.json
+-- schema
¦   +-- create-db.sh
¦   +-- db.sql
+-- scripts
¦   +-- deploy-production.sh 
+-- src
¦   +-- app -> Containes API routes
¦   +-- db -> DB Models (ORM)
¦   +-- server.js -> the Server initlializer.
+-- test

Basically, the logical app separated to DB and APP folders inside the SRC dir.

How can I properly handle 404 in ASP.NET MVC?

I have gone through all articles but nothing works for me: My requirement user type anything in your url custom 404 page should show.I thought it is very straight forward.But you should understand handling of 404 properly:

 <system.web>
    <customErrors mode="On" redirectMode="ResponseRewrite">
      <error statusCode="404" redirect="~/PageNotFound.aspx"/>
    </customErrors>
  </system.web>
<system.webServer>
    <httpErrors errorMode="Custom">
      <remove statusCode="404"/>
      <error statusCode="404" path="/PageNotFound.html" responseMode="ExecuteURL"/>
    </httpErrors>
</system.webServer>

I found this article very helpfull.should be read at once.Custome error page-Ben Foster

C# using streams

There is only one basic type of Stream. However in various circumstances some members will throw an exception when called because in that context the operation was not available.

For example a MemoryStream is simply a way to moves bytes into and out of a chunk of memory. Hence you can call Read and Write on it.

On the other hand a FileStream allows you to read or write (or both) from/to a file. Whether you can actually Read or Write depends on how the file was opened. You can't Write to a file if you only opened it for Read access.

Search for "does-not-contain" on a DataFrame in pandas

I had to get rid of the NULL values before using the command recommended by Andy above. An example:

df = pd.DataFrame(index = [0, 1, 2], columns=['first', 'second', 'third'])
df.ix[:, 'first'] = 'myword'
df.ix[0, 'second'] = 'myword'
df.ix[2, 'second'] = 'myword'
df.ix[1, 'third'] = 'myword'
df

    first   second  third
0   myword  myword   NaN
1   myword  NaN      myword 
2   myword  myword   NaN

Now running the command:

~df["second"].str.contains(word)

I get the following error:

TypeError: bad operand type for unary ~: 'float'

I got rid of the NULL values using dropna() or fillna() first and retried the command with no problem.

Serialize an object to string

In some rare cases you might want to implement your own String serialization.

But that probably is a bad idea unless you know what you are doing. (e.g. serializing for I/O with a batch file)

Something like that would do the trick (and it would be easy to edit by hand/batch), but be careful that some more checks should be done, like that name doesn't contain a newline.

public string name {get;set;}
public int age {get;set;}

Person(string serializedPerson) 
{
    string[] tmpArray = serializedPerson.Split('\n');
    if(tmpArray.Length>2 && tmpArray[0].Equals("#")){
        this.name=tmpArray[1];
        this.age=int.TryParse(tmpArray[2]);
    }else{
        throw new ArgumentException("Not a valid serialization of a person");
    }
}

public string SerializeToString()
{
    return "#\n" +
           name + "\n" + 
           age;
}

Simple dynamic breadcrumb

A better one using explode() function is as follows...

Don't forget to replace your URL variable in the hyperlink href.

<?php 
    if($url != ''){
        $b = '';
        $links = explode('/',rtrim($url,'/'));
        foreach($links as $l){
            $b .= $l;
            if($url == $b){
                echo $l;
            }else{
                echo "<a href='URL?url=".$b."'>".$l."/</a>";
            }
            $b .= '/';
         }
     }
?>

Replace a value in a data frame based on a conditional (`if`) statement

Short answer is:

junk$nm[junk$nm %in% "B"] <- "b"

Take a look at Index vectors in R Introduction (if you don't read it yet).


EDIT. As noticed in comments this solution works for character vectors so fail on your data.

For factor best way is to change level:

levels(junk$nm)[levels(junk$nm)=="B"] <- "b"

Bootstrap 4 - Responsive cards in card-columns

I realize this question was posted a while ago; nonetheless, Bootstrap v4.0 has card layout support out of the box. You can find the documentation here: Bootstrap Card Layouts.

I've gotten back into using Bootstrap for a recent project that relies heavily on the card layout UI. I've found success with the following implementation across the standard breakpoints:

_x000D_
_x000D_
<link href="https://unpkg.com/[email protected]/css/tachyons.min.css" rel="stylesheet"/>_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="flex justify-center" id="cars" v-cloak>_x000D_
    <!-- RELEVANT MARKUP BEGINS HERE -->_x000D_
    <div class="container mh0 w-100">_x000D_
        <div class="page-header text-center mb5">_x000D_
            <h1 class="avenir text-primary mb-0">Cars</h1>_x000D_
            <p class="text-secondary">Add and manage your cars for sale.</p>_x000D_
            <div class="header-button">_x000D_
                <button class="btn btn-outline-primary" @click="clickOpenAddCarModalButton">Add a car for sale</button>_x000D_
            </div>_x000D_
        </div>_x000D_
        <div class="container pa0 flex justify-center">_x000D_
            <div class="listings card-columns">_x000D_
                <div class="card mv2">_x000D_
                    <img src="https://farm4.staticflickr.com/3441/3361756632_8d84aa8560.jpg" class="card-img-top"_x000D_
                        alt="Mazda hatchback">_x000D_
                    <div class="card-body">_x000D_
                        <h5 class="card-title">Card title</h5>_x000D_
                        <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's_x000D_
                            content._x000D_
                        </p>_x000D_
                        <a href="#" class="btn btn-primary">Go somewhere</a>_x000D_
                    </div>_x000D_
                    <div class="card-footer">_x000D_
                        buttons here_x000D_
                    </div>_x000D_
                </div>_x000D_
                <div class="card mv2">_x000D_
                    <img src="https://farm4.staticflickr.com/3441/3361756632_8d84aa8560.jpg" class="card-img-top"_x000D_
                        alt="Mazda hatchback">_x000D_
                    <div class="card-body">_x000D_
                        <h5 class="card-title">Card title</h5>_x000D_
                        <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's_x000D_
                            content._x000D_
                        </p>_x000D_
                        <a href="#" class="btn btn-primary">Go somewhere</a>_x000D_
                    </div>_x000D_
                    <div class="card-footer">_x000D_
                        buttons here_x000D_
                    </div>_x000D_
                </div>_x000D_
                <div class="card mv2">_x000D_
                    <img src="https://farm4.staticflickr.com/3441/3361756632_8d84aa8560.jpg" class="card-img-top"_x000D_
                        alt="Mazda hatchback">_x000D_
                    <div class="card-body">_x000D_
                        <h5 class="card-title">Card title</h5>_x000D_
                        <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's_x000D_
                            content._x000D_
                        </p>_x000D_
                        <a href="#" class="btn btn-primary">Go somewhere</a>_x000D_
                    </div>_x000D_
                    <div class="card-footer">_x000D_
                        buttons here_x000D_
                    </div>_x000D_
                </div>_x000D_
                <div class="card mv2">_x000D_
                    <img src="https://farm4.staticflickr.com/3441/3361756632_8d84aa8560.jpg" class="card-img-top"_x000D_
                        alt="Mazda hatchback">_x000D_
                    <div class="card-body">_x000D_
                        <h5 class="card-title">Card title</h5>_x000D_
                        <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's_x000D_
                            content._x000D_
                        </p>_x000D_
                        <a href="#" class="btn btn-primary">Go somewhere</a>_x000D_
                    </div>_x000D_
                    <div class="card-footer">_x000D_
                        buttons here_x000D_
                    </div>_x000D_
                </div>_x000D_
                <div class="card mv2">_x000D_
                    <img src="https://farm4.staticflickr.com/3441/3361756632_8d84aa8560.jpg" class="card-img-top"_x000D_
                        alt="Mazda hatchback">_x000D_
                    <div class="card-body">_x000D_
                        <h5 class="card-title">Card title</h5>_x000D_
                        <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's_x000D_
                            content._x000D_
                        </p>_x000D_
                        <a href="#" class="btn btn-primary">Go somewhere</a>_x000D_
                    </div>_x000D_
                    <div class="card-footer">_x000D_
                        buttons here_x000D_
                    </div>_x000D_
                </div>_x000D_
            </div>_x000D_
        </div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

After trying both the Bootstrap .card-group and .card-deck card layout classes with quirky results at best across the standard breakpoints, I finally decided to give the .card-columns class a shot. And it worked!

Your results may vary, but .card-columns seems to be the most stable implementation here.

jquery change button color onclick

I would just create a separate CSS class:

.ButtonClicked {
    background-color:red;
}

And then add the class on click:

$('#ButtonId').on('click',function(){
    !$(this).hasClass('ButtonClicked') ? addClass('ButtonClicked') : '';
});

This should do what you're looking for, showing by this jsFiddle. If you're curious about the logic with the ? and such, its called ternary (or conditional) operators, and its just a concise way to do the simple if logic to check if the class has already been added.

You can also create the ability to have an "on/off" switch feel by toggling the class:

$('#ButtonId').on('click',function(){
    $(this).toggleClass('ButtonClicked');
});

Shown by this jsFiddle. Just food for thought.

How to convert BigDecimal to Double in Java?

You need to use the doubleValue() method to get the double value from a BigDecimal object.

BigDecimal bd; // the value you get
double d = bd.doubleValue(); // The double you want

Monitoring the Full Disclosure mailinglist

Two generic ways to do the same thing... I'm not aware of any specific open solutions to do this, but it'd be rather trivial to do.

You could write a daily or weekly cron/jenkins job to scrape the previous time period's email from the archive looking for your keyworkds/combinations. Sending a batch digest with what it finds, if anything.

But personally, I'd Setup a specific email account to subscribe to the various security lists you're interested in. Add a simple automated script to parse the new emails for various keywords or combinations of keywords, when it finds a match forward that email on to you/your team. Just be sure to keep the keywords list updated with new products you're using.

You could even do this with a gmail account and custom rules, which is what I currently do, but I have setup an internal inbox in the past with a simple python script to forward emails that were of interest.

WPF C# button style

To solve your question definitely need to use the Style and Template for the Button. But how exactly does he look like? Decisions may be several. For example, Button are two texts to better define the relevant TextBlocks? Can be directly in the template, but then use the buttons will be limited, because the template can be only one ContentPresenter. I decided to do things differently, to identify one ContentPresenter with an icon in the form of a Path, and the content is set using the buttons on the side.

The style:

<Style TargetType="{x:Type Button}">
    <Setter Property="Background" Value="#373737" />
    <Setter Property="Foreground" Value="White" />
    <Setter Property="FontSize" Value="15" />
    <Setter Property="SnapsToDevicePixels" Value="True" />

    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Button}">
                <Border CornerRadius="4" Background="{TemplateBinding Background}">
                    <Grid>
                        <Path x:Name="PathIcon" Width="15" Height="25" Stretch="Fill" Fill="#4C87B3" HorizontalAlignment="Left" Margin="17,0,0,0" Data="F1 M 30.0833,22.1667L 50.6665,37.6043L 50.6665,38.7918L 30.0833,53.8333L 30.0833,22.1667 Z "/>
                        <ContentPresenter x:Name="MyContentPresenter" Content="{TemplateBinding Content}" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="0,0,0,0" />                                
                    </Grid>
                </Border>

                <ControlTemplate.Triggers>
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter Property="Background" Value="#E59400" />
                        <Setter Property="Foreground" Value="White" />
                        <Setter TargetName="PathIcon" Property="Fill" Value="Black" />
                    </Trigger>

                    <Trigger Property="IsPressed" Value="True">
                        <Setter Property="Background" Value="OrangeRed" />
                        <Setter Property="Foreground" Value="White" />
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

Sample of using:

<Button Width="200" Height="50" VerticalAlignment="Top" Margin="0,20,0,0" />
    <Button.Content>
        <StackPanel>
            <TextBlock Text="Watch Now" FontSize="20" />
            <TextBlock Text="Duration: 50m" FontSize="12" Foreground="Gainsboro" />
        </StackPanel>
    </Button.Content>
</Button>

Output

enter image description here

It is best to StackPanel determine the Resources and set the Button so:

<Window.Resources>
    <StackPanel x:Key="MyStackPanel">
        <TextBlock Name="MainContent" Text="Watch Now" FontSize="20" />
        <TextBlock Name="DurationValue" Text="Duration: 50m" FontSize="12" Foreground="Gainsboro" />
    </StackPanel>
</Window.Resources>

<Button Width="200" Height="50" Content="{StaticResource MyStackPanel}" VerticalAlignment="Top" Margin="0,20,0,0" />

The question remains with setting the value for TextBlock Duration, because this value must be dynamic. I implemented it using attached DependencyProperty. Set it to the window, like that:

<Window Name="MyWindow" local:MyDependencyClass.CurrentDuration="Duration: 50m" ... />

Using in TextBlock:

<TextBlock Name="DurationValue" Text="{Binding ElementName=MyWindow, Path=(local:MyDependencyClass.CurrentDuration)}" FontSize="12" Foreground="Gainsboro" />

In fact, there is no difference for anyone to determine the attached DependencyProperty, because it is the predominant feature.

Example of set value:

private void Button_Click(object sender, RoutedEventArgs e)
{
    MyDependencyClass.SetCurrentDuration(MyWindow, "Duration: 101m");
}

A complete listing of examples:

XAML

<Window x:Class="ButtonHelp.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:ButtonHelp"
    Name="MyWindow"
    Title="MainWindow" Height="350" Width="525"
    WindowStartupLocation="CenterScreen"
    local:MyDependencyClass.CurrentDuration="Duration: 50m">

<Window.Resources>
    <Style TargetType="{x:Type Button}">
        <Setter Property="Background" Value="#373737" />
        <Setter Property="Foreground" Value="White" />
        <Setter Property="FontSize" Value="15" />
        <Setter Property="FontFamily" Value="./#Segoe UI" />
        <Setter Property="SnapsToDevicePixels" Value="True" />

        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Button}">
                    <Border CornerRadius="4" Background="{TemplateBinding Background}">
                        <Grid>
                            <Path x:Name="PathIcon" Width="15" Height="25" Stretch="Fill" Fill="#4C87B3" HorizontalAlignment="Left" Margin="17,0,0,0" Data="F1 M 30.0833,22.1667L 50.6665,37.6043L 50.6665,38.7918L 30.0833,53.8333L 30.0833,22.1667 Z "/>
                            <ContentPresenter x:Name="MyContentPresenter" Content="{TemplateBinding Content}" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="0,0,0,0" />                                
                        </Grid>
                    </Border>

                    <ControlTemplate.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter Property="Background" Value="#E59400" />
                            <Setter Property="Foreground" Value="White" />
                            <Setter TargetName="PathIcon" Property="Fill" Value="Black" />
                        </Trigger>

                        <Trigger Property="IsPressed" Value="True">
                            <Setter Property="Background" Value="OrangeRed" />
                            <Setter Property="Foreground" Value="White" />
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

    <StackPanel x:Key="MyStackPanel">
        <TextBlock Name="MainContent" Text="Watch Now" FontSize="20" />
        <TextBlock Name="DurationValue" Text="{Binding ElementName=MyWindow, Path=(local:MyDependencyClass.CurrentDuration)}" FontSize="12" Foreground="Gainsboro" />
    </StackPanel>
</Window.Resources>

<Grid>        
    <Button Width="200" Height="50" Content="{StaticResource MyStackPanel}" VerticalAlignment="Top" Margin="0,20,0,0" />

    <Button Content="Set some duration" Style="{x:Null}" Width="140" Height="30" VerticalAlignment="Top" HorizontalAlignment="Left" Click="Button_Click" />
</Grid>

Code behind

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        MyDependencyClass.SetCurrentDuration(MyWindow, "Duration: 101m");
    }
}

public class MyDependencyClass : DependencyObject
{
    public static readonly DependencyProperty CurrentDurationProperty;        

    public static void SetCurrentDuration(DependencyObject DepObject, string value)
    {
        DepObject.SetValue(CurrentDurationProperty, value);
    }

    public static string GetCurrentDuration(DependencyObject DepObject)
    {
        return (string)DepObject.GetValue(CurrentDurationProperty);
    }

    static MyDependencyClass()
    {
        PropertyMetadata MyPropertyMetadata = new PropertyMetadata("Duration: 0m");

        CurrentDurationProperty = DependencyProperty.RegisterAttached("CurrentDuration",
                                                            typeof(string),
                                                            typeof(MyDependencyClass),
                                                            MyPropertyMetadata);
    }
}

How to access parent Iframe from JavaScript

Simply call window.frameElement from your framed page. If the page is not in a frame then frameElement will be null.

The other way (getting the window element inside a frame is less trivial) but for sake of completeness:

/**
 * @param f, iframe or frame element
 * @return Window object inside the given frame
 * @effect will append f to document.body if f not yet part of the DOM
 * @see Window.frameElement
 * @usage myFrame.document = getFramedWindow(myFrame).document;
 */
function getFramedWindow(f)
{
    if(f.parentNode == null)
        f = document.body.appendChild(f);
    var w = (f.contentWindow || f.contentDocument);
    if(w && w.nodeType && w.nodeType==9)
        w = (w.defaultView || w.parentWindow);
    return w;
}

Unable to connect to SQL Server instance remotely

  1. Launch SQL Server Configuration Manager on your VPS.

  2. Take a look at the SQL Server Network Configuration. Make sure that TCP/IP is enabled.

  3. Next look at SQL Server Services. Make sure that SQL Server Browser is running.

  4. Restart the service for your instance of SQL Server.

Drop shadow for PNG image in CSS

Maybe you are in search of this. http://lineandpixel.com/blog/png-shadow

img { png-shadow: 5px 5px 5px #222; }

Chrome disable SSL checking for sites?

To disable the errors windows related with certificates you can start Chrome from console and use this option: --ignore-certificate-errors.

"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --ignore-certificate-errors

You should use it for testing purposes. A more complete list of options is here: http://peter.sh/experiments/chromium-command-line-switches/

What's the easiest way to escape HTML in Python?

cgi.escape extended

This version improves cgi.escape. It also preserves whitespace and newlines. Returns a unicode string.

def escape_html(text):
    """escape strings for display in HTML"""
    return cgi.escape(text, quote=True).\
           replace(u'\n', u'<br />').\
           replace(u'\t', u'&emsp;').\
           replace(u'  ', u' &nbsp;')

for example

>>> escape_html('<foo>\nfoo\t"bar"')
u'&lt;foo&gt;<br />foo&emsp;&quot;bar&quot;'

Check folder size in Bash

To check the size of all of the directories within a directory, you can use:

du -h --max-depth=1

How to verify that a specific method was not called using Mockito?

Use the second argument on the Mockito.verify method, as in:

Mockito.verify(dependency, Mockito.times(0)).someMethod()

Show how many characters remaining in a HTML text box using JavaScript

Just register an Eventhandler on keydown events and check the length of the input field on that function and write it into a separate element.

See the demo.

var maxchar = 160;
var i = document.getElementById("textinput");
var c = document.getElementById("count");
c.innerHTML = maxchar;

i.addEventListener("keydown",count);

function count(e){
    var len =  i.value.length;
    if (len >= maxchar){
       e.preventDefault();
    } else{
       c.innerHTML = maxchar - len-1;   
    }
}
?

You should check the length on your server too, because Javascript might be disabled or the user wants to do something nasty on purpose.

What's the difference between ClusterIP, NodePort and LoadBalancer service types in Kubernetes?

A ClusterIP exposes the following:

  • spec.clusterIp:spec.ports[*].port

You can only access this service while inside the cluster. It is accessible from its spec.clusterIp port. If a spec.ports[*].targetPort is set it will route from the port to the targetPort. The CLUSTER-IP you get when calling kubectl get services is the IP assigned to this service within the cluster internally.

A NodePort exposes the following:

  • <NodeIP>:spec.ports[*].nodePort
  • spec.clusterIp:spec.ports[*].port

If you access this service on a nodePort from the node's external IP, it will route the request to spec.clusterIp:spec.ports[*].port, which will in turn route it to your spec.ports[*].targetPort, if set. This service can also be accessed in the same way as ClusterIP.

Your NodeIPs are the external IP addresses of the nodes. You cannot access your service from spec.clusterIp:spec.ports[*].nodePort.

A LoadBalancer exposes the following:

  • spec.loadBalancerIp:spec.ports[*].port
  • <NodeIP>:spec.ports[*].nodePort
  • spec.clusterIp:spec.ports[*].port

You can access this service from your load balancer's IP address, which routes your request to a nodePort, which in turn routes the request to the clusterIP port. You can access this service as you would a NodePort or a ClusterIP service as well.

Core dump file is not generated

If one is on a Linux distro (e.g. CentOS, Debian) then perhaps the most accessible way to find out about core files and related conditions is in the man page. Just run the following command from a terminal:

man 5 core

How to run cron once, daily at 10pm

Here is what I look at everytime I am writing a new crontab entry:

To start editing from terminal -type:

 zee$ crontab -e

what you will add to crontab file:

0 22 * * 0  some-user /opt/somescript/to/run.sh

What it means:

[ 
+ user => 'some-user',      
+ minute => ‘0’,             <<= on top of the hour.
+ hour => '22',              <<= at 10 PM. Military time.
+ monthday => '*',           <<= Every day of the month*
+ month => '*',              <<= Every month*
+ weekday => ‘0’,            <<= Everyday (0 thru 6) = sunday thru saturday
] 

Also, check what shell your machine is running and name the the file accordingly OR it wont execute.

Check the shell with either echo $SHELL or echo $0

It can be "Bourne shell (sh) , Bourne again shell (bash),Korn shell (ksh)..etc"

How to edit binary file on Unix systems

There are much more hexeditors on Linux/Unix....

I use hexedit on Ubuntu

sudo apt-get install hexedit

How to parse JSON in Java

Since nobody mentioned it yet, here is a beginning of a solution using Nashorn (JavaScript runtime part of Java 8, but deprecated in Java 11).

Solution

private static final String EXTRACTOR_SCRIPT =
    "var fun = function(raw) { " +
    "var json = JSON.parse(raw); " +
    "return [json.pageInfo.pageName, json.pageInfo.pagePic, json.posts[0].post_id];};";

public void run() throws ScriptException, NoSuchMethodException {
    ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
    engine.eval(EXTRACTOR_SCRIPT);
    Invocable invocable = (Invocable) engine;
    JSObject result = (JSObject) invocable.invokeFunction("fun", JSON);
    result.values().forEach(e -> System.out.println(e));
}

Performance comparison

I wrote JSON content containing three arrays of respectively 20, 20 and 100 elements. I only want to get the 100 elements from the third array. I use the following JavaScript function to parse and get my entries.

var fun = function(raw) {JSON.parse(raw).entries};

Running the call a million times using Nashorn takes 7.5~7.8 seconds

(JSObject) invocable.invokeFunction("fun", json);

org.json takes 20~21 seconds

new JSONObject(JSON).getJSONArray("entries");

Jackson takes 6.5~7 seconds

mapper.readValue(JSON, Entries.class).getEntries();

In this case Jackson performs better than Nashorn, which performs much better than org.json. Nashorn API is harder to use than org.json's or Jackson's. Depending on your requirements Jackson and Nashorn both can be viable solutions.

Java Date cut off time information

With Joda-Time since version 2.0 you can use LocalDate.toDate().

Simply

// someDatetime is whatever java.util.Date you have.
Date someDay = new LocalDate(someDatetime).toDate();

Spring: how do I inject an HttpServletRequest into a request-scoped bean?

As suggested here you can also inject the HttpServletRequest as a method param, e.g.:

public MyResponseObject myApiMethod(HttpServletRequest request, ...) {
    ...
}

Detect iPhone/iPad purely by css

You might want to try the solution from this O'Reilly article.

The important part are these CSS media queries:

<link rel="stylesheet" media="all and (max-device-width: 480px)" href="iphone.css"> 
<link rel="stylesheet" media="all and (min-device-width: 481px) and (max-device-width: 1024px) and (orientation:portrait)" href="ipad-portrait.css"> 
<link rel="stylesheet" media="all and (min-device-width: 481px) and (max-device-width: 1024px) and (orientation:landscape)" href="ipad-landscape.css"> 
<link rel="stylesheet" media="all and (min-device-width: 1025px)" href="ipad-landscape.css"> 

How to completely hide the navigation bar in iPhone / HTML5

Remy Sharp has a good description of the process in his article "Doing it right: skipping the iPhone url bar":

Making the iPhone hide the url bar is fairly simple, you need run the following JavaScript:

window.scrollTo(0, 1); 

However there's the question of when? You have to do this once the height is correct so that the iPhone can scroll to the first pixel of the document, otherwise it will try, then the height will load forcing the url bar back in to view.

You could wait until the images have loaded and the window.onload event fires, but this doesn't always work, if everything is cached, the event fires too early and the scrollTo never has a chance to jump. Here's an example using window.onload: http://jsbin.com/edifu4/4/

I personally use a timer for 1 second - which is enough time on a mobile device while you wait to render, but long enough that it doesn't fire too early:

setTimeout(function () {   window.scrollTo(0, 1); }, 1000);

However, you only want this to setup if it's an iPhone (or just mobile) browser, so a sneaky sniff (I don't generally encourage this, but I'm comfortable with this to prevent "normal" desktop browsers from jumping one pixel):

/mobile/i.test(navigator.userAgent) && setTimeout(function
() {   window.scrollTo(0, 1); }, 1000); 

The very last part of this, and this is the part that seems to be missing from some examples I've seen around the web is this: if the user specifically linked to a url fragment, i.e. the url has a hash on it, you don't want to jump. So if I navigate to http://full-frontal.org/tickets#dayconf - I want the browser to scroll naturally to the element whose id is dayconf, and not jump to the top using scrollTo(0, 1):

/mobile/i.test(navigator.userAgent) && !location.hash &&
setTimeout(function () {   window.scrollTo(0, 1); }, 1000);?

Try this out on an iPhone (or simulator) http://jsbin.com/edifu4/10 and you'll see it will only scroll when you've landed on the page without a url fragment.

Configure Log4net to write to multiple files

Use below XML configuration to configure logs into two or more files:

<log4net>
    <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="logs\log.txt" />         
      <appendToFile value="true" /> 
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="10MB" />
      <staticLogFileName value="true" />
      <layout type="log4net.Layout.PatternLayout">           
        <conversionPattern value="%date [%thread] %level %logger - %message%newline" />
      </layout>
    </appender>
     <appender name="RollingLogFileAppender2" type="log4net.Appender.RollingFileAppender">
      <file value="logs\log1.txt" />         
      <appendToFile value="true" /> 
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="10MB" />
      <staticLogFileName value="true" />
      <layout type="log4net.Layout.PatternLayout">        
        <conversionPattern value="%date [%thread] %level %logger - %message%newline" />
      </layout>
    </appender>
    <root>
      <level value="All" />
      <appender-ref ref="RollingLogFileAppender" />
    </root>
     <logger additivity="false" name="RollingLogFileAppender2">
    <level value="All"/>
    <appender-ref ref="RollingLogFileAppender2" />
    </logger>
  </log4net>

Above XML configuration logs into two different files. To get specific instance of logger programmatically:

ILog logger = log4net.LogManager.GetLogger ("RollingLogFileAppender2");

You can append two or more appender elements inside log4net root element for logging into multiples files.

More info about above XML configuration structure or which appender is best for your application, read details from below links:

https://logging.apache.org/log4net/release/manual/configuration.html https://logging.apache.org/log4net/release/sdk/index.html

android image button

You can just set the onClick of an ImageView and also set it to be clickable, Or set the drawableBottom property of a regular button.

    ImageView iv = (ImageView)findViewById(R.id.ImageView01);
   iv.setOnClickListener(new OnClickListener() {
   public void onClick(View v) {
    // TODO Auto-generated method stub

   }
   });

UnicodeDecodeError: 'utf8' codec can't decode bytes in position 3-6: invalid data

The string you're trying to parse as a JSON is not encoded in UTF-8. Most likely it is encoded in ISO-8859-1. Try the following:

json.loads(unicode(opener.open(...), "ISO-8859-1"))

That will handle any umlauts that might get in the JSON message.

You should read Joel Spolsky's The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!). I hope that it will clarify some issues you're having around Unicode.

How to connect to a docker container from outside the host (same network) [Windows]

  1. Open Oracle VM VirtualBox Manager
  2. Select the VM used by Docker
  3. Click Settings -> Network
  4. Adapter 1 should (default?) be "Attached to: NAT"
  5. Click Advanced -> Port Forwarding
  6. Add rule: Protocol TCP, Host Port 8080, Guest Port 8080 (leave Host IP and Guest IP empty)
  7. Guest is your docker container and Host is your machine

You should now be able to browse to your container via localhost:8080 and your-internal-ip:8080.

urllib2 and json

You certainly want to hack the header to have a proper Ajax Request :

headers = {'X_REQUESTED_WITH' :'XMLHttpRequest',
           'ACCEPT': 'application/json, text/javascript, */*; q=0.01',}
request = urllib2.Request(path, data, headers)
response = urllib2.urlopen(request).read()

And to json.loads the POST on the server-side.

Edit : By the way, you have to urllib.urlencode(mydata_dict) before sending them. If you don't, the POST won't be what the server expect

How to copy and paste code without rich text formatting?

If you're pasting into Word you can use the Paste Special command.

How to unload a package without restarting R

You can try all you want to remove a package (and all the dependencies it brought in alongside) using unloadNamespace() but the memory footprint will still persist. And no, detach("package:,packageName", unload=TRUE, force = TRUE) will not work either.

From a fresh new console or Session > Restart R check memory with the pryr package:

pryr::mem_used()

# 40.6 MB   ## This will depend on which packages are loaded obviously (can also fluctuate a bit after the decimal)

Check my sessionInfo()

R version 3.6.1 (2019-07-05)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 17763)

Matrix products: default

locale:
[1] LC_COLLATE=English_Canada.1252  LC_CTYPE=English_Canada.1252    LC_MONETARY=English_Canada.1252 LC_NUMERIC=C                   
[5] LC_TIME=English_Canada.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

loaded via a namespace (and not attached):
[1] compiler_3.6.1   pryr_0.1.4       magrittr_1.5     tools_3.6.1      Rcpp_1.0.3       stringi_1.4.3    codetools_0.2-16 stringr_1.4.0   
[9] packrat_0.5.0   

Let's load the Seurat package and check the new memory footprint:

library(Seurat)
pryr::mem_used()

# 172 MB    ## Likely to change in the future but just to give you an idea

Let's use unloadNamespace() to remove everything:

unloadNamespace("Seurat")
unloadNamespace("ape")
unloadNamespace("cluster")
unloadNamespace("cowplot")
unloadNamespace("ROCR")
unloadNamespace("gplots")
unloadNamespace("caTools")
unloadNamespace("bitops")
unloadNamespace("fitdistrplus")
unloadNamespace("RColorBrewer")
unloadNamespace("sctransform")
unloadNamespace("future.apply")
unloadNamespace("future")
unloadNamespace("plotly")
unloadNamespace("ggrepel")
unloadNamespace("ggridges")
unloadNamespace("ggplot2")
unloadNamespace("gridExtra")
unloadNamespace("gtable")
unloadNamespace("uwot")
unloadNamespace("irlba")
unloadNamespace("leiden")
unloadNamespace("reticulate")
unloadNamespace("rsvd")
unloadNamespace("survival")
unloadNamespace("Matrix")
unloadNamespace("nlme")
unloadNamespace("lmtest")
unloadNamespace("zoo")
unloadNamespace("metap")
unloadNamespace("lattice")
unloadNamespace("grid")
unloadNamespace("httr")
unloadNamespace("ica")
unloadNamespace("igraph")
unloadNamespace("irlba")
unloadNamespace("KernSmooth")
unloadNamespace("leiden")
unloadNamespace("MASS")
unloadNamespace("pbapply")
unloadNamespace("plotly")
unloadNamespace("png")
unloadNamespace("RANN")
unloadNamespace("RcppAnnoy")
unloadNamespace("tidyr")
unloadNamespace("dplyr")
unloadNamespace("tibble")
unloadNamespace("RANN")
unloadNamespace("tidyselect")
unloadNamespace("purrr")
unloadNamespace("htmlwidgets")
unloadNamespace("htmltools")
unloadNamespace("lifecycle")
unloadNamespace("pillar")
unloadNamespace("vctrs")
unloadNamespace("rlang")
unloadNamespace("Rtsne")
unloadNamespace("SDMTools")
unloadNamespace("Rdpack")
unloadNamespace("bibtex")
unloadNamespace("tsne")
unloadNamespace("backports")
unloadNamespace("R6")
unloadNamespace("lazyeval")
unloadNamespace("scales")
unloadNamespace("munsell")
unloadNamespace("colorspace")
unloadNamespace("npsurv")
unloadNamespace("compiler")
unloadNamespace("digest")
unloadNamespace("R.utils")
unloadNamespace("pkgconfig")
unloadNamespace("gbRd")
unloadNamespace("parallel")
unloadNamespace("gdata")
unloadNamespace("listenv")
unloadNamespace("crayon")
unloadNamespace("splines")
unloadNamespace("zeallot")
unloadNamespace("reshape")
unloadNamespace("glue")
unloadNamespace("lsei")
unloadNamespace("RcppParallel")
unloadNamespace("data.table")
unloadNamespace("viridisLite")
unloadNamespace("globals")

Now check sessionInfo():

R version 3.6.1 (2019-07-05)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 17763)

Matrix products: default

locale:
[1] LC_COLLATE=English_Canada.1252  LC_CTYPE=English_Canada.1252    LC_MONETARY=English_Canada.1252 LC_NUMERIC=C                   
[5] LC_TIME=English_Canada.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

loaded via a namespace (and not attached):
 [1] tools_3.6.1       stringr_1.4.0     rstudioapi_0.10   pryr_0.1.4        jsonlite_1.6      gtools_3.8.1      R.oo_1.22.0      
 [8] magrittr_1.5      Rcpp_1.0.3        R.methodsS3_1.7.1 stringi_1.4.3     plyr_1.8.4        reshape2_1.4.3    codetools_0.2-16 
[15] packrat_0.5.0     assertthat_0.2.1 

Check the memory footprint:

pryr::mem_used()

# 173 MB

Link to screen-cast demonstration

M_PI works with math.h but not with cmath in Visual Studio

According to Microsoft documentation about Math Constants:

The file ATLComTime.h includes math.h when your project is built in Release mode. If you use one or more of the math constants in a project that also includes ATLComTime.h, you must define _USE_MATH_DEFINES before you include ATLComTime.h.

File ATLComTime.h may be included indirectly in your project. In my case one possible order of including was the following:

project's "stdafx.h" ? <afxdtctl.h> ? <afxdisp.h> ? <ATLComTime.h> ? <math.h>

How to Add Stacktrace or debug Option when Building Android Studio Project

Go into your project.

install Gradle.

https://docs.gradle.org/current/userguide/installation.html

On a mac: brew install gradle

Then gradle build --stacktrace

Rails 3.1 and Image Assets

http://railscasts.com/episodes/279-understanding-the-asset-pipeline

This railscast (Rails Tutorial video on asset pipeline) helps a lot to explain the paths in assets pipeline as well. I found it pretty useful, and actually watched it a few times.

The solution I chose is @Lee McAlilly's above, but this railscast helped me to understand why it works. Hope it helps!

How to open a link in new tab (chrome) using Selenium WebDriver?

Selenium can only automate on the WebElements of the browser. Opening a new tab is an operation performed on the webBrowser which is a stand alone application. For doing this you can make use of the Robot class from the java.util.* package which can perform operations using the keyboard regardless of what type of application it is. So here's the code for your operation. Note that you cannot automate stand alone applications using the Robot class but you can perform keyboard or mouse operations

System.setProperty("webdriver.chrome.driver","softwares\\chromedriver_win32\\chromedriver.exe"); 
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(20,TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get("http://www.google.com");
Robot rob = new Robot();
rob.keyPress(keyEvent.VK_CONTROL);
rob.keyPress(keyEvent.VK_T);
rob.keyRelease(keyEvent.VK_CONTROL);
rob.keyRelease(keyEvent.VK_T);

After this step you will need a window iterator to switch to the new tab:

Set <String> ids = driver.getWindowHandles();
Iterator <String> it = ids.iterator();
String currentWindow = it.next();
String newWindow = it.next();
driver.switchTo().window(newWindow);
driver.findElement(By.linkText("www.facebook.com")).sendKeys(selectLinkOpeninNewTab);

git push rejected

Jarret Hardie is correct. Or, first merge your changes back into master and then try the push. By default, git push pushes all branches that have names that match on the remote -- and no others. So those are your two choices -- either specify it explicitly like Jarret said or merge back to a common branch and then push.

There's been talk about this on the Git mail list and it's clear that this behavior is not about to change anytime soon -- many developers rely on this behavior in their workflows.

Edit/Clarification

Assuming your upstreammaster branch is ready to push then you could do this:

  1. Pull in any changes from the upstream.

    $ git pull upstream master

  2. Switch to my local master branch

    $ git checkout master

  3. Merge changes in from upstreammaster

    $ git merge upstreammaster

  4. Push my changes up

    $ git push upstream

Another thing that you may want to do before pushing is to rebase your changes against upstream/master so that your commits are all together. You can either do that as a separate step between #1 and #2 above (git rebase upstream/master) or you can do it as part of your pull (git pull --rebase upstream master)

I'm getting the "missing a using directive or assembly reference" and no clue what's going wrong

I had the same problem earlier today. I could not figure out why the class file I was trying to reference was not being seen by the compiler. I had recently changed the namespace of the class file in question to a different but already existing namespace. (I also had using references to the class's new and previous namespaces where I was trying to instantiate it)

Where the compiler was telling me I was missing a reference when trying to instantiate the class, I right clicked and hit "generate class stub". Once Visual Studio generated a class stub for me, I coped and pasted the code from the old class file into this stub, saved the stub and when I tried to compile again it worked! No issues.

Might be a solution specific to my build, but its worth a try.

EXCEL VBA Check if entry is empty or not 'space'

Here is the code to check whether value is present or not.

If Trim(textbox1.text) <> "" Then
     'Your code goes here
Else
     'Nothing
End If

I think this will help.

Modifying location.hash without page scrolling

if you use hashchange event with hash parser, you can prevent default action on links and change location.hash adding one character to have difference with id property of an element

$('a[href^=#]').on('click', function(e){
    e.preventDefault();
    location.hash = $(this).attr('href')+'/';
});

$(window).on('hashchange', function(){
    var a = /^#?chapter(\d+)-section(\d+)\/?$/i.exec(location.hash);
});

mean() warning: argument is not numeric or logical: returning NA

The same error appears if you do not use the correct (numeric) format of your data in your data.frame column using mean() function. Therefore, check your data using str(data.frame&column) function to see what data type you have, and convert it to numeric format if necessary. For example, if your data is Character convert it with as.numeric(data.frame$column), or as a factor with as.numeric(as.character(data.frame$column)). The mean function does not work with types other than numeric.

Javascript foreach loop on associative array object

This is (essentially) incorrect in most cases:

var array = [];
array["Main"] = "Main page";

That creates a non-element property on the array with the name Main. Although arrays are objects, normally you don't want to create non-element properties on them.

If you want to index into array by those names, typically you'd use a Map or a plain object, not an array.

With a Map (ES2015+), which I'll call map because I'm creative:

let map = new Map();
map.set("Main", "Main page");

you then iterate it using the iterators from its values, keys, or entries methods, for instance:

for (const value of map.values()) {
    // Here, `value` will be `"Main page"`, etc.
}

Using a plain object, which I'll creatively call obj:

let obj = Object.create(null); // Creates an object with no prototype
obj.Main = "Main page"; // Or: `obj["Main"] = "Main page";`

you'd then iterate its contents using Object.keys, Object.values, or Object.entries, for instance:

for (const value of Object.values(proches_X)) {
    // Here, `value` will be `"Main page"`, etc.
}

POST request with a simple string in body with Alamofire

I have done it for array from strings. This solution is adjusted for string in body.

The "native" way from Alamofire 4:

struct JSONStringArrayEncoding: ParameterEncoding {
    private let myString: String

    init(string: String) {
        self.myString = string
    }

    func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
        var urlRequest = urlRequest.urlRequest

        let data = myString.data(using: .utf8)!

        if urlRequest?.value(forHTTPHeaderField: "Content-Type") == nil {
            urlRequest?.setValue("application/json", forHTTPHeaderField: "Content-Type")
        }

        urlRequest?.httpBody = data

        return urlRequest!
    }
}

And then make your request with:

Alamofire.request("your url string", method: .post, parameters: [:], encoding: JSONStringArrayEncoding.init(string: "My string for body"), headers: [:])

What does the return keyword do in a void method in Java?

The keyword simply pops a frame from the call stack returning the control to the line following the function call.

how to sort order of LEFT JOIN in SQL query?

This will get you the most expensive car for the user:

SELECT users.userName, MAX(cars.carPrice)
FROM users
LEFT JOIN cars ON cars.belongsToUser=users.id
WHERE users.id=4
GROUP BY users.userName

However, this statement makes me think that you want all of the cars prices sorted, descending:

So question: How do I set the LEFT JOIN table to be ordered by carPrice, DESC ?

So you could try this:

SELECT users.userName, cars.carPrice
FROM users
LEFT JOIN cars ON cars.belongsToUser=users.id
WHERE users.id=4
GROUP BY users.userName
ORDER BY users.userName ASC, cars.carPrice DESC

Using scanner.nextLine()

It's because when you enter a number then press Enter, input.nextInt() consumes only the number, not the "end of line". Primitive data types like int, double etc do not consume "end of line", therefore the "end of line" remains in buffer and When input.next() executes, it consumes the "end of line" from buffer from the first input. That's why, your String sentence = scanner.next() only consumes the "end of line" and does not wait to read from keyboard.

Tip: use scanner.nextLine() instead of scanner.next() because scanner.next() does not read white spaces from the keyboard. (Truncate the string after giving some space from keyboard, only show string before space.)

How to make Toolbar transparent?

All you need to is to define theme which hide action bar, define action bar style with transparent background and set this style to the toolbar widget. Please note that toolbar should be drawen as last view (over all view tree)

<style name="Theme.Custom" parent="@android:style/Theme.AppCompat">
    <item name="windowActionBar">false</item>
    <item name="windowActionBarOverlay">true</item>
    <item name="android:windowActionBarOverlay">true</item>
</style>

<style name="CustomActionBar" parent="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
    <item name="android:windowActionBarOverlay">true</item>
    <!-- Support library compatibility -->
    <item name="windowActionBarOverlay">true</item>
</style>

Layout:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- Toolbar should be above content-->
    <include layout="@layout/toolbar" />

</RelativeLayout>

Toolbar layout:

<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:theme="@style/CustomActionBar"/>

How do I get current date/time on the Windows command line in a suitable format for usage in a file/folder name?

Regional independent solution generating the ISO date format:

rem save the existing format definition
for /f "skip=2 tokens=3" %%a in ('reg query "HKCU\Control Panel\International" /v sShortDate') do set FORMAT=%%a
rem set ISO specific format definition
reg add "HKCU\Control Panel\International" /v sShortDate /t REG_SZ /f /d yyyy-MM-dd 1>nul:
rem query the date in the ISO specific format 
set ISODATE=%DATE%
rem restore previous format definition
reg add "HKCU\Control Panel\International" /v sShortDate /t REG_SZ /f /d %FORMAT% 1>nul:

What could still be optimized: Other processes might get confused if using the date format in the short period while it is modified. So parsing the output according to the existing format string could be 'safer' - but will be more complicated

How to pass arguments to addEventListener listener function?

I was stuck in this as I was using it in a loop for finding elements and adding listner to it. If you're using it in a loop, then this will work perfectly

for (var i = 0; i < states_array.length; i++) {
     var link = document.getElementById('apply_'+states_array[i].state_id);
     link.my_id = i;
     link.addEventListener('click', function(e) {   
        alert(e.target.my_id);        
        some_function(states_array[e.target.my_id].css_url);
     });
}

Getting only response header from HTTP POST using curl

Much easier – this is what I use to avoid Shortlink tracking – is the following:

curl -IL http://bit.ly/in-the-shadows

…which also follows links.

What is cardinality in Databases?

Cardinality refers to the uniqueness of data contained in a column. If a column has a lot of duplicate data (e.g. a column that stores either "true" or "false"), it has low cardinality, but if the values are highly unique (e.g. Social Security numbers), it has high cardinality.

How to correctly use "section" tag in HTML5?

My understanding is that SECTION holds a section with a heading which is an important part of the "flow" of the page (not an aside). SECTIONs would be chapters, numbered parts of documents and so on.

ARTICLE is for syndicated content -- e.g. posts, news stories etc. ARTICLE and SECTION are completely separate -- you can have one without the other as they are very different use cases.

Another thing about SECTION is that you shouldn't use it if your page has only the one section. Also, each section must have a heading (H1-6, HGROUP, HEADING). Headings are "scoped" withing the SECTION, so e.g. if you use a H1 in the main page (outside a SECTION) and then a H1 inside the section, the latter will be treated as an H2.

The examples in the spec are pretty good at time of writing.

So in your first example would be correct if you had several sections of content which couldn't be described as ARTICLEs. (With a minor point that you wouldn't need the #primary DIV unless you wanted it for a style hook - P tags would be better).

The second example would be correct if you removed all the SECTION tags -- the data in that document would be articles, posts or something like this.

SECTIONs should not be used as containers -- DIV is still the correct use for that, and any other custom box you might come up with.

How do I get cURL to not show the progress bar?

I found that with curl 7.18.2 the download progress bar is not hidden with:

curl -s http://google.com > temp.html

but it is with:

curl -ss http://google.com > temp.html

Remove end of line characters from Java string

Regex with replaceAll.

public class Main
{
    public static void main(final String[] argv) 
    {
        String str;

        str = "hello\r\njava\r\nbook";
        str = str.replaceAll("(\\r|\\n)", "");
        System.out.println(str);
    }
}

If you only want to remove \r\n when they are pairs (the above code removes either \r or \n) do this instead:

str = str.replaceAll("\\r\\n", "");

Reliable and fast FFT in Java

Late to the party - here as a pure java solution for those when JNI is not an option.JTransforms

How to determine the current language of a wordpress page when using polylang?

Simple:

if(pll_current_language() == 'en'){
   //do your work here
}

SMTP server response: 530 5.7.0 Must issue a STARTTLS command first

In my case, Swift Mailer couldn't help either. I found a solution here: http://forum.powweb.com/showthread.php?t=73406 - so after EHLO command one needs to send STARTTLS command, enabling cryptography with stream_socket_enable_crypto( $connection, true, STREAM_CRYPTO_METHOD_TLS_CLIENT ); and again EHLO command. Only this allowed me to send emails with my "stubborn" SMTP server.

Determine if an element has a CSS class with jQuery

Without jQuery:

var hasclass=!!(' '+elem.className+' ').indexOf(' check_class ')+1;

Or:

function hasClass(e,c){
    return e&&(e instanceof HTMLElement)&&!!((' '+e.className+' ').indexOf(' '+c+' ')+1);
}
/*example of usage*/
var has_class_medium=hasClass(document.getElementsByTagName('input')[0],'medium');

This is WAY faster than jQuery!

How to get EditText value and display it on screen through TextView?

in "String.xml" you can notice any String or value you want to use, here are two examples:

<string name="app_name">My Calculator App
    </string>
<color name="color_menu_home">#ffcccccc</color>

Used for the layout.xml: android:text="@string/app_name"

The advantage: you can use them as often you want, you only need to link them in your Layout-xml, and you can change the String-Content easily in the strings.xml, without searching in your source-code for the right position. Important for changing language, you only need to replace the strings.xml - file

How to check the differences between local and github before the pull

And another useful command to do this (after git fetch) is:

git log origin/master ^master

This shows the commits that are in origin/master but not in master. You can also do it in opposite when doing git pull, to check what commits will be submitted to remote.

How do I tell a Python script to use a particular version

Perhaps not exactly what you asked, but I find this to be useful to put at the start of my programs:

import sys

if sys.version_info[0] < 3:
    raise Exception("Python 3 or a more recent version is required.")

Creating an empty Pandas DataFrame, then filling it?

Initialize empty frame with column names

import pandas as pd

col_names =  ['A', 'B', 'C']
my_df  = pd.DataFrame(columns = col_names)
my_df

Add a new record to a frame

my_df.loc[len(my_df)] = [2, 4, 5]

You also might want to pass a dictionary:

my_dic = {'A':2, 'B':4, 'C':5}
my_df.loc[len(my_df)] = my_dic 

Append another frame to your existing frame

col_names =  ['A', 'B', 'C']
my_df2  = pd.DataFrame(columns = col_names)
my_df = my_df.append(my_df2)

Performance considerations

If you are adding rows inside a loop consider performance issues. For around the first 1000 records "my_df.loc" performance is better, but it gradually becomes slower by increasing the number of records in the loop.

If you plan to do thins inside a big loop (say 10M? records or so), you are better off using a mixture of these two; fill a dataframe with iloc until the size gets around 1000, then append it to the original dataframe, and empty the temp dataframe. This would boost your performance by around 10 times.

How to add a named sheet at the end of all Excel sheets?


Try switching the order of your code. You must create the worksheet first in order to name it.

Private Sub CreateSheet()
    Dim ws As Worksheet
    Set ws = Sheets.Add(After:=Sheets(Sheets.Count))
    ws.Name = "Tempo"
End Sub

thanks,

Test if object implements interface

For the instance:

if (obj is IMyInterface) {}

For the class:

Check if typeof(MyClass).GetInterfaces() contains the interface.

Determine if Android app is being used for the first time

There is support for just this in the support library revision 23.3.0 (in the v4 which means compability back to Android 1.6).

In your Launcher activity, first call:

AppLaunchChecker.onActivityCreate(activity);

Then call:

AppLaunchChecker.hasStartedFromLauncher(activity);

Which will return if this was the first time the app was launched.

Adding simple legend to plot in R

Take a look at ?legend and try this:

legend('topright', names(a)[-1] , 
   lty=1, col=c('red', 'blue', 'green',' brown'), bty='n', cex=.75)

enter image description here

Android JSONObject - How can I loop through a flat JSON object to get each key and value

Take a look at the JSONObject reference:

http://www.json.org/javadoc/org/json/JSONObject.html

Without actually using the object, it looks like using either getNames() or keys() which returns an Iterator is the way to go.

Eslint: How to disable "unexpected console statement" in Node.js?

in "rules", "no-console": [false, "log", "error"]

mongod command not recognized when trying to connect to a mongodb server

It is probably too late, but for the sake of others (like me) who faced the same problem. It is all about the little '\' at the end of the path variable. When you insert the path to MongoDB's bin directory at the end of the PATH windows variable, do not forget to put the '\' (Backslash) at the end, which tells windows it is a directory and not an executable named bin... e.g. I:\Program Files\MongoDB\Server\3.0\bin\

How to set ChartJS Y axis title?

chart.js supports this by defaul check the link. chartjs

you can set the label in the options attribute.

options object looks like this.

options = {
            scales: {
                yAxes: [
                    {
                        id: 'y-axis-1',
                        display: true,
                        position: 'left',
                        ticks: {
                            callback: function(value, index, values) {
                                return value + "%";
                            }
                        },
                        scaleLabel:{
                            display: true,
                            labelString: 'Average Personal Income',
                            fontColor: "#546372"
                        }
                    }   
                ]
            }
        };

Return Max Value of range that is determined by an Index & Match lookup

You don't need an index match formula. You can use this array formula. You have to press CTL + SHIFT + ENTER after you enter the formula.

=MAX(IF((A1:A6=A10)*(B1:B6=B10),C1:F6))

SNAPSHOT

enter image description here

Python match a string with regex

Are you sure you need a regex? It seems that you only need to know if a word is present in a string, so you can do:

>>> line = 'This,is,a,sample,string'
>>> "sample" in line
 True

Datepicker: How to popup datepicker when click on edittext

import android.app.DatePickerDialog;
import android.content.Context;
import android.view.View;
import android.widget.DatePicker;
import android.widget.TextView;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

public class DatePickerHelper {

private final Calendar calendar = Calendar.getInstance();
private final String dateFormat = "MM/dd/yy";
private TextView textView = null;

public DatePickerHelper(final Context context, TextView textView) {
    this.textView = textView;

    // Setup on click listener if the TextView is not null
    if (textView != null) {
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getDatePickerDialog(context).show();
            }
        });
    }
}

/**
 * Return a new date picker listener tied to the specified TextView field
 * @return
 */
private DatePickerDialog.OnDateSetListener getOnDateSetListener() {
    return new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                              int dayOfMonth) {
            calendar.set(Calendar.YEAR, year);
            calendar.set(Calendar.MONTH, monthOfYear);
            calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);

            SimpleDateFormat sdf = new SimpleDateFormat(dateFormat, Locale.US);
            textView.setText(sdf.format(calendar.getTime()));
        }
    };
}

/**
 * Return new DatePickerDialog for field
 * @param context
 * @return
 */
private DatePickerDialog getDatePickerDialog(Context context) {
    return new DatePickerDialog(context, getOnDateSetListener(), calendar
            .get(Calendar.YEAR), calendar.get(Calendar.MONTH),
            calendar.get(Calendar.DAY_OF_MONTH));
}

}

Usage:

  DatePickerHelper assessmentDueDateHelper = new DatePickerHelper(AssessmentsDetailActivity.this,
            (TextView) findViewById(R.id.assessmentDueDateEditText));

Capturing window.onbeforeunload

There seems to be a lot of misinformation about how to use this event going around (even in upvoted answers on this page).

The onbeforeunload event API is supplied by the browser for a specific purpose: The only thing you can do that's worth doing in this method is to return a string which the browser will then prompt to the user to indicate to them that action should be taken before they navigate away from the page. You CANNOT prevent them from navigating away from a page (imagine what a nightmare that would be for the end user).

Because browsers use a confirm prompt to show the user the string you returned from your event listener, you can't do anything else in the method either (like perform an ajax request).

In an application I wrote, I want to prompt the user to let them know they have unsaved changes before they leave the page. The browser prompts them with the message and, after that, it's out of my hands, the user can choose to stay or leave, but you no longer have control of the application at that point.

An example of how I use it (pseudo code):

onbeforeunload = function() {

  if(Application.hasUnsavedChanges()) {
    return 'You have unsaved changes. Please save them before leaving this page';
  }


};

If (and only if) the application has unsaved changes, then the browser prompts the user to either ignore my message (and leave the page anyway) or to not leave the page. If they choose to leave the page anyway, too bad, there's nothing you can do (nor should be able to do) about it.

A full list of all the new/popular databases and their uses?

To file under both 'established' and 'key-value store': Berkeley DB.

Has transactions and replication. Usually linked as a lib (no standalone server, although you may write one). Values and keys are just binary strings, you can provide a custom sorting function for them (where applicable).

Does not prevent from shooting yourself in the foot. Switch off locking/transaction support, access the db from two threads at once, end up with a corrupt file.

How to set web.config file to show full error message

If you're using ASP.NET MVC you might also need to remove the HandleErrorAttribute from the Global.asax.cs file:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new HandleErrorAttribute());
}

How to correctly implement custom iterators and const_iterators?

I'm going to show you how you can easily define iterators for your custom containers, but just in case I have created a c++11 library that allows you to easily create custom iterators with custom behavior for any type of container, contiguous or non-contiguous.

You can find it on Github

Here are the simple steps to creating and using custom iterators:

  1. Create your "custom iterator" class.
  2. Define typedefs in your "custom container" class.
    • e.g. typedef blRawIterator< Type > iterator;
    • e.g. typedef blRawIterator< const Type > const_iterator;
  3. Define "begin" and "end" functions
    • e.g. iterator begin(){return iterator(&m_data[0]);};
    • e.g. const_iterator cbegin()const{return const_iterator(&m_data[0]);};
  4. We're Done!!!

Finally, onto defining our custom iterator classes:

NOTE: When defining custom iterators, we derive from the standard iterator categories to let STL algorithms know the type of iterator we've made.

In this example, I define a random access iterator and a reverse random access iterator:

  1. //-------------------------------------------------------------------
    // Raw iterator with random access
    //-------------------------------------------------------------------
    template<typename blDataType>
    class blRawIterator
    {
    public:
    
        using iterator_category = std::random_access_iterator_tag;
        using value_type = blDataType;
        using difference_type = std::ptrdiff_t;
        using pointer = blDataType*;
        using reference = blDataType&;
    
    public:
    
        blRawIterator(blDataType* ptr = nullptr){m_ptr = ptr;}
        blRawIterator(const blRawIterator<blDataType>& rawIterator) = default;
        ~blRawIterator(){}
    
        blRawIterator<blDataType>&                  operator=(const blRawIterator<blDataType>& rawIterator) = default;
        blRawIterator<blDataType>&                  operator=(blDataType* ptr){m_ptr = ptr;return (*this);}
    
        operator                                    bool()const
        {
            if(m_ptr)
                return true;
            else
                return false;
        }
    
        bool                                        operator==(const blRawIterator<blDataType>& rawIterator)const{return (m_ptr == rawIterator.getConstPtr());}
        bool                                        operator!=(const blRawIterator<blDataType>& rawIterator)const{return (m_ptr != rawIterator.getConstPtr());}
    
        blRawIterator<blDataType>&                  operator+=(const difference_type& movement){m_ptr += movement;return (*this);}
        blRawIterator<blDataType>&                  operator-=(const difference_type& movement){m_ptr -= movement;return (*this);}
        blRawIterator<blDataType>&                  operator++(){++m_ptr;return (*this);}
        blRawIterator<blDataType>&                  operator--(){--m_ptr;return (*this);}
        blRawIterator<blDataType>                   operator++(int){auto temp(*this);++m_ptr;return temp;}
        blRawIterator<blDataType>                   operator--(int){auto temp(*this);--m_ptr;return temp;}
        blRawIterator<blDataType>                   operator+(const difference_type& movement){auto oldPtr = m_ptr;m_ptr+=movement;auto temp(*this);m_ptr = oldPtr;return temp;}
        blRawIterator<blDataType>                   operator-(const difference_type& movement){auto oldPtr = m_ptr;m_ptr-=movement;auto temp(*this);m_ptr = oldPtr;return temp;}
    
        difference_type                             operator-(const blRawIterator<blDataType>& rawIterator){return std::distance(rawIterator.getPtr(),this->getPtr());}
    
        blDataType&                                 operator*(){return *m_ptr;}
        const blDataType&                           operator*()const{return *m_ptr;}
        blDataType*                                 operator->(){return m_ptr;}
    
        blDataType*                                 getPtr()const{return m_ptr;}
        const blDataType*                           getConstPtr()const{return m_ptr;}
    
    protected:
    
        blDataType*                                 m_ptr;
    };
    //-------------------------------------------------------------------
    
  2. //-------------------------------------------------------------------
    // Raw reverse iterator with random access
    //-------------------------------------------------------------------
    template<typename blDataType>
    class blRawReverseIterator : public blRawIterator<blDataType>
    {
    public:
    
        blRawReverseIterator(blDataType* ptr = nullptr):blRawIterator<blDataType>(ptr){}
        blRawReverseIterator(const blRawIterator<blDataType>& rawIterator){this->m_ptr = rawIterator.getPtr();}
        blRawReverseIterator(const blRawReverseIterator<blDataType>& rawReverseIterator) = default;
        ~blRawReverseIterator(){}
    
        blRawReverseIterator<blDataType>&           operator=(const blRawReverseIterator<blDataType>& rawReverseIterator) = default;
        blRawReverseIterator<blDataType>&           operator=(const blRawIterator<blDataType>& rawIterator){this->m_ptr = rawIterator.getPtr();return (*this);}
        blRawReverseIterator<blDataType>&           operator=(blDataType* ptr){this->setPtr(ptr);return (*this);}
    
        blRawReverseIterator<blDataType>&           operator+=(const difference_type& movement){this->m_ptr -= movement;return (*this);}
        blRawReverseIterator<blDataType>&           operator-=(const difference_type& movement){this->m_ptr += movement;return (*this);}
        blRawReverseIterator<blDataType>&           operator++(){--this->m_ptr;return (*this);}
        blRawReverseIterator<blDataType>&           operator--(){++this->m_ptr;return (*this);}
        blRawReverseIterator<blDataType>            operator++(int){auto temp(*this);--this->m_ptr;return temp;}
        blRawReverseIterator<blDataType>            operator--(int){auto temp(*this);++this->m_ptr;return temp;}
        blRawReverseIterator<blDataType>            operator+(const int& movement){auto oldPtr = this->m_ptr;this->m_ptr-=movement;auto temp(*this);this->m_ptr = oldPtr;return temp;}
        blRawReverseIterator<blDataType>            operator-(const int& movement){auto oldPtr = this->m_ptr;this->m_ptr+=movement;auto temp(*this);this->m_ptr = oldPtr;return temp;}
    
        difference_type                             operator-(const blRawReverseIterator<blDataType>& rawReverseIterator){return std::distance(this->getPtr(),rawReverseIterator.getPtr());}
    
        blRawIterator<blDataType>                   base(){blRawIterator<blDataType> forwardIterator(this->m_ptr); ++forwardIterator; return forwardIterator;}
    };
    //-------------------------------------------------------------------
    

Now somewhere in your custom container class:

template<typename blDataType>
class blCustomContainer
{
public: // The typedefs

    typedef blRawIterator<blDataType>              iterator;
    typedef blRawIterator<const blDataType>        const_iterator;

    typedef blRawReverseIterator<blDataType>       reverse_iterator;
    typedef blRawReverseIterator<const blDataType> const_reverse_iterator;

                            .
                            .
                            .

public:  // The begin/end functions

    iterator                                       begin(){return iterator(&m_data[0]);}
    iterator                                       end(){return iterator(&m_data[m_size]);}

    const_iterator                                 cbegin(){return const_iterator(&m_data[0]);}
    const_iterator                                 cend(){return const_iterator(&m_data[m_size]);}

    reverse_iterator                               rbegin(){return reverse_iterator(&m_data[m_size - 1]);}
    reverse_iterator                               rend(){return reverse_iterator(&m_data[-1]);}

    const_reverse_iterator                         crbegin(){return const_reverse_iterator(&m_data[m_size - 1]);}
    const_reverse_iterator                         crend(){return const_reverse_iterator(&m_data[-1]);}

                            .
                            .
                            .
    // This is the pointer to the
    // beginning of the data
    // This allows the container
    // to either "view" data owned
    // by other containers or to
    // own its own data
    // You would implement a "create"
    // method for owning the data
    // and a "wrap" method for viewing
    // data owned by other containers

    blDataType*                                    m_data;
};

Return number of rows affected by UPDATE statements

This is exactly what the OUTPUT clause in SQL Server 2005 onwards is excellent for.

EXAMPLE

CREATE TABLE [dbo].[test_table](
    [LockId] [int] IDENTITY(1,1) NOT NULL,
    [StartTime] [datetime] NULL,
    [EndTime] [datetime] NULL,
PRIMARY KEY CLUSTERED 
(
    [LockId] ASC
) ON [PRIMARY]
) ON [PRIMARY]

INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 07','2009 JUL 07')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 08','2009 JUL 08')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 09','2009 JUL 09')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 10','2009 JUL 10')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 11','2009 JUL 11')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 12','2009 JUL 12')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 13','2009 JUL 13')

UPDATE test_table
    SET StartTime = '2011 JUL 01'
    OUTPUT INSERTED.* -- INSERTED reflect the value after the UPDATE, INSERT, or MERGE statement is completed 
WHERE
    StartTime > '2009 JUL 09'

Results in the following being returned

    LockId StartTime                EndTime
-------------------------------------------------------
4      2011-07-01 00:00:00.000  2009-07-10 00:00:00.000
5      2011-07-01 00:00:00.000  2009-07-11 00:00:00.000
6      2011-07-01 00:00:00.000  2009-07-12 00:00:00.000
7      2011-07-01 00:00:00.000  2009-07-13 00:00:00.000

In your particular case, since you cannot use aggregate functions with OUTPUT, you need to capture the output of INSERTED.* in a table variable or temporary table and count the records. For example,

DECLARE @temp TABLE (
  [LockId] [int],
  [StartTime] [datetime] NULL,
  [EndTime] [datetime] NULL 
)

UPDATE test_table
    SET StartTime = '2011 JUL 01'
    OUTPUT INSERTED.* INTO @temp
WHERE
    StartTime > '2009 JUL 09'


-- now get the count of affected records
SELECT COUNT(*) FROM @temp

How to JOIN three tables in Codeigniter

Use this code in model

public function funcname($id)
{
    $this->db->select('*');
    $this->db->from('Album a'); 
    $this->db->join('Category b', 'b.cat_id=a.cat_id', 'left');
    $this->db->join('Soundtrack c', 'c.album_id=a.album_id', 'left');
    $this->db->where('c.album_id',$id);
    $this->db->order_by('c.track_title','asc');         
    $query = $this->db->get(); 
    if($query->num_rows() != 0)
    {
        return $query->result_array();
    }
    else
    {
        return false;
    }
}

Oracle "(+)" Operator

In practice, the + symbol is placed directly in the conditional statement and on the side of the optional table (the one which is allowed to contain empty or null values within the conditional).

Calculate summary statistics of columns in dataframe

To clarify one point in @EdChum's answer, per the documentation, you can include the object columns by using df.describe(include='all'). It won't provide many statistics, but will provide a few pieces of info, including count, number of unique values, top value. This may be a new feature, I don't know as I am a relatively new user.

Fuzzy matching using T-SQL

I've found that the stuff SQL Server gives you to do fuzzy matching is pretty clunky. I've had really good luck with my own CLR functions using the Levenshtein distance algorithm and some weighting. Using that algorithm, I've then made a UDF called GetSimilarityScore that takes two strings and returns a score between 0.0 and 1.0. The closer to 1.0 the match is, the better. Then, query with a threshold of >=0.8 or so to get the most likely matches. Something like this:

if object_id('tempdb..#similar') is not null drop table #similar
select a.id, (
    select top 1 x.id
   from MyTable x
   where x.id <> a.id
   order by dbo.GetSimilarityScore(a.MyField, x.MyField) desc
) as MostSimilarId
into #similar
from MyTable a

select *, dbo.GetSimilarityScore(a.MyField, c.MyField)
from MyTable a
join #similar b on a.id = b.id
join MyTable c on b.MostSimilarId = c.id

Just don't do it with really large tables. It's a slow process.

Here's the CLR UDFs:

''' <summary>
''' Compute the distance between two strings.
''' </summary>
''' <param name="s1">The first of the two strings.</param>
''' <param name="s2">The second of the two strings.</param>
''' <returns>The Levenshtein cost.</returns>
<Microsoft.SqlServer.Server.SqlFunction()> _
Public Shared Function ComputeLevenstheinDistance(ByVal string1 As SqlString, ByVal string2 As SqlString) As SqlInt32
    If string1.IsNull OrElse string2.IsNull Then Return SqlInt32.Null
    Dim s1 As String = string1.Value
    Dim s2 As String = string2.Value

    Dim n As Integer = s1.Length
    Dim m As Integer = s2.Length
    Dim d As Integer(,) = New Integer(n, m) {}

    ' Step 1
    If n = 0 Then Return m
    If m = 0 Then Return n

    ' Step 2
    For i As Integer = 0 To n
        d(i, 0) = i
    Next

    For j As Integer = 0 To m
        d(0, j) = j
    Next

    ' Step 3
    For i As Integer = 1 To n
        'Step 4
        For j As Integer = 1 To m
            ' Step 5
            Dim cost As Integer = If((s2(j - 1) = s1(i - 1)), 0, 1)

            ' Step 6
            d(i, j) = Math.Min(Math.Min(d(i - 1, j) + 1, d(i, j - 1) + 1), d(i - 1, j - 1) + cost)
        Next
    Next
    ' Step 7
    Return d(n, m)
End Function

''' <summary>
''' Returns a score between 0.0-1.0 indicating how closely two strings match.  1.0 is a 100%
''' T-SQL equality match, and the score goes down from there towards 0.0 for less similar strings.
''' </summary>
<Microsoft.SqlServer.Server.SqlFunction()> _
Public Shared Function GetSimilarityScore(string1 As SqlString, string2 As SqlString) As SqlDouble
    If string1.IsNull OrElse string2.IsNull Then Return SqlInt32.Null

    Dim s1 As String = string1.Value.ToUpper().TrimEnd(" "c)
    Dim s2 As String = string2.Value.ToUpper().TrimEnd(" "c)
    If s1 = s2 Then Return 1.0F ' At this point, T-SQL would consider them the same, so I will too

    Dim flatLevScore As Double = InternalGetSimilarityScore(s1, s2)

    Dim letterS1 As String = GetLetterSimilarityString(s1)
    Dim letterS2 As String = GetLetterSimilarityString(s2)
    Dim letterScore As Double = InternalGetSimilarityScore(letterS1, letterS2)

    'Dim wordS1 As String = GetWordSimilarityString(s1)
    'Dim wordS2 As String = GetWordSimilarityString(s2)
    'Dim wordScore As Double = InternalGetSimilarityScore(wordS1, wordS2)

    If flatLevScore = 1.0F AndAlso letterScore = 1.0F Then Return 1.0F
    If flatLevScore = 0.0F AndAlso letterScore = 0.0F Then Return 0.0F

    ' Return weighted result
    Return (flatLevScore * 0.2F) + (letterScore * 0.8F)
End Function

Private Shared Function InternalGetSimilarityScore(s1 As String, s2 As String) As Double
    Dim dist As SqlInt32 = ComputeLevenstheinDistance(s1, s2)
    Dim maxLen As Integer = If(s1.Length > s2.Length, s1.Length, s2.Length)
    If maxLen = 0 Then Return 1.0F
    Return 1.0F - Convert.ToDouble(dist.Value) / Convert.ToDouble(maxLen)
End Function

''' <summary>
''' Sorts all the alpha numeric characters in the string in alphabetical order
''' and removes everything else.
''' </summary>
Private Shared Function GetLetterSimilarityString(s1 As String) As String
    Dim allChars = If(s1, "").ToUpper().ToCharArray()
    Array.Sort(allChars)
    Dim result As New StringBuilder()
    For Each ch As Char In allChars
        If Char.IsLetterOrDigit(ch) Then
            result.Append(ch)
        End If
    Next
    Return result.ToString()
End Function

''' <summary>
''' Removes all non-alpha numeric characters and then sorts
''' the words in alphabetical order.
''' </summary>
Private Shared Function GetWordSimilarityString(s1 As String) As String
    Dim words As New List(Of String)()
    Dim curWord As StringBuilder = Nothing
    For Each ch As Char In If(s1, "").ToUpper()
        If Char.IsLetterOrDigit(ch) Then
            If curWord Is Nothing Then
                curWord = New StringBuilder()
            End If
            curWord.Append(ch)
        Else
            If curWord IsNot Nothing Then
                words.Add(curWord.ToString())
                curWord = Nothing
            End If
        End If
    Next
    If curWord IsNot Nothing Then
        words.Add(curWord.ToString())
    End If

    words.Sort(StringComparer.OrdinalIgnoreCase)
    Return String.Join(" ", words.ToArray())
End Function

How to generate a core dump in Linux on a segmentation fault?

As explained above the real question being asked here is how to enable core dumps on a system where they are not enabled. That question is answered here.

If you've come here hoping to learn how to generate a core dump for a hung process, the answer is

gcore <pid>

if gcore is not available on your system then

kill -ABRT <pid>

Don't use kill -SEGV as that will often invoke a signal handler making it harder to diagnose the stuck process

What is the purpose of the "role" attribute in HTML?

Is this role attribute necessary?

Answer: Yes.

  • The role attribute is necessary to support Accessible Rich Internet Applications (WAI-ARIA) to define roles in XML-based languages, when the languages do not define their own role attribute.
  • Although this is the reason the role attribute is published by the Protocols and Formats Working Group, the attribute has more general use cases as well.

It provides you:

  • Accessibility
  • Device adaptation
  • Server-side processing
  • Complex data description,...etc.

Spark specify multiple column conditions for dataframe join

As of Spark version 1.5.0 (which is currently unreleased), you can join on multiple DataFrame columns. Refer to SPARK-7990: Add methods to facilitate equi-join on multiple join keys.

Python

Leads.join(
    Utm_Master, 
    ["LeadSource","Utm_Source","Utm_Medium","Utm_Campaign"],
    "left_outer"
)

Scala

The question asked for a Scala answer, but I don't use Scala. Here is my best guess....

Leads.join(
    Utm_Master,
    Seq("LeadSource","Utm_Source","Utm_Medium","Utm_Campaign"),
    "left_outer"
)

How to round up integer division and have int result in Java?

Another one-liner that is not too complicated:

private int countNumberOfPages(int numberOfObjects, int pageSize) {
    return numberOfObjects / pageSize + (numberOfObjects % pageSize == 0 ? 0 : 1);
}

Could use long instead of int; just change the parameter types and return type.

jQuery rotate/transform

It's because you have a recursive function inside of rotate. It's calling itself again:

// Animate rotation with a recursive call
setTimeout(function() { rotate(++degree); },65);

Take that out and it won't keep on running recursively.

I would also suggest just using this function instead:

function rotate($el, degrees) {
    $el.css({
  '-webkit-transform' : 'rotate('+degrees+'deg)',
     '-moz-transform' : 'rotate('+degrees+'deg)',  
      '-ms-transform' : 'rotate('+degrees+'deg)',  
       '-o-transform' : 'rotate('+degrees+'deg)',  
          'transform' : 'rotate('+degrees+'deg)',  
               'zoom' : 1

    });
}

It's much cleaner and will work for the most amount of browsers.