Programs & Examples On #Linked tables

Installing OpenCV for Python on Ubuntu, getting ImportError: No module named cv2.cv

If you really sure that you installed cv2 but it gives no module error. There is a solution for this. Probably you have cv2.so file in your directory

/usr/local/lib/python2.7/site-packages/cv2.so

move this cv2.so file to

/usr/lib/python2.7/site-packages

copy the file into site-packages directory

Regex: ignore case sensitivity

The i flag is normally used for case insensitivity. You don't give a language here, but it'll probably be something like /G[ab].*/i or /(?i)G[ab].*/.

if statement in ng-click

If you do have to do it this way, here's a few ways of doing it:

Disabling the button with ng-disabled

By far the easiest solution.

<input ng-disabled="!profileForm.$valid" ng-click="updateMyProfile()" ... >

Hiding the button (and showing something else) with ng-if

Might be OK if you're showing/hiding some complex markup.

<div ng-if="profileForm.$valid">
    <input ng-click="updateMyProfile()" ... >
</div>
<div ng-if="!profileForm.$valid">
    Sorry! We need all form fields properly filled out to continue.
</div>

(remember, there's no ng-else ...)

A mix of both

Communicating to the user where the button is (he won't look for it any longer), but explain why it can't be clicked.

<input ng-disabled="!profileForm.$valid" ng-click="updateMyProfile()" ... >
<div ng-if="!profileForm.$valid">
    Sorry! We need all form fields properly filled out to continue.
</div>

Scaling a System.Drawing.Bitmap to a given size while maintaining aspect ratio

Just to add to yamen's answer, which is perfect for images but not so much for text.

If you are trying to use this to scale text, like say a Word document (which is in this case in bytes from Word Interop), you will need to make a few modifications or you will get giant bars on the side.

May not be perfect but works for me!

using (MemoryStream ms = new MemoryStream(wordBytes))
{
    float width = 3840;
    float height = 2160;
    var brush = new SolidBrush(Color.White);

    var rawImage = Image.FromStream(ms);
    float scale = Math.Min(width / rawImage.Width, height / rawImage.Height);
    var scaleWidth  = (int)(rawImage.Width  * scale);
    var scaleHeight = (int)(rawImage.Height * scale);
    var scaledBitmap = new Bitmap(scaleWidth, scaleHeight);

    Graphics graph = Graphics.FromImage(scaledBitmap);
    graph.InterpolationMode = InterpolationMode.High;
    graph.CompositingQuality = CompositingQuality.HighQuality;
    graph.SmoothingMode = SmoothingMode.AntiAlias;
    graph.FillRectangle(brush, new RectangleF(0, 0, width, height));
    graph.DrawImage(rawImage, new Rectangle(0, 0 , scaleWidth, scaleHeight));

    scaledBitmap.Save(fileName, ImageFormat.Png);
    return scaledBitmap;
}

How to clear the Entry widget after a button is pressed in Tkinter?

real gets the value ent.get() which is just a string. It has no idea where it came from, and no way to affect the widget.

Instead of real.delete(), call .delete() on the entry widget itself:

def res(ent, real, secret):
    if secret == eval(real):
        showinfo(message='that is right!')
    ent.delete(0, END)

def guess():
    ...
    btn = Button(ge, text="Enter", command=lambda: res(ent, ent.get(), secret))

How do I open a URL from C++?

Here's an example in windows code using winsock.

#include <winsock2.h>
#include <windows.h>
#include <iostream>
#include <string>
#include <locale>
#pragma comment(lib,"ws2_32.lib")
using namespace std;

string website_HTML;
locale local;


void get_Website(char *url );

int main ()
{
    //open website
    get_Website("www.google.com" );

    //format website HTML
    for (size_t i=0; i<website_HTML.length(); ++i) 
        website_HTML[i]= tolower(website_HTML[i],local);

    //display HTML
    cout <<website_HTML;

    cout<<"\n\n";



    return 0;
}



//***************************
void get_Website(char *url )
{
    WSADATA wsaData;
    SOCKET Socket;
    SOCKADDR_IN SockAddr;


    int lineCount=0;
    int rowCount=0;

    struct hostent *host;
    char *get_http= new char[256];

        memset(get_http,' ', sizeof(get_http) );
        strcpy(get_http,"GET / HTTP/1.1\r\nHost: ");
        strcat(get_http,url);
        strcat(get_http,"\r\nConnection: close\r\n\r\n");

        if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0) 
        {
            cout << "WSAStartup failed.\n";
            system("pause");
            //return 1;
        }

        Socket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
        host = gethostbyname(url);

        SockAddr.sin_port=htons(80);
        SockAddr.sin_family=AF_INET;
        SockAddr.sin_addr.s_addr = *((unsigned long*)host->h_addr);

        cout << "Connecting to "<< url<<" ...\n";

        if(connect(Socket,(SOCKADDR*)(&SockAddr),sizeof(SockAddr)) != 0)
        {
            cout << "Could not connect";
            system("pause");
            //return 1;
        }

        cout << "Connected.\n";     
        send(Socket,get_http, strlen(get_http),0 );

        char buffer[10000];

        int nDataLength;
            while ((nDataLength = recv(Socket,buffer,10000,0)) > 0)
            {       
                int i = 0;

                while (buffer[i] >= 32 || buffer[i] == '\n' || buffer[i] == '\r') 
                {                    
                    website_HTML+=buffer[i];                     
                    i += 1;
                }               
            }
        closesocket(Socket);
        WSACleanup();

            delete[] get_http;
}

What does "Changes not staged for commit" mean

What worked for me was to go to the root folder, where .git/ is. I was inside one the child folders and got there error.

Change form size at runtime in C#

Something like this works fine for me:

public partial class Form1 : Form
{
    Form mainFormHandler;
...
}

private void Form1_Load(object sender, EventArgs e){
    mainFormHandler = Application.OpenForms[0];
   //or instead use this one:
   //mainFormHandler = Application.OpenForms["Form1"];
}

Then you can change the size as below:

mainFormHandler.Width = 600;
mainFormHandler.Height= 400;

or

mainFormHandler.Size = new Size(600, 400);

Another useful point is that if you want to change the size of mainForm from another Form, you can simply use Property to set the size.

TypeError: p.easing[this.easing] is not a function

I got this error today whilst trying to initiate a slide effect on a div. Thanks to the answer from 'I Hate Lazy' above (which I've upvoted), I went looking for a custom jQuery UI script, and you can in fact build your own file directly on the jQuery ui website http://jqueryui.com/download/. All you have to do is mark the effect(s) that you're looking for and then download.

I was looking for the slide effect. So I first unchecked all the checkboxes, then clicked on the 'slide effect' checkbox and the page automatically then checks those other components necessary to make the slide effect work. Very simple.

easeOutBounce is an easing effect, for which you'll need to check the 'Effects Core' checkbox.

Purpose of #!/usr/bin/python3 shebang

  1. And this line is how.

  2. It is ignored.

  3. It will fail to run, and should be changed to point to the proper location. Or env should be used.

  4. It will fail to run, and probably fail to run under a different version regardless.

Authentication failed for https://xxx.visualstudio.com/DefaultCollection/_git/project

After struggling with git authentication and azure devops server and trying other answers this tip here worked for me.

Using Visual Studio? Team Explorer handles authentication with Azure Repos for you.

Once I connected to the repo using Team Explorer I could use command line to execute git commands.

What is the best method of handling currency/money?

If you are using Postgres (and since we're in 2017 now) you might want to give their :money column type a try.

add_column :products, :price, :money, default: 0

How to get the 'height' of the screen using jquery

use with responsive website (view in mobile or ipad)

jQuery(window).height();   // return height of browser viewport
jQuery(window).width();    // return width of browser viewport

rarely use

jQuery(document).height(); // return height of HTML document
jQuery(document).width();  // return width of HTML document

How to develop Android app completely using python?

There are two primary contenders for python apps on Android

Chaquopy

https://chaquo.com/chaquopy/

This integrates with the Android build system, it provides a Python API for all android features. To quote the site "The complete Android API and user interface toolkit are directly at your disposal."

Beeware (Toga widget toolkit)

https://pybee.org/

This provides a multi target transpiler, supports many targets such as Android and iOS. It uses a generic widget toolkit (toga) that maps to the host interface calls.

Which One?

Both are active projects and their github accounts shows a fair amount of recent activity.

Beeware Toga like all widget libraries is good for getting the basics out to multiple platforms. If you have basic designs, and a desire to expand to other platforms this should work out well for you.

On the other hand, Chaquopy is a much more precise in its mapping of the python API to Android. It also allows you to mix in Java, useful if you want to use existing code from other resources. If you have strict design targets, and predominantly want to target Android this is a much better resource.

Compare dates with javascript

The best way is,

var first = '2012-11-21';
var second = '2012-11-03';

if (new Date(first) > new Date(second) {
    .....
}

How to vertically center <div> inside the parent element with CSS?

Centering the child elements in a div. It works for all screen sizes

#parent {
    padding: 5% 0;
}

#child {
    padding: 10% 0;
}

<div id="parent">
    <div id="child">Content here</div>
</div>

for more details, you can visit to this link

Access to file download dialog in Firefox

I didnt unserstood your objective, Do you wanted your test to automatically download file when test is getting executed, if yes, then You need to use custom Firefox profile in your test execution.

In the custom profile, for first time execute test manually and if download dialog comes, the set it Save it to Disk, also check Always perform this action checkbox which will ensure that file automatically get downloaded next time you run your test.

How do I update Ruby Gems from behind a Proxy (ISA-NTLM)

for anyone tunnelling with SSH; you can create a version of the gem command that uses SOCKS proxy:

  1. Install socksify with gem install socksify (you'll need to be able to do this step without proxy, at least)
  2. Copy your existing gem exe

    cp $(command which gem) /usr/local/bin/proxy_gem
    
  3. Open it in your favourite editor and add this at the top (after the shebang)

    require 'socksify'
    
    if ENV['SOCKS_PROXY']
      require 'socksify'
      host, port = ENV['SOCKS_PROXY'].split(':')
      TCPSocket.socks_server = host || 'localhost'
      TCPSocket.socks_port = port.to_i || 1080
    end
    
  4. Set up your tunnel

    ssh -D 8123 -f -C -q -N user@proxy
    
  5. Run your gem command with proxy_gem

    SOCKS_PROXY=localhost:8123 proxy_gem push mygem
    

How to get the difference between two dictionaries in Python?

You were right to look at using a set, we just need to dig in a little deeper to get your method to work.

First, the example code:

test_1 = {"foo": "bar", "FOO": "BAR"}
test_2 = {"foo": "bar", "f00": "b@r"}

We can see right now that both dictionaries contain a similar key/value pair:

{"foo": "bar", ...}

Each dictionary also contains a completely different key value pair. But how do we detect the difference? Dictionaries don't support that. Instead, you'll want to use a set.

Here is how to turn each dictionary into a set we can use:

set_1 = set(test_1.items())
set_2 = set(test_2.items())

This returns a set containing a series of tuples. Each tuple represents one key/value pair from your dictionary.

Now, to find the difference between set_1 and set_2:

print set_1 - set_2
>>> {('FOO', 'BAR')}

Want a dictionary back? Easy, just:

dict(set_1 - set_2)
>>> {'FOO': 'BAR'}

Keyboard shortcut to change font size in Eclipse?

Take a look at this project: http://code.google.com/p/tarlog-plugins/downloads/detail?name=tarlog.eclipse.plugins_1.4.2.jar&can=2&q=

It has some other features, but most importantly, it has Ctrl++ and Ctrl+- to change the font size, it's awesome.

How are people unit testing with Entity Framework 6, should you bother?

In order to unit test code that relies on your database you need to setup a database or mock for each and every test.

  1. Having a database (real or mocked) with a single state for all your tests will bite you quickly; you cannot test all records are valid and some aren't from the same data.
  2. Setting up an in-memory database in a OneTimeSetup will have issues where the old database is not cleared down before the next test starts up. This will show as tests working when you run them individually, but failing when you run them all.
  3. A Unit test should ideally only set what affects the test

I am working in an application that has a lot of tables with a lot of connections and some massive Linq blocks. These need testing. A simple grouping missed, or a join that results in more than 1 row will affect results.

To deal with this I have setup a heavy Unit Test Helper that is a lot of work to setup, but enables us to reliably mock the database in any state, and running 48 tests against 55 interconnected tables, with the entire database setup 48 times takes 4.7 seconds.

Here's how:

  1. In the Db context class ensure each table class is set to virtual

    public virtual DbSet<Branch> Branches { get; set; }
    public virtual DbSet<Warehouse> Warehouses { get; set; }
    
  2. In a UnitTestHelper class create a method to setup your database. Each table class is an optional parameter. If not supplied, it will be created through a Make method

    internal static Db Bootstrap(bool onlyMockPassedTables = false, List<Branch> branches = null, List<Products> products = null, List<Warehouses> warehouses = null)
    {
        if (onlyMockPassedTables == false) {
            branches ??= new List<Branch> { MakeBranch() };
            warehouses ??= new List<Warehouse>{ MakeWarehouse() };
        }
    
  3. For each table class, each object in it is mapped to the other lists

        branches?.ForEach(b => {
            b.Warehouse = warehouses.FirstOrDefault(w => w.ID == b.WarehouseID);
        });
    
        warehouses?.ForEach(w => {
            w.Branches = branches.Where(b => b.WarehouseID == w.ID);
        });
    
  4. And add it to the DbContext

         var context = new Db(new DbContextOptionsBuilder<Db>().UseInMemoryDatabase(Guid.NewGuid().ToString()).Options);
         context.Branches.AddRange(branches);
         context.Warehouses.AddRange(warehouses);
         context.SaveChanges();
         return context;
     }
    
  5. Define a list of IDs to make is easier to reuse them and make sure joins are valid

     internal const int BranchID = 1;
     internal const int WarehouseID = 2;
    
  6. Create a Make for each table to setup the most basic, but connected version it can be

     internal static Branch MakeBranch(int id = BranchID, string code = "The branch", int warehouseId = WarehouseID) => new Branch { ID = id, Code = code, WarehouseID = warehouseId };
     internal static Warehouse MakeWarehouse(int id = WarehouseID, string code = "B", string name = "My Big Warehouse") => new Warehouse { ID = id, Code = code, Name = name };
    

It's a lot of work, but it only needs doing once, and then your tests can be very focused because the rest of the database will be setup for it.

[Test]
[TestCase(new string [] {"ABC", "DEF"}, "ABC", ExpectedResult = 1)]
[TestCase(new string [] {"ABC", "BCD"}, "BC", ExpectedResult = 2)]
[TestCase(new string [] {"ABC"}, "EF", ExpectedResult = 0)]
[TestCase(new string[] { "ABC", "DEF" }, "abc", ExpectedResult = 1)]
public int Given_SearchingForBranchByName_Then_ReturnCount(string[] codesInDatabase, string searchString)
{
    // Arrange
    var branches = codesInDatabase.Select(x => UnitTestHelpers.MakeBranch(code: $"qqqq{x}qqq")).ToList();
    var db = UnitTestHelpers.Bootstrap(branches: branches);
    var service = new BranchService(db);

    // Act
    var result = service.SearchByName(searchString);

    // Assert
    return result.Count();
}

git push says "everything up-to-date" even though I have local changes

I had this happen (commits in my git log were not on GitHub even though git said everything was up to date) and I'm confident the problem was Github. I didn't get any error messages in git, but GitHub had status errors and my commits were there several hours later.

https://status.github.com/messages

The GitHub status messages were:

  • We are investigating reports of service unavailability.
  • We're investigating problems accessing GitHub.com.
  • We're failing over a data storage system in order to restore access to GitHub.com.

How to logout and redirect to login page using Laravel 5.4?

In your web.php (routes):

add:

Route::get('logout', '\App\Http\Controllers\Auth\LoginController@logout');

In your LoginController.php

add:

public function logout(Request $request) {
  Auth::logout();
  return redirect('/login');
}

Also, in the top of LoginController.php, after namespace

add:

use Auth;

Now, you are able to logout using yourdomain.com/logout URL or if you have created logout button, add href to /logout

Jquery Open in new Tab (_blank)

you cannot set target attribute to div, becacuse div does not know how to handle http requests. instead of you set target attribute for link tag.

$(this).find("a").target = "_blank";
window.location= $(this).find("a").attr("href")

How to clear exisiting dropdownlist items when its content changes?

just compiled your code and the only thing that is missing from it is that you have to Bind your ddl2 to an empty datasource before binding it again like this:

Protected Sub ddl1_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) //ddl2.Items.Clear()

ddl2.DataSource=New List(Of String)()
ddl2.DataSource = sql2
ddl2.DataBind() End Sub

and it worked just fine

Print all properties of a Python Class

Here is full code. The result is exactly what you want.

class Animal(object):
    def __init__(self):
        self.legs = 2
        self.name = 'Dog'
        self.color= 'Spotted'
        self.smell= 'Alot'
        self.age  = 10
        self.kids = 0

if __name__ == '__main__':
    animal = Animal()
    temp = vars(animal)
    for item in temp:
        print item , ' : ' , temp[item]
        #print item , ' : ', temp[item] ,

Adding headers to requests module

From http://docs.python-requests.org/en/latest/user/quickstart/

url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
headers = {'content-type': 'application/json'}

r = requests.post(url, data=json.dumps(payload), headers=headers)

You just need to create a dict with your headers (key: value pairs where the key is the name of the header and the value is, well, the value of the pair) and pass that dict to the headers parameter on the .get or .post method.

So more specific to your question:

headers = {'foobar': 'raboof'}
requests.get('http://himom.com', headers=headers)

Is there a way to get element by XPath using JavaScript in Selenium WebDriver?

For something like $x from chrome command line api (to select multiple elements) try:

var xpath = function(xpathToExecute){
  var result = [];
  var nodesSnapshot = document.evaluate(xpathToExecute, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null );
  for ( var i=0 ; i < nodesSnapshot.snapshotLength; i++ ){
    result.push( nodesSnapshot.snapshotItem(i) );
  }
  return result;
}

This MDN overview helped: https://developer.mozilla.org/en-US/docs/Introduction_to_using_XPath_in_JavaScript

How to store command results in a shell variable?

The syntax to store the command output into a variable is var=$(command).

So you can directly do:

result=$(ls -l | grep -c "rahul.*patle")

And the variable $result will contain the number of matches.

Getting title and meta tags from external website

<?php 

// ------------------------------------------------------ 

function curl_get_contents($url) {

    $timeout = 5; 
    $useragent = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0'; 

    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_URL, $url); 
    curl_setopt($ch, CURLOPT_USERAGENT, $useragent); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); 
    $data = curl_exec($ch); 
    curl_close($ch); 

    return $data; 
}

// ------------------------------------------------------ 

function fetch_meta_tags($url) { 

    $html = curl_get_contents($url); 
    $mdata = array(); 

    $doc = new DOMDocument();
    $doc->loadHTML($html);

    $titlenode = $doc->getElementsByTagName('title'); 
    $title = $titlenode->item(0)->nodeValue;

    $metanodes = $doc->getElementsByTagName('meta'); 
    foreach($metanodes as $node) { 
    $key = $node->getAttribute('name'); 
    $val = $node->getAttribute('content'); 
    if (!empty($key)) { $mdata[$key] = $val; } 
    }

    $res = array($url, $title, $mdata); 

    return $res;
}

// ------------------------------------------------------ 

?>

Split value from one field to two

It seems that existing responses are over complicated or not a strict answer to the particular question.

I think, the simple answer is the following query:

SELECT
    SUBSTRING_INDEX(`membername`, ' ', 1) AS `memberfirst`,
    SUBSTRING_INDEX(`membername`, ' ', -1) AS `memberlast`
;

I think it is not necessary to deal with more-than-two-word names in this particular situation. If you want to do it properly, splitting can be very hard or even impossible in some cases:

  • Johann Sebastian Bach
  • Johann Wolfgang von Goethe
  • Edgar Allan Poe
  • Jakob Ludwig Felix Mendelssohn-Bartholdy
  • Petofi Sándor
  • ?? ?

In a properly designed database, human names should be stored both in parts and in whole. This is not always possible, of course.

How to check if current thread is not main thread

Allow me to preface this with: I acknowledged this post has the 'Android' tag, however, my search had nothing to do with 'Android' and this was my top result. To that end, for the non-Android SO Java users landing here, don't forget about:

public static void main(String[] args{
    Thread.currentThread().setName("SomeNameIChoose");
    /*...the rest of main...*/
}

After setting this, elsewhere in your code, you can easily check if you're about to execute on the main thread with:

if(Thread.currentThread().getName().equals("SomeNameIChoose"))
{
    //do something on main thread
}

A bit embarrassed I had searched before remembering this, but hopefully it will help someone else!

How do I install a pip package globally instead of locally?

Where does pip installations happen in python?

I will give a windows solution which I was facing and took a while to solve.

First of all, in windows (I will be taking Windows as the OS here), if you do pip install <package_name>, it will be by default installed globally (if you have not activated a virtual enviroment). Once you activate a virtual enviroment and you are inside it, all pip installations will be inside that virtual enviroment.


pip is installing the said packages but not I cannot use them?

For this pip might be giving you a warning that the pip executables like pip3.exe, pip.exe are not on your path variable. For this you might add this path ( usually - C:\Users\<your_username>\AppData\Roaming\Programs\Python\ ) to your enviromental variables. After this restart your cmd, and now try to use your installed python package. It should work now.

HTTP Basic: Access denied fatal: Authentication failed

Before digging into the solution lets first see why this happens.

Before any transaction with git that your machine does git checks for your authentication which can be done using

  1. An SSH key token present in your machine and shared with git-repo(most preferred) OR
  2. Using your username/password (mostly used)

Why did this happen

In simple words, this happened because the credentials stored in your machine are not authentic i.e.there are chances that your password stored in the machine has changed from whats there in git therefore

Solution

Head towards, control panel and search for Credential Manager look for your use git url and change the creds.

There you go this works with mostly every that windows keep track off

How can I get the Windows last reboot reason

This article explains in detail how to find the reason for last startup/shutdown. In my case, this was due to windows SCCM pushing updates even though I had it disabled locally. Visit the article for full details with pictures. For reference, here are the steps copy/pasted from the website:

  1. Press the Windows + R keys to open the Run dialog, type eventvwr.msc, and press Enter.

  2. If prompted by UAC, then click/tap on Yes (Windows 7/8) or Continue (Vista).

  3. In the left pane of Event Viewer, double click/tap on Windows Logs to expand it, click on System to select it, then right click on System, and click/tap on Filter Current Log.

  4. Do either step 5 or 6 below for what shutdown events you would like to see.

  5. To See the Dates and Times of All User Shut Downs of the Computer

    A) In Event sources, click/tap on the drop down arrow and check the USER32 box.

    B) In the All Event IDs field, type 1074, then click/tap on OK.

    C) This will give you a list of power off (shutdown) and restart Shutdown Type of events at the top of the middle pane in Event Viewer.

    D) You can scroll through these listed events to find the events with power off as the Shutdown Type. You will notice the date and time, and what user was responsible for shutting down the computer per power off event listed.

    E) Go to step 7.

  6. To See the Dates and Times of All Unexpected Shut Downs of the Computer

    A) In the All Event IDs field, type 6008, then click/tap on OK.

    B) This will give you a list of unexpected shutdown events at the top of the middle pane in Event Viewer. You can scroll through these listed events to see the date and time of each one.

Concatenate String in String Objective-c

Iam amazed that none of the top answers pointed out that under recent Objective-C versions (after they added literals), you can concatenate just like this:

@"first" @"second"

And it will result in:

@"firstsecond"

You can not use it with NSString objects, only with literals, but it can be useful in some cases.

VS 2012: Scroll Solution Explorer to current file

On Visual Studio 2017, the shortcut is: Ctrl+´,S.

enter image description here

Multidimensional arrays in Swift

Your problem may have been due to a deficiency in an earlier version of Swift or of the Xcode Beta. Working with Xcode Version 6.0 (6A279r) on August 21, 2014, your code works as expected with this output:

column: 0 row: 0 value:1.0
column: 0 row: 1 value:4.0
column: 0 row: 2 value:7.0
column: 1 row: 0 value:2.0
column: 1 row: 1 value:5.0
column: 1 row: 2 value:8.0
column: 2 row: 0 value:3.0
column: 2 row: 1 value:6.0
column: 2 row: 2 value:9.0

I just copied and pasted your code into a Swift playground and defined two constants:

let NumColumns = 3, NumRows = 3

How to check if an Object is a Collection Type in Java?

Java conveniently has the instanceof operator (JLS 15.20.2) to test if a given object is of a given type.

 if (x instanceof List<?>) {   
    List<?> list = (List<?>) x;
    // do something with list
 } else if (x instanceof Collection<?>) {
    Collection<?> col = (Collection<?>) x;
    // do something with col
 }

One thing should be mentioned here: it's important in these kinds of constructs to check in the right order. You will find that if you had swapped the order of the check in the above snippet, the code will still compile, but it will no longer work. That is the following code doesn't work:

 // DOESN'T WORK! Wrong order!
 if (x instanceof Collection<?>) {
    Collection<?> col = (Collection<?>) x;
    // do something with col
 } else if (x instanceof List<?>) { // this will never be reached!
    List<?> list = (List<?>) x;
    // do something with list
 }

The problem is that a List<?> is-a Collection<?>, so it will pass the first test, and the else means that it will never reach the second test. You have to test from the most specific to the most general type.

How to check list A contains any value from list B?

I've profiled Justins two solutions. a.Any(a => b.Contains(a)) is fastest.

using System;
using System.Collections.Generic;
using System.Linq;

namespace AnswersOnSO
{
    public class Class1
    {
        public static void Main(string []args)
        {
//            How to check if list A contains any value from list B?
//            e.g. something like A.contains(a=>a.id = B.id)?
            var a = new List<int> {1,2,3,4};
            var b = new List<int> {2,5};
            var times = 10000000;

            DateTime dtAny = DateTime.Now;
            for (var i = 0; i < times; i++)
            {
                var aContainsBElements = a.Any(b.Contains);
            }
            var timeAny = (DateTime.Now - dtAny).TotalSeconds;

            DateTime dtIntersect = DateTime.Now;
            for (var i = 0; i < times; i++)
            {
                var aContainsBElements = a.Intersect(b).Any();
            }
            var timeIntersect = (DateTime.Now - dtIntersect).TotalSeconds;

            // timeAny: 1.1470656 secs
            // timeIn.: 3.1431798 secs
        }
    }
}

JPA - Returning an auto generated id after persist()

The ID is only guaranteed to be generated at flush time. Persisting an entity only makes it "attached" to the persistence context. So, either flush the entity manager explicitely:

em.persist(abc);
em.flush();
return abc.getId();

or return the entity itself rather than its ID. When the transaction ends, the flush will happen, and users of the entity outside of the transaction will thus see the generated ID in the entity.

@Override
public ABC addNewABC(ABC abc) {
    abcDao.insertABC(abc);
    return abc;
}

Order a MySQL table by two columns

The following will order your data depending on both column in descending order.

ORDER BY article_rating DESC, article_time DESC

Calculating Pearson correlation and significance in Python

The Pearson correlation can be calculated with numpy's corrcoef.

import numpy
numpy.corrcoef(list1, list2)[0, 1]

How to convert from []byte to int in Go Programming

var bs []byte
value, _ := strconv.ParseInt(string(bs), 10, 64)

When do Java generics require <? extends T> instead of <T> and is there any downside of switching?

Thanks to everyone who answered the question, it really helped clarify things for me. In the end Scott Stanchfield's answer got the closest to how I ended up understanding it, but since I didn't understand him when he first wrote it, I am trying to restate the problem so that hopefully someone else will benefit.

I'm going to restate the question in terms of List, since it has only one generic parameter and that will make it easier to understand.

The purpose of the parametrized class (such as List<Date> or Map<K, V> as in the example) is to force a downcast and to have the compiler guarantee that this is safe (no runtime exceptions).

Consider the case of List. The essence of my question is why a method that takes a type T and a List won't accept a List of something further down the chain of inheritance than T. Consider this contrived example:

List<java.util.Date> dateList = new ArrayList<java.util.Date>();
Serializable s = new String();
addGeneric(s, dateList);

....
private <T> void addGeneric(T element, List<T> list) {
    list.add(element);
}

This will not compile, because the list parameter is a list of dates, not a list of strings. Generics would not be very useful if this did compile.

The same thing applies to a Map<String, Class<? extends Serializable>> It is not the same thing as a Map<String, Class<java.util.Date>>. They are not covariant, so if I wanted to take a value from the map containing date classes and put it into the map containing serializable elements, that is fine, but a method signature that says:

private <T> void genericAdd(T value, List<T> list)

Wants to be able to do both:

T x = list.get(0);

and

list.add(value);

In this case, even though the junit method doesn't actually care about these things, the method signature requires the covariance, which it is not getting, therefore it does not compile.

On the second question,

Matcher<? extends T>

Would have the downside of really accepting anything when T is an Object, which is not the APIs intent. The intent is to statically ensure that the matcher matches the actual object, and there is no way to exclude Object from that calculation.

The answer to the third question is that nothing would be lost, in terms of unchecked functionality (there would be no unsafe typecasting within the JUnit API if this method was not genericized), but they are trying to accomplish something else - statically ensure that the two parameters are likely to match.

EDIT (after further contemplation and experience):

One of the big issues with the assertThat method signature is attempts to equate a variable T with a generic parameter of T. That doesn't work, because they are not covariant. So for example you may have a T which is a List<String> but then pass a match that the compiler works out to Matcher<ArrayList<T>>. Now if it wasn't a type parameter, things would be fine, because List and ArrayList are covariant, but since Generics, as far as the compiler is concerned require ArrayList, it can't tolerate a List for reasons that I hope are clear from the above.

How to send email via Django?

You need to use smtp as backend in settings.py

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'

If you use backend as console, you will receive output in console

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

And also below settings in addition

EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = '[email protected]'
EMAIL_HOST_PASSWORD = 'password'

If you are using gmail for this, setup 2-step verification and Application specific password and copy and paste that password in above EMAIL_HOST_PASSWORD value.

Passing parameter via url to sql server reporting service

I had the same question and more, and though this thread is old, it is still a good one, so in summary for SSRS 2008R2 I found...

Situations

  1. You want to use a value from a URL to look up data
  2. You want to display a parameter from a URL in a report
  3. You want to pass a parameter from one report to another report

Actions

If applicable, be sure to replace Reports/Pages/Report.aspx?ItemPath= with ReportServer?. In other words: Instead of this:

http://server/Reports/Pages/Report.aspx?ItemPath=/ReportFolder/ReportSubfolder/ReportName

Use this syntax:

http://server/ReportServer?/ReportFolder/ReportSubfolder/ReportName

Add parameter(s) to the report and set as hidden (or visible if user action allowed, though keep in mind that while the report parameter will change, the URL will not change based on an updated entry).

Attach parameters to URL with &ParameterName=Value

Parameters can be referenced or displayed in report using @ParameterName, whether they're set in the report or in the URL

To hide the toolbar where parameters are displayed, add &rc:Toolbar=false to the URL (reference)

Putting that all together, you can run a URL with embedded values, or call this as an action from one report and read by another report:

http://server.domain.com/ReportServer?/ReportFolder1/ReportSubfolder1/ReportName&UserID=ABC123&rc:Toolbar=false

In report dataset properties query: SELECT stuff FROM view WHERE User = @UserID

In report, set expression value to [UserID] (or =Fields!UserID.Value)

Keep in mind that if a report has multiple parameters, you might need to include all parameters in the URL, even if blank, depending on how your dataset query is written.

To pass a parameter using Action = Go to URL, set expression to:

="http://server.domain.com/ReportServer?/ReportFolder1/ReportSubfolder1/ReportName&UserID="
 &Fields!UserID.Value 
 &"&rc:Toolbar=false"
 &"&rs:ClearSession=True"

Be sure to have a space after an expression if followed by & (a line break is isn't enough). No space is required before an expression. This method can pass a parameter but does not hide it as it is visible in the URL.

If you don't include &rs:ClearSession=True then the report won't refresh until browser session cache is cleared.

To pass a parameter using Action = Go to report:

  • Specify the report
  • Add parameter(s) to run the report
  • Add parameter(s) you wish to pass (the parameters need to be defined in the destination report, so to my knowledge you can't use URL-specific commands such as rc:toolbar using this method); however, I suppose it would be possible to read or set the Prompt User checkbox, as seen in reporting sever parameters, through custom code in the report.)

For reference, / = %2f

How can I display a tooltip message on hover using jQuery?

You can do it using just css without using any jQiuery.

<a class="tooltips">
    Hover Me
    <span>My Tooltip Text</span>
</a>
<style>
    a.tooltips {
        position: relative;
        display: inline;
    }

        a.tooltips span {
            position: absolute;
            width: 200px;
            color: #FFFFFF;
            background: #000000;
            height: 30px;
            line-height: 30px;
            text-align: center;
            visibility: hidden;
            border-radius: 6px;
        }

            a.tooltips span:after {
                content: '';
                position: absolute;
                top: 100%;
                left: 35%;
                margin-left: -8px;
                width: 0;
                height: 0;
                border-top: 8px solid #000000;
                border-right: 8px solid transparent;
                border-left: 8px solid transparent;
            }

    a:hover.tooltips span {
        visibility: visible;
        opacity: 0.8;
        bottom: 30px;
        left: 50%;
        margin-left: -76px;
        z-index: 999;
    }
</style>

How SQL query result insert in temp table?

In MySQL:

create table temp as select * from original_table

How can I test if a letter in a string is uppercase or lowercase using JavaScript?

Assuming that a string is only considered to not be all uppercase if at least one lowercase letter is present, this works fine. I understand it's not concise and succinct like everybody else tried to do, but does it works =)

function isUpperCase(str) {
    for (var i = 0, len = str.length; i < len; i++) {
        var letter = str.charAt(i);
        var keyCode = letter.charCodeAt(i);
        if (keyCode > 96 && keyCode < 123) {
            return false;
        }
    }

    return true;
}

Failed loading english.pickle with nltk.data.load

From bash command line, run:

$ python -c "import nltk; nltk.download('punkt')"

AsyncTask Android example

I'm sure it is executing properly, but you're trying to change the UI elements in the background thread and that won't do.

Revise your call and AsyncTask as follows:

Calling Class

Note: I personally suggest using onPostExecute() wherever you execute your AsyncTask thread and not in the class that extends AsyncTask itself. I think it makes the code easier to read especially if you need the AsyncTask in multiple places handling the results slightly different.

new LongThread() {
    @Override public void onPostExecute(String result) {
        TextView txt = (TextView) findViewById(R.id.output);
        txt.setText(result);
    }
}.execute("");

LongThread class (extends AsyncTask):

@Override
protected String doInBackground(String... params) {
    for (int i = 0; i < 5; i++) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    return "Executed";
}      

How can I read the client's machine/computer name from the browser?

You can do it with IE 'sometimes' as I have done this for an internal application on an intranet which is IE only. Try the following:

function GetComputerName() {
    try {
        var network = new ActiveXObject('WScript.Network');
        // Show a pop up if it works
        alert(network.computerName);
    }
    catch (e) { }
}

It may or may not require some specific security setting setup in IE as well to allow the browser to access the ActiveX object.

Here is a link to some more info on WScript: More Information

good postgresql client for windows?

Actually there is a freeware version of EMS's SQL Manager which is quite powerful

Android Studio doesn't see device

Try changing mode of usb connection to midi devices. Thats what worked for me.

Javascript one line If...else...else if statement

I know this is an old thread, but thought I'd put my two cents in. Ternary operators are able to be nested in the following fashion:

var variable = conditionA ? valueA : (conditionB ? valueB: (conditionC ? valueC : valueD));

Example:

var answer = value === 'foo' ? 1 :
    (value === 'bar' ? 2 : 
        (value === 'foobar' ? 3 : 0));

How can I open a Shell inside a Vim Window?

Shougo's VimShell, which can auto-complete file names if used with neocomplcache

How to completely uninstall Visual Studio 2010?

Download and install IOBIT uninstaller: http://www.iobit.com/advanceduninstaller.php, find the date in which you install Visual Studio and select all programas from that date r elated to VS. Then run de batch uninstaller. It is not a fully automated solution but it is a lot quicker than going one by one int he add / remove programs in Windows. It even has a power scan to clean the registry.

Update with two tables?

For Microsoft Access

UPDATE TableA A
    INNER JOIN TableB B
    ON A.ID = B.ID
SET A.Name = B.Name

Convert an enum to List<string>

Use Enum's static method, GetNames. It returns a string[], like so:

Enum.GetNames(typeof(DataSourceTypes))

If you want to create a method that does only this for only one type of enum, and also converts that array to a List, you can write something like this:

public List<string> GetDataSourceTypes()
{
    return Enum.GetNames(typeof(DataSourceTypes)).ToList();
}

You will need Using System.Linq; at the top of your class to use .ToList()

Best way to store chat messages in a database?

There's nothing wrong with saving the whole history in the database, they are prepared for that kind of tasks.

Actually you can find here in Stack Overflow a link to an example schema for a chat: example

If you are still worried for the size, you could apply some optimizations to group messages, like adding a buffer to your application that you only push after some time (like 1 minute or so); that way you would avoid having only 1 line messages

CodeIgniter: Load controller within controller

If you're interested, there's a well-established package out there that you can add to your Codeigniter project that will handle this:

https://bitbucket.org/wiredesignz/codeigniter-modular-extensions-hmvc/

Modular Extensions makes the CodeIgniter PHP framework modular. Modules are groups of independent components, typically model, controller and view, arranged in an application modules sub-directory, that can be dropped into other CodeIgniter applications.

OK, so the big change is that now you'd be using a modular structure - but to me this is desirable. I have used CI for about 3 years now, and can't imagine life without Modular Extensions.

Now, here's the part that deals with directly calling controllers for rendering view partials:

// Using a Module as a view partial from within a view is as easy as writing:
<?php echo modules::run('module/controller/method', $param1, $params2); ?>

That's all there is to it. I typically use this for loading little "widgets" like:

  • Event calendars
  • List of latest news articles
  • Newsletter signup forms
  • Polls

Typically I build a "widget" controller for each module and use it only for this purpose.

Your question was also one of my first questions when I started with Codeigniter. I hope this helps you out, even though it may be a bit more than you were looking for. I've been using MX ever since and haven't looked back.

Make sure to read the docs and check out the multitude of information regarding this package on the Codeigniter forums. Enjoy!

Getting error: Peer authentication failed for user "postgres", when trying to get pgsql working with rails

If you want to keep the default config but want md5 authentication with socket connection for one specific user/db connection, add a "local" line BEFORE the "local all/all" line:

# TYPE  DATABASE     USER         ADDRESS             METHOD

# "local" is for Unix domain socket connections only
local   dbname       username                         md5  # <-- this line
local   all          all                              peer
# IPv4 local connections:
host    all          all          127.0.0.1/32        ident
# IPv6 local connections:
host    all          all          ::1/128             ident

Trusting all certificates using HttpClient over HTTPS

There a many answers above but I wasn't able to get any of them working correctly (with my limited time), so for anyone else in the same situation you can try the code below which worked perfectly for my java testing purposes:

    public static HttpClient wrapClient(HttpClient base) {
    try {
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {
            public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException { }

            public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException { }

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        ctx.init(null, new TrustManager[]{tm}, null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx);
        ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        ClientConnectionManager ccm = base.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", ssf, 443));
        return new DefaultHttpClient(ccm, base.getParams());
    } catch (Exception ex) {
        return null;
    }
}

and call like:

DefaultHttpClient baseClient = new DefaultHttpClient();
HttpClient httpClient = wrapClient(baseClient );

Reference: http://tech.chitgoks.com/2011/04/24/how-to-avoid-javax-net-ssl-sslpeerunverifiedexception-peer-not-authenticated-problem-using-apache-httpclient/

Spark: Add column to dataframe conditionally

My bad, I had missed one part of the question.

Best, cleanest way is to use a UDF. Explanation within the code.

// create some example data...BY DataFrame
// note, third record has an empty string
case class Stuff(a:String,b:Int)
val d= sc.parallelize(Seq( ("a",1),("b",2),
     ("",3) ,("d",4)).map { x => Stuff(x._1,x._2)  }).toDF

// now the good stuff.
import org.apache.spark.sql.functions.udf
// function that returns 0 is string empty 
val func = udf( (s:String) => if(s.isEmpty) 0 else 1 )
// create new dataframe with added column named "notempty"
val r = d.select( $"a", $"b", func($"a").as("notempty") )

    scala> r.show
+---+---+--------+
|  a|  b|notempty|
+---+---+--------+
|  a|  1|    1111|
|  b|  2|    1111|
|   |  3|       0|
|  d|  4|    1111|
+---+---+--------+

Shrink a YouTube video to responsive width

With credits to previous answer https://stackoverflow.com/a/36549068/7149454

Boostrap compatible, adust your container width (300px in this example) and you're good to go:

<div class="embed-responsive embed-responsive-16by9" style="height: 100 %; width: 300px; ">
<iframe class="embed-responsive-item" src="https://www.youtube.com/embed/LbLB0K-mXMU?start=1841" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" frameborder="0"></iframe>
</div>

Hyper-V: Create shared folder between host and guest with internal network

Share Files, Folders or Drives Between Host and Hyper-V Virtual Machine

Prerequisites

  1. Ensure that Enhanced session mode settings are enabled on the Hyper-V host.

    Start Hyper-V Manager, and in the Actions section, select "Hyper-V Settings".

    hyper-v-settings

    Make sure that enhanced session mode is allowed in the Server section. Then, make sure that the enhanced session mode is available in the User section.

    use-enhanced-session-mode

  2. Enable Hyper-V Guest Services for your virtual machine

    Right-click on Virtual Machine > Settings. Select the Integration Services in the left-lower corner of the menu. Check Guest Service and click OK.

    enable-guest-services

Steps to share devices with Hyper-v virtual machine:

  1. Start a virtual machine and click Show Options in the pop-up windows.

    connect-to-vm

    Or click "Edit Session Settings..." in the Actions panel on the right

    edit-session-sessions

    It may only appear when you're (able to get) connected to it. If it doesn't appear try Starting and then Connecting to the VM while paying close attention to the panel in the Hyper-V Manager.

  2. View local resources. Then, select the "More..." menu.

    click-more

  3. From there, you can choose which devices to share. Removable drives are especially useful for file sharing.

    choose-the-devices-that-you-want-to-use

  4. Choose to "Save my settings for future connections to this virtual machine".

    save-my-settings-for-future-connections-to-this-vm

  5. Click Connect. Drive sharing is now complete, and you will see the shared drive in this PC > Network Locations section of Windows Explorer after using the enhanced session mode to sigh to the VM. You should now be able to copy files from a physical machine and paste them into a virtual machine, and vice versa.

    shared-drives-from-local-pc

Source (and for more info): Share Files, Folders or Drives Between Host and Hyper-V Virtual Machine

Android Studio - How to Change Android SDK Path

When I ran into trouble with this on Android Studio 3.1.4 the solution was to go into the app dropdown on my project, then Edit Configurations > Defaults > JAR Application where there is a JRE box on the initial Configuration tab. Setting that to my JRE path solved the problem for me.

How to set the LDFLAGS in CMakeLists.txt?

For linking against libraries see Andre's answer.

For linker flags - the following 4 CMake variables:

CMAKE_EXE_LINKER_FLAGS
CMAKE_MODULE_LINKER_FLAGS
CMAKE_SHARED_LINKER_FLAGS
CMAKE_STATIC_LINKER_FLAGS

can be easily manipulated for different configs (debug, release...) with the ucm_add_linker_flags macro of ucm

In android how to set navigation drawer header image and name programmatically in class file?

don't add header in xml add using code by inflating layout

View hView =  navigationView.inflateHeaderView(R.layout.nav_header_main);
ImageView imgvw = (ImageView)hView.findViewById(R.id.imageView);
TextView tv = (TextView)hView.findViewById(R.id.textview);
imgvw .setImageResource();
tv.settext("new text");

Detecting an "invalid date" Date instance in JavaScript

For Angular.js projects you can use:

angular.isDate(myDate);

Import Script from a Parent Directory

From the docs:

from .. import scriptA

You can do this in packages, but not in scripts you run directly. From the link above:

Note that both explicit and implicit relative imports are based on the name of the current module. Since the name of the main module is always "__main__", modules intended for use as the main module of a Python application should always use absolute imports.

If you create a script that imports A.B.B, you won't receive the ValueError.

What is it exactly a BLOB in a DBMS context

This may seem like a silly question, but what do you actually want to use a RDBMS for ?

If you just want to store files, then the operating system's filesystem is generally adequate. An RDBMS is generally used for structured data and (except for embedded ones like SQLite) handling concurrent manipulation of that data (locking etc). Other useful features are security (handling access to the data) and backup/recovery. In the latter, the primary advantage over a regular filesystem backup is being able to recover to a point in time between backups by applying some form of log files.

BLOBs are, as far as the database concerned, unstructured and opaque. Oracle does have some specific ORDSYS types for multi-media objects (eg images) that also have a bunch of metadata attached, and have associated methods (eg rescaling or recolouring an image).

Determine Whether Integer Is Between Two Other Integers?

Suppose there are 3 non-negative integers: a, b, and c. Mathematically speaking, if we want to determine if c is between a and b, inclusively, one can use this formula:

(c - a) * (b - c) >= 0

or in Python:

> print((c - a) * (b - c) >= 0)
True

How to get the full url in Express?

I would suggest using originalUrl instead of URL:

var url = req.protocol + '://' + req.get('host') + req.originalUrl;

See the description of originalUrl here: http://expressjs.com/api.html#req.originalUrl

In our system, we do something like this, so originalUrl is important to us:

  foo = express();
  express().use('/foo', foo);
  foo.use(require('/foo/blah_controller'));

blah_controller looks like this:

  controller = express();
  module.exports = controller;
  controller.get('/bar/:barparam', function(req, res) { /* handler code */ });

So our URLs have the format:

www.example.com/foo/bar/:barparam

Hence, we need req.originalUrl in the bar controller get handler.

Handling NULL values in Hive

Try to include length > 0 as well.

column1 is not NULL AND column1 <> '' AND length(column1) > 0 

Email address validation in C# MVC 4 application: with or without using Regex

Expanding on Ehsan's Answer....

If you are using .Net framework 4.5 then you can have a simple method to verify email address using EmailAddressAttribute Class in code.

private static bool IsValidEmailAddress(string emailAddress)
{
    return new System.ComponentModel.DataAnnotations
                        .EmailAddressAttribute()
                        .IsValid(emailAddress);
}

If you are considering REGEX to verify email address then read:

I Knew How To Validate An Email Address Until I Read The RFC By Phil Haack

When to use virtual destructors?

What is a virtual destructor or how to use virtual destructor

A class destructor is a function with same name of the class preceding with ~ that will reallocate the memory that is allocated by the class. Why we need a virtual destructor

See the following sample with some virtual functions

The sample also tell how you can convert a letter to upper or lower

#include "stdafx.h"
#include<iostream>
using namespace std;
// program to convert the lower to upper orlower
class convertch
{
public:
  //void convertch(){};
  virtual char* convertChar() = 0;
  ~convertch(){};
};

class MakeLower :public convertch
{
public:
  MakeLower(char *passLetter)
  {
    tolower = true;
    Letter = new char[30];
    strcpy(Letter, passLetter);
  }

  virtual ~MakeLower()
  {
    cout<< "called ~MakeLower()"<<"\n";
    delete[] Letter;
  }

  char* convertChar()
  {
    size_t len = strlen(Letter);
    for(int i= 0;i<len;i++)
      Letter[i] = Letter[i] + 32;
    return Letter;
  }

private:
  char *Letter;
  bool tolower;
};

class MakeUpper : public convertch
{
public:
  MakeUpper(char *passLetter)
  {
    Letter = new char[30];
    toupper = true;
    strcpy(Letter, passLetter);
  }

  char* convertChar()
  {   
    size_t len = strlen(Letter);
    for(int i= 0;i<len;i++)
      Letter[i] = Letter[i] - 32;
    return Letter;
  }

  virtual ~MakeUpper()
  {
    cout<< "called ~MakeUpper()"<<"\n";
    delete Letter;
  }

private:
  char *Letter;
  bool toupper;
};


int _tmain(int argc, _TCHAR* argv[])
{
  convertch *makeupper = new MakeUpper("hai"); 
  cout<< "Eneterd : hai = " <<makeupper->convertChar()<<" ";     
  delete makeupper;
  convertch *makelower = new MakeLower("HAI");;
  cout<<"Eneterd : HAI = " <<makelower->convertChar()<<" "; 
  delete makelower;
  return 0;
}

From the above sample you can see that the destructor for both MakeUpper and MakeLower class is not called.

See the next sample with the virtual destructor

#include "stdafx.h"
#include<iostream>

using namespace std;
// program to convert the lower to upper orlower
class convertch
{
public:
//void convertch(){};
virtual char* convertChar() = 0;
virtual ~convertch(){}; // defined the virtual destructor

};
class MakeLower :public convertch
{
public:
MakeLower(char *passLetter)
{
tolower = true;
Letter = new char[30];
strcpy(Letter, passLetter);
}
virtual ~MakeLower()
{
cout<< "called ~MakeLower()"<<"\n";
      delete[] Letter;
}
char* convertChar()
{
size_t len = strlen(Letter);
for(int i= 0;i<len;i++)
{
Letter[i] = Letter[i] + 32;

}

return Letter;
}

private:
char *Letter;
bool tolower;

};
class MakeUpper : public convertch
{
public:
MakeUpper(char *passLetter)
{
Letter = new char[30];
toupper = true;
strcpy(Letter, passLetter);
}
char* convertChar()
{

size_t len = strlen(Letter);
for(int i= 0;i<len;i++)
{
Letter[i] = Letter[i] - 32;
}
return Letter;
}
virtual ~MakeUpper()
{
      cout<< "called ~MakeUpper()"<<"\n";
delete Letter;
}
private:
char *Letter;
bool toupper;
};


int _tmain(int argc, _TCHAR* argv[])
{

convertch *makeupper = new MakeUpper("hai");

cout<< "Eneterd : hai = " <<makeupper->convertChar()<<" \n";

delete makeupper;
convertch *makelower = new MakeLower("HAI");;
cout<<"Eneterd : HAI = " <<makelower->convertChar()<<"\n ";


delete makelower;
return 0;
}

The virtual destructor will call explicitly the most derived run time destructor of class so that it will be able to clear the object in a proper way.

Or visit the link

https://web.archive.org/web/20130822173509/http://www.programminggallery.com/article_details.php?article_id=138

CSS Printing: Avoiding cut-in-half DIVs between pages?

In my case I managed to fix the page break difficulties in webkit by setting my selected divs to page-break-inside:avoid, and also setting all elements to display:inline. So like this:

@media print{
* {
    display:inline;
}
script, style { 
    display:none; 
}
div {
    page-break-inside:avoid;
}

}

It seems like page-break-properties can only be applied to inline elements (in webkit). I tried to only apply display:inline to the particular elements I needed, but this didn't work. The only thing that worked was applying inline to all elements. I guess it's one of the large container div' that's messing things up.

Maybe someone could expand on this.

How do you right-justify text in an HTML textbox?

Using inline styles:

<input type="text" style="text-align: right"/>

or, put it in a style sheet, like so:

<style>
   .rightJustified {
        text-align: right;
    }
</style>

and reference the class:

<input type="text" class="rightJustified"/>

How to get a value from a Pandas DataFrame and not the index and object type

Use the values attribute to return the values as a np array and then use [0] to get the first value:

In [4]:
df.loc[df.Letters=='C','Letters'].values[0]

Out[4]:
'C'

EDIT

I personally prefer to access the columns using subscript operators:

df.loc[df['Letters'] == 'C', 'Letters'].values[0]

This avoids issues where the column names can have spaces or dashes - which mean that accessing using ..

apc vs eaccelerator vs xcache

APC segfaults all day and all night, got no experience with eAccelerator but XCache is very reliable with loads of options and constant development.

Entity Framework 5 Updating a Record

I really like the accepted answer. I believe there is yet another way to approach this as well. Let's say you have a very short list of properties that you wouldn't want to ever include in a View, so when updating the entity, those would be omitted. Let's say that those two fields are Password and SSN.

db.Users.Attach(updatedUser);

var entry = db.Entry(updatedUser);
entry.State = EntityState.Modified;

entry.Property(e => e.Password).IsModified = false;
entry.Property(e => e.SSN).IsModified = false;   

db.SaveChanges();   

This example allows you to essentially leave your business logic alone after adding a new field to your Users table and to your View.

Using client certificate in Curl command

TLS client certificates are not sent in HTTP headers. They are transmitted by the client as part of the TLS handshake, and the server will typically check the validity of the certificate during the handshake as well.

If the certificate is accepted, most web servers can be configured to add headers for transmitting the certificate or information contained on the certificate to the application. Environment variables are populated with certificate information in Apache and Nginx which can be used in other directives for setting headers.

As an example of this approach, the following Nginx config snippet will validate a client certificate, and then set the SSL_CLIENT_CERT header to pass the entire certificate to the application. This will only be set when then certificate was successfully validated, so the application can then parse the certificate and rely on the information it bears.

server {
    listen 443 ssl;
    server_name example.com;
    ssl_certificate /path/to/chainedcert.pem;  # server certificate
    ssl_certificate_key /path/to/key;          # server key

    ssl_client_certificate /path/to/ca.pem;    # client CA
    ssl_verify_client on;
    proxy_set_header SSL_CLIENT_CERT $ssl_client_cert;

    location / {
        proxy_pass http://localhost:3000;
    }
}

How to get all properties values of a JavaScript Object (without knowing the keys)?

use a polyfill like:

if(!Object.values){Object.values=obj=>Object.keys(obj).map(key=>obj[key])}

then use

Object.values(my_object)

3) profit!

Most Useful Attributes

I have been using the [DataObjectMethod] lately. It describes the method so you can use your class with the ObjectDataSource ( or other controls).

[DataObjectMethod(DataObjectMethodType.Select)] 
[DataObjectMethod(DataObjectMethodType.Delete)] 
[DataObjectMethod(DataObjectMethodType.Update)] 
[DataObjectMethod(DataObjectMethodType.Insert)] 

More info

Ctrl+click doesn't work in Eclipse Juno

I faced this issue several times. As described by Ashutosh Jindal, if the Hyperlinking is already enabled and still the ctrl+click doesn't work then you need to:

  1. Navigate to Java -> Editor -> Mark Occurrences in Preferences
  2. Uncheck "Mark occurrences of the selected element in the current file" if its already checked.
  3. Now, check on the above mentioned option and then check on all the items under it. Click Apply.

This should now enabled the ctrl+click functionality.

jQuery prevent change for select

You might need to use the ".live" option in jQuery since the behavior will be evaluated in real-time based on the condition you've set.

$('#my_select').live('change', function(ev) {
  if(my_condition)
  {
    ev.preventDefault();
    return false;
  }
});

Cannot connect to local SQL Server with Management Studio

I was having this problem on a Windows 7 (64 bit) after a power outage. The SQLEXPRESS service was not started even though is status was set to 'Automatic' and the mahine had been rebooted several times. Had to start the service manually.

How to increase application heap size in Eclipse?

In the run configuration you want to customize (just click on it) open the tab Arguments and add -Xmx2048min the VM arguments section. You might want to set the -Xms as well (small heap size).

How to enable Logger.debug() in Log4j

This is happening due to the fact that the logging level of your logger is set to 'error' - therefore you will only see error messages or above this level in terms of severity so this is why you also see the 'fatal' message.

If you set the logging level to 'debug' on your logger in your log4j.xml you should see all messages.

Have a look at the log4j introduction for explaination.

C++ Get name of type in template

typeid(uint8_t).name() is nice, but it returns "unsigned char" while you may expect "uint8_t".

This piece of code will return you the appropriate type

#define DECLARE_SET_FORMAT_FOR(type) \
    if ( typeid(type) == typeid(T) ) \
        formatStr = #type;

template<typename T>
static std::string GetFormatName()
{
    std::string formatStr;

    DECLARE_SET_FORMAT_FOR( uint8_t ) 
    DECLARE_SET_FORMAT_FOR( int8_t ) 

    DECLARE_SET_FORMAT_FOR( uint16_t )
    DECLARE_SET_FORMAT_FOR( int16_t )

    DECLARE_SET_FORMAT_FOR( uint32_t )
    DECLARE_SET_FORMAT_FOR( int32_t )

    DECLARE_SET_FORMAT_FOR( float )

    // .. to be exptended with other standard types you want to be displayed smartly

    if ( formatStr.empty() )
    {
        assert( false );
        formatStr = typeid(T).name();
    }

    return formatStr;
}

Automatically pass $event with ng-click?

Add a $event to the ng-click, for example:

<button type="button" ng-click="saveOffer($event)" accesskey="S"></button>

Then the jQuery.Event was passed to the callback:

enter image description here

how to use javascript Object.defineProperty

get is a function that is called when you try to read the value player.health, like in:

console.log(player.health);

It's effectively not much different than:

player.getHealth = function(){
  return 10 + this.level*15;
}
console.log(player.getHealth());

The opposite of get is set, which would be used when you assign to the value. Since there is no setter, it seems that assigning to the player's health is not intended:

player.health = 5; // Doesn't do anything, since there is no set function defined

A very simple example:

_x000D_
_x000D_
var player = {_x000D_
  level: 5_x000D_
};_x000D_
_x000D_
Object.defineProperty(player, "health", {_x000D_
  get: function() {_x000D_
    return 10 + (player.level * 15);_x000D_
  }_x000D_
});_x000D_
_x000D_
console.log(player.health); // 85_x000D_
player.level++;_x000D_
console.log(player.health); // 100_x000D_
_x000D_
player.health = 5; // Does nothing_x000D_
console.log(player.health); // 100
_x000D_
_x000D_
_x000D_

Limit text length to n lines using CSS

Basic Example Code, learning to code is easy. Check Style CSS comments.

_x000D_
_x000D_
table tr {_x000D_
  display: flex;_x000D_
}_x000D_
table tr td {_x000D_
  /* start */_x000D_
  display: inline-block; /* <- Prevent <tr> in a display css */_x000D_
  text-overflow: ellipsis;_x000D_
  white-space: nowrap;_x000D_
  /* end */_x000D_
  padding: 10px;_x000D_
  width: 150px; /* Space size limit */_x000D_
  border: 1px solid black;_x000D_
  overflow: hidden;_x000D_
}
_x000D_
<table>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td>_x000D_
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla egestas erat ut luctus posuere. Praesent et commodo eros. Vestibulum eu nisl vel dui ultrices ultricies vel in tellus._x000D_
      </td>_x000D_
      <td>_x000D_
        Praesent vitae tempus nulla. Donec vel porta velit. Fusce mattis enim ex. Mauris eu malesuada ante. Aenean id aliquet leo, nec ultricies tortor. Curabitur non mollis elit. Morbi euismod ante sit amet iaculis pharetra. Mauris id ultricies urna. Cras ut_x000D_
        nisi dolor. Curabitur tellus erat, condimentum ac enim non, varius tempor nisi. Donec dapibus justo odio, sed consequat eros feugiat feugiat._x000D_
      </td>_x000D_
      <td>_x000D_
        Pellentesque mattis consequat ipsum sed sagittis. Pellentesque consectetur vestibulum odio, aliquet auctor ex elementum sed. Suspendisse porta massa nisl, quis molestie libero auctor varius. Ut erat nibh, fringilla sed ligula ut, iaculis interdum sapien._x000D_
        Ut dictum massa mi, sit amet interdum mi bibendum nec._x000D_
      </td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>_x000D_
        Sed viverra massa laoreet urna dictum, et fringilla dui molestie. Duis porta, ligula ut venenatis pretium, sapien tellus blandit felis, non lobortis orci erat sed justo. Vivamus hendrerit, quam at iaculis vehicula, nibh nisi fermentum augue, at sagittis_x000D_
        nibh dui et erat._x000D_
      </td>_x000D_
      <td>_x000D_
        Nullam mollis nulla justo, nec tincidunt urna suscipit non. Donec malesuada dolor non dolor interdum, id ultrices neque egestas. Integer ac ante sed magna gravida dapibus sit amet eu diam. Etiam dignissim est sit amet libero dapibus, in consequat est_x000D_
        aliquet._x000D_
      </td>_x000D_
      <td>_x000D_
        Vestibulum mollis, dui eu eleifend tincidunt, erat eros tempor nibh, non finibus quam ante nec felis. Fusce egestas, orci in volutpat imperdiet, risus velit convallis sapien, sodales lobortis risus lectus id leo. Nunc vel diam vel nunc congue finibus._x000D_
        Vestibulum turpis tortor, pharetra sed ipsum eu, tincidunt imperdiet lorem. Donec rutrum purus at tincidunt sagittis. Quisque nec hendrerit justo._x000D_
      </td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How to remove/ignore :hover css style on touch devices

Try this (i use background and background-color in this example):

var ClickEventType = ((document.ontouchstart !== null) ? 'click' : 'touchstart');

if (ClickEventType == 'touchstart') {
            $('a').each(function() { // save original..
                var back_color = $(this).css('background-color');
                var background = $(this).css('background');
                $(this).attr('data-back_color', back_color);
                $(this).attr('data-background', background);
            });

            $('a').on('touchend', function(e) { // overwrite with original style..
                var background = $(this).attr('data-background');
                var back_color = $(this).attr('data-back_color');
                if (back_color != undefined) {
                    $(this).css({'background-color': back_color});
                }
                if (background != undefined) {
                    $(this).css({'background': background});
                }
            }).on('touchstart', function(e) { // clear added stlye="" elements..
                $(this).css({'background': '', 'background-color': ''});
            });
}

css:

a {
    -webkit-touch-callout: none;
    -webkit-tap-highlight-color: transparent;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

window.onbeforeunload and window.onunload is not working in Firefox, Safari, Opera?

Here is the working solution for ie, firefox and chrome:

var myEvent = window.attachEvent || window.addEventListener;
var chkevent = window.attachEvent ? 'onbeforeunload' : 'beforeunload'; /// make IE7, IE8 compitable

            myEvent(chkevent, function(e) { // For >=IE7, Chrome, Firefox
                var confirmationMessage = 'Are you sure to leave the page?';  // a space
                (e || window.event).returnValue = confirmationMessage;
                return confirmationMessage;
            });

How do I turn off Oracle password expiration?

For development you can disable password policy if no other profile was set (i.e. disable password expiration in default one):

ALTER PROFILE "DEFAULT" LIMIT PASSWORD_VERIFY_FUNCTION NULL;

Then, reset password and unlock user account. It should never expire again:

alter user user_name identified by new_password account unlock;

What is the difference between class and instance methods?

Take for example a game where lots of cars are spawned.. each belongs to the class CCar. When a car is instantiated, it makes a call to

[CCar registerCar:self]

So the CCar class, can make a list of every CCar instantiated. Let's say the user finishes a level, and wants to remove all cars... you could either: 1- Go through a list of every CCar you created manually, and do whicheverCar.remove(); or 2- Add a removeAllCars method to CCar, which will do that for you when you call [CCar removeAllCars]. I.e. allCars[n].remove();

Or for example, you allow the user to specify a default font size for the whole app, which is loaded and saved at startup. Without the class method, you might have to do something like

fontSize = thisMenu.getParent().fontHandler.getDefaultFontSize();

With the class method, you could get away with [FontHandler getDefaultFontSize].

As for your removeVowels function, you'll find that languages like C# actually have both with certain methods such as toLower or toUpper.

e.g. myString.removeVowels() and String.removeVowels(myString) (in ObjC that would be [String removeVowels:myString]).

In this case the instance likely calls the class method, so both are available. i.e.

public function toLower():String{
  return String.toLower();
}

public static function toLower( String inString):String{
 //do stuff to string..
 return newString;
}

basically, myString.toLower() calls [String toLower:ownValue]

There's no definitive answer, but if you feel like shoving a class method in would improve your code, give it a shot, and bear in mind that a class method will only let you use other class methods/variables.

Constructor overloading in Java - best practice

While there are no "official guidelines" I follow the principle of KISS and DRY. Make the overloaded constructors as simple as possible, and the simplest way is that they only call this(...). That way you only need to check and handle the parameters once and only once.

public class Simple {

    public Simple() {
        this(null);
    }

    public Simple(Resource r) {
        this(r, null);
    }

    public Simple(Resource r1, Resource r2) {
        // Guard statements, initialize resources or throw exceptions if
        // the resources are wrong
        if (r1 == null) {
            r1 = new Resource();
        }
        if (r2 == null) {
            r2 = new Resource();
        }

        // do whatever with resources
    }

}

From a unit testing standpoint, it'll become easy to test the class since you can put in the resources into it. If the class has many resources (or collaborators as some OO-geeks call it), consider one of these two things:

Make a parameter class

public class SimpleParams {
    Resource r1;
    Resource r2;
    // Imagine there are setters and getters here but I'm too lazy 
    // to write it out. you can make it the parameter class 
    // "immutable" if you don't have setters and only set the 
    // resources through the SimpleParams constructor
}

The constructor in Simple only either needs to split the SimpleParams parameter:

public Simple(SimpleParams params) {
    this(params.getR1(), params.getR2());
}

…or make SimpleParams an attribute:

public Simple(Resource r1, Resource r2) {
    this(new SimpleParams(r1, r2));
}

public Simple(SimpleParams params) {
    this.params = params;
}

Make a factory class

Make a factory class that initializes the resources for you, which is favorable if initializing the resources is a bit difficult:

public interface ResourceFactory {
    public Resource createR1();
    public Resource createR2();
}

The constructor is then done in the same manner as with the parameter class:

public Simple(ResourceFactory factory) {
    this(factory.createR1(), factory.createR2());
} 

Make a combination of both

Yeah... you can mix and match both ways depending on what is easier for you at the time. Parameter classes and simple factory classes are pretty much the same thing considering the Simple class that they're used the same way.

Access to the path 'c:\inetpub\wwwroot\myapp\App_Data' is denied

For me i had already created a folder with name excel in wwroot D:\working directory\OnlineExam\wwwroot\excel And i was trying to copy a file with name excel which was already existing as a folder name. the path which was required was D:\working directory\OnlineExam\wwwroot\excel\finance.csv so according i changed the code as below

string copyPath = Path.Combine(_webHostEnvironment.WebRootPath, "excel\\finance");
                    questionExcelUpload.Upload.CopyTo(new FileStream(copyPath, FileMode.Create));

Basically check if a folder or a file with same name as your path exist already.

Postgresql - select something where date = "01/01/11"

I think you want to cast your dt to a date and fix the format of your date literal:

SELECT *
FROM table
WHERE dt::date = '2011-01-01' -- This should be ISO-8601 format, YYYY-MM-DD

Or the standard version:

SELECT *
FROM table
WHERE CAST(dt AS DATE) = '2011-01-01' -- This should be ISO-8601 format, YYYY-MM-DD

The extract function doesn't understand "date" and it returns a number.

Open new Terminal Tab from command line (Mac OS X)

I added these to my .bash_profile so I can have access to tabname and newtab

tabname() {
  printf "\e]1;$1\a"
}

new_tab() {
  TAB_NAME=$1
  COMMAND=$2
  osascript \
    -e "tell application \"Terminal\"" \
    -e "tell application \"System Events\" to keystroke \"t\" using {command down}" \
    -e "do script \"printf '\\\e]1;$TAB_NAME\\\a'; $COMMAND\" in front window" \
    -e "end tell" > /dev/null
}

So when you're on a particular tab you can just type

tabname "New TabName"

to organize all the open tabs you have. It's much better than getting info on the tab and changing it there.

How to generate a simple popup using jQuery

ONLY CSS POPUP LOGIC! TRY DO IT . EASY! I think this mybe be hack popular in future

            <a href="#openModal">OPEN</a>

            <div id="openModal" class="modalDialog">
                <div>
                    <a href="#close"  class="close">X</a>
                    <h2>MODAL</h2>

                </div>
            </div>


.modalDialog {
    position: fixed;
    font-family: Arial, Helvetica, sans-serif;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background: rgba(0,0,0,0.8);
    z-index: 99999;
    -webkit-transition: opacity 400ms ease-in;
    -moz-transition: opacity 400ms ease-in;
    transition: opacity 400ms ease-in;
    display: none;
    pointer-events: none;
}

.modalDialog:target {
    display: block;
    pointer-events: auto;
}

.modalDialog > div {
    width: 400px;
    position: relative;
    margin: 10% auto;
    padding: 5px 20px 13px 20px;
    border-radius: 10px;
    background: #fff;
    background: -moz-linear-gradient(#fff, #999);
    background: -webkit-linear-gradient(#fff, #999);
    background: -o-linear-gradient(#fff, #999);
}

How to specify new GCC path for CMake

Do not overwrite CMAKE_C_COMPILER, but export CC (and CXX) before calling cmake:

export CC=/usr/local/bin/gcc
export CXX=/usr/local/bin/g++
cmake /path/to/your/project
make

The export only needs to be done once, the first time you configure the project, then those values will be read from the CMake cache.


UPDATE: longer explanation on why not overriding CMAKE_C(XX)_COMPILER after Jake's comment

I recommend against overriding the CMAKE_C(XX)_COMPILER value for two main reasons: because it won't play well with CMake's cache and because it breaks compiler checks and tooling detection.

When using the set command, you have three options:

  • without cache, to create a normal variable
  • with cache, to create a cached variable
  • force cache, to always force the cache value when configuring

Let's see what happens for the three possible calls to set:

Without cache

set(CMAKE_C_COMPILER /usr/bin/clang)
set(CMAKE_CXX_COMPILER /usr/bin/clang++)

When doing this, you create a "normal" variable CMAKE_C(XX)_COMPILER that hides the cache variable of the same name. That means your compiler is now hard-coded in your build script and you cannot give it a custom value. This will be a problem if you have multiple build environments with different compilers. You could just update your script each time you want to use a different compiler, but that removes the value of using CMake in the first place.

Ok, then, let's update the cache...

With cache

set(CMAKE_C_COMPILER /usr/bin/clang CACHE PATH "")
set(CMAKE_CXX_COMPILER /usr/bin/clang++ CACHE PATH "")

This version will just "not work". The CMAKE_C(XX)_COMPILER variable is already in the cache, so it won't get updated unless you force it.

Ah... let's use the force, then...

Force cache

set(CMAKE_C_COMPILER /usr/bin/clang CACHE PATH "" FORCE)
set(CMAKE_CXX_COMPILER /usr/bin/clang++ CACHE PATH "" FORCE)

This is almost the same as the "normal" variable version, the only difference is your value will be set in the cache, so users can see it. But any change will be overwritten by the set command.

Breaking compiler checks and tooling

Early in the configuration process, CMake performs checks on the compiler: Does it work? Is it able to produce executables? etc. It also uses the compiler to detect related tools, like ar and ranlib. When you override the compiler value in a script, it's "too late", all checks and detections are already done.

For instance, on my machine with gcc as default compiler, when using the set command to /usr/bin/clang, ar is set to /usr/bin/gcc-ar-7. When using an export before running CMake it is set to /usr/lib/llvm-3.8/bin/llvm-ar.

Write variable to file, including name

You can use pickle

import pickle
dict = {'one': 1, 'two': 2}
file = open('dump.txt', 'wb')
pickle.dump(dict, file)
file.close()

and to read it again

file = open('dump.txt', 'rb')
dict = pickle.load(file)

EDIT: Guess I misread your question, sorry ... but pickle might help all the same. :)

Curl error 60, SSL certificate issue: self signed certificate in certificate chain

Important: This issue drove me crazy for a couple days and I couldn't figure out what was going on with my curl & openssl installations. I finally figured out that it was my intermediate certificate (in my case, GoDaddy) which was out of date. I went back to my godaddy SSL admin panel, downloaded the new intermediate certificate, and the issue disappeared.

I'm sure this is the issue for some of you.

Apparently, GoDaddy had changed their intermediate certificate at some point, due to scurity issues, as they now display this warning:

"Please be sure to use the new SHA-2 intermediate certificates included in your downloaded bundle."

Hope this helps some of you, because I was going nuts and this cleaned up the issue on ALL my servers.

NullPointerException in eclipse in Eclipse itself at PartServiceImpl.internalFixContext

After exiting eclipse I moved .eclipse (found in the user's home directory) to .eclipse.old (just in case I may have had to undo). The error does not show up any more and my projects are working fine after restarting eclipse.

Caution: I have a simple setup and this may not be the best for environments with advanced settings.

I am posting this as a separate answer as previously listed methods did not work for me.

Can I read the hash portion of the URL on my server-side application (PHP, Ruby, Python, etc.)?

I think the hash-value is only used client-side, so you can't get it with php.

you could redirect it with javascript to php though.

MAC addresses in JavaScript

The quick and simple answer is No.

Javascript is quite a high level language and does not have access to this sort of information.

Excel VBA - Delete empty rows

How about

sub foo()
  dim r As Range, rows As Long, i As Long
  Set r = ActiveSheet.Range("A1:Z50")
  rows = r.rows.Count
  For i = rows To 1 Step (-1)
    If WorksheetFunction.CountA(r.rows(i)) = 0 Then r.rows(i).Delete
  Next
End Sub

Try this

Option Explicit

Sub Sample()
    Dim i As Long
    Dim DelRange As Range

    On Error GoTo Whoa

    Application.ScreenUpdating = False

    For i = 1 To 50
        If Application.WorksheetFunction.CountA(Range("A" & i & ":" & "Z" & i)) = 0 Then
            If DelRange Is Nothing Then
                Set DelRange = Range("A" & i & ":" & "Z" & i)
            Else
                Set DelRange = Union(DelRange, Range("A" & i & ":" & "Z" & i))
            End If
        End If
    Next i

    If Not DelRange Is Nothing Then DelRange.Delete shift:=xlUp
LetsContinue:
    Application.ScreenUpdating = True

    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume LetsContinue
End Sub

IF you want to delete the entire row then use this code

Option Explicit

Sub Sample()
    Dim i As Long
    Dim DelRange As Range

    On Error GoTo Whoa

    Application.ScreenUpdating = False

    For i = 1 To 50
        If Application.WorksheetFunction.CountA(Range("A" & i & ":" & "Z" & i)) = 0 Then
            If DelRange Is Nothing Then
                Set DelRange = Rows(i)
            Else
                Set DelRange = Union(DelRange, Rows(i))
            End If
        End If
    Next i

    If Not DelRange Is Nothing Then DelRange.Delete shift:=xlUp
LetsContinue:
    Application.ScreenUpdating = True

    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume LetsContinue
End Sub

SQL Server Configuration Manager not found

On windows 10 Control Panel?Administrative Tools?Computer Management

Win 10 SQL configuration manager

Deleting all files from a folder using PHP?

public static function recursiveDelete($dir)
{
    foreach (new \DirectoryIterator($dir) as $fileInfo) {
        if (!$fileInfo->isDot()) {
            if ($fileInfo->isDir()) {
                recursiveDelete($fileInfo->getPathname());
            } else {
                unlink($fileInfo->getPathname());
            }
        }
    }
    rmdir($dir);
}

Go Back to Previous Page

We can show a back button using html code in our pages which can take the browser window to the previous page. This page will have a button or a link and by clicking it browser will return to previous page. This can be done by using html or by using JavaScript in the client side.

Here is the code of this button

<INPUT TYPE="button" VALUE="Back" onClick="history.go(-1);">

Using JavaScript

We can use JavaScript to create a link to take us back to previous or history page. Here is the code to move back the browser using client side JavaScript.

<a href = "javascript:history.back()">Back to previous page</a>

What causes a SIGSEGV

SigSegV means a signal for memory access violation, trying to read or write from/to a memory area that your process does not have access to. These are not C or C++ exceptions and you can’t catch signals. It’s possible indeed to write a signal handler that ignores the problem and allows continued execution of your unstable program in undefined state, but it should be obvious that this is a very bad idea.

Most of the time this is because of a bug in the program. The memory address given can help debug what’s the problem (if it’s close to zero then it’s likely a null pointer dereference, if the address is something like 0xadcedfe then it’s intentional safeguard or a debug check, etc.)

One way of “catching” the signal is to run your stuff in a separate child process that can then abruptly terminate without taking your main process down with it. Finding the root cause and fixing it is obviously preferred over workarounds like this.

How to implement __iter__(self) for a container object (Python)

usually __iter__() just return self if you have already define the next() method (generator object):

here is a Dummy example of a generator :

class Test(object):

    def __init__(self, data):
       self.data = data

    def next(self):
        if not self.data:
           raise StopIteration
        return self.data.pop()

    def __iter__(self):
        return self

but __iter__() can also be used like this: http://mail.python.org/pipermail/tutor/2006-January/044455.html

Showing the same file in both columns of a Sublime Text window

Here is a simple plugin to "open / close a splitter" into the current file, as found in other editors:

import sublime_plugin

class SplitPaneCommand(sublime_plugin.WindowCommand):
    def run(self):
        w = self.window
        if w.num_groups() == 1:
            w.run_command('set_layout', {
                'cols': [0.0, 1.0],
                'rows': [0.0, 0.33, 1.0],
                'cells': [[0, 0, 1, 1], [0, 1, 1, 2]]
            })
            w.focus_group(0)
            w.run_command('clone_file')
            w.run_command('move_to_group', {'group': 1})
            w.focus_group(1)
        else:
            w.focus_group(1)
            w.run_command('close')
            w.run_command('set_layout', {
                'cols': [0.0, 1.0],
                'rows': [0.0, 1.0],
                'cells': [[0, 0, 1, 1]]
            })

Save it as Packages/User/split_pane.py and bind it to some hotkey:

{"keys": ["f6"], "command": "split_pane"},

If you want to change to vertical split change with following

        "cols": [0.0, 0.46, 1.0],
        "rows": [0.0, 1.0],
        "cells": [[0, 0, 1, 1], [1, 0, 2, 1]]

Java 8 stream's .min() and .max(): why does this compile?

Comparator is a functional interface, and Integer::max complies with that interface (after autoboxing/unboxing is taken into consideration). It takes two int values and returns an int - just as you'd expect a Comparator<Integer> to (again, squinting to ignore the Integer/int difference).

However, I wouldn't expect it to do the right thing, given that Integer.max doesn't comply with the semantics of Comparator.compare. And indeed it doesn't really work in general. For example, make one small change:

for (int i = 1; i <= 20; i++)
    list.add(-i);

... and now the max value is -20 and the min value is -1.

Instead, both calls should use Integer::compare:

System.out.println(list.stream().max(Integer::compare).get());
System.out.println(list.stream().min(Integer::compare).get());

T-SQL: Export to new Excel file

This is by far the best post for exporting to excel from SQL:

http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=49926

To quote from user madhivanan,

Apart from using DTS and Export wizard, we can also use this query to export data from SQL Server2000 to Excel

Create an Excel file named testing having the headers same as that of table columns and use these queries

1 Export data to existing EXCEL file from SQL Server table

insert into OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
    'Excel 8.0;Database=D:\testing.xls;', 
    'SELECT * FROM [SheetName$]') select * from SQLServerTable

2 Export data from Excel to new SQL Server table

select * 
into SQLServerTable FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
    'Excel 8.0;Database=D:\testing.xls;HDR=YES', 
    'SELECT * FROM [Sheet1$]')

3 Export data from Excel to existing SQL Server table (edited)

Insert into SQLServerTable Select * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
    'Excel 8.0;Database=D:\testing.xls;HDR=YES', 
    'SELECT * FROM [SheetName$]')

4 If you dont want to create an EXCEL file in advance and want to export data to it, use

EXEC sp_makewebtask 
    @outputfile = 'd:\testing.xls', 
    @query = 'Select * from Database_name..SQLServerTable', 
    @colheaders =1, 
    @FixedFont=0,@lastupdated=0,@resultstitle='Testing details'

(Now you can find the file with data in tabular format)

5 To export data to new EXCEL file with heading(column names), create the following procedure

create procedure proc_generate_excel_with_columns
(
    @db_name    varchar(100),
    @table_name varchar(100),   
    @file_name  varchar(100)
)
as

--Generate column names as a recordset
declare @columns varchar(8000), @sql varchar(8000), @data_file varchar(100)
select 
    @columns=coalesce(@columns+',','')+column_name+' as '+column_name 
from 
    information_schema.columns
where 
    table_name=@table_name
select @columns=''''''+replace(replace(@columns,' as ',''''' as '),',',',''''')

--Create a dummy file to have actual data
select @data_file=substring(@file_name,1,len(@file_name)-charindex('\',reverse(@file_name)))+'\data_file.xls'

--Generate column names in the passed EXCEL file
set @sql='exec master..xp_cmdshell ''bcp " select * from (select '+@columns+') as t" queryout "'+@file_name+'" -c'''
exec(@sql)

--Generate data in the dummy file
set @sql='exec master..xp_cmdshell ''bcp "select * from '+@db_name+'..'+@table_name+'" queryout "'+@data_file+'" -c'''
exec(@sql)

--Copy dummy file to passed EXCEL file
set @sql= 'exec master..xp_cmdshell ''type '+@data_file+' >> "'+@file_name+'"'''
exec(@sql)

--Delete dummy file 
set @sql= 'exec master..xp_cmdshell ''del '+@data_file+''''
exec(@sql)

After creating the procedure, execute it by supplying database name, table name and file path:

EXEC proc_generate_excel_with_columns 'your dbname', 'your table name','your file path'

Its a whomping 29 pages but that is because others show various other ways as well as people asking questions just like this one on how to do it.

Follow that thread entirely and look at the various questions people have asked and how they are solved. I picked up quite a bit of knowledge just skimming it and have used portions of it to get expected results.

To update single cells

A member also there Peter Larson posts the following: I think one thing is missing here. It is great to be able to Export and Import to Excel files, but how about updating single cells? Or a range of cells?

This is the principle of how you do manage that

update OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
'Excel 8.0;Database=c:\test.xls;hdr=no', 
'SELECT * FROM [Sheet1$b7:b7]') set f1 = -99

You can also add formulas to Excel using this:

update OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
'Excel 8.0;Database=c:\test.xls;hdr=no', 
'SELECT * FROM [Sheet1$b7:b7]') set f1 = '=a7+c7'

Exporting with column names using T-SQL

Member Mladen Prajdic also has a blog entry on how to do this here

References: www.sqlteam.com (btw this is an excellent blog / forum for anyone looking to get more out of SQL Server). For error referencing I used this

Errors that may occur

If you get the following error:

OLE DB provider 'Microsoft.Jet.OLEDB.4.0' cannot be used for distributed queries

Then run this:

sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ad Hoc Distributed Queries', 1;
GO
RECONFIGURE;
GO

How can I fix MySQL error #1064?

For my case, I was trying to execute procedure code in MySQL, and due to some issue with server in which Server can't figure out where to end the statement I was getting Error Code 1064. So I wrapped the procedure with custom DELIMITER and it worked fine.

For example, Before it was:

DROP PROCEDURE IF EXISTS getStats;
CREATE PROCEDURE `getStats` (param_id INT, param_offset INT, param_startDate datetime, param_endDate datetime)
BEGIN
    /*Procedure Code Here*/
END;

After putting DELIMITER it was like this:

DROP PROCEDURE IF EXISTS getStats;
DELIMITER $$
CREATE PROCEDURE `getStats` (param_id INT, param_offset INT, param_startDate datetime, param_endDate datetime)
BEGIN
    /*Procedure Code Here*/
END;
$$
DELIMITER ;

Efficient way to return a std::vector in c++

A common pre-C++11 idiom is to pass a reference to the object being filled.

Then there is no copying of the vector.

void f( std::vector & result )
{
  /*
    Insert elements into result
  */
} 

how to configuring a xampp web server for different root directory

In case, if anyone prefers a simpler solution, especially on Linux (e.g. Ubuntu), a very easy way out is to create a symbolic link to the intended folder in the htdocs folder. For example, if I want to be able to serve files from a folder called "/home/some/projects/testserver/" and my htdocs is located in "/opt/lampp/htdocs/". Just create a symbolic link like so:

ln -s /home/some/projects/testserver /opt/lampp/htdocs/testserver

The command for symbolic link works like so: ln -s target source where,

target - The existing file/directory you would like to link TO.
source - The file/folder to be created, copying the contents of the target. The LINK itself.

For more help see ln --help Source: Create Symbolic Links in Ubuntu

And that's done. just visit http://localhost/testserver/ In fact, you don't even need to restart your server.

Render HTML in React Native

 <WebView ref={'webview'} automaticallyAdjustContentInsets={false} source={require('../Assets/aboutus.html')} />

This worked for me :) I have html text aboutus file.

104, 'Connection reset by peer' socket error, or When does closing a socket result in a RST rather than FIN?

Normally, you'd get an RST if you do a close which doesn't linger (i.e. in which data can be discarded by the stack if it hasn't been sent and ACK'd) and a normal FIN if you allow the close to linger (i.e. the close waits for the data in transit to be ACK'd).

Perhaps all you need to do is set your socket to linger so that you remove the race condition between a non lingering close done on the socket and the ACKs arriving?

MySQL "WITH" clause

Oracle does support WITH.

It would look like this.

WITH emps as (SELECT * FROM Employees)
SELECT * FROM emps WHERE ID < 20
UNION ALL
SELECT * FROM emps where Sex = 'F'

@ysth WITH is hard to google because it's a common word typically excluded from searches.

You'd want to look at the SELECT docs to see how subquery factoring works.

I know this doesn't answer the OP but I'm cleaning up any confusion ysth may have started.

"unrecognized import path" with go get

I had exactly the same issue, after moving from old go version (installed from old PPA) to newer (1.2.1) default packages in ubuntu 14.04.

The first step was to purge existing go:

sudo apt-get purge golang*

Which outputs following warnings:

dpkg: warning: while removing golang-go, directory '/usr/lib/go/src' not empty so not removed
dpkg: warning: while removing golang-go.tools, directory '/usr/lib/go' not empty so not removed

It looks like removing go leaves some files behind, which in turn can confuse newer install. More precisely, installation itself will complete fine, but afterwards any go command, like "go get something" gives those "unrecognized import path" errors.

All I had to do was to remove those dirs first, reinstall golang, and all works like a charm (assuming you also set GOPATH)

# careful!
sudo rm -rf /usr/lib/go /usr/lib/go/src
sudo apt-get install golang-go golang-go.tools

Why does Eclipse complain about @Override on interface methods?

Using the @Override annotation on methods that implement those declared by an interface is only valid from Java 6 onward. It's an error in Java 5.

Make sure that your IDE projects are setup to use a Java 6 JRE, and that the "source compatibility" is set to 1.6 or greater:

  1. Open the Window > Preferences dialog
  2. Browse to Java > Compiler.
  3. There, set the "Compiler compliance level" to 1.6.

Remember that Eclipse can override these global settings for a specific project, so check those too.


Update:

The error under Java 5 isn't just with Eclipse; using javac directly from the command line will give you the same error. It is not valid Java 5 source code.

However, you can specify the -target 1.5 option to JDK 6's javac, which will produce a Java 5 version class file from the Java 6 source code.

Unable to update the EntitySet - because it has a DefiningQuery and no <UpdateFunction> element exist

I had this issue come up and believe it was caused because I had deleted the Index on my tables primary key and replaced it with an index on some of the other fields in the table.

After I deleted the primary key index and refreshed the edmx, inserts stopped working.

I refreshed the table to the older version, refreshed the edmx and everything works again.

I should note that when I opened the EDMX to troubleshoot this issue, checking to see if there was a primary key defined, there was. So none of the above suggestions were helping me. But refreshing the index on the primary key seemed to work.

What is a segmentation fault?

There are several good explanations of "Segmentation fault" in the answers, but since with segmentation fault often there's a dump of the memory content, I wanted to share where the relationship between the "core dumped" part in Segmentation fault (core dumped) and memory comes from:

From about 1955 to 1975 - before semiconductor memory - the dominant technology in computer memory used tiny magnetic doughnuts strung on copper wires. The doughnuts were known as "ferrite cores" and main memory thus known as "core memory" or "core".

Taken from here.

How to add an existing folder with files to SVN?

3 Steps:

  • Open "Repo Browser" (Use Link of yr parent folder) .
  • Right click Choose "Add Folder".
  • Browse to your folder.

enter image description here

Styling the arrow on bootstrap tooltips

In case you are going around and around to figure this out and none of the options above are working, it is possible you are experiencing a name space conflict of .tooltip with bootstrap and jquery.

See this answer on how to fix: jQueryUI Tooltips are competing with Twitter Bootstrap

MacOSX homebrew mysql root password

Got this error after installing mysql via home brew.

So first remove the installation. Then Reinstall via Homebrew

brew update
brew doctor
brew install mysql

Then restart mysql service

 mysql.server restart

Then run this command to set your new root password.

 mysql_secure_installation

Finally it will ask to reload the privileges. Say yes. Then login to mysql again. And use the new password you have set.

mysql -u root -p

How to recover Git objects damaged by hard disk failure?

Git checkout can actually pick out individual files from a revision. Just give it the commit hash and the file name. More detailed info here.

I guess the easiest way to fix this safely is to revert to the newest uncommited backup and then selectively pick out uncorrupted files from newer commits. Good luck!

AttributeError: 'datetime' module has no attribute 'strptime'

I got the same problem and it is not the solution that you told. So I changed the "from datetime import datetime" to "import datetime". After that with the help of "datetime.datetime" I can get the whole modules correctly. I guess this is the correct answer to that question.

Reusing a PreparedStatement multiple times

The loop in your code is only an over-simplified example, right?

It would be better to create the PreparedStatement only once, and re-use it over and over again in the loop.

In situations where that is not possible (because it complicated the program flow too much), it is still beneficial to use a PreparedStatement, even if you use it only once, because the server-side of the work (parsing the SQL and caching the execution plan), will still be reduced.

To address the situation that you want to re-use the Java-side PreparedStatement, some JDBC drivers (such as Oracle) have a caching feature: If you create a PreparedStatement for the same SQL on the same connection, it will give you the same (cached) instance.

About multi-threading: I do not think JDBC connections can be shared across multiple threads (i.e. used concurrently by multiple threads) anyway. Every thread should get his own connection from the pool, use it, and return it to the pool again.

How to COUNT rows within EntityFramework without loading contents?

Query syntax:

var count = (from o in context.MyContainer
             where o.ID == '1'
             from t in o.MyTable
             select t).Count();

Method syntax:

var count = context.MyContainer
            .Where(o => o.ID == '1')
            .SelectMany(o => o.MyTable)
            .Count()

Both generate the same SQL query.

How to combine class and ID in CSS selector?

.sectionA[id='content'] { color : red; }

Won't work when the doctype is html 4.01 though...

Get: TypeError: 'dict_values' object does not support indexing when using python 3.2.3

In Python 3 the dict.values() method returns a dictionary view object, not a list like it does in Python 2. Dictionary views have a length, can be iterated, and support membership testing, but don't support indexing.

To make your code work in both versions, you could use either of these:

{names[i]:value for i,value in enumerate(d.values())}

    or

values = list(d.values())
{name:values[i] for i,name in enumerate(names)}

By far the simplest, fastest way to do the same thing in either version would be:

dict(zip(names, d.values()))

Note however, that all of these methods will give you results that will vary depending on the actual contents of d. To overcome that, you may be able use an OrderedDict instead, which remembers the order that keys were first inserted into it, so you can count on the order of what is returned by the values() method.

JavaScript: How to join / combine two arrays to concatenate into one array?

var a = ['a','b','c'];
var b = ['d','e','f'];
var c = a.concat(b); //c is now an an array with: ['a','b','c','d','e','f']
console.log( c[3] ); //c[3] will be 'd'

ORA-00932: inconsistent datatypes: expected - got CLOB

I found that selecting a clob column in CTE caused this explosion. ie

with cte as (
    select
        mytable1.myIntCol,
        mytable2.myClobCol
    from mytable1
    join mytable2 on ...
)
select myIntCol, myClobCol
from cte
where ...

presumably because oracle can't handle a clob in a temporary table.

Because my values were longer than 4K, I couldn't use to_char().
My work around was to select it from the final select, ie

with cte as (
    select
        mytable1.myIntCol
    from mytable1
)
select myIntCol, myClobCol
from cte
join mytable2 on ...
where ...

Too bad if this causes a performance problem.

How to deal with missing src/test/java source folder in Android/Maven project?

I had the same issue, fixed it. Create the missing folder directly in your file system (Using windows explorer for example) . And then, refresh your project under eclipse.

How to forcefully set IE's Compatibility Mode off from the server-side?

Changing my header to the following solve the problem:

<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />

How to detect a loop in a linked list?

// linked list find loop function

int findLoop(struct Node* head)
{
    struct Node* slow = head, *fast = head;
    while(slow && fast && fast->next)
    {
        slow = slow->next;
        fast = fast->next->next;
        if(slow == fast)
            return 1;
    }
 return 0;
}

Eclipse plugin for generating a class diagram

Must it be an Eclipse plug-in? I use doxygen, just supply your code folder, it handles the rest.

Importing variables from another file?

Actually this is not really the same to import a variable with:

from file1 import x1
print(x1)

and

import file1
print(file1.x1)

Altough at import time x1 and file1.x1 have the same value, they are not the same variables. For instance, call a function in file1 that modifies x1 and then try to print the variable from the main file: you will not see the modified value.

How to save a BufferedImage as a File

  1. Download and add imgscalr-lib-x.x.jar and imgscalr-lib-x.x-javadoc.jar to your Projects Libraries.
  2. In your code:

    import static org.imgscalr.Scalr.*;
    
    public static BufferedImage resizeBufferedImage(BufferedImage image, Scalr.Method scalrMethod, Scalr.Mode scalrMode, int width, int height)  {
        BufferedImage bi = image;
        bi = resize( image, scalrMethod, scalrMode, width, height);
    return bi;
    }
    
    // Save image:
    ImageIO.write(Scalr.resize(etotBImage, 150), "jpg", new File(myDir));
    

append new row to old csv file python

If the file exists and contains data, then it is possible to generate the fieldname parameter for csv.DictWriter automatically:

# read header automatically
with open(myFile, "r") as f:
    reader = csv.reader(f)
    for header in reader:
        break

# add row to CSV file
with open(myFile, "a", newline='') as f:
    writer = csv.DictWriter(f, fieldnames=header)
    writer.writerow(myDict)

how to avoid a new line with p tag?

Use the display: inline CSS property.

Ideal: In the stylesheet:

#container p { display: inline }

Bad/Extreme situation: Inline:

<p style="display:inline">...</p>

PUT and POST getting 405 Method Not Allowed Error for Restful Web Services

The problem is that POST method is forbidden for Nginx server's static files requests. Here is the workaround:

# Pass 405 as 200 for requested address:

server {
listen       80;
server_name  localhost;

location / {
    root   html;
    index  index.html index.htm;
}

error_page  404     /404.html;
error_page  403     /403.html;

error_page  405     =200 $uri;
}

If using proxy:

# If Nginx is like proxy for Apache:

error_page 405 =200 @405; 

location @405 { 
    root /htdocs; 
    proxy_pass http://localhost:8080; 
}

If using FastCGI:

location ~\.php(.*) {
fastcgi_pass 127.0.0.1:9000;
fastcgi_split_path_info ^(.+\.php)(.*)$;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info;
include /etc/nginx/fastcgi_params;
}

Browsers usually use GET, so you can use online tools like ApiTester to test your requests.

Source

webpack command not working

The quickest way, just to get this working is to use the web pack from another location, this will stop you having to install it globally or if npm run webpack fails.

When you install webpack with npm it goes inside the "node_modules\.bin" folder of your project.

in command prompt (as administrator)

  1. go to the location of the project where your webpack.config.js is located.
  2. in command prompt write the following
"C:\Users\..\ProjectName\node_modules\.bin\webpack" --config webpack.config.vendor.js

Getting Database connection in pure JPA setup

If you are using JAVA EE 5.0, the best way to do this is to use the @Resource annotation to inject the datasource in an attribute of a class (for instance an EJB) to hold the datasource resource (for instance an Oracle datasource) for the legacy reporting tool, this way:

@Resource(mappedName="jdbc:/OracleDefaultDS") DataSource datasource;

Later you can obtain the connection, and pass it to the legacy reporting tool in this way:

Connection conn = dataSource.getConnection();

A server with the specified hostname could not be found

I faced the same problem, it turned out to be VPN related. If you are testing on a device against a corporate network, chances are your Mac has proper VPN set up, but your phone does not. Connect phone to the corporate VPN for your apps deployed to device to see corporate servers.

How to center text vertically with a large font-awesome icon?

Try set your icon as height: 100%

You don't need to do anything with the wrapper (say, your button).

This requires Font Awesome 5. Not sure if it works for older FA versions.

.wrap svg {
    height: 100%;
}

Note that the icon is actually a svg graphic.

Demo

How to write an ArrayList of Strings into a text file?

You can do that with a single line of code nowadays. Create the arrayList and the Path object representing the file where you want to write into:

Path out = Paths.get("output.txt");
List<String> arrayList = new ArrayList<> ( Arrays.asList ( "a" , "b" , "c" ) );

Create the actual file, and fill it with the text in the ArrayList:

Files.write(out,arrayList,Charset.defaultCharset());

How to implement swipe gestures for mobile devices?

Have you tried Hammerjs? It supports swipe gestures by using the velocity of the touch. http://eightmedia.github.com/hammer.js/

What is the difference between <p> and <div>?

DIV is a generic block level container that can contain any other block or inline elements, including other DIV elements, whereas P is to wrap paragraphs (text).

Google Play Services Missing in Emulator (Android 4.4.2)

http://developer.android.com/google/play-services/setup.html

Quoting docs

If you want to test your app on the emulator, expand the directory for Android 4.2.2 (API 17) or a higher version, select Google APIs, and install it. Then create a new AVD with Google APIs as the platform target.

Needs Emulator of Google API"S

See the target in the snap

Snap

enter image description here

I prefer testing on a real device which has google play services installed

How to resolve "Could not find schema information for the element/attribute <xxx>"?

An XSD is included with EntLib 5, and is installed in the Visual Studio schema directory. In my case, it could be found at:

"C:\Program Files (x86)\Microsoft Visual Studio 10.0\Xml\Schemas\EnterpriseLibrary.Configuration.xsd"

CONTEXT

  • Visual Studio 2010
  • Enterprise Library 5

STEPS TO REMOVE THE WARNINGS

  1. open app.config in your Visual Studio project
  2. right click in the XML Document editor, select "Properties"
  3. add the fully qualified path to the "EnterpriseLibrary.Configuration.xsd"

ASIDE

It is worth repeating that these "Error List" "Messages" ("Could not find schema information for the element") are only visible when you open the app.config file. If you "Close All Documents" and compile... no messages will be reported.

How do I get the backtrace for all the threads in GDB?

Generally, the backtrace is used to get the stack of the current thread, but if there is a necessity to get the stack trace of all the threads, use the following command.

thread apply all bt

Best C++ IDE or Editor for Windows

notepad++ or codeblocks for large projects

How to change the name of an iOS app?

Project Navigator>General>Display Name

enter image description here

Displaying a vector of strings in C++

You have to insert the elements using the insert method present in vectors STL, check the below program to add the elements to it, and you can use in the same way in your program.

#include <iostream>
#include <vector>
#include <string.h>

int main ()
{
  std::vector<std::string> myvector ;
  std::vector<std::string>::iterator it;

   it = myvector.begin();
  std::string myarray [] = { "Hi","hello","wassup" };
  myvector.insert (myvector.begin(), myarray, myarray+3);

  std::cout << "myvector contains:";
  for (it=myvector.begin(); it<myvector.end(); it++)
    std::cout << ' ' << *it;
    std::cout << '\n';

  return 0;
}

.toLowerCase not working, replacement function?

It is a number, not a string. Numbers don't have a toLowerCase() function because numbers do not have case in the first place.

To make the function run without error, run it on a string.

var ans = "334";

Of course, the output will be the same as the input since, as mentioned, numbers don't have case in the first place.

How do you represent a JSON array of strings?

I'll elaborate a bit more on ChrisR awesome answer and bring images from his awesome reference.

A valid JSON always starts with either curly braces { or square brackets [, nothing else.

{ will start an object:

left brace followed by a key string (a name that can't be repeated, in quotes), colon and a value (valid types shown below), followed by an optional comma to add more pairs of string and value at will and finished with a right brace

{ "key": value, "another key": value }

Hint: although javascript accepts single quotes ', JSON only takes double ones ".

[ will start an array:

left bracket followed by value, optional comma to add more value at will and finished with a right bracket

[value, value]

Hint: spaces among elements are always ignored by any JSON parser.

And value is an object, array, string, number, bool or null:

Image showing the 6 types a JSON value can be: string, number, JSON object, Array/list, boolean, and null

So yeah, ["a", "b"] is a perfectly valid JSON, like you could try on the link Manish pointed.

Here are a few extra valid JSON examples, one per block:

{}

[0]

{"__comment": "json doesn't accept comments and you should not be commenting even in this way", "avoid!": "also, never add more than one key per line, like this"}

[{   "why":null} ]

{
  "not true": [0, false],
  "true": true,
  "not null": [0, 1, false, true, {
    "obj": null
  }, "a string"]
}

How to manually reload Google Map with JavaScript

You can refresh with this:

map.panBy(0, 0);

AngularJS: Basic example to use authentication in Single Page Application

I think that every JSON response should contain a property (e.g. {authenticated: false}) and the client has to test it everytime: if false, then the Angular controller/service will "redirect" to the login page.

And what happen if the user catch de JSON and change the bool to True?

I think you should never rely on client side to do these kind of stuff. If the user is not authenticated, the server should just redirect to a login/error page.

Sending email from Azure

Sending from a third party SMTP isn't restricted by or specific to Azure. Using System.Net.Mail, create your message, configure your SMTP client, send the email:

// create the message
var msg = new MailMessage();
msg.From = new MailAddress("[email protected]"); 
msg.To.Add(strTo); 
msg.Subject = strSubject; 
msg.IsBodyHtml = true; 
msg.Body = strMessage;

// configure the smtp server
var smtp = new SmtpClient("YourSMTPServer"); 
var = new System.Net.NetworkCredential("YourSMTPServerUserName", "YourSMTPServerPassword");

// send the message
smtp.Send(msg); 

UPDATE: I added a post on Medium about how to do this with an Azure Function - https://medium.com/@viperguynaz/building-a-serverless-contact-form-f8f0bff46ba9

How do I set up Vim autoindentation properly for editing Python files?

for more advanced python editing consider installing the simplefold vim plugin. it allows you do advanced code folding using regular expressions. i use it to fold my class and method definitions for faster editing.

How to close off a Git Branch?

We request that the developer asking for the pull request state that they would like the branch deleted. Most of the time this is the case. There are times when a branch is needed (e.g. copying the changes to another release branch).

My fingers have memorized our process:

git checkout <feature-branch>
git pull
git checkout <release-branch>
git pull
git merge --no-ff <feature-branch>
git push
git tag -a branch-<feature-branch> -m "Merge <feature-branch> into <release-branch>"
git push --tags
git branch -d <feature-branch>
git push origin :<feature-branch>

A branch is for work. A tag marks a place in time. By tagging each branch merge we can resurrect a branch if that is needed. The branch tags have been used several times to review changes.

jQuery Loop through each div

Just as we refer to scrolling class

$( ".scrolling" ).each( function(){
    var img = $( "img", this );
    $(this).width( img.width() * img.length * 1.2 ) 
})

How to fix a Div to top of page with CSS only

You can also use flexbox, but you'd have to add a parent div that covers div#top and div#term-defs. So the HTML looks like this:

_x000D_
_x000D_
    #content {_x000D_
        width: 100%;_x000D_
        height: 100%;_x000D_
        display: flex;_x000D_
        flex-direction: column;_x000D_
    }_x000D_
_x000D_
    #term-defs {_x000D_
        flex-grow: 1;_x000D_
        overflow: auto;_x000D_
    } 
_x000D_
    <body>_x000D_
        <div id="content">_x000D_
            <div id="top">_x000D_
                <a href="#A">A</a> |_x000D_
                <a href="#B">B</a> |_x000D_
                <a href="#Z">Z</a>_x000D_
            </div>_x000D_
    _x000D_
            <div id="term-defs">_x000D_
                <dl>_x000D_
                    <span id="A"></span>_x000D_
                    <dt>foo</dt>_x000D_
                    <dd>This is the sound made by a fool</dd>_x000D_
                    <!-- and so on ... -->_x000D_
                </dl>_x000D_
            </div>_x000D_
        </div>_x000D_
    </body>
_x000D_
_x000D_
_x000D_

flex-grow ensures that the div's size is equal to the remaining size.

You could do the same without flexbox, but it would be more complicated to work out the height of #term-defs (you'd have to know the height of #top and use calc(100% - 999px) or set the height of #term-defs directly).
With flexbox dynamic sizes of the divs are possible.

One difference is that the scrollbar only appears on the term-defs div.

PHPExcel Make first row bold

Assuming headers are on the first row of the sheet starting at A1, and you know how many of them there are, this was my solution:

$header = array(
    'Header 1',
    'Header 2'
);

$objPHPExcel = new PHPExcel();
$objPHPExcelSheet = $objPHPExcel->getSheet(0);
$objPHPExcelSheet->fromArray($header, NULL);
$first_letter = PHPExcel_Cell::stringFromColumnIndex(0);
$last_letter = PHPExcel_Cell::stringFromColumnIndex(count($header)-1);
$header_range = "{$first_letter}1:{$last_letter}1";
$objPHPExcelSheet->getStyle($header_range)->getFont()->setBold(true);

How to use `replace` of directive definition?

Replace [True | False (default)]

Effect

1.  Replace the directive element. 

Dependency:

1. When replace: true, the template or templateUrl must be required. 

Xcode 4 - build output directory

Keep derived data but use the DSTROOT to specify the destination.

Use DEPLOYMENT_LOCATION to force deployment.

Use the undocumented DWARF_DSYM_FOLDER_PATH to copy the dSYM over too.

This allows you to use derived data location from xcodebuild and not have to do wacky stuff to find the app.

xcodebuild -sdk "iphoneos" -workspace Foo.xcworkspace -scheme Foo -configuration "Debug" DEPLOYMENT_LOCATION=YES DSTROOT=tmp DWARF_DSYM_FOLDER_PATH=tmp build

How to stretch a table over multiple pages

You should \usepackage{longtable}.

RegEx match open tags except XHTML self-contained tags

I used a open source tool called HTMLParser before. It's designed to parse HTML in various ways and serves the purpose quite well. It can parse HTML as different treenode and you can easily use its API to get attributes out of the node. Check it out and see if this can help you.

Powershell import-module doesn't find modules

I experienced the same error and tried numerous things before I succeeded. The solution was to prepend the path of the script to the relative path of the module like this:

// Note that .Path will only be available during script-execution
$ScriptPath = Split-Path $MyInvocation.MyCommand.Path

Import-Module $ScriptPath\Modules\Builder.psm1

Btw you should take a look at http://msdn.microsoft.com/en-us/library/dd878284(v=vs.85).aspx which states:

Beginning in Windows PowerShell 3.0, modules are imported automatically when any cmdlet or function in the module is used in a command. This feature works on any module in a directory that this included in the value of the PSModulePath environment variable ($env:PSModulePath)

How to convert a byte array to its numeric value (Java)?

One could use the Buffers that are provided as part of the java.nio package to perform the conversion.

Here, the source byte[] array has a of length 8, which is the size that corresponds with a long value.

First, the byte[] array is wrapped in a ByteBuffer, and then the ByteBuffer.getLong method is called to obtain the long value:

ByteBuffer bb = ByteBuffer.wrap(new byte[] {0, 0, 0, 0, 0, 0, 0, 4});
long l = bb.getLong();

System.out.println(l);

Result

4

I'd like to thank dfa for pointing out the ByteBuffer.getLong method in the comments.


Although it may not be applicable in this situation, the beauty of the Buffers come with looking at an array with multiple values.

For example, if we had a 8 byte array, and we wanted to view it as two int values, we could wrap the byte[] array in an ByteBuffer, which is viewed as a IntBuffer and obtain the values by IntBuffer.get:

ByteBuffer bb = ByteBuffer.wrap(new byte[] {0, 0, 0, 1, 0, 0, 0, 4});
IntBuffer ib = bb.asIntBuffer();
int i0 = ib.get(0);
int i1 = ib.get(1);

System.out.println(i0);
System.out.println(i1);

Result:

1
4

How can I tell if a DOM element is visible in the current viewport?

The new Intersection Observer API addresses this question very directly.

This solution will need a polyfill as Safari, Opera and Internet Explorer don't support this yet (the polyfill is included in the solution).

In this solution, there is a box out of view that is the target (observed). When it comes into view, the button at the top in the header is hidden. It is shown once the box leaves the view.

_x000D_
_x000D_
const buttonToHide = document.querySelector('button');_x000D_
_x000D_
const hideWhenBoxInView = new IntersectionObserver((entries) => {_x000D_
  if (entries[0].intersectionRatio <= 0) { // If not in view_x000D_
    buttonToHide.style.display = "inherit";_x000D_
  } else {_x000D_
    buttonToHide.style.display = "none";_x000D_
  }_x000D_
});_x000D_
_x000D_
hideWhenBoxInView.observe(document.getElementById('box'));
_x000D_
header {_x000D_
  position: fixed;_x000D_
  top: 0;_x000D_
  width: 100vw;_x000D_
  height: 30px;_x000D_
  background-color: lightgreen;_x000D_
}_x000D_
_x000D_
.wrapper {_x000D_
  position: relative;_x000D_
  margin-top: 600px;_x000D_
}_x000D_
_x000D_
#box {_x000D_
  position: relative;_x000D_
  left: 175px;_x000D_
  width: 150px;_x000D_
  height: 135px;_x000D_
  background-color: lightblue;_x000D_
  border: 2px solid;_x000D_
}
_x000D_
<script src="https://polyfill.io/v2/polyfill.min.js?features=IntersectionObserver"></script>_x000D_
<header>_x000D_
  <button>NAVIGATION BUTTON TO HIDE</button>_x000D_
</header>_x000D_
  <div class="wrapper">_x000D_
    <div id="box">_x000D_
    </div>_x000D_
  </div>
_x000D_
_x000D_
_x000D_

Excel formula to reference 'CELL TO THE LEFT'

When creating your conditional formatting, set the range to which it applies to what you want (the whole sheet), then enter a relative formula (remove the $ signs) as if you were only formatting the upper-left corner.

Excel will properly apply the formatting to the rest of the cells accordingly.

In this example, starting in B1, the left cell would be A1. Just use that--no advanced formula required.


If you're looking for something more advanced, you can play around with column(), row(), and indirect(...).

Are loops really faster in reverse?

Since none of the other answers seem to answer your specific question (more than half of them show C examples and discuss lower-level languages, your question is for JavaScript) I decided to write my own.

So, here you go:

Simple answer: i-- is generally faster because it doesn't have to run a comparison to 0 each time it runs, test results on various methods are below:

Test results: As "proven" by this jsPerf, arr.pop() is actually the fastest loop by far. But, focusing on --i, i--, i++ and ++i as you asked in your question, here are jsPerf (they are from multiple jsPerf's, please see sources below) results summarized:

--i and i-- are the same in Firefox while i-- is faster in Chrome.

In Chrome a basic for loop (for (var i = 0; i < arr.length; i++)) is faster than i-- and --i while in Firefox it's slower.

In Both Chrome and Firefox a cached arr.length is significantly faster with Chrome ahead by about 170,000 ops/sec.

Without a significant difference, ++i is faster than i++ in most browsers, AFAIK, it's never the other way around in any browser.

Shorter summary: arr.pop() is the fastest loop by far; for the specifically mentioned loops, i-- is the fastest loop.

Sources: http://jsperf.com/fastest-array-loops-in-javascript/15, http://jsperf.com/ipp-vs-ppi-2

I hope this answers your question.

C# Error: Parent does not contain a constructor that takes 0 arguments

You need to change the constructor of the child class to this:

public child(int i) : base(i)
{
    Console.WriteLine("child");
}

The part : base(i) means that the constructor of the base class with one int parameter should be used. If this is missing, you are implicitly telling the compiler to use the default constructor without parameters. Because no such constructor exists in the base class it is giving you this error.

Split string based on a regular expression

Its very simple actually. Try this:

str1="a    b     c      d"
splitStr1 = str1.split()
print splitStr1

warning: Insecure world writable dir /usr/local/bin in PATH, mode 040777

Try: sudo chmod go-w /usr/local/bin

The /usr/local/bin directory is owned by the root (i.e. administrator) account, so even if you can write to it, you can't change the permissions on it. The sudo command means "run the following command as root", and works a lot like clicking that lock icon in the System Preferences dialogs.

How to download all files (but not HTML) from a website using wget?

Try this. It always works for me

wget --mirror -p --convert-links -P ./LOCAL-DIR WEBSITE-URL

Simple java program of pyramid

You can try in this way.

   for(int a=5;a>0;a--){
        int b=0;
       for(b=0;b<a;b++){
           System.out.print(" ");
       }
        for (int j=b;j<5;j++){
            System.out.print(" $ ");
        }
        System.out.println("");

    }

Out put

      $ 
     $  $ 
    $  $  $ 
   $  $  $  $ 

Custom ImageView with drop shadow

Here the Implementation of Paul Burkes answer:

public class ShadowImageView extends ImageView {

    public ShadowImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public ShadowImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ShadowImageView(Context context) {
        super(context);
    }

    private Paint createShadow() {
        Paint mShadow = new Paint();

        float radius = 10.0f;
        float xOffset = 0.0f;
        float yOffset = 2.0f;

        // color=black
        int color = 0xFF000000;
        mShadow.setShadowLayer(radius, xOffset, yOffset, color);


        return mShadow;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        Paint mShadow = createShadow();
        Drawable d = getDrawable();
        if (d != null){
            setLayerType(LAYER_TYPE_SOFTWARE, mShadow);
            Bitmap bitmap = ((BitmapDrawable) getDrawable()).getBitmap();
            canvas.drawBitmap(bitmap, 0.0f, 0.0f, mShadow);
        } else {
            super.onDraw(canvas);
        }

    };

}

TODO: execute setLayerType(LAYER_TYPE_SOFTWARE, mShadow); only if API Level is > 10

Convert UTC/GMT time to local time

In answer to Dana's suggestion:

The code sample now looks like:

string date = "Web service date"..ToString("R", ci);
DateTime convertedDate = DateTime.Parse(date);            
DateTime dt = TimeZone.CurrentTimeZone.ToLocalTime(convertedDate);

The original date was 20/08/08; the kind was UTC.

Both "convertedDate" and "dt" are the same:

21/08/08 10:00:26; the kind was local

How do I get user IP address in django?

here is a short one liner to accomplish this:

request.META.get('HTTP_X_FORWARDED_FOR', request.META.get('REMOTE_ADDR', '')).split(',')[0].strip()

Kotlin Android start new Activity

Simply you can start an Activity in KOTLIN by using this simple method,

val intent = Intent(this, SecondActivity::class.java)
intent.putExtra("key", value)
startActivity(intent)

Change Date Format(DD/MM/YYYY) in SQL SELECT Statement

Changed to:

SELECT FORMAT(SA.[RequestStartDate],'dd/MM/yyyy') as 'Service Start Date', SA.[RequestEndDate] as 'Service End Date', FROM (......)SA WHERE......

Have no idea which SQL engine you are using, for other SQL engine, CONVERT can be used in SELECT statement to change the format in the form you needed.

Filtering a data frame by values in a column

Thought I'd update this with a dplyr solution

library(dplyr)    
filter(studentdata, Drink == "water")

What is the difference between RTP or RTSP in a streaming server?

You are getting something wrong... RTSP is a realtime streaming protocol. Meaning, you can stream whatever you want in real time. So you can use it to stream LIVE content (no matter what it is, video, audio, text, presentation...). RTP is a transport protocol which is used to transport media data which is negotiated over RTSP.

You use RTSP to control media transmission over RTP. You use it to setup, play, pause, teardown the stream...

So, if you want your server to just start streaming when the URL is requested, you can implement some sort of RTP-only server. But if you want more control and if you are streaming live video, you must use RTSP, because it transmits SDP and other important decoding data.

Read the documents I linked here, they are a good starting point.

How to get HQ youtube thumbnails?

Depending on the resolution you need, you can use a different URL:

Default Thumbnail

http://img.youtube.com/vi/<insert-youtube-video-id-here>/default.jpg

High Quality Thumbnail

http://img.youtube.com/vi/<insert-youtube-video-id-here>/hqdefault.jpg

Medium Quality

http://img.youtube.com/vi/<insert-youtube-video-id-here>/mqdefault.jpg

Standard Definition

http://img.youtube.com/vi/<insert-youtube-video-id-here>/sddefault.jpg

Maximum Resolution

http://img.youtube.com/vi/<insert-youtube-video-id-here>/maxresdefault.jpg

Note: it's a work-around if you don't want to use the YouTube Data API. Furthermore not all videos have the thumbnail images set, so the above method doesn’t work.

How to read/write a boolean when implementing the Parcelable interface?

you declare like this

 private boolean isSelectionRight;

write

 out.writeInt(isSelectionRight ? 1 : 0);

read

isSelectionRight  = in.readInt() != 0;

boolean type needs to be converted to something that Parcel supports and so we can convert it to int.

How do I determine file encoding in OS X?

Using the -I (that's a capital i) option on the file command seems to show the file encoding.

file -I {filename}

How to merge two json string in Python?

To append key-value pairs to a json string, you can use dict.update: dictA.update(dictB).

For your case, this will look like this:

dictA = json.loads(jsonStringA)
dictB = json.loads('{"error_1395952167":"Error Occured on machine h1 in datacenter dc3 on the step2 of process test"}')

dictA.update(dictB)
jsonStringA = json.dumps(dictA)

Note that key collisions will cause values in dictB overriding dictA.

OpenCV !_src.empty() in function 'cvtColor' error

Your code can't find the figure or the name of your figure named the by error message. Solution:

import cv2
import numpy as np 
import matplotlib.pyplot as plt 
img=cv2.imread('??.jpg')#solution:img=cv2.imread('haha.jpg')
print(img)