Programs & Examples On #Return code

How to call jQuery function onclick?

JS

 $(function () {
    var url = $(location).attr('href');
    $('#spn_url').html('<strong>' + url + '</strong>');
    $("#submit").click(function () {
        alert('button clicked');
    });
});

html

<input id="submit" type="submit" value="submit" name="submit">

Jquery submit form

Since a jQuery object inherits from an array, and this array contains the selected DOM elements. Saying you're using an id and so the element should be unique within the DOM, you could perform a direct call to submit by doing :

$(".nextbutton").click(function() { 
  $("#formID")[0].submit();
});

Replace all non-alphanumeric characters in a string

Use \W which is equivalent to [^a-zA-Z0-9_]. Check the documentation, https://docs.python.org/2/library/re.html

Import re
s =  'h^&ell`.,|o w]{+orld'
replaced_string = re.sub(r'\W+', '*', s)
output: 'h*ell*o*w*orld'

update: This solution will exclude underscore as well. If you want only alphabets and numbers to be excluded, then solution by nneonneo is more appropriate.

React Native Border Radius with background color

Remember if you want to give Text a backgroundcolor and then also borderRadius in that case also write overflow:'hidden' your text having a background colour will also get the radius otherwise it's impossible to achieve until unless you wrap it with View and give backgroundcolor and radius to it.

<Text style={{ backgroundColor: 'black', color:'white', borderRadius:10, overflow:'hidden'}}>Dummy</Text>

Why is there no Constant feature in Java?

const in C++ does not mean that a value is a constant.

const in C++ implies that the client of a contract undertakes not to alter its value.

Whether the value of a const expression changes becomes more evident if you are in an environment which supports thread based concurrency.

As Java was designed from the start to support thread and lock concurrency, it didn't add to confusion by overloading the term to have the semantics that final has.

eg:

#include <iostream>

int main ()
{
    volatile const int x = 42;

    std::cout << x << std::endl;

    *const_cast<int*>(&x) = 7;

    std::cout << x << std::endl;

    return 0;
}

outputs 42 then 7.

Although x marked as const, as a non-const alias is created, x is not a constant. Not every compiler requires volatile for this behaviour (though every compiler is permitted to inline the constant)

With more complicated systems you get const/non-const aliases without use of const_cast, so getting into the habit of thinking that const means something won't change becomes more and more dangerous. const merely means that your code can't change it without a cast, not that the value is constant.

What is the difference between find(), findOrFail(), first(), firstOrFail(), get(), list(), toArray()

  1. find($id) takes an id and returns a single model. If no matching model exist, it returns null.

  2. findOrFail($id) takes an id and returns a single model. If no matching model exist, it throws an error1.

  3. first() returns the first record found in the database. If no matching model exist, it returns null.

  4. firstOrFail() returns the first record found in the database. If no matching model exist, it throws an error1.

  5. get() returns a collection of models matching the query.

  6. pluck($column) returns a collection of just the values in the given column. In previous versions of Laravel this method was called lists.

  7. toArray() converts the model/collection into a simple PHP array.


Note: a collection is a beefed up array. It functions similarly to an array, but has a lot of added functionality, as you can see in the docs.

Unfortunately, PHP doesn't let you use a collection object everywhere you can use an array. For example, using a collection in a foreach loop is ok, put passing it to array_map is not. Similarly, if you type-hint an argument as array, PHP won't let you pass it a collection. Starting in PHP 7.1, there is the iterable typehint, which can be used to accept both arrays and collections.

If you ever want to get a plain array from a collection, call its all() method.


1 The error thrown by the findOrFail and firstOrFail methods is a ModelNotFoundException. If you don't catch this exception yourself, Laravel will respond with a 404, which is what you want most of the time.

I want to delete all bin and obj folders to force all projects to rebuild everything

I think you can right click to your solution/project and click "Clean" button.

As far as I remember it was working like that. I don't have my VS.NET with me now so can't test it.

Difference between static and shared libraries?

Static libraries are compiled as part of an application, whereas shared libraries are not. When you distribute an application that depends on shared libaries, the libraries, eg. dll's on MS Windows need to be installed.

The advantage of static libraries is that there are no dependencies required for the user running the application - e.g. they don't have to upgrade their DLL of whatever. The disadvantage is that your application is larger in size because you are shipping it with all the libraries it needs.

As well as leading to smaller applications, shared libraries offer the user the ability to use their own, perhaps better version of the libraries rather than relying on one that's part of the application

Changing the maximum length of a varchar column?

Using Maria-DB and DB-Navigator tool inside IntelliJ, MODIFY Column worked for me instead of Alter Column

update one table with data from another

UPDATE table1
SET 
`ID` = (SELECT table2.id FROM table2 WHERE table1.`name`=table2.`name`)

Printing out all the objects in array list

Override toString() method in Student class as below:

   @Override
   public String toString() {
        return ("StudentName:"+this.getStudentName()+
                    " Student No: "+ this.getStudentNo() +
                    " Email: "+ this.getEmail() +
                    " Year : " + this.getYear());
   }

custom facebook share button

You can simply do something like...

...
<head>
...
<script>
  window.fbAsyncInit = function() {
    FB.init({
      appId            : 'your-app-id', // you need to create an facebook app
      autoLogAppEvents : true,
      xfbml            : true,
      version          : 'v3.3'
    });
  };
</script>
<script async defer src="https://connect.facebook.net/en_US/sdk.js"></script>
</head>
<body>
...
<button id="share-btn"></button>
<!-- load jquery -->
<script>
    $('#share-btn').on('click', function () {
        FB.ui({
            method: 'share',
            href: location.href, // Current url
        }, function (response) { });
    });
</script>
</body>

Remove directory from remote repository after adding them to .gitignore

As per my Answer here: How to remove a directory from git repository?

To remove folder/directory only from git repository and not from the local try 3 simple steps.


Steps to remove directory

git rm -r --cached FolderName
git commit -m "Removed folder from repository"
git push origin master

Steps to ignore that folder in next commits

To ignore that folder from next commits make one file in root named .gitignore and put that folders name into it. You can put as many as you want

.gitignore file will be look like this

/FolderName

remove directory

Passing route control with optional parameter after root in express?

Express version:

"dependencies": {
    "body-parser": "^1.19.0",
    "express": "^4.17.1"
  }

Optional parameter are very much handy, you can declare and use them easily using express:

app.get('/api/v1/tours/:cId/:pId/:batchNo?', (req, res)=>{
    console.log("category Id: "+req.params.cId);
    console.log("product ID: "+req.params.pId);
    if (req.params.batchNo){
        console.log("Batch No: "+req.params.batchNo);
    }
});

In the above code batchNo is optional. Express will count it optional because after in URL construction, I gave a '?' symbol after batchNo '/:batchNo?'

Now I can call with only categoryId and productId or with all three-parameter.

http://127.0.0.1:3000/api/v1/tours/5/10
//or
http://127.0.0.1:3000/api/v1/tours/5/10/8987

enter image description here enter image description here

Making HTTP Requests using Chrome Developer tools

if you use jquery on you website, you can use something like this your console

_x000D_
_x000D_
$.post(_x000D_
    'dom/data-home.php',_x000D_
    {_x000D_
    type : "home", id : "0"_x000D_
    },function(data){_x000D_
        console.log(data)_x000D_
    })
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Calling a user defined function in jQuery

in my case I did

function myFunc() {
  console.log('myFunc', $(this));
}
$("selector").on("click", "selector", function(e) {
  e.preventDefault();
  myFunc.call(this);
});

properly calls myFunc with the correct this.

What does 'URI has an authority component' mean?

An authority is a portion of a URI. Your error suggests that it was not expecting one. The authority section is shown below, it is what is known as the website part of the url.

From RFC3986 on URIs:

The following is an example URI and its component parts:

     foo://example.com:8042/over/there?name=ferret#nose
     \_/   \______________/\_________/ \_________/ \__/
      |           |            |            |        |
   scheme     authority       path        query   fragment
      |   _____________________|__
     / \ /                        \
     urn:example:animal:ferret:nose

So there are two formats, one with an authority and one not. Regarding slashes:

"When authority is not present, the path cannot begin with two slash
characters ("//")."

Source: https://tools.ietf.org/rfc/rfc3986.txt (search for text 'authority is not present, the path cannot begin with two slash')

Remove '\' char from string c#

Why not simply this?

resultString = Regex.Replace(subjectString, @"\\", "");

Codeigniter LIKE with wildcard(%)

For Full like you can user :

$this->db->like('title',$query);

For %$query you can use

$this->db->like('title', $query, 'before');

and for $query% you can use

$this->db->like('title', $query, 'after');

How to set Spinner Default by its Value instead of Position?

If you are setting the spinner values by arraylist or array you can set the spinner's selection by using the index of the value.

String myString = "some value"; //the value you want the position for

ArrayAdapter myAdap = (ArrayAdapter) mySpinner.getAdapter(); //cast to an ArrayAdapter

int spinnerPosition = myAdap.getPosition(myString);

//set the default according to value
spinner.setSelection(spinnerPosition);

see the link How to set selected item of Spinner by value, not by position?

How to completely uninstall Android Studio on Mac?

Some of the files individually listed by Simon would also be found with something like the following command, but with some additional assurance about thoroughness, and without the recklessness of using rm -rf with wildcards:

find ~ \
  -path ~/Library/Caches/Metadata/Safari -prune -o \
  -iname \*android\*studio\* -print -prune

Also don't forget about the SDK, which is now separate from the application, and ~/.gradle/ (see vijay's answer).

super() raises "TypeError: must be type, not classobj" for new-style class

The problem is that super needs an object as an ancestor:

>>> class oldstyle:
...     def __init__(self): self.os = True

>>> class myclass(oldstyle):
...     def __init__(self): super(myclass, self).__init__()

>>> myclass()
TypeError: must be type, not classobj

On closer examination one finds:

>>> type(myclass)
classobj

But:

>>> class newstyle(object): pass

>>> type(newstyle)
type    

So the solution to your problem would be to inherit from object as well as from HTMLParser. But make sure object comes last in the classes MRO:

>>> class myclass(oldstyle, object):
...     def __init__(self): super(myclass, self).__init__()

>>> myclass().os
True

How to get a list of column names

Yes, you can achieve this by using the following commands:

sqlite> .headers on
sqlite> .mode column

The result of a select on your table will then look like:

id          foo         bar         age         street      address
----------  ----------  ----------  ----------  ----------  ----------
1           val1        val2        val3        val4        val5
2           val6        val7        val8        val9        val10

How to check if a view controller is presented modally or pushed on a navigation stack?

Swift 5
This handy extension handles few more cases than previous answers. These cases are VC(view controller) is the root VC of app window, VC is added as child to parent VC. It tries to return true only if the viewcontroller is modally presented.

extension UIViewController {
    /**
      returns true only if the viewcontroller is presented.
    */
    var isModal: Bool {
        if let index = navigationController?.viewControllers.firstIndex(of: self), index > 0 {
            return false
        } else if presentingViewController != nil {
            if let parent = parent, !(parent is UINavigationController || parent is UITabBarController) {
                return false
            }
            return true
        } else if let navController = navigationController, navController.presentingViewController?.presentedViewController == navController {
            return true
        } else if tabBarController?.presentingViewController is UITabBarController {
            return true
        }
        return false
    }
}

Thanks to Jonauz's answer. Again there is space for more optimizations. Please discuss about case that need to be handled in comment section.

File tree view in Notepad++

As of Notepad++ 6.9, the new Folder as Workspace feature can be used.

Folder as Workspace opens your folder(s) in a panel so you can browse folder(s) and open any file in Notepad++. Every changement in the folder(s) from outside will be synchronized in the panel. Usage: Simply drop 1 (or more) folder(s) in Notepad++.

Folder as Workspace

This feature has the advantage of not showing your entire file system when just the working directory is needed. It also means you don't need plugins for it to work.

Increasing the timeout value in a WCF service

Under the Tools menu in Visual Studio 2008 (or 2005 if you have the right WCF stuff installed) there is an options called 'WCF Service Configuration Editor'.

From there you can change the binding options for both the client and the services, one of these options will be for time-outs.

Javascript Error Null is not an Object

Any JS code which executes and deals with DOM elements should execute after the DOM elements have been created. JS code is interpreted from top to down as layed out in the HTML. So, if there is a tag before the DOM elements, the JS code within script tag will execute as the browser parses the HTML page.

So, in your case, you can put your DOM interacting code inside a function so that only function is defined but not executed.

Then you can add an event listener for document load to execute the function.

That will give you something like:

<script>
  function init() {
    var myButton = document.getElementById("myButton");
    var myTextfield = document.getElementById("myTextfield");
    myButton.onclick = function() {
      var userName = myTextfield.value;
      greetUser(userName);
    }
  }

  function greetUser(userName) {
    var greeting = "Hello " + userName + "!";
    document.getElementsByTagName ("h2")[0].innerHTML = greeting;
  }

  document.addEventListener('readystatechange', function() {
    if (document.readyState === "complete") {
      init();
    }
  });

</script>
<h2>Hello World!</h2>
<p id="myParagraph">This is an example website</p>

<form>
  <input type="text" id="myTextfield" placeholder="Type your name" />
  <input type="button" id="myButton" value="Go" />
</form>

Fiddle at - http://jsfiddle.net/poonia/qQMEg/4/

Why do you need to put #!/bin/bash at the beginning of a script file?

Every distribution has a default shell. Bash is the default on the majority of the systems. If you happen to work on a system that has a different default shell, then the scripts might not work as intended if they are written specific for Bash.

Bash has evolved over the years taking code from ksh and sh.

Adding #!/bin/bash as the first line of your script, tells the OS to invoke the specified shell to execute the commands that follow in the script.

#! is often referred to as a "hash-bang", "she-bang" or "sha-bang".

Can you split/explode a field in a MySQL query?

Based on Alex answer above (https://stackoverflow.com/a/11022431/1466341) I came up with even better solution. Solution which doesn't contain exact one record ID.

Assuming that the comma separated list is in table data.list, and it contains listing of codes from other table classification.code, you can do something like:

SELECT 
    d.id, d.list, c.code
FROM 
    classification c
    JOIN data d
        ON d.list REGEXP CONCAT('[[:<:]]', c.code, '[[:>:]]');

So if you have tables and data like this:

CLASSIFICATION (code varchar(4) unique): ('A'), ('B'), ('C'), ('D')
MY_DATA (id int, list varchar(255)): (100, 'C,A,B'), (150, 'B,A,D'), (200,'B')

above SELECT will return

(100, 'C,A,B', 'A'),
(100, 'C,A,B', 'B'),
(100, 'C,A,B', 'C'),
(150, 'B,A,D', 'A'),
(150, 'B,A,D', 'B'),
(150, 'B,A,D', 'D'),
(200, 'B', 'B'),

How to create a template function within a class? (C++)

Your guess is the correct one. The only thing you have to remember is that the member function template definition (in addition to the declaration) should be in the header file, not the cpp, though it does not have to be in the body of the class declaration itself.

How do I change Bootstrap 3's glyphicons to white?

You can just create your own .white class and add it to the glyphicon element.

.white, .white a {
  color: #fff;
}
<i class="glyphicon glyphicon-home white"></i>

TypeError: 'float' object is not callable

There is an operator missing, likely a *:

-3.7 need_something_here (prof[x])

The "is not callable" occurs because the parenthesis -- and lack of operator which would have switched the parenthesis into precedence operators -- make Python try to call the result of -3.7 (a float) as a function, which is not allowed.

The parenthesis are also not needed in this case, the following may be sufficient/correct:

-3.7 * prof[x]

As Legolas points out, there are other things which may need to be addressed:

2.25 * (1 - math.pow(math.e, (-3.7(prof[x])/2.25))) * (math.e, (0/2.25)))
                                  ^-- op missing
                                                    extra parenthesis --^
               valid but questionable float*tuple --^
                                     expression yields 0.0 always --^

How to print like printf in Python3?

Simple printf() function from O'Reilly's Python Cookbook.

import sys
def printf(format, *args):
    sys.stdout.write(format % args)

Example output:

i = 7
pi = 3.14159265359
printf("hi there, i=%d, pi=%.2f\n", i, pi)
# hi there, i=7, pi=3.14

Check if a String contains a special character

You can use the following code to detect special character from string.

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DetectSpecial{ 
public int getSpecialCharacterCount(String s) {
     if (s == null || s.trim().isEmpty()) {
         System.out.println("Incorrect format of string");
         return 0;
     }
     Pattern p = Pattern.compile("[^A-Za-z0-9]");
     Matcher m = p.matcher(s);
    // boolean b = m.matches();
     boolean b = m.find();
     if (b)
        System.out.println("There is a special character in my string ");
     else
         System.out.println("There is no special char.");
     return 0;
 }
}

Remove git mapping in Visual Studio 2015

In addition to Juliano Nunes Silva Oliveira's answer, the simplest and most clean way without hacking into the regedit, removing hidden .git folders or changing your VS15 settings is by connecting to a different repository. When connected you see the text of the other repository bold then select your Git local repository. Now you see that the

Remove

menu item is enabled so you are able to delete your Git local repository.

It's the same type of behaviour when dealing with Branches when using Git with visual studio 2015. You need to select different branch before you can delete the branch you wan to delete.

For the ones who needs visualization to understand it better. see link image: how it's done

Happy coding

Launch custom android application from android browser

There should also be <category android:name="android.intent.category.BROWSABLE"/> added to the intent filter to make the activity recognized properly from the link.

How to get the last char of a string in PHP?

Use substr() with a negative number for the 2nd argument.$newstring = substr($string1, -1);

What is a software framework?

Technically, you don't need a framework. If you're making a really really simple site (think of the web back in 1992), you can just do it all with hard-coded HTML and some CSS.

And if you want to make a modern webapp, you don't actually need to use a framework for that, either.

You can instead choose to write all of the logic you need yourself, every time. You can write your own data-persistence/storage layer, or - if you're too busy - just write custom SQL for every single database access. You can write your own authentication and session handling layers. And your own template rending logic. And your own exception-handling logic. And your own security functions. And your own unit test framework to make sure it all works fine. And your own... [goes on for quite a long time]

Then again, if you do use a framework, you'll be able to benefit from the good, usually peer-reviewed and very well tested work of dozens if not hundreds of other developers, who may well be better than you. You'll get to build what you want rapidly, without having to spend time building or worrying too much about the infrastructure items listed above.

You can get more done in less time, and know that the framework code you're using or extending is very likely to be done better than you doing it all yourself.

And the cost of this? Investing some time learning the framework. But - as virtually every web dev out there will attest - it's definitely worth the time spent learning to get massive (really, massive) benefits from using whatever framework you choose.

Typescript es6 import module "File is not a module error"

In addition to Tim's answer, this issue occurred for me when I was splitting up a refactoring a file, splitting it up into their own files.

VSCode, for some reason, indented parts of my [class] code, which caused this issue. This was hard to notice at first, but after I realised the code was indented, I formatted the code and the issue disappeared.

for example, everything after the first line of the Class definition was auto-indented during the paste.

export class MyClass extends Something<string> {
    public blah: string = null;

    constructor() { ... }
  }

make *** no targets specified and no makefile found. stop

Try

make clean
./configure --with-option=/path/etc
make && make install

Could not reserve enough space for object heap

Error occurred during initialization of VM Could not reserve enough space for 1572864KB object heap

I changed value of memory in settings.grade file 1536 to 512 and it helped

How to fix Ora-01427 single-row subquery returns more than one row in select?

The only subquery appears to be this - try adding a ROWNUM limit to the where to be sure:

(SELECT C.I_WORKDATE
         FROM T_COMPENSATION C
         WHERE C.I_COMPENSATEDDATE = A.I_REQDATE AND ROWNUM <= 1
         AND C.I_EMPID = A.I_EMPID)

You do need to investigate why this isn't unique, however - e.g. the employee might have had more than one C.I_COMPENSATEDDATE on the matched date.

For performance reasons, you should also see if the lookup subquery can be rearranged into an inner / left join, i.e.

 SELECT 
    ...
    REPLACE(TO_CHAR(C.I_WORKDATE, 'DD-Mon-YYYY'),
            ' ',
            '') AS WORKDATE,
    ...
 INNER JOIN T_EMPLOYEE_MS E
    ...
     LEFT OUTER JOIN T_COMPENSATION C
          ON C.I_COMPENSATEDDATE = A.I_REQDATE
          AND C.I_EMPID = A.I_EMPID
    ...

How to Set/Update State of StatefulWidget from other StatefulWidget in Flutter?

Old one but I would add my answer as per my findings:

var ancestralState = context.findAncestorStateOfType<ParentState>();
      ancestralState.setState(() {
        // here you can access public vars and update state.
        ...
      });

Convert generic list to dataset in C#

One option would be to use a System.ComponenetModel.BindingList rather than a list.

This allows you to use it directly within a DataGridView. And unlike a normal System.Collections.Generic.List updates the DataGridView on changes.

How to pick just one item from a generator?

generator = myfunct()
while True:
   my_element = generator.next()

make sure to catch the exception thrown after the last element is taken

Typescript Type 'string' is not assignable to type

If you're casting to a dropdownvalue[] when mocking data for example, compose it as an array of objects with value and display properties.

example:

[{'value': 'test1', 'display1': 'test display'},{'value': 'test2', 'display': 'test display2'},]

How do I select an entire row which has the largest ID in the table?

SELECT * 
FROM table 
WHERE id = (SELECT MAX(id) FROM TABLE)

How can I detect the touch event of an UIImageView?

In practical terms, don't do that.

Instead add a button with Custom style (no button graphics unless you specify images) over the UIImageView. Then attach whatever methods you want called to that.

You can use that technique for many cases where you really want some area of the screen to act as a button instead of messing with the Touch stuff.

Foreign key referencing a 2 columns primary key in SQL Server

The Content table likely to have multiple duplicate Application values that can't be mapped to Libraries. Is it possible to drop the Application column from the Libraries Primary Key Index and add it as a Unique Key Index instead?

NotificationCenter issue on Swift 3

Swift 3 & 4

Swift 3, and now Swift 4, have replaced many "stringly-typed" APIs with struct "wrapper types", as is the case with NotificationCenter. Notifications are now identified by a struct Notfication.Name rather than by String. For more details see the now legacy Migrating to Swift 3 guide

Swift 2.2 usage:

// Define identifier
let notificationIdentifier: String = "NotificationIdentifier"

// Register to receive notification
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(YourClassName.methodOfReceivedNotification(_:)), name: notificationIdentifier, object: nil)

// Post a notification
NSNotificationCenter.defaultCenter().postNotificationName(notificationIdentifier, object: nil)

Swift 3 & 4 usage:

// Define identifier
let notificationName = Notification.Name("NotificationIdentifier")

// Register to receive notification
NotificationCenter.default.addObserver(self, selector: #selector(YourClassName.methodOfReceivedNotification), name: notificationName, object: nil)

// Post notification
NotificationCenter.default.post(name: notificationName, object: nil)

// Stop listening notification
NotificationCenter.default.removeObserver(self, name: notificationName, object: nil)

All of the system notification types are now defined as static constants on Notification.Name; i.e. .UIApplicationDidFinishLaunching, .UITextFieldTextDidChange, etc.

You can extend Notification.Name with your own custom notifications in order to stay consistent with the system notifications:

// Definition:
extension Notification.Name {
    static let yourCustomNotificationName = Notification.Name("yourCustomNotificationName")
}

// Usage:
NotificationCenter.default.post(name: .yourCustomNotificationName, object: nil)

Swift 4.2 usage:

Same as Swift 4, except now system notifications names are part of UIApplication. So in order to stay consistent with the system notifications you can extend UIApplication with your own custom notifications instead of Notification.Name :

// Definition:
UIApplication {
    public static let yourCustomNotificationName = Notification.Name("yourCustomNotificationName")
}

// Usage:
NotificationCenter.default.post(name: UIApplication.yourCustomNotificationName, object: nil)

The maximum recursion 100 has been exhausted before statement completion

Specify the maxrecursion option at the end of the query:

...
from EmployeeTree
option (maxrecursion 0)

That allows you to specify how often the CTE can recurse before generating an error. Maxrecursion 0 allows infinite recursion.

JavaScript: remove event listener

I think you may need to define the handler function ahead of time, like so:

var myHandler = function(event) {
    click++; 
    if(click == 50) { 
        this.removeEventListener('click', myHandler);
    } 
}
canvas.addEventListener('click', myHandler);

This will allow you to remove the handler by name from within itself.

How to create an array containing 1...N

All of these are too complicated. Just do:

function count(num) {
  var arr = [];
  var i = 0;

  while (num--) {
    arr.push(i++);
  }

  return arr;
}

console.log(count(9))
//=> [ 0, 1, 2, 3, 4, 5, 6, 7, 8 ]

Or to do a range from a to b

function range(a, b) {
  var arr = [];

  while (a < b + 1) {
    arr.push(a++);
  }

  return arr;
}

console.log(range(4, 9))
//=> [ 4, 5, 6, 7, 8, 9 ]

/exclude in xcopy just for a file type

Change *.cs to .cs in the excludefileslist.txt

Is there an onSelect event or equivalent for HTML <select>?

I needed something exactly the same. This is what worked for me:

<select onchange="doSomething();" onfocus="this.selectedIndex = -1;">
  <option>A</option>
  <option>B</option>
  <option>C</option>
</select>

Supports this:

when the user selects any option, possibly the same one again

How to sort a List<Object> alphabetically using Object name field

Here is a version of Robert B's answer that works for List<T> and sorting by a specified String property of the object using Reflection and no 3rd party libraries

/**
 * Sorts a List by the specified String property name of the object.
 * 
 * @param list
 * @param propertyName
 */
public static <T> void sortList(List<T> list, final String propertyName) {

    if (list.size() > 0) {
        Collections.sort(list, new Comparator<T>() {
            @Override
            public int compare(final T object1, final T object2) {
                String property1 = (String)ReflectionUtils.getSpecifiedFieldValue (propertyName, object1);
                String property2 = (String)ReflectionUtils.getSpecifiedFieldValue (propertyName, object2);
                return property1.compareToIgnoreCase (property2);
            }
        });
    }
}


public static Object getSpecifiedFieldValue (String property, Object obj) {

    Object result = null;

    try {
        Class<?> objectClass = obj.getClass();
        Field objectField = getDeclaredField(property, objectClass);
        if (objectField!=null) {
            objectField.setAccessible(true);
            result = objectField.get(obj);
        }
    } catch (Exception e) {         
    }
    return result;
}

public static Field getDeclaredField(String fieldName, Class<?> type) {

    Field result = null;
    try {
        result = type.getDeclaredField(fieldName);
    } catch (Exception e) {
    }       

    if (result == null) {
        Class<?> superclass = type.getSuperclass();     
        if (superclass != null && !superclass.getName().equals("java.lang.Object")) {       
            return getDeclaredField(fieldName, type.getSuperclass());
        }
    }
    return result;
}

How to implement if-else statement in XSLT?

You have to reimplement it using <xsl:choose> tag:

       <xsl:choose>
         <xsl:when test="$CreatedDate > $IDAppendedDate">
           <h2> mooooooooooooo </h2>
         </xsl:when>
         <xsl:otherwise>
          <h2> dooooooooooooo </h2>
         </xsl:otherwise>
       </xsl:choose>

How do I read an attribute on a class at runtime?

I used Darin Dimitrov's answer to create a generic extension to get member attributes for any member in a class (instead of attributes for a class). I'm posting it here because others may find it useful:

public static class AttributeExtensions
{
    /// <summary>
    /// Returns the value of a member attribute for any member in a class.
    ///     (a member is a Field, Property, Method, etc...)    
    /// <remarks>
    /// If there is more than one member of the same name in the class, it will return the first one (this applies to overloaded methods)
    /// </remarks>
    /// <example>
    /// Read System.ComponentModel Description Attribute from method 'MyMethodName' in class 'MyClass': 
    ///     var Attribute = typeof(MyClass).GetAttribute("MyMethodName", (DescriptionAttribute d) => d.Description);
    /// </example>
    /// <param name="type">The class that contains the member as a type</param>
    /// <param name="MemberName">Name of the member in the class</param>
    /// <param name="valueSelector">Attribute type and property to get (will return first instance if there are multiple attributes of the same type)</param>
    /// <param name="inherit">true to search this member's inheritance chain to find the attributes; otherwise, false. This parameter is ignored for properties and events</param>
    /// </summary>    
    public static TValue GetAttribute<TAttribute, TValue>(this Type type, string MemberName, Func<TAttribute, TValue> valueSelector, bool inherit = false) where TAttribute : Attribute
    {
        var att = type.GetMember(MemberName).FirstOrDefault().GetCustomAttributes(typeof(TAttribute), inherit).FirstOrDefault() as TAttribute;
        if (att != null)
        {
            return valueSelector(att);
        }
        return default(TValue);
    }
}

Usage example:

//Read System.ComponentModel Description Attribute from method 'MyMethodName' in class 'MyClass'
var Attribute = typeof(MyClass).GetAttribute("MyMethodName", (DescriptionAttribute d) => d.Description);

JavaScript: changing the value of onclick with or without jQuery

Note that following gnarf's idea you can also do:

var js = "alert('B:' + this.id); return false;";<br/>
var newclick = eval("(function(){"+js+"});");<br/>
$("a").get(0).onclick = newclick;

That will set the onclick without triggering the event (had the same problem here and it took me some time to find out).

Aligning two divs side-by-side

The HTML code is for three div align side by side and can be used for two also by some changes

<div id="wrapper">
  <div id="first">first</div>
  <div id="second">second</div>
  <div id="third">third</div>
</div>

The CSS will be

#wrapper {
  display:table;
  width:100%;
}
#row {
  display:table-row;
}
#first {
  display:table-cell;
  background-color:red;
  width:33%;
}
#second {
  display:table-cell;
  background-color:blue;
  width:33%;
}
#third {
  display:table-cell;
  background-color:#bada55;
  width:34%;
}

This code will workup towards responsive layout as it will resize the

<div> 

according to device width. Even one can silent anyone

<div>

as

<!--<div id="third">third</div> --> 

and can use rest two for two

<div> 

side by side.

make a header full screen (width) css

html:

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css"
</head>
<body>
<ul class="menu">
    <li><a href="#">My Dashboard</a>
        <ul>
            <li><a href="#" class="learn">Learn</a></li>
            <li><a href="#" class="teach">Teach</a></li>
            <li><a href="#" class="Mylibrary">My Library</a></li>
        </ul>
    </li>
    <li><a href="#">Likes</a>
        <ul>
            <li><a href="#" class="Pics">Pictures</a></li>
            <li><a href="#" class="audio">Audio</a></li>
            <li><a href="#" class="Videos">Videos</a></li>
        </ul>
</li>
    <li><a href="#">Views</a>
        <ul>
            <li><a href="#" class="documents">Documents</a></li>
            <li><a href="#" class="messages">Messages</a></li>
            <li><a href="#" class="signout">Videos</a></li>
        </ul>
    </li>
        <li><a href="#">account</a>
        <ul>
            <li><a href="#" class="SI">Sign In</a></li>
            <li><a href="#" class="Reg">Register</a></li>
            <li><a href="#" class="Deactivate">Deactivate</a></li>
        </ul>
    </li>
    <li><a href="#">Uploads</a>
        <ul>
            <li><a href="#" class="Pics">Pictures</a></li>
            <li><a href="#" class="audio">Audio</a></li>
            <li><a href="#" class="Videos">Videos</a></li>
        </ul>
    </li>
    <li><a href="#">Videos</a>
    <ul>
            <li><a href="#" class="Add">Add</a></li>
            <li><a href="#" class="delete">Delete</a></li>
    </ul>
    </li>
    <li><a href="#">Documents</a>
    <ul>
            <li><a href="#" class="Add">Upload</a></li>
            <li><a href="#" class="delete">Download</a></li>
    </ul>
    </li>
</ul>
</body>
</html>

css:

.menu,
.menu ul,
.menu li,
.menu a {
    margin: 0;
    padding: 0;
    border: none;
    outline: none;
}
body{
    max-width:110%;
    margin-left:0;
}
.menu {
    height: 40px;
    width:110%;
    margin-left:-4px;
    margin-top:-10px;

    background: #4c4e5a;
    background: -webkit-linear-gradient(top, #4c4e5a 0%,#2c2d33 100%);
    background: -moz-linear-gradient(top, #4c4e5a 0%,#2c2d33 100%);
    background: -o-linear-gradient(top, #4c4e5a 0%,#2c2d33 100%);
    background: -ms-linear-gradient(top, #4c4e5a 0%,#2c2d33 100%);
    background: linear-gradient(top, #4c4e5a 0%,#2c2d33 100%);

    -webkit-border-radius: 5px;
    -moz-border-radius: 5px;
    border-radius: 5px;
}
.menu li {
    position: relative;
    list-style: none;
    float: left;
    display: block;
    height: 40px;
}
.menu li a {
    display: block;
    padding: 0 14px;
    margin: 6px 0;
    line-height: 28px;
    text-decoration: none;

    border-left: 1px solid #393942;
    border-right: 1px solid #4f5058;

    font-family: Helvetica, Arial, sans-serif;
    font-weight: bold;
    font-size: 13px;

    color: #f3f3f3;
    text-shadow: 1px 1px 1px rgba(0,0,0,.6);

    -webkit-transition: color .2s ease-in-out;
    -moz-transition: color .2s ease-in-out;
    -o-transition: color .2s ease-in-out;
    -ms-transition: color .2s ease-in-out;
    transition: color .2s ease-in-out;
}

.menu li:first-child a { border-left: none; }
.menu li:last-child a{ border-right: none; }

.menu li:hover > a { color: #8fde62; }
.menu ul {
    position: absolute;
    top: 40px;
    left: 0;

    opacity: 0;
    background: #1f2024;

    -webkit-border-radius: 0 0 5px 5px;
    -moz-border-radius: 0 0 5px 5px;
    border-radius: 0 0 5px 5px;

    -webkit-transition: opacity .25s ease .1s;
    -moz-transition: opacity .25s ease .1s;
    -o-transition: opacity .25s ease .1s;
    -ms-transition: opacity .25s ease .1s;
    transition: opacity .25s ease .1s;
}

.menu li:hover > ul { opacity: 1; }

.menu ul li {
    height: 0;
    overflow: hidden;
    padding: 0;

    -webkit-transition: height .25s ease .1s;
    -moz-transition: height .25s ease .1s;
    -o-transition: height .25s ease .1s;
    -ms-transition: height .25s ease .1s;
    transition: height .25s ease .1s;
}

.menu li:hover > ul li {
    height: 36px;
    overflow: visible;
    padding: 0;
}

.menu ul li a {
    width: 100px;
    padding: 4px 0 4px 40px;
    margin: 0;

    border: none;
    border-bottom: 1px solid #353539;
}

.menu ul li:last-child a { border: none; }

demo here

try also resizing the browser tab to see it in action

How do I disable TextBox using JavaScript?

With the help of jquery it can be done as follows.

$("#color").prop('disabled', true);

Background images: how to fill whole div if image is small and vice versa

To automatically enlarge the image and cover the entire div section without leaving any part of it unfilled, use:

background-size: cover;

List of Java processes

jps -lV

is most useful. Prints just pid and qualified main class name:

2472 com.intellij.idea.Main
11111 sun.tools.jps.Jps
9030 play.server.Server
2752 org.jetbrains.idea.maven.server.RemoteMavenServer

Count number of 1's in binary representation

The function takes an int and returns the number of Ones in binary representation

public static int findOnes(int number)
{

   if(number < 2)
    {
        if(number == 1)
        {
            count ++;
        }
        else
        {
            return 0;
        }
    }

    value = number % 2;

    if(number != 1 && value == 1)
        count ++;

    number /= 2;

    findOnes(number);

    return count;
}

find vs find_by vs where

The best part of working with any open source technology is that you can inspect length and breadth of it. Checkout this link

find_by ~> Finds the first record matching the specified conditions. There is no implied ordering so if order matters, you should specify it yourself. If no record is found, returns nil.

find ~> Finds the first record matching the specified conditions , but if no record is found, it raises an exception but that is done deliberately.

Do checkout the above link, it has all the explanation and use cases for the following two functions.

Getting the difference between two sets

You can make a union using .addAll(), and an intersection using .retainAll(), of the two sets and use .removeIf(), to remove the intersection (or the duplicated element) from the union.

HashSet union = new HashSet(group1);
union.addAll(group2);
        
System.out.println("Union: " + union);
        
HashSet intersection = new HashSet(group1);
intersection.retainAll(group2);
        
System.out.println("Intersection: " + intersection);
        
HashSet difference = new HashSet(union);
difference.removeIf(n -> (difference.contains(intersection)));
        
System.out.println("Difference: " + difference);

How do I call Objective-C code from Swift?

After you created a Bridging header, go to Build Setting => Search for "Objective-C Bridging Header".

Just below you will find the ""Objective-C Generated Interface Header Name" file.

Import that file in your view controller.

Example: In my case: "Dauble-Swift.h"

eEter image description here

Need to get current timestamp in Java

Print a Timestamp in java, using the java.sql.Timestamp.

import java.sql.Timestamp;
import java.util.Date;

public class GetCurrentTimeStamp {
    public static void main( String[] args ){
        java.util.Date date= new java.util.Date();
        System.out.println(new Timestamp(date.getTime()));
    }
}

This prints:

2014-08-07 17:34:16.664

Print a Timestamp in Java using SimpleDateFormat on a one-liner.

import java.util.Date;
import java.text.SimpleDateFormat;

class Runner{
    public static void main(String[] args){

        System.out.println(
            new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").format(new Date()));

    }

}

Prints:

08/14/2014 14:10:38

Java date format legend:

G Era designation      Text               AD
y Year                 Year               1996; 96
M Month in year        Month              July; Jul; 07
w Week in year         Number             27
W Week in month        Number             2
D Day in year          Number             189
d Day in month         Number             10
F Day of week in month Number             2
E Day in week          Text               Tuesday; Tue
a Am/pm marker         Text               PM
H Hour in day (0-23)   Number             0
k Hour in day (1-24)   Number             24
K Hour in am/pm (0-11) Number             0
h Hour in am/pm (1-12) Number             12
m Minute in hour       Number             30
s Second in minute     Number             55
S Millisecond          Number             978
z Time zone            General time zone  Pacific Standard Time; PST; GMT-08:00
Z Time zone            RFC 822 time zone  -0800

How can I start pagenumbers, where the first section occurs in LaTex?

You can also reset page number counter:

\setcounter{page}{1}

However, with this technique you get wrong page numbers in Acrobat in the top left page numbers field:

\maketitle: 1
\tableofcontents: 2
\setcounter{page}{1}
\section{Introduction}: 1
...

What is the difference between json.dumps and json.load?

json loads -> returns an object from a string representing a json object.

json dumps -> returns a string representing a json object from an object.

load and dump -> read/write from/to file instead of string

Finding the median of an unsorted array

The answer is "No, one can't find the median of an arbitrary, unsorted dataset in linear time". The best one can do as a general rule (as far as I know) is Median of Medians (to get a decent start), followed by Quickselect. Ref: [https://en.wikipedia.org/wiki/Median_of_medians][1]

Xcode 5.1 - No architectures to compile for (ONLY_ACTIVE_ARCH=YES, active arch=x86_64, VALID_ARCHS=i386)

To avoid having "pod install" reset only_active_arch for debug each time it's run, you can add the following to your pod file

# Append to your Podfile
post_install do |installer_representation|
    installer_representation.project.targets.each do |target|
        target.build_configurations.each do |config|
            config.build_settings['ONLY_ACTIVE_ARCH'] = 'NO'
        end
    end
end

Remove large .pack file created by git

Scenario A: If your large files were only added to a branch, you don't need to run git filter-branch. You just need to delete the branch and run garbage collection:

git branch -D mybranch
git reflog expire --expire-unreachable=all --all
git gc --prune=all

Scenario B: However, it looks like based on your bash history, that you did merge the changes into master. If you haven't shared the changes with anyone (no git push yet). The easiest thing would be to reset master back to before the merge with the branch that had the big files. This will eliminate all commits from your branch and all commits made to master after the merge. So you might lose changes -- in addition to the big files -- that you may have actually wanted:

git checkout master
git log # Find the commit hash just before the merge
git reset --hard <commit hash>

Then run the steps from the scenario A.

Scenario C: If there were other changes from the branch or changes on master after the merge that you want to keep, it would be best to rebase master and selectively include commits that you want:

git checkout master
git log # Find the commit hash just before the merge
git rebase -i <commit hash>

In your editor, remove lines that correspond to the commits that added the large files, but leave everything else as is. Save and quit. Your master branch should only contain what you want, and no large files. Note that git rebase without -p will eliminate merge commits, so you'll be left with a linear history for master after <commit hash>. This is probably okay for you, but if not, you could try with -p, but git help rebase says combining -p with the -i option explicitly is generally not a good idea unless you know what you are doing.

Then run the commands from scenario A.

Exiting from python Command Line

In my python interpreter exit is actually a string and not a function -- 'Use Ctrl-D (i.e. EOF) to exit.'. You can check on your interpreter by entering type(exit)

In active python what is happening is that exit is a function. If you do not call the function it will print out the string representation of the object. This is the default behaviour for any object returned. It's just that the designers thought people might try to type exit to exit the interpreter, so they made the string representation of the exit function a helpful message. You can check this behaviour by typing str(exit) or even print exit.

What to do with commit made in a detached head

This is what I did:

Basically, think of the detached HEAD as a new branch, without name. You can commit into this branch just like any other branch. Once you are done committing, you want to push it to the remote.

So the first thing you need to do is give this detached HEAD a name. You can easily do it like, while being on this detached HEAD:

git checkout -b some-new-branch

Now you can push it to remote like any other branch.

In my case, I also wanted to fast-forward this branch to master along with the commits I made in the detached HEAD (now some-new-branch). All I did was

git checkout master

git pull # To make sure my local copy of master is up to date

git checkout some-new-branch

git merge master // This added current state of master to my changes

Of course, I merged it later to master.

That's about it.

"An attempt was made to load a program with an incorrect format" even when the platforms are the same

I just had this problem also. Tried all the suggestions here, but they didn't help.

I found another thing to check that fixed it for me. In Visual Studio, right-click on the project and open "Properties". Click on the "Compile" (or "Build") tab and then click on "Advanced Compile Options" at the bottom.

Check the dropdown "Target CPU". It should match the "Platform" you are building. That is, if you are building "Any CPU" then "Target CPU" should say "Any CPU". Go through all of your Platforms by making them active and check this setting.

Update a local branch with the changes from a tracked remote branch

You don't use the : syntax - pull always modifies the currently checked-out branch. Thus:

git pull origin my_remote_branch

while you have my_local_branch checked out will do what you want.

Since you already have the tracking branch set, you don't even need to specify - you could just do...

git pull

while you have my_local_branch checked out, and it will update from the tracked branch.

Git's famous "ERROR: Permission to .git denied to user"

I had the same problem as you. After a long time spent Googling, I found out my error was caused by multiple users that had added the same key in their accounts.

So, here is my solution: delete the wrong-user's ssh-key (I can do it because the wrong-user is also my account). If the wrong-user isn't your account, you may need to change your ssh-key, but I don't think this gonna happen.

And I think your problem may be caused by a mistyping error in your accounts name.

How can I display a tooltip on an HTML "option" tag?

It seems in the 2 years since this was asked, the other browsers have caught up (at least on Windows... not sure about others). You can set a "title" attribute on the option tag:

<option value="" title="Tooltip">Some option</option>

This worked in Chrome 20, IE 9 (and its 8 & 7 modes), Firefox 3.6, RockMelt 16 (Chromium based) all on Windows 7

How to install libusb in Ubuntu

Here is what worked for me.

Install the userspace USB programming library development files

sudo apt-get install libusb-1.0-0-dev
sudo updatedb && locate libusb.h

The path should appear as (or similar)

/usr/include/libusb-1.0/libusb.h

Include the header to your C code

#include <libusb-1.0/libusb.h>

Compile your C file

gcc -o example example.c -lusb-1.0

Send data from javascript to a mysql database

You will have to submit this data to the server somehow. I'm assuming that you don't want to do a full page reload every time a user clicks a link, so you'll have to user XHR (AJAX). If you are not using jQuery (or some other JS library) you can read this tutorial on how to do the XHR request "by hand".

Passing a variable from one php include file to another: global vs. not

Here is a pitfall to avoid. In case you need to access your variable $name within a function, you need to say "global $name;" at the beginning of that function. You need to repeat this for each function in the same file.

include('front.inc');
global $name;

function foo() {
  echo $name;
}

function bar() {
  echo $name;
}

foo();
bar();

will only show errors. The correct way to do that would be:

include('front.inc');

function foo() {
  global $name;
  echo $name;
}

function bar() {
  global $name;
  echo $name;
}

foo();
bar();

Entity framework code-first null foreign key

I prefer this (below):

public class User
{
    public int Id { get; set; }
    public int? CountryId { get; set; }
    [ForeignKey("CountryId")]
    public virtual Country Country { get; set; }
}

Because EF was creating 2 foreign keys in the database table: CountryId, and CountryId1, but the code above fixed that.

Check list of words in another string

if any(word in 'some one long two phrase three' for word in list_):

PHP class not found but it's included

I had this problem and the solution was namespaces. The included file was included in its own namespace. Obvious thing, easy to overlook.

Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect)

First check your imports, when you use session, transaction it should be org.hibernate and remove @Transactinal annotation. and most important in Entity class if you have used @GeneratedValue(strategy=GenerationType.AUTO) or any other then at the time of model object creation/entity object creation should not create id. final conclusion is if you want pass id filed i.e PK then remove @GeneratedValue from entity class.

SQL SELECT multi-columns INTO multi-variable

SELECT @var = col1,
       @var2 = col2
FROM   Table

Here is some interesting information about SET / SELECT

  • SET is the ANSI standard for variable assignment, SELECT is not.
  • SET can only assign one variable at a time, SELECT can make multiple assignments at once.
  • If assigning from a query, SET can only assign a scalar value. If the query returns multiple values/rows then SET will raise an error. SELECT will assign one of the values to the variable and hide the fact that multiple values were returned (so you'd likely never know why something was going wrong elsewhere - have fun troubleshooting that one)
  • When assigning from a query if there is no value returned then SET will assign NULL, where SELECT will not make the assignment at all (so the variable will not be changed from it's previous value)
  • As far as speed differences - there are no direct differences between SET and SELECT. However SELECT's ability to make multiple assignments in one shot does give it a slight speed advantage over SET.

Passing on command line arguments to runnable JAR

When you run your application this way, the java excecutable read the MANIFEST inside your jar and find the main class you defined. In this class you have a static method called main. In this method you may use the command line arguments.

How to disable scrolling the document body?

I know this is an ancient question, but I just thought that I'd weigh in.

I'm using disableScroll. Simple and it works like in a dream.

I have had some trouble disabling scroll on body, but allowing it on child elements (like a modal or a sidebar). It looks like that something can be done using disableScroll.on([element], [options]);, but I haven't gotten that to work just yet.


The reason that this is prefered compared to overflow: hidden; on body is that the overflow-hidden can get nasty, since some things might add overflow: hidden; like this:

... This is good for preloaders and such, since that is rendered before the CSS is finished loading.

But it gives problems, when an open navigation should add a class to the body-tag (like <body class="body__nav-open">). And then it turns into one big tug-of-war with overflow: hidden; !important and all kinds of crap.

Upgrading PHP in XAMPP for Windows?

http://www.apachefriends.org/en/xampp-windows.html

In this site you can get

XAMPP Add-Ons

by using this add on you can upgrade the latest versions.

Which is faster: Stack allocation or Heap allocation

A stack has a limited capacity, while a heap is not. The typical stack for a process or thread is around 8K. You cannot change the size once it's allocated.

A stack variable follows the scoping rules, while a heap one doesn't. If your instruction pointer goes beyond a function, all the new variables associated with the function go away.

Most important of all, you can't predict the overall function call chain in advance. So a mere 200 bytes allocation on your part may raise a stack overflow. This is especially important if you're writing a library, not an application.

JavaScript: clone a function

I've impoved Jared's answer in my own manner:

    Function.prototype.clone = function() {
        var that = this;
        function newThat() {
            return (new that(
                arguments[0],
                arguments[1],
                arguments[2],
                arguments[3],
                arguments[4],
                arguments[5],
                arguments[6],
                arguments[7],
                arguments[8],
                arguments[9]
            ));
        }
        function __clone__() {
            if (this instanceof __clone__) {
                return newThat.apply(null, arguments);
            }
            return that.apply(this, arguments);
        }
        for(var key in this ) {
            if (this.hasOwnProperty(key)) {
                __clone__[key] = this[key];
            }
        }
        return __clone__;
    };

1) now it supports cloning of constructors (can call with new); in that case takes only 10 arguments (you can vary it) - due to impossibility of passing all arguments in original constructor

2) everything is in correct closures

React: Expected an assignment or function call and instead saw an expression

In my case the problem was the line with default instructions in switch block:

  handlePageChange = ({ btnType}) => {
    let { page } = this.state;
    switch (btnType) {
      case 'next':
        this.updatePage(page + 1);
        break;
      case 'prev':
        this.updatePage(page - 1);
        break;
      default: null;
    } 
  }

Instead of

default: null;

The line

default: ;

worked for me.

'const int' vs. 'int const' as function parameters in C++ and C

Prakash is correct that the declarations are the same, although a little more explanation of the pointer case might be in order.

"const int* p" is a pointer to an int that does not allow the int to be changed through that pointer. "int* const p" is a pointer to an int that cannot be changed to point to another int.

See https://isocpp.org/wiki/faq/const-correctness#const-ptr-vs-ptr-const.

How do you remove an array element in a foreach loop?

There are already answers which are giving light on how to unset. Rather than repeating code in all your classes make function like below and use it in code whenever required. In business logic, sometimes you don't want to expose some properties. Please see below one liner call to remove

public static function removeKeysFromAssociativeArray($associativeArray, $keysToUnset)
{
    if (empty($associativeArray) || empty($keysToUnset))
        return array();

    foreach ($associativeArray as $key => $arr) {
        if (!is_array($arr)) {
            continue;
        }

        foreach ($keysToUnset as $keyToUnset) {
            if (array_key_exists($keyToUnset, $arr)) {
                unset($arr[$keyToUnset]);
            }
        }
        $associativeArray[$key] = $arr;
    }
    return $associativeArray;
}

Call like:

removeKeysFromAssociativeArray($arrValues, $keysToRemove);

Difference between if () { } and if () : endif;

Both are the same.

But: If you want to use PHP as your templating language in your view files(the V of MVC) you can use this alternate syntax to distinguish between php code written to implement business-logic (Controller and Model parts of MVC) and gui-logic. Of course it is not mandatory and you can use what ever syntax you like.

ZF uses that approach.

How to split a line into words separated by one or more spaces in bash?

More simple,

echo $line | sed 's/\s/\n/g'

\s --> whitespace character (space, tab, NL, FF, VT, CR). In many systems also valid [:space:]

\n --> new line

How to set min-height for bootstrap container

Two things are happening here.

  1. You are not using the container class properly.
  2. You are trying to override Bootstrap's CSS for the container class

Bootstrap uses a grid system and the .container class is defined in its own CSS. The grid has to exist within a container class DIV. The container DIV is just an indication to Bootstrap that the grid within has that parent. Therefore, you cannot set the height of a container.

What you want to do is the following:

<div class="container-fluid"> <!-- this is to make it responsive to your screen width -->
    <div class="row">
        <div class="col-md-4 myClassName">  <!-- myClassName is defined in my CSS as you defined your container -->
            <img src="#.jpg" height="200px" width="300px">
        </div>
    </div>
</div>

Here you can find more info on the Bootstrap grid system.

That being said, if you absolutely MUST override the Bootstrap CSS then I would try using the "!important" clause to my CSS definition as such...

.container {
   padding-right: 15px;
   padding-left: 15px;
   margin-right: auto;
   margin-left: auto;
   max-width: 900px;
   overflow:hidden;
   min-height:0px !important;
}

But I have always found that the "!important" clause just makes for messy CSS.

HTML input fields does not get focus when clicked

When you say

and nope, they don't have attributes: disabled="disabled" or readonly ;-)

Is this through viewing your html, the source code of the page, or the DOM?

If you inspect the DOM with Chrome or Firefox, then you will be able to see any attributes added to the input fields through javasript, or even an overlaying div

SSIS Connection not found in package

The previous remarks about deleting or removing a connection are absolutely a possibility. But you can also get this error when you attempt to invoke a package that uses project level connections (instead of package level connections).

If you are using project level connections and still want to use dtexec, never fear there is a way. I would not recommend converting them to package level connections (assuming you created them as project level connections for a good reason).

You will need to deploy your SSIS project. Your SSIS server will need to have a catalog created (https://msdn.microsoft.com/en-us/library/gg471509.aspx). Once you have the catalog, in your SSIS project select Project->Deploy and follow the wizard. The result will be a *.ispac file generated in your SSIS solution folder/bin/Development

Now for the money command, instead of invoking your package with a simple: dtexec.exe /f "package.dtsx"

instead call it this way: dtexec.exe /project "<...>/project.ispac" /package "<...>/package.dtsx"

The ispac file has the project level connection info that is needed to execute your package and you should be set!

Cannot open include file: 'unistd.h': No such file or directory

The "uni" in unistd stands for "UNIX" - you won't find it on a Windows system.

Most widely used, portable libraries should offer alternative builds or detect the platform and only try to use headers/functions that will be provided, so it's worth checking documentation to see if you've missed some build step - e.g. perhaps running "make" instead of loading a ".sln" Visual C++ solution file.

If you need to fix it yourself, remove the include and see which functions are actually needed, then try to find a Windows equivalent.

How to export JavaScript array info to csv (on client side)?

This is a modified answer based on the accepted answer wherein the data would be coming from JSON.

            JSON Data Ouptut:
             0 :{emails: "SAMPLE Co., [email protected]"}, 1:{emails: "Another CO. , [email protected]"}


            JS:
            $.getJSON('yourlink_goes_here', { if_you_have_parameters}, function(data) {
            var csvContent = "data:text/csv;charset=utf-8,";
            var dataString = '';
             $.each(data, function(k, v) {
                dataString += v.emails + "\n";
             });

            csvContent += dataString;

            var encodedUri = encodeURI(csvContent);
            var link = document.createElement("a");
            link.setAttribute("href", encodedUri);
            link.setAttribute("download", "your_filename.csv");
            document.body.appendChild(link); // Required for FF

            link.click();
        });

How to use pip with python 3.4 on windows?

"py -m pip install requests" works fine with Windows and its up gradation. Just change the path after installing Python 3.4 in the command prompt and type in "py -m pip install requests"command prompt. pip install

Authenticate with GitHub using a token

I'm on Ubuntu 20.04 and I kept getting the message that soon I wouldn't be able to login from console. I was terribly confused. Finally, I got to the URL below which will work. But you need to know how to create a PAT (Personal Access Token) which you are going to have to keep in a file on your computer.

Here's what the final URL will look like:

git push https://[email protected]/user-name/repo.git

long PAT (Personal Access Token) value -- The entire long value between the // and the @ sign in the url is your PAT.

user-name will be your exact username

repo.git will be your exact repo name

You need to generate a PAT following the steps at: https://docs.github.com/en/github/authenticating-to-github/creating-a-personal-access-token

That will give you the PAT value that you will place in your URL.

When you create the PAT make sure you choose the following options so it has the ability to allow you to manage your REPOs. PAT settings

Save Your PAT Or Lose It

Once you have your PAT. You're going to need to save it in a file locally so you can use it again. If you don't save it somewhere there is no way to ever see it again and you'll be forced to create a new PAT

Now you're going to need at the very least :

  1. a way to display it in your console so you can see it again.
  2. or, A way to copy it to your clipboard automatically.

For 1, just use :

$ cat ~/files/myPatFile.txt

Where the path is a real path to the location and file where you stored your PAT value.

For 2

$ xclip -selection clipboard < ~/files/myPatFile.txt

That'll copy the contents of the file to the clipboard so you can use your PAT more easily.

FYI - if you don't have xclip do the following:

$ sudo apt-get install xclip

Downloads and installs xclip. If you don't have apt-get, you might need to use another installer (like yum)

Iterate over model instance field names and values in template

There should really be a built-in way to do this. I wrote this utility build_pretty_data_view that takes a model object and form instance (a form based on your model) and returns a SortedDict.

Benefits to this solution include:

  • It preserves order using Django's built-in SortedDict.
  • When tries to get the label/verbose_name, but falls back to the field name if one is not defined.
  • It will also optionally take an exclude() list of field names to exclude certain fields.
  • If your form class includes a Meta: exclude(), but you still want to return the values, then add those fields to the optional append() list.

To use this solution, first add this file/function somewhere, then import it into your views.py.

utils.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ai ts=4 sts=4 et sw=4
from django.utils.datastructures import SortedDict


def build_pretty_data_view(form_instance, model_object, exclude=(), append=()):
    i=0
    sd=SortedDict()

    for j in append:
        try:
            sdvalue={'label':j.capitalize(),
                     'fieldvalue':model_object.__getattribute__(j)}
            sd.insert(i, j, sdvalue)
            i+=1
        except(AttributeError):
            pass

    for k,v in form_instance.fields.items():
        sdvalue={'label':"", 'fieldvalue':""}
        if not exclude.__contains__(k):
            if v.label is not None:
                sdvalue = {'label':v.label,
                           'fieldvalue': model_object.__getattribute__(k)}
            else:
                sdvalue = {'label':k,
                           'fieldvalue': model_object.__getattribute__(k)}
            sd.insert(i, k, sdvalue)
            i+=1
    return sd

So now in your views.py you might do something like this

from django.shortcuts import render_to_response
from django.template import RequestContext
from utils import build_pretty_data_view
from models import Blog
from forms import BlogForm
.
.
def my_view(request):
   b=Blog.objects.get(pk=1)
   bf=BlogForm(instance=b)
   data=build_pretty_data_view(form_instance=bf, model_object=b,
                        exclude=('number_of_comments', 'number_of_likes'),
                        append=('user',))

   return render_to_response('my-template.html',
                          RequestContext(request,
                                         {'data':data,}))

Now in your my-template.html template you can iterate over the data like so...

{% for field,value in data.items %}

    <p>{{ field }} : {{value.label}}: {{value.fieldvalue}}</p>

{% endfor %}

Good Luck. Hope this helps someone!

How do I drag and drop files into an application?

Be aware of windows vista/windows 7 security rights - if you are running Visual Studio as administrator, you will not be able to drag files from a non-administrator explorer window into your program when you run it from within visual studio. The drag related events will not even fire! I hope this helps somebody else out there not waste hours of their life...

Angular2: custom pipe could not be found

If you are declaring your pipe in another module, make sure to add it to that module Declarations and Exports array, then import that module in whatever module is consuming that pipe.

How do you round to 1 decimal place in Javascript?

function rnd(v,n=2) {
    return Math.round((v+Number.EPSILON)*Math.pow(10,n))/Math.pow(10,n)
}

this one catch the corner cases well

SELECT list is not in GROUP BY clause and contains nonaggregated column .... incompatible with sql_mode=only_full_group_by

Use any one solution (out of below 3)

(1) PHPMyAdmin

if you are using phpMyAdmin then change the "sql_mode" setting as mentioned in the below screenshot. enter image description here

Edit "sql mode" variable and remove the "ONLY_FULL_GROUP_BY" text from the value

OR

(2) SQL/Command prompt Run the below command.

SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));

OR

(3) Don't use SELECT *

Use relevant column in SELECT query. relevant means columns, which are either coming in "group by" clause or column with the aggregate function (MAX, MIN, SUM, COUNT etc)


Important note

Changes made by using point(1) OR point(2) does not set it PERMANENTLY, and it will revert after every restart.

So you should set this in your config file (e.g. /etc/mysql/my.cnf in the [mysqld] section), so that the changes remain in effect after MySQL restart:

Config File: /etc/mysql/my.cnf

Variable name : sql_mode OR sql-mode

Remove word ONLY_FULL_GROUP_BY from the value and save the file.

Note : If you have not found "sql_mode" variable in the config file than please insert below 2 lines at the end of the file

[mysqld]
sql_mode = STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION

Laravel 5 route not defined, while it is?

I'm using Laravel 5.7 and tried all of the above answers but nothing seemed to be hitting the spot.

For me, it was a rather simple fix by removing the cache files created by Laravel.
It seemed that my changes were not being reflected, and therefore my application wasn't seeing the routes.

A bit overkill, but I decided to reset all my cache at the same time using the following commands:

php artisan route:clear
php artisan view:clear
php artisan cache:clear

The main one here is the first command which will delete the bootstrap/cache/routes.php file.
The second command will remove the cached files for the views that are stored in the storage/framework/cache folder.
Finally, the last command will clear the application cache.

How to read values from the querystring with ASP.NET Core?

I have a better solution for this problem,

  • request is a member of abstract class ControllerBase
  • GetSearchParams() is an extension method created in bellow helper class.

var searchparams = await Request.GetSearchParams();

I have created a static class with few extension methods

public static class HttpRequestExtension
{
  public static async Task<SearchParams> GetSearchParams(this HttpRequest request)
        {
            var parameters = await request.TupledParameters();

            try
            {
                for (var i = 0; i < parameters.Count; i++)
                {
                    if (parameters[i].Item1 == "_count" && parameters[i].Item2 == "0")
                    {
                        parameters[i] = new Tuple<string, string>("_summary", "count");
                    }
                }
                var searchCommand = SearchParams.FromUriParamList(parameters);
                return searchCommand;
            }
            catch (FormatException formatException)
            {
                throw new FhirException(formatException.Message, OperationOutcome.IssueType.Invalid, OperationOutcome.IssueSeverity.Fatal, HttpStatusCode.BadRequest);
            }
        }



public static async Task<List<Tuple<string, string>>> TupledParameters(this HttpRequest request)
{
        var list = new List<Tuple<string, string>>();


        var query = request.Query;
        foreach (var pair in query)
        {
            list.Add(new Tuple<string, string>(pair.Key, pair.Value));
        }

        if (!request.HasFormContentType)
        {
            return list;
        }
        var getContent = await request.ReadFormAsync();

        if (getContent == null)
        {
            return list;
        }
        foreach (var key in getContent.Keys)
        {
            if (!getContent.TryGetValue(key, out StringValues values))
            {
                continue;
            }
            foreach (var value in values)
            {
                list.Add(new Tuple<string, string>(key, value));
            }
        }
        return list;
    }
}

in this way you can easily access all your search parameters. I hope this will help many developers :)

Purpose of "%matplotlib inline"

If you want to add plots to your Jupyter notebook, then %matplotlib inline is a standard solution. And there are other magic commands will use matplotlib interactively within Jupyter.

%matplotlib: any plt plot command will now cause a figure window to open, and further commands can be run to update the plot. Some changes will not draw automatically, to force an update, use plt.draw()

%matplotlib notebook: will lead to interactive plots embedded within the notebook, you can zoom and resize the figure

%matplotlib inline: only draw static images in the notebook

Trying to use fetch and pass in mode: no-cors

So if you're like me and developing a website on localhost where you're trying to fetch data from Laravel API and use it in your Vue front-end, and you see this problem, here is how I solved it:

  1. In your Laravel project, run command php artisan make:middleware Cors. This will create app/Http/Middleware/Cors.php for you.
  2. Add the following code inside the handles function in Cors.php:

    return $next($request)
        ->header('Access-Control-Allow-Origin', '*')
        ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    
  3. In app/Http/kernel.php, add the following entry in $routeMiddleware array:

    ‘cors’ => \App\Http\Middleware\Cors::class
    

    (There would be other entries in the array like auth, guest etc. Also make sure you're doing this in app/Http/kernel.php because there is another kernel.php too in Laravel)

  4. Add this middleware on route registration for all the routes where you want to allow access, like this:

    Route::group(['middleware' => 'cors'], function () {
        Route::get('getData', 'v1\MyController@getData');
        Route::get('getData2', 'v1\MyController@getData2');
    });
    
  5. In Vue front-end, make sure you call this API in mounted() function and not in data(). Also make sure you use http:// or https:// with the URL in your fetch() call.

Full credits to Pete Houston's blog article.

How To Launch Git Bash from DOS Command Line?

If you want to launch from a batch file:

  • for x86

    start "" "%SYSTEMDRIVE%\Program Files (x86)\Git\bin\sh.exe" --login
    
  • for x64

    start "" "%PROGRAMFILES%\Git\bin\sh.exe" --login
    

What file uses .md extension and how should I edit them?

Github's Atom text editor has a live-preview mode for markdown files.

The keyboard shortcut is CTRL+SHIFT+M.

It can be activated from the editor using the CTRL+SHIFT+M key-binding and is currently enabled for .markdown, .md, .mkd, .mkdown, and .ron files.

enter image description here

Powershell Log Off Remote Session

Adding plain DOS commands, if someone is so inclined. Yes, this still works for Win 8 and Server 2008 + Server 2012.

Query session /server:Server100

Will return:

SESSIONNAME       USERNAME                 ID  STATE   TYPE        DEVICE
rdp-tcp#0         Bob                       3  Active  rdpwd
rdp-tcp#5         Jim                       9  Active  rdpwd
rdp-tcp                                 65536  Listen

And to log off a session, use:

Reset session 3 /server:Server100

Convert HTML + CSS to PDF

I've tried a lot of different libraries for PHP. All the listed I've tried. In my opinion TCPDF library is the best compromise performance/usability. It's very simply to install and use, also good performance in small medium application. If you need high performance and very big PDF document, use Zend_PDF module, but get ready to coding hard!

MySQL Cannot Add Foreign Key Constraint

I had set one field as "Unsigned" and other one not. Once I set both columns to Unsigned it worked.

Reading in double values with scanf in c

Using %lf will help you in solving this problem.

Use :

scanf("%lf",&doub)

python dictionary sorting in descending order based on values

Python dicts are not sorted, by definition. You cannot sort one, nor control the order of its elements by how you insert them. You might want to look at collections.OrderDict, which even comes with a little tutorial for almost exactly what you're trying to do: http://docs.python.org/2/library/collections.html#ordereddict-examples-and-recipes

How to update and delete a cookie?

check this out A little framework: a complete cookies reader/writer with full Unicode support

/*\
|*|
|*|  :: cookies.js ::
|*|
|*|  A complete cookies reader/writer framework with full unicode support.
|*|
|*|  Revision #1 - September 4, 2014
|*|
|*|  https://developer.mozilla.org/en-US/docs/Web/API/document.cookie
|*|  https://developer.mozilla.org/User:fusionchess
|*|  https://github.com/madmurphy/cookies.js
|*|
|*|  This framework is released under the GNU Public License, version 3 or later.
|*|  http://www.gnu.org/licenses/gpl-3.0-standalone.html
|*|
|*|  Syntaxes:
|*|
|*|  * docCookies.setItem(name, value[, end[, path[, domain[, secure]]]])
|*|  * docCookies.getItem(name)
|*|  * docCookies.removeItem(name[, path[, domain]])
|*|  * docCookies.hasItem(name)
|*|  * docCookies.keys()
|*|
\*/

var docCookies = {
  getItem: function (sKey) {
    if (!sKey) { return null; }
    return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
  },
  setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
    if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
    var sExpires = "";
    if (vEnd) {
      switch (vEnd.constructor) {
        case Number:
          sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
          break;
        case String:
          sExpires = "; expires=" + vEnd;
          break;
        case Date:
          sExpires = "; expires=" + vEnd.toUTCString();
          break;
      }
    }
    document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
    return true;
  },
  removeItem: function (sKey, sPath, sDomain) {
    if (!this.hasItem(sKey)) { return false; }
    document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "");
    return true;
  },
  hasItem: function (sKey) {
    if (!sKey) { return false; }
    return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
  },
  keys: function () {
    var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
    for (var nLen = aKeys.length, nIdx = 0; nIdx < nLen; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); }
    return aKeys;
  }
};

MySQL error - #1062 - Duplicate entry ' ' for key 2

Seems like the second column is set as a unique index. If you dont need that remove it and your errors will go away. Possibly you added the index by mistake and thats why you are seeing the errors today and werent seeing them yesterday

MySQL & Java - Get id of the last inserted value (JDBC)

Alternatively you can do:

Statement stmt = db.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
numero = stmt.executeUpdate();

ResultSet rs = stmt.getGeneratedKeys();
if (rs.next()){
    risultato=rs.getString(1);
}

But use Sean Bright's answer instead for your scenario.

jQuery - checkbox enable/disable

_x000D_
_x000D_
$jQuery(function() {_x000D_
  enable_cb();_x000D_
  jQuery("#group1").click(enable_cb);_x000D_
});_x000D_
_x000D_
function enable_cb() {_x000D_
  if (this.checked) {_x000D_
    jQuery("input.group1").removeAttr("disabled");_x000D_
  } else {_x000D_
    jQuery("input.group1").attr("disabled", true);_x000D_
  }_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<form name="frmChkForm" id="frmChkForm">_x000D_
  <input type="checkbox" name="chkcc9" id="group1">Check Me <br>_x000D_
  <input type="checkbox" name="chk9[120]" class="group1"><br>_x000D_
  <input type="checkbox" name="chk9[140]" class="group1"><br>_x000D_
  <input type="checkbox" name="chk9[150]" class="group1"><br>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Best practices for SQL varchar column length

Whenever I set up a new SQL table I feel the same way about 2^n being more "even"... but to sum up the answers here, there is no significant impact on storage space simply by defining varchar(2^n) or even varchar(MAX).

That said, you should still anticipate the potential implications on storage and performance when setting a high varchar() limit. For example, let's say you create a varchar(MAX) column to hold product descriptions with full-text indexing. If 99% of descriptions are only 500 characters long, and then suddenly you get somebody who replaces said descriptions with wikipedia articles, you may notice unanticipated significant storage and performance hits.

Another thing to consider from Bill Karwin:

There's one possible performance impact: in MySQL, temporary tables and MEMORY tables store a VARCHAR column as a fixed-length column, padded out to its maximum length. If you design VARCHAR columns much larger than the greatest size you need, you will consume more memory than you have to. This affects cache efficiency, sorting speed, etc.

Basically, just come up with reasonable business constraints and error on a slightly larger size. As @onedaywhen pointed out, family names in UK are usually between 1-35 characters. If you decide to make it varchar(64), you're not really going to hurt anything... unless you're storing this guy's family name that's said to be up to 666 characters long. In that case, maybe varchar(1028) makes more sense.

And in case it's helpful, here's what varchar 2^5 through 2^10 might look like if filled:

varchar(32)     Lorem ipsum dolor sit amet amet.

varchar(64)     Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donecie

varchar(128)    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donecie
                vestibulum massa. Nullam dignissim elementum molestie. Vehiculas

varchar(256)    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donecie
                vestibulum massa. Nullam dignissim elementum molestie. Vehiculas
                velit metus, sit amet tristique purus condimentum eleifend. Quis
                que mollis magna vel massa malesuada bibendum. Proinde tincidunt

varchar(512)    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donecie
                vestibulum massa. Nullam dignissim elementum molestie. Vehiculas
                velit metus, sit amet tristique purus condimentum eleifend. Quis
                que mollis magna vel massa malesuada bibendum. Proinde tincidunt
                dolor tellus, sit amet porta neque varius vitae. Seduse molestie
                lacus id lacinia tempus. Vestibulum accumsan facilisis lorem, et
                mollis diam pretium gravida. In facilisis vitae tortor id vulput
                ate. Proin ornare arcu in sollicitudin pharetra. Crasti molestie

varchar(1024)   Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donecie
                vestibulum massa. Nullam dignissim elementum molestie. Vehiculas
                velit metus, sit amet tristique purus condimentum eleifend. Quis
                que mollis magna vel massa malesuada bibendum. Proinde tincidunt
                dolor tellus, sit amet porta neque varius vitae. Seduse molestie
                lacus id lacinia tempus. Vestibulum accumsan facilisis lorem, et
                mollis diam pretium gravida. In facilisis vitae tortor id vulput
                ate. Proin ornare arcu in sollicitudin pharetra. Crasti molestie
                dapibus leo lobortis eleifend. Vivamus vitae diam turpis. Vivamu
                nec tristique magna, vel tincidunt diam. Maecenas elementum semi
                quam. In ut est porttitor, sagittis nulla id, fermentum turpist.
                Curabitur pretium nibh a imperdiet cursus. Sed at vulputate este
                proin fermentum pretium justo, ac malesuada eros et Pellentesque
                vulputate hendrerit molestie. Aenean imperdiet a enim at finibus
                fusce ut ullamcorper risus, a cursus massa. Nunc non dapibus vel
                Lorem ipsum dolor sit amet, consectetur Praesent ut ultrices sit

SQL SERVER, SELECT statement with auto generate row id

This will work in SQL Server 2008.

select  top 100 ROW_NUMBER() OVER (ORDER BY tmp.FirstName) ,* from tmp

Cheers

MySQL error 1241: Operand should contain 1 column(s)

Another way to make the parser raise the same exception is the following incorrect clause.

SELECT r.name
FROM roles r
WHERE id IN ( SELECT role_id ,
                     system_user_id
                 FROM role_members m
                 WHERE r.id = m.role_id
                 AND m.system_user_id = intIdSystemUser
             )

The nested SELECT statement in the IN clause returns two columns, which the parser sees as operands, which is technically correct, since the id column matches values from but one column (role_id) in the result returned by the nested select statement, which is expected to return a list.

For sake of completeness, the correct syntax is as follows.

SELECT r.name
FROM roles r
WHERE id IN ( SELECT role_id
                 FROM role_members m
                 WHERE r.id = m.role_id
                 AND m.system_user_id = intIdSystemUser
             )

The stored procedure of which this query is a portion not only parsed, but returned the expected result.

How to use Apple's new .p8 certificate for APNs in firebase console

I was able to do this by selecting "All" located under the "Keys" header from the left column

enter image description here

Then I clicked the plus button in the top right corner to add a new key

enter image description here

Enter a name for your key and check "APNs"

enter image description here

Then scroll down and select Continue. You will then be brought to a screen presenting you with the option to download your .p8 now or later. In my case, I was presented with a warning that it could only be downloaded once so keep the file safe.

SQL - using alias in Group By

Beware of using aliases when grouping the results from a view in SQLite. You will get unexpected results if the alias name is the same as the column name of any underlying tables (to the views.)

Get selected value/text from Select on change

<script>
function test(a) {
    var x = a.selectedIndex;
    alert(x);
}
</script>
<select onchange="test(this)" id="select_id">
    <option value="0">-Select-</option>
    <option value="1">Communication</option>
    <option value="2">Communication</option>
    <option value="3">Communication</option>
</select>

in the alert you'll see the INT value of the selected index, treat the selection as an array and you'll get the value

Exception in thread "main" java.lang.Error: Unresolved compilation problems

You have to Import the Scanner and Timer Package Properly using the java.util classes.

import java.util.Scanner;
import java.util.Timer;

How do I create a link to add an entry to a calendar?

To add to squarecandy's google calendar contribution, here the brand new

OUTLOOK CALENDAR format (Without a need to create .ics) !!

<a href="https://bay02.calendar.live.com/calendar/calendar.aspx?rru=addevent&dtstart=20151119T140000Z&dtend=20151119T160000Z&summary=Summary+of+the+event&location=Location+of+the+event&description=example+text.&allday=false&uid=">add to Outlook calendar</a>

test it

Best would be to url_encode the summary, location and description variable's values.

For the sake of knowledge,

YAHOO CALENDAR format

<a href="https://calendar.yahoo.com/?v=60&view=d&type=20&title=Summary+of+the+event&st=20151119T090000&et=20151119T110000&desc=example+text.%0A%0AThis+is+the+text+entered+in+the+event+description+field.&in_loc=Location+of+the+event&uid=">add to Yahoo calendar</a>

test it

Doing it without a third party holds a lot of advantages for example using it in emails.

DynamoDB vs MongoDB NoSQL

For quick overview comparisons, I really like this website, that has many comparison pages, eg AWS DynamoDB vs MongoDB; http://db-engines.com/en/system/Amazon+DynamoDB%3BMongoDB

Construct pandas DataFrame from items in nested dictionary

A pandas MultiIndex consists of a list of tuples. So the most natural approach would be to reshape your input dict so that its keys are tuples corresponding to the multi-index values you require. Then you can just construct your dataframe using pd.DataFrame.from_dict, using the option orient='index':

user_dict = {12: {'Category 1': {'att_1': 1, 'att_2': 'whatever'},
                  'Category 2': {'att_1': 23, 'att_2': 'another'}},
             15: {'Category 1': {'att_1': 10, 'att_2': 'foo'},
                  'Category 2': {'att_1': 30, 'att_2': 'bar'}}}

pd.DataFrame.from_dict({(i,j): user_dict[i][j] 
                           for i in user_dict.keys() 
                           for j in user_dict[i].keys()},
                       orient='index')


               att_1     att_2
12 Category 1      1  whatever
   Category 2     23   another
15 Category 1     10       foo
   Category 2     30       bar

An alternative approach would be to build your dataframe up by concatenating the component dataframes:

user_ids = []
frames = []

for user_id, d in user_dict.iteritems():
    user_ids.append(user_id)
    frames.append(pd.DataFrame.from_dict(d, orient='index'))

pd.concat(frames, keys=user_ids)

               att_1     att_2
12 Category 1      1  whatever
   Category 2     23   another
15 Category 1     10       foo
   Category 2     30       bar

Check mySQL version on Mac 10.8.5

Every time you used the mysql console, the version is shown.

 mysql -u user

Successful console login shows the following which includes the mysql server version.

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 1432
Server version: 5.5.9-log Source distribution

Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

You can also check the mysql server version directly by executing the following command:

mysql --version

You may also check the version information from the mysql console itself using the version variables:

mysql> SHOW VARIABLES LIKE "%version%";

Output will be something like this:

+-------------------------+---------------------+
| Variable_name           | Value               |
+-------------------------+---------------------+
| innodb_version          | 1.1.5               |
| protocol_version        | 10                  |
| slave_type_conversions  |                     |
| version                 | 5.5.9-log           |
| version_comment         | Source distribution |
| version_compile_machine | i386                |
| version_compile_os      | osx10.4             |
+-------------------------+---------------------+
7 rows in set (0.01 sec)

You may also use this:

mysql> select @@version;

The STATUS command display version information as well.

mysql> STATUS

You can also check the version by executing this command:

mysql -v

It's worth mentioning that if you have encountered something like this:

ERROR 2002 (HY000): Can't connect to local MySQL server through socket
'/tmp/mysql.sock' (2)

you can fix it by:

sudo ln -s /Applications/MAMP/tmp/mysql/mysql.sock /tmp/mysql.sock

"An access token is required to request this resource" while accessing an album / photo with Facebook php sdk

To get the actual access_token, you can also do pro grammatically via the following PHP code:

 require 'facebook.php';

 $facebook = new Facebook(array(
   'appId'  => 'YOUR_APP_ID',
   'secret' => 'YOUR_APP_SECRET',
 ));

 // Get User ID
 $user = $facebook->getUser();

 if ($user) {
   try {
     $user_profile = $facebook->api('/me');
     $access_token = $facebook->getAccessToken();
   } catch (FacebookApiException $e) {
     error_log($e);
     $user = null;
   }
 }

Using jQuery to compare two arrays of Javascript objects

My approach was quite different - I flattened out both collections using JSON.stringify and used a normal string compare to check for equality.

I.e.

var arr1 = [
             {Col: 'a', Val: 1}, 
             {Col: 'b', Val: 2}, 
             {Col: 'c', Val: 3}
           ];

var arr2 = [
             {Col: 'x', Val: 24}, 
             {Col: 'y', Val: 25}, 
             {Col: 'z', Val: 26}
           ];

if(JSON.stringify(arr1) == JSON.stringify(arr2)){
    alert('Collections are equal');
}else{
    alert('Collections are not equal');
}

NB: Please note that his method assumes that both Collections are sorted in a similar fashion, if not, it would give you a false result!

How to apply box-shadow on all four sides?

Just simple as this code:

box-shadow: 0px 0px 2px 2px black; /*any color you want*/

Add unique constraint to combination of two columns

Once you have removed your duplicate(s):

ALTER TABLE dbo.yourtablename
  ADD CONSTRAINT uq_yourtablename UNIQUE(column1, column2);

or

CREATE UNIQUE INDEX uq_yourtablename
  ON dbo.yourtablename(column1, column2);

Of course, it can often be better to check for this violation first, before just letting SQL Server try to insert the row and returning an exception (exceptions are expensive).

http://www.sqlperformance.com/2012/08/t-sql-queries/error-handling

http://www.mssqltips.com/sqlservertip/2632/checking-for-potential-constraint-violations-before-entering-sql-server-try-and-catch-logic/

If you want to prevent exceptions from bubbling up to the application, without making changes to the application, you can use an INSTEAD OF trigger:

CREATE TRIGGER dbo.BlockDuplicatesYourTable
 ON dbo.YourTable
 INSTEAD OF INSERT
AS
BEGIN
  SET NOCOUNT ON;

  IF NOT EXISTS (SELECT 1 FROM inserted AS i 
    INNER JOIN dbo.YourTable AS t
    ON i.column1 = t.column1
    AND i.column2 = t.column2
  )
  BEGIN
    INSERT dbo.YourTable(column1, column2, ...)
      SELECT column1, column2, ... FROM inserted;
  END
  ELSE
  BEGIN
    PRINT 'Did nothing.';
  END
END
GO

But if you don't tell the user they didn't perform the insert, they're going to wonder why the data isn't there and no exception was reported.


EDIT here is an example that does exactly what you're asking for, even using the same names as your question, and proves it. You should try it out before assuming the above ideas only treat one column or the other as opposed to the combination...

USE tempdb;
GO

CREATE TABLE dbo.Person
(
  ID INT IDENTITY(1,1) PRIMARY KEY,
  Name NVARCHAR(32),
  Active BIT,
  PersonNumber INT
);
GO

ALTER TABLE dbo.Person 
  ADD CONSTRAINT uq_Person UNIQUE(PersonNumber, Active);
GO

-- succeeds:
INSERT dbo.Person(Name, Active, PersonNumber)
  VALUES(N'foo', 1, 22);
GO

-- succeeds:
INSERT dbo.Person(Name, Active, PersonNumber)
  VALUES(N'foo', 0, 22);
GO

-- fails:
INSERT dbo.Person(Name, Active, PersonNumber)
  VALUES(N'foo', 1, 22);
GO

Data in the table after all of this:

ID   Name   Active PersonNumber
---- ------ ------ ------------
1    foo    1      22
2    foo    0      22

Error message on the last insert:

Msg 2627, Level 14, State 1, Line 3 Violation of UNIQUE KEY constraint 'uq_Person'. Cannot insert duplicate key in object 'dbo.Person'. The statement has been terminated.

force css grid container to fill full screen of device

If you want the .wrapper to be fullscreen, just add the following in the wrapper class:

position: absolute; width: 100%; height: 100%;

You can also add top: 0 and left:0

SQL count rows in a table

Why don't you just right click on the table and then properties -> Storage and it would tell you the row count. You can use the below for row count in a view

SELECT SUM (row_count) 
FROM sys.dm_db_partition_stats 
WHERE object_id=OBJECT_ID('Transactions')    
AND (index_id=0 or index_id=1)`

How to print a dictionary's key?

I'm adding this answer as one of the other answers here (https://stackoverflow.com/a/5905752/1904943) is dated (Python 2; iteritems), and the code presented -- if updated for Python 3 per the suggested workaround in a comment to that answer -- silently fails to return all relevant data.


Background

I have some metabolic data, represented in a graph (nodes, edges, ...). In a dictionary representation of those data, keys are of the form (604, 1037, 0) (representing source and target nodes, and the edge type), with values of the form 5.3.1.9 (representing EC enzyme codes).

Find keys for given values

The following code correctly finds my keys, given values:

def k4v_edited(my_dict, value):
    values_list = []
    for k, v in my_dict.items():
        if v == value:
            values_list.append(k)
    return values_list

print(k4v_edited(edge_attributes, '5.3.1.9'))
## [(604, 1037, 0), (604, 3936, 0), (1037, 3936, 0)]

whereas this code returns only the first (of possibly several matching) keys:

def k4v(my_dict, value):
    for k, v in my_dict.items():
        if v == value:
            return k

print(k4v(edge_attributes, '5.3.1.9'))
## (604, 1037, 0)

The latter code, naively updated replacing iteritems with items, fails to return (604, 3936, 0), (1037, 3936, 0.

How to use onClick() or onSelect() on option tag in a JSP page?

example dom onchange usage:

<select name="app_id" onchange="onAppSelection(this);">
    <option name="1" value="1">space.ecoins.beta.v3</option>
    <option name="2" value="2">fun.rotator.beta.v1</option>
    <option name="3" value="3">fun.impactor.beta.v1</option>
    <option name="4" value="4">fun.colorotator.beta.v1</option>
    <option name="5" value="5">fun.rotator.v1</option>
    <option name="6" value="6">fun.impactor.v1</option>
    <option name="7" value="7">fun.colorotator.v1</option>
    <option name="8" value="8">fun.deluxetor.v1</option>
    <option name="9" value="9">fun.winterotator.v1</option>
    <option name="10" value="10">fun.eastertor.v1</option>
    <option name="11" value="11">info.locatizator.v3</option>
    <option name="12" value="12">market.apks.ecoins.v2</option>
    <option name="13" value="13">fun.ecoins.v1b</option>
    <option name="14" value="14">place.sin.v2b</option>
    <option name="15" value="15">cool.poczta.v1b</option>
    <option name="16" value="16" id="app_id" selected="">systems.ecoins.launch.v1b</option>
    <option name="17" value="17">fun.eastertor.v2</option>
    <option name="18" value="18">space.ecoins.v4b</option>
    <option name="19" value="19">services.devcode.v1b</option>
    <option name="20" value="20">space.bonoloto.v1b</option>
    <option name="21" value="21">software.devcode.vpnfree.uk.v1</option>
    <option name="22" value="22">software.devcode.smsfree.v1b</option>
    <option name="23" value="23">services.devcode.smsfree.v1b</option>
    <option name="24" value="24">services.devcode.smsfree.v1</option>
    <option name="25" value="25">software.devcode.smsfree.v1</option>
    <option name="26" value="26">software.devcode.vpnfree.v1b</option>
    <option name="27" value="27">software.devcode.vpnfree.v1</option>
    <option name="28" value="28">software.devcode.locatizator.v1</option>
    <option name="29" value="29">software.devcode.netinfo.v1b</option>
    <option name="-1" value="-1">none</option>
</select>


<script type="text/javascript">

    function onAppSelection(selectBox) {
        // clear selection
        for(var i=0;i<=selectBox.length;i++) {
          var selectedNode  = selectBox.options[i];
             if(selectedNode!=null) {
                  selectedNode.removeAttribute("id");
                  selectedNode.removeAttribute("selected");
            }
        } 
        // assign  id and selected
        var selectedNode = selectBox.options[selectBox.selectedIndex];
        if(selectedNode!=null) {
            selectedNode.setAttribute("id","app_id");
            selectedNode.setAttribute("selected","");
        }
     }

</script>

Update my gradle dependencies in eclipse

You have to select "Refresh Dependencies" in the "Gradle" context menu that appears when you right-click the project in the Package Explorer.

Package name does not correspond to the file path - IntelliJ

I was just fighting with similar problem. My way to solve it was to set the root source file for Intellij module to match the original project root folder. Then i needed to mark some folders as Excluded in project navigation panel (the one that should not be used in new one project, for me it was part used under Android). That's all.

How do I format a date in VBA with an abbreviated month?

I'm using

Sheet1.Range("E2", "E3000").NumberFormat = "dd/mm/yyyy hh:mm:ss"

to format a column

So I guess

Sheet1.Range("E2", "E3000").NumberFormat = "MMM dd yyyy"

would do the trick for you.

More: NumberFormat function.

How to find cube root using Python?

def cube(x):
    if 0<=x: return x**(1./3.)
    return -(-x)**(1./3.)
print (cube(8))
print (cube(-8))

Here is the full answer for both negative and positive numbers.

>>> 
2.0
-2.0
>>> 

Or here is a one-liner;

root_cube = lambda x: x**(1./3.) if 0<=x else -(-x)**(1./3.)

Make a table fill the entire window

You can use position like this to stretch an element across the parent container.

<table style="position: absolute; top: 0; bottom: 0; left: 0; right: 0;">
    <tr style="height: 25%; font-size: 180px;">
        <td>Region</td>
    </tr>
    <tr style="height: 75%; font-size: 540px;">
        <td>100.00%</td>
    </tr>
</table>

Cannot read property 'style' of undefined -- Uncaught Type Error

Add your <script> to the bottom of your <body>, or add an event listener for DOMContentLoaded following this StackOverflow question.

If that script executes in the <head> section of the code, document.getElementsByClassName(...) will return an empty array because the DOM is not loaded yet.

You're getting the Type Error because you're referencing search_span[0], but search_span[0] is undefined.

This works when you execute it in Dev Tools because the DOM is already loaded.

"Javac" doesn't work correctly on Windows 10

If you have set all PATH variables correctly after installation, just restart it.

I had the same problem, I had also installed new Windows7 OS then I upgraded it to Win 10. Then i started setup necessary tools like IntelliJ, Java jdk,jre, eclipse so on. In cmd, java -version worked but javac compiler got unrecognized. I checked and all good, the files in the folders, path are correct and so on.

I restarted and checked it again in cmd ,it worked.

How to set iframe size dynamically

The height is different depending on the browser's window size. It should be set dynamically depending on the size of the browser window

<!DOCTYPE html>
    <html>
    <body>
    
    <center><h2>Heading</h2></center>
    <center><p>Paragraph</p></center>
    
    <iframe src="url" height="600" width="1350" title="Enter Here"></iframe>
    
    </body>
    </html>

Java 8 Lambda function that throws exception?

You can.

Extending @marcg 's UtilException and adding generic <E extends Exception> where necessary: this way, the compiler will force you again to add throw clauses and everything's as if you could throw checked exceptions natively on java 8's streams.

public final class LambdaExceptionUtil {

    @FunctionalInterface
    public interface Function_WithExceptions<T, R, E extends Exception> {
        R apply(T t) throws E;
    }

    /**
     * .map(rethrowFunction(name -> Class.forName(name))) or .map(rethrowFunction(Class::forName))
     */
    public static <T, R, E extends Exception> Function<T, R> rethrowFunction(Function_WithExceptions<T, R, E> function) throws E  {
        return t -> {
            try {
                return function.apply(t);
            } catch (Exception exception) {
                throwActualException(exception);
                return null;
            }
        };
    }

    @SuppressWarnings("unchecked")
    private static <E extends Exception> void throwActualException(Exception exception) throws E {
        throw (E) exception;
    }

}

public class LambdaExceptionUtilTest {

    @Test
    public void testFunction() throws MyTestException {
        List<Integer> sizes = Stream.of("ciao", "hello").<Integer>map(rethrowFunction(s -> transform(s))).collect(toList());
        assertEquals(2, sizes.size());
        assertEquals(4, sizes.get(0).intValue());
        assertEquals(5, sizes.get(1).intValue());
    }

    private Integer transform(String value) throws MyTestException {
        if(value==null) {
            throw new MyTestException();
        }
        return value.length();
    }

    private static class MyTestException extends Exception { }
}

HTTP test server accepting GET/POST requests

There is http://ptsv2.com/

"Here you will find a server which receives any POST you wish to give it and stores the contents for you to review."

Can I set subject/content of email using mailto:?

The mailto: URL scheme is defined in RFC 2368. Also, the convention for encoding information into URLs and URIs is defined in RFC 1738 and then RFC 3986. These prescribe how to include the body and subject headers into a URL (URI):

mailto:[email protected]?subject=current-issue&body=send%20current-issue

Specifically, you must percent-encode the email address, subject, and body and put them into the format above. Percent-encoded text is legal for use in HTML, however this URL must be entity encoded for use in an href attribute, according to the HTML4 standard:

<a href="mailto:[email protected]?subject=current-issue&amp;body=send%20current-issue">Send email</a>

And most generally, here is a simple PHP script that encodes per the above.

<?php
$encodedTo = rawurlencode($message->to);
$encodedSubject = rawurlencode($message->subject);
$encodedBody = rawurlencode($message->body);
$uri = "mailto:$encodedTo?subject=$encodedSubject&body=$encodedBody";
$encodedUri = htmlspecialchars($uri);
echo "<a href=\"$encodedUri\">Send email</a>";
?>

On Selenium WebDriver how to get Text from Span Tag

I agree css is better. If you did want to do it via Xpath you could try:

    String kk = wd.findElement(By.xpath(.//*div[@id='customSelect_3']/div/span[@class='selectLabel clear'].getText()))

getting "No column was specified for column 2 of 'd'" in sql server cte?

evidently, as stated in the parser response, a column name is needed for both cases. In either versions the columns of "d" are not named.

in case 1: your column 2 of d is sum(totalitems) which is not named. duration will retain the name "duration"

in case 2: both month(clothdeliverydate) and SUM(CONVERT(INT, deliveredqty)) have to be named

How to get number of rows using SqlDataReader in C#

Per above, a dataset or typed dataset might be a good temorary structure which you could use to do your filtering. A SqlDataReader is meant to read the data very quickly. While you are in the while() loop you are still connected to the DB and it is waiting for you to do whatever you are doing in order to read/process the next result before it moves on. In this case you might get better performance if you pull in all of the data, close the connection to the DB and process the results "offline".

People seem to hate datasets, so the above could be done wiht a collection of strongly typed objects as well.

Converting A String To Hexadecimal In Java

To get the Integer value of hex

        //hex like: 0xfff7931e to int
        int hexInt = Long.decode(hexString).intValue();

Converting a POSTMAN request to Curl

Starting from Postman 8 you need to visit here

enter image description here

angular-cli server - how to specify default port

Update for @angular/[email protected]: and over

In angular.json you can specify a port per "project"

"projects": {
    "my-cool-project": {
        ... rest of project config omitted
        "architect": {
            "serve": {
                "options": {
                    "port": 1337
                }
            }
        }
    }
}

All options available:

https://angular.io/guide/workspace-config#project-tool-configuration-options

Alternatively, you may specify the port each time when running ng serve like this:

ng serve --port 1337

With this approach you may wish to put this into a script in your package.json to make it easier to run each time / share the config with others on your team:

"scripts": {
    "start": "ng serve --port 1337"
}

Legacy:

Update for @angular/cli final:

Inside angular-cli.json you can specify the port in the defaults:

"defaults": {
  "serve": {
    "port": 1337
  }
}

Legacy-er:

Tested in [email protected]

The server in angular-cli comes from the ember-cli project. To configure the server, create an .ember-cli file in the project root. Add your JSON config in there:

{
   "port": 1337
}

Restart the server and it will serve on that port.

There are more options specified here: http://ember-cli.com/#runtime-configuration

{
  "skipGit" : true,
  "port" : 999,
  "host" : "0.1.0.1",
  "liveReload" : true,
  "environment" : "mock-development",
  "checkForUpdates" : false
}

Get the date of next monday, tuesday, etc

PHP 7.1:

$next_date = new DateTime('next Thursday');
$stamp = $next_date->getTimestamp();

PHP manual getTimestamp()

Which .NET Dependency Injection frameworks are worth looking into?

The great thing about C# is that it is following a path beaten by years of Java developers before it. So, my advice, generally speaking when looking for tools of this nature, is to look for the solid Java answer and see if there exists a .NET adaptation yet.

So when it comes to DI (and there are so many options out there, this really is a matter of taste) is Spring.NET. Additionally, it's always wise to research the people behind projects. I have no issue suggesting SourceGear products for source control (outside of using them) because I have respect for Eric Sink. I have seen Mark Pollack speak and what can I say, the guy just gets it.

In the end, there are a lot of DI frameworks and your best bet is to do some sample projects with a few of them and make an educated choice.

Good luck!

Open and write data to text file using Bash?

I thought there were a few perfectly fine answers, but no concise summary of all possibilities; thus:

The core principal behind most answers here is redirection. Two are important redirection operators for writing to files:

Redirecting Output:

echo 'text to completely overwrite contents of myfile' > myfile

Appending Redirected Output

echo 'text to add to end of myfile' >> myfile

Here Documents

Others mentioned, rather than from a fixed input source like echo 'text', you could also interactively write to files via a "Here Document", which are also detailed in the link to the bash manual above. Those answers, e.g.

cat > FILE.txt <<EOF or cat >> FILE.txt <<EOF

make use of the same redirection operators, but add another layer via "Here Documents". In the above syntax, you write to the FILE.txt via the output of cat. The writing only takes place after the interactive input is given some specific string, in this case 'EOF', but this could be any string, e.g.:

cat > FILE.txt <<'StopEverything' or cat >> FILE.txt <<'StopEverything'

would work just as well. Here Documents also look for various delimiters and other interesting parsing characters, so have a look at the docs for further info on that.

Here Strings

A bit convoluted, and more of an exercise in understanding both redirection and Here Documents syntax, but you could combine Here Document style syntax with standard redirect operators to become a Here String:

Redirecting Output of cat Input

cat > myfile <<<'text to completely overwrite contents of myfile'

Appending Redirected Output of cat Input

cat >> myfile <<<'text to completely overwrite contents of myfile'

How to create a global variable?

Global variables that are defined outside of any method or closure can be scope restricted by using the private keyword.

import UIKit

// MARK: Local Constants

private let changeSegueId = "MasterToChange"
private let bookSegueId   = "MasterToBook"

Don't change link color when a link is clicked

Don't over complicate it. Just give the link a color using the tags. It will leave a constant color that won't change even if you click it. So in your case just set it to blue. If it is set to a particular color of blue just you want to copy, you can press "print scrn" on your keyboard, paste in paint, and using the color picker(shaped as a dropper) pick the color of the link and view the code in the color settings.

Clear the cache in JavaScript

I found a solution to this problem recently. In my case, I was trying to update an html element using javascript; I had been using XHR to update text based on data retrieved from a GET request. Although the XHR request happened frequently, the cached HTML data remained frustratingly the same.

Recently, I discovered a cache busting method in the fetch api. The fetch api replaces XHR, and it is super simple to use. Here's an example:

        async function updateHTMLElement(t) {
            let res = await fetch(url, {cache: "no-store"});
            if(res.ok){
                let myTxt = await res.text();
                document.getElementById('myElement').innerHTML = myTxt;
            }
        }

Notice that {cache: "no-store"} argument? This causes the browser to bust the cache for that element, so that new data gets loaded properly. My goodness, this was a godsend for me. I hope this is helpful for you, too.

Tangentially, to bust the cache for an image that gets updated on the server side, but keeps the same src attribute, the simplest and oldest method is to simply use Date.now(), and append that number as a url variable to the src attribute for that image. This works reliably for images, but not for HTML elements. But between these two techniques, you can update any info you need to now :-)

How to consume a SOAP web service in Java

I will use CXF also you can think of AXIS 2 .

The best way to do it may be using JAX RS Refer this example

Example:

wsimport -p stockquote http://stockquote.xyz/quote?wsdl

This will generate the Java artifacts and compile them by importing the http://stockquote.xyz/quote?wsdl.

I

Should I use 'border: none' or 'border: 0'?

While results will most likely be the same (no border), the 0 and none are technically addressing different things.

0 addresses border width and none addresses border style. Obviously a border of 0 width is nonexistent so will therefore have no style.

However, if later on in your stylesheet you intend to override this, you would naturally specifically address one or the other. If I now wanted a 3px border, that would be directly overriding border: 0 in regards to width. If I now wanted a dotted border, that would be directly overriding border: none in regards to styling.

Vue.js getting an element within a component

The answers are not making it clear:

Use this.$refs.someName, but, in order to use it, you must add ref="someName" in the parent.

See demo below.

_x000D_
_x000D_
new Vue({_x000D_
  el: '#app',_x000D_
  mounted: function() {_x000D_
    var childSpanClassAttr = this.$refs.someName.getAttribute('class');_x000D_
    _x000D_
    console.log('<span> was declared with "class" attr -->', childSpanClassAttr);_x000D_
  }_x000D_
})
_x000D_
<script src="https://unpkg.com/[email protected]/dist/vue.min.js"></script>_x000D_
_x000D_
<div id="app">_x000D_
  Parent._x000D_
  <span ref="someName" class="abc jkl xyz">Child Span</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

$refs and v-for

Notice that when used in conjunction with v-for, the this.$refs.someName will be an array:

_x000D_
_x000D_
new Vue({_x000D_
  el: '#app',_x000D_
  data: {_x000D_
    ages: [11, 22, 33]_x000D_
  },_x000D_
  mounted: function() {_x000D_
    console.log("<span> one's text....:", this.$refs.mySpan[0].innerText);_x000D_
    console.log("<span> two's text....:", this.$refs.mySpan[1].innerText);_x000D_
    console.log("<span> three's text..:", this.$refs.mySpan[2].innerText);_x000D_
  }_x000D_
})
_x000D_
span { display: inline-block; border: 1px solid red; }
_x000D_
<script src="https://unpkg.com/[email protected]/dist/vue.min.js"></script>_x000D_
_x000D_
<div id="app">_x000D_
  Parent._x000D_
  <div v-for="age in ages">_x000D_
    <span ref="mySpan">Age is {{ age }}</span>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to get date, month, year in jQuery UI datepicker?

what about that simple way)

$(document).ready ->
 $('#datepicker').datepicker( dateFormat: 'yy-mm-dd',  onSelect: (dateStr) ->
    alert dateStr # yy-mm-dd
    #OR
    alert $("#datepicker").val(); # yy-mm-dd

Detecting locked tables (locked by LOCK TABLE)

You could also get all relevant details from performance_schema:

SELECT
OBJECT_SCHEMA
,OBJECT_NAME
,GROUP_CONCAT(DISTINCT EXTERNAL_LOCK)
FROM performance_schema.table_handles 
WHERE EXTERNAL_LOCK IS NOT NULL

GROUP BY
OBJECT_SCHEMA
,OBJECT_NAME

This works similar as

show open tables WHERE In_use > 0

Compile/run assembler in Linux?

The assembler(GNU) is as(1)

How do I get the size of a java.sql.ResultSet?

[Speed consideration]

Lot of ppl here suggests ResultSet.last() but for that you would need to open connection as a ResultSet.TYPE_SCROLL_INSENSITIVE which for Derby embedded database is up to 10 times SLOWER than ResultSet.TYPE_FORWARD_ONLY.

According to my micro-tests for embedded Derby and H2 databases it is significantly faster to call SELECT COUNT(*) before your SELECT.

Here is in more detail my code and my benchmarks

RegEx to exclude a specific string constant

You have to use a negative lookahead assertion.

(?!^ABC$)

You could for example use the following.

(?!^ABC$)(^.*$)

If this does not work in your editor, try this. It is tested to work in ruby and javascript:

^((?!ABC).)*$

Your password does not satisfy the current policy requirements

Step 1: check your default authentication plugin

SHOW VARIABLES LIKE 'default_authentication_plugin';

Step 2: veryfing your password validation requirements

SHOW VARIABLES LIKE 'validate_password%';

Step 3: setting up your user with correct password requirements

CREATE USER '<your_user>'@'localhost' IDENTIFIED WITH '<your_default_auth_plugin>' BY 'password';

What is "android:allowBackup"?

It is privacy concern. It is recommended to disallow users to backup an app if it contains sensitive data. Having access to backup files (i.e. when android:allowBackup="true"), it is possible to modify/read the content of an app even on a non-rooted device.

Solution - use android:allowBackup="false" in the manifest file.

You can read this post to have more information: Hacking Android Apps Using Backup Techniques

how can I debug a jar at runtime?

You can activate JVM's debugging capability when starting up the java command with a special option:

java -agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=y -jar path/to/some/war/or/jar.jar

Starting up jar.jar like that on the command line will:

  • put this JVM instance in the role of a server (server=y) listening on port 8000 (address=8000)
  • write Listening for transport dt_socket at address: 8000 to stdout and
  • then pause the application (suspend=y) until some debugger connects. The debugger acts as the client in this scenario.

Common options for selecting a debugger are:

  • Eclipse Debugger: Under Run -> Debug Configurations... -> select Remote Java Application -> click the New launch configuration button. Provide an arbitrary Name for this debug configuration, Connection Type: Standard (Socket Attach) and as Connection Properties the entries Host: localhost, Port: 8000. Apply the Changes and click Debug. At the moment the Eclipse Debugger has successfully connected to the JVM, jar.jar should begin executing.
  • jdb command-line tool: Start it up with jdb -connect com.sun.jdi.SocketAttach:port=8000

How to use registerReceiver method?

Broadcast receivers receive events of a certain type. I don't think you can invoke them by class name.

First, your IntentFilter must contain an event.

static final String SOME_ACTION = "com.yourcompany.yourapp.SOME_ACTION";
IntentFilter intentFilter = new IntentFilter(SOME_ACTION);

Second, when you send a broadcast, use this same action:

Intent i = new Intent(SOME_ACTION);
sendBroadcast(i);

Third, do you really need MyIntentService to be inline? Static? [EDIT] I discovered that MyIntentSerivce MUST be static if it is inline.

Fourth, is your service declared in the AndroidManifest.xml?

Python, print all floats to 2 decimal places in output

I have just discovered the round function - it is in Python 2.7, not sure about 2.6. It takes a float and the number of dps as arguments, so round(22.55555, 2) gives the result 22.56.

HTML&CSS + Twitter Bootstrap: full page layout or height 100% - Npx

Is this what you are looking for? Here is a fiddle demo.

The layout is based on percentage, colors are for clarity. If the content column overflows, a scrollbar should appear.

body, html, .container-fluid {
  height: 100%;
}

.navbar {
  width:100%;
  background:yellow;
}

.article-tree {
  height:100%;
  width: 25%;
  float:left;
  background: pink;
}

.content-area {
  overflow: auto;
  height: 100%;
  background:orange;
}

.footer {
   background: red;
   width:100%;
   height: 20px;
}

How to vertically align a html radio button to it's label?

input {
    display: table-cell;
    vertical-align: middle
}

Put class for all radio. This will work for all radio button on the html page.

Fiddle

Python: find position of element in array

Have you thought about using Python list's .index(value) method? It return the index in the list of where the first instance of the value passed in is found.

Best way to detect when a user leaves a web page?

Here's an alternative solution - since in most browsers the navigation controls (the nav bar, tabs, etc.) are located above the page content area, you can detect the mouse pointer leaving the page via the top and display a "before you leave" dialog. It's completely unobtrusive and it allows you to interact with the user before they actually perform the action to leave.

$(document).bind("mouseleave", function(e) {
    if (e.pageY - $(window).scrollTop() <= 1) {    
        $('#BeforeYouLeaveDiv').show();
    }
});

The downside is that of course it's a guess that the user actually intends to leave, but in the vast majority of cases it's correct.

How to linebreak an svg text within javascript?

With the tspan solution, let's say you don't know in advance where to put your line breaks: you can use this nice function, that I found here: http://bl.ocks.org/mbostock/7555321

That automatically does line breaks for long text svg for a given width in pixel.

function wrap(text, width) {
  text.each(function() {
    var text = d3.select(this),
        words = text.text().split(/\s+/).reverse(),
        word,
        line = [],
        lineNumber = 0,
        lineHeight = 1.1, // ems
        y = text.attr("y"),
        dy = parseFloat(text.attr("dy")),
        tspan = text.text(null).append("tspan").attr("x", 0).attr("y", y).attr("dy", dy + "em");
    while (word = words.pop()) {
      line.push(word);
      tspan.text(line.join(" "));
      if (tspan.node().getComputedTextLength() > width) {
        line.pop();
        tspan.text(line.join(" "));
        line = [word];
        tspan = text.append("tspan").attr("x", 0).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);
      }
    }
  });
}

How to convert a String to long in javascript?

JavaScript has a Number type which is a 64 bit floating point number*.

If you're looking to convert a string to a number, use

  1. either parseInt or parseFloat. If using parseInt, I'd recommend always passing the radix too.
  2. use the Unary + operator e.g. +"123456"
  3. use the Number constructor e.g. var n = Number("12343")

*there are situations where the number will internally be held as an integer.

Compiler error "archive for required library could not be read" - Spring Tool Suite

Delete corrupted files from your local .m2 repository and Ctrl+F5 (Update Maven Project) in Eclipse/STS. It'll download and install these files.

Location Services not working in iOS 8

The problem for me was that the class that was the CLLocationManagerDelegate was private, which prevented all the delegate methods from being called. Guess it's not a very common situation but thought I'd mention it in case t helps anyone.

How to rename with prefix/suffix?

If it's open to a modification, you could use a suffix instead of a prefix. Then you could use tab-completion to get the original filename and add the suffix.

Otherwise, no this isn't something that is supported by the mv command. A simple shell script could cope though.

Creating a very simple linked list

I have a doubly Linked List which can be used as a stack or a queue. If you look at the code and think about what it does and how it does it I bet you will understand everything about it. I am sorry but somehow I couldn't pate the full code here so I here is the link for the linkedlist(also I got the binary tree in the solution): https://github.com/szabeast/LinkedList_and_BinaryTree

Making a POST call instead of GET using urllib2

The requests module may ease your pain.

url = 'http://myserver/post_service'
data = dict(name='joe', age='10')

r = requests.post(url, data=data, allow_redirects=True)
print r.content

How to insert a line break <br> in markdown

I know this post is about adding a single line break but I thought I would mention that you can create multiple line breaks with the backslash (\) character:

Hello
\
\
\
World!

This would result in 3 new lines after "Hello". To clarify, that would mean 2 empty lines between "Hello" and "World!". It would display like this:


Hello



World!



Personally I find this cleaner for a large number of line breaks compared to using <br>.

Note that backslashes are not recommended for compatibility reasons. So this may not be supported by your Markdown parser but it's handy when it is.

Order by descending date - month, day and year

Assuming that you have the power to make schema changes the only acceptable answer to this question IMO is to change the base data type to something more appropriate (e.g. date if SQL Server 2008).

Storing dates as mm/dd/yyyy strings is space inefficient, difficult to validate correctly and makes sorting and date calculations needlessly painful.

How to remove specific substrings from a set of strings in Python?

if you delete something from list , u can use this way : (method sub is case sensitive)

new_list = []
old_list= ["ABCDEFG","HKLMNOP","QRSTUV"]

for data in old_list:
     new_list.append(re.sub("AB|M|TV", " ", data))

print(new_list) // output : [' CDEFG', 'HKL NOP', 'QRSTUV']

how to print float value upto 2 decimal place without rounding off

i'd suggest shorter and faster approach:

printf("%.2f", ((signed long)(fVal * 100) * 0.01f));

this way you won't overflow int, plus multiplication by 100 shouldn't influence the significand/mantissa itself, because the only thing that really is changing is exponent.

Submit form without page reloading

You will need to use JavaScript without resulting to an iframe (ugly approach).

You can do it in JavaScript; using jQuery will make it painless.

I suggest you check out AJAX and Posting.

Getting the WordPress Post ID of current post

you can use $post->ID for current id.