Programs & Examples On #Checkboxpreference

Detect if the device is iPhone X

With the release of iOS 12, devices like iPhone X may come under this category.

`

extension UIDevice {
    var isPortrait: Bool {

       return UIDeviceOrientationIsPortrait(orientation) ||
      UIInterfaceOrientationIsPortrait(UIApplication.shared.statusBarOrientation)

  }

   var isDeviceWith_XShape : Bool {

    if self.userInterfaceIdiom == .phone {

        if isPortrait
        {
            switch UIScreen.main.nativeBounds.height {

            case 2436,2688,1792:
                print("iPhone X, Xs, Xr, Xs Max")
                return true
            default:
                print("Any other device")
                return false
            }
        }
        else
        {
            switch UIScreen.main.nativeBounds.width {

            case 2436,2688,1792:
                print("iPhone X, Xs, Xr, Xs Max")
                return true
            default:
                print("Any other device")
                return false
            }
        }


    }
    else
    {
        return false
    }

}`

'xmlParseEntityRef: no name' warnings while loading xml into a php file

I use a combined version :

strip_tags(preg_replace("/&(?!#?[a-z0-9]+;)/", "&",$textorhtml))

Getting file names without extensions

using System;

using System.IO;

public class GetwithoutExtension
{

    public static void Main()
    {
        //D:Dir dhould exists in ur system
        DirectoryInfo dir1 = new DirectoryInfo(@"D:Dir");
        FileInfo [] files = dir1.GetFiles("*xls", SearchOption.AllDirectories);
        foreach (FileInfo f in files)
        {
            string filename = f.Name.ToString();
            filename= filename.Replace(".xls", "");
            Console.WriteLine(filename);
        }
        Console.ReadKey();

    }

}

How to print_r $_POST array?

Why are you wrapping the $_POST array in an array?

You can access your "id" and "value" arrays using the following

// assuming the appropriate isset() checks for $_POST['id'] and $_POST['value']

$ids = $_POST['id'];
$values = $_POST['value'];

foreach ($ids as $idx => $id) {
    // ...
}

foreach ($values as $idx => $value) {
    // ...
}

How to replace comma (,) with a dot (.) using java

For the current information you are giving, it will be enought with this simple regex to do the replacement:

str.replaceAll(",", ".");

Looping over a list in Python

Do this instead:

values = [[1,2,3],[4,5]]
for x in values:
    if len(x) == 3:
       print(x)

'ls' in CMD on Windows is not recognized

enter image description here

First

Make a dir c:\command

Second Make a ll.bat

ll.bat

dir

Third Add to Path C:/commands enter image description here

Timestamp to human readable format

use Date.prototype.toLocaleTimeString() as documented here

please note the locale example en-US in the url.

How can I select an element with multiple classes in jQuery?

You do not need jQuery for this

In Vanilla you can do :

document.querySelectorAll('.a.b')

How to add List<> to a List<> in asp.net

Use .AddRange to append any Enumrable collection to the list.

How to update data in one table from corresponding data in another table in SQL Server 2005

update test1 t1, test2 t2
set t2.deptid = t1.deptid
where t2.employeeid = t1.employeeid

you can not use from keyword for the mysql

REST API Login Pattern

Principled Design of the Modern Web Architecture by Roy T. Fielding and Richard N. Taylor, i.e. sequence of works from all REST terminology came from, contains definition of client-server interaction:

All REST interactions are stateless. That is, each request contains all of the information necessary for a connector to understand the request, independent of any requests that may have preceded it.

This restriction accomplishes four functions, 1st and 3rd are important in this particular case:

  • 1st: it removes any need for the connectors to retain application state between requests, thus reducing consumption of physical resources and improving scalability;
  • 3rd: it allows an intermediary to view and understand a request in isolation, which may be necessary when services are dynamically rearranged;

And now lets go back to your security case. Every single request should contains all required information, and authorization/authentication is not an exception. How to achieve this? Literally send all required information over wires with every request.

One of examples how to archeive this is hash-based message authentication code or HMAC. In practice this means adding a hash code of current message to every request. Hash code calculated by cryptographic hash function in combination with a secret cryptographic key. Cryptographic hash function is either predefined or part of code-on-demand REST conception (for example JavaScript). Secret cryptographic key should be provided by server to client as resource, and client uses it to calculate hash code for every request.

There are a lot of examples of HMAC implementations, but I'd like you to pay attention to the following three:

How it works in practice

If client knows the secret key, then it's ready to operate with resources. Otherwise he will be temporarily redirected (status code 307 Temporary Redirect) to authorize and to get secret key, and then redirected back to the original resource. In this case there is no need to know beforehand (i.e. hardcode somewhere) what the URL to authorize the client is, and it possible to adjust this schema with time.

Hope this will helps you to find the proper solution!

Enterprise app deployment doesn't work on iOS 7.1

After reading this post I had still a problem with downloading my app. Problem was because of self signed SSL certificate.

I've found a solution for this problem. You need to upload your certificate file with extension '.crt' on the web and type address of it in your mobile safari. System ask you about adding your certificate to the list of trusted certificates. After this operation you will be able to install your ad-hoc app.

How to read GET data from a URL using JavaScript?

Please see this, more current solution before using a custom parsing function like below, or a 3rd party library.

The a code below works and is still useful in situations where URLSearchParams is not available, but it was written in a time when there was no native solution available in JavaScript. In modern browsers or Node.js, prefer to use the built-in functionality.


function parseURLParams(url) {
    var queryStart = url.indexOf("?") + 1,
        queryEnd   = url.indexOf("#") + 1 || url.length + 1,
        query = url.slice(queryStart, queryEnd - 1),
        pairs = query.replace(/\+/g, " ").split("&"),
        parms = {}, i, n, v, nv;

    if (query === url || query === "") return;

    for (i = 0; i < pairs.length; i++) {
        nv = pairs[i].split("=", 2);
        n = decodeURIComponent(nv[0]);
        v = decodeURIComponent(nv[1]);

        if (!parms.hasOwnProperty(n)) parms[n] = [];
        parms[n].push(nv.length === 2 ? v : null);
    }
    return parms;
}

Use as follows:

var urlString = "http://www.example.com/bar?a=a+a&b%20b=b&c=1&c=2&d#hash";
    urlParams = parseURLParams(urlString);

which returns a an object like this:

{
  "a"  : ["a a"],     /* param values are always returned as arrays */
  "b b": ["b"],       /* param names can have special chars as well */
  "c"  : ["1", "2"]   /* an URL param can occur multiple times!     */
  "d"  : [null]       /* parameters without values are set to null  */ 
} 

So

parseURLParams("www.mints.com?name=something")

gives

{name: ["something"]}

EDIT: The original version of this answer used a regex-based approach to URL-parsing. It used a shorter function, but the approach was flawed and I replaced it with a proper parser.

Code coverage for Jest built on top of Jasmine

UPDATE: 7/20/2018 - Added links and updated name for coverageReporters.

UPDATE: 8/14/2017 - This answer is totally outdated. Just look at the Jest docs now. They have official support and documentation about how to do this.

@hankhsiao has got a forked repo where Istanbul is working with Jest. Add this to your dev dependencies

 "devDependencies": {
     "jest-cli": "git://github.com/hankhsiao/jest.git"
 }

Also make sure coverage is enabled in your package.json jest entry and you can also specify formats you want. (The html is pretty bad ass).

 "jest": {
     "collectCoverage": true,
     "coverageReporters": ["json", "html"],
 }

See Jest documentation for coverageReporters (default is ["json", "lcov", "text"])

Or add --coverage when you invoke jest.

Using IF ELSE statement based on Count to execute different Insert statements

Not very clear what you mean by

"I cant find any examples to help me understand how I can use this to run 2 different statements:"

. Is it using CASE like a SWITCH you are after?

select case when totalCount >= 0 and totalCount < 11 then '0-10'
            when tatalCount > 10 and totalCount < 101 then '10-100'
            else '>100' end as newColumn
from (
  SELECT [Some Column], COUNT(*) TotalCount
  FROM INCIDENTS
  WHERE [Some Column] = 'Target Data'
  GROUP BY [Some Column]
) A

Pass array to ajax request in $.ajax()

info = [];
info[0] = 'hi';
info[1] = 'hello';


$.ajax({
   type: "POST",
   data: {info:info},
   url: "index.php",
   success: function(msg){
     $('.answer').html(msg);
   }
});

Express-js can't GET my static files, why?

The problem with serving __dirname is that __dirname returns the path of the current file, not the project's file. Also, if you use a dynamic header, each page will look for the static files in a different path and it won't work. The best, for me, is to substitute __dirname for process.cwd() which ALWAYS donates the path to the project file.

app.use(express.static(process.cwd() + '/public'));

And in your project:

link rel="stylesheet" href="/styles/default.css"

See: What's the difference between process.cwd() vs __dirname?

Javascript String to int conversion

Although parseInt is the official function to do this, you can achieve the same with this code:

number*1

The advantage is that you save some characters, which might save bandwidth if your code has to lots of such conversations.

Replacing a fragment with another fragment inside activity group

Use ViewPager. It's work for me.

final ViewPager viewPager = (ViewPager) getActivity().findViewById(R.id.vp_pager); 
button = (Button)result.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        viewPager.setCurrentItem(1);
    }
});

How to convert "Mon Jun 18 00:00:00 IST 2012" to 18/06/2012?

You can also use a formula in excel in order to convert this type of date to a date type excel can read: =DATEVALUE(CONCATENATE(MID(A1,8,3),MID(A1,4,4),RIGHT(A1,4)))

And you get: 12/7/2016 from: Wed Dec 07 00:00:00 UTC 2016

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

Simply define vertical-align property for the icon element:

div .icon {
   vertical-align: middle;
}

How to "git show" a merge commit with combined diff output even when every changed file agrees with one of the parents?

A better solution (mentioned by @KrisNuttycombe):

git diff fc17405...ee2de56

for the merge commit:

commit 0e1329e551a5700614a2a34d8101e92fd9f2cad6 (HEAD, master)
Merge: fc17405 ee2de56
Author: Tilman Vogel <email@email>
Date:   Tue Feb 22 00:27:17 2011 +0100

to show all of the changes on ee2de56 that are reachable from commits on fc17405. Note the order of the commit hashes - it's the same as shown in the merge info: Merge: fc17405 ee2de56

Also note the 3 dots ... instead of two!

For a list of changed files, you can use:

git diff fc17405...ee2de56 --name-only

Javascript: output current datetime in YYYY/mm/dd hh:m:sec format

No library, one line, properly padded

const str = (new Date()).toISOString().slice(0, 19).replace(/-/g, "/").replace("T", " ");

It uses the built-in function Date.toISOString(), chops off the ms, replaces the hyphens with slashes, and replaces the T with a space to go from say '2019-01-05T09:01:07.123' to '2019/01/05 09:01:07'.

Local time instead of UTC

const now = new Date();
const offsetMs = now.getTimezoneOffset() * 60 * 1000;
const dateLocal = new Date(now.getTime() - offsetMs);
const str = dateLocal.toISOString().slice(0, 19).replace(/-/g, "/").replace("T", " ");

How to compare Boolean?

As long as checker is not null, you may use !checker as posted. This is possible since Java 5, because this Boolean variable will be autoboxed to the primivite boolean value.

How to add google-play-services.jar project dependency so my project will run and present map

Some of the solutions described here did not work for me. Others did, however they produced warnings on runtime and javadoc was still not linked. After some experimenting, I managed to solve this. The steps are:

  1. Install the Google Play Services as recommended on Android Developers.

  2. Set up your project as recommended on Android Developers.

  3. If you followed 1. and 2., you should see two projects in your workspace: your project and google-play-services_lib project. Copy the docs folder which contains the javadoc from <android-sdk>/extras/google/google_play_services/ to libs folder of your project.

  4. Copy google-play-services.jar from <android-sdk>/extras/google/google_play_services/libproject/google-play-services_lib/libs to 'libs' folder of your project.

  5. In google-play-services_lib project, edit libs/google-play-services.jar.properties . The <path> in doc=<path> should point to the subfolder reference of the folder docs, which you created in step 3.

  6. In Eclipse, do Project > Clean. Done, javadoc is now linked.

Returning a value even if no result

You can use COALESCE

SELECT COALESCE(SUM(column),0)
FROM   table

How to make sure docker's time syncs with that of the host?

Although this is not a general solution for every host, someone may find it useful. If you know where you are based (UK for me) then look at tianon's answer here.

FROM alpine:3.6
RUN apk add --no-cache tzdata
ENV TZ Europe/London

This is what I added to my Dockerfile ^ and the timezone problem was fixed.

CSS flexbox not working in IE10

As Ennui mentioned, IE 10 supports the -ms prefixed version of Flexbox (IE 11 supports it unprefixed). The errors I can see in your code are:

  • You should have display: -ms-flexbox instead of display: -ms-flex
  • I think you should specify all 3 flex values, like flex: 0 1 auto to avoid ambiguity

So the final updated code is...

.flexbox form {
    display: -webkit-flex;
    display: -moz-flex;
    display: -ms-flexbox;
    display: -o-flex;
    display: flex;

    /* Direction defaults to 'row', so not really necessary to specify */
    -webkit-flex-direction: row;
    -moz-flex-direction: row;
    -ms-flex-direction: row;
    -o-flex-direction: row;
    flex-direction: row;
}

.flexbox form input[type=submit] {
    width: 31px;
}

.flexbox form input[type=text] {
    width: auto;

    /* Flex should have 3 values which is shorthand for 
       <flex-grow> <flex-shrink> <flex-basis> */
    -webkit-flex: 1 1 auto;
    -moz-flex: 1 1 auto;
    -ms-flex: 1 1 auto;
    -o-flex: 1 1 auto;
    flex: 1 1 auto;

    /* I don't think you need 'display: flex' on child elements * /
    display: -webkit-flex;
    display: -moz-flex;
    display: -ms-flex;
    display: -o-flex;
    display: flex;
    /**/
}

Convert a byte array to integer in Java and vice versa

A basic implementation would be something like this:

public class Test {
    public static void main(String[] args) {
        int[] input = new int[] { 0x1234, 0x5678, 0x9abc };
        byte[] output = new byte[input.length * 2];

        for (int i = 0, j = 0; i < input.length; i++, j+=2) {
            output[j] = (byte)(input[i] & 0xff);
            output[j+1] = (byte)((input[i] >> 8) & 0xff);
        }

        for (int i = 0; i < output.length; i++)
            System.out.format("%02x\n",output[i]);
    }
}

In order to understand things you can read this WP article: http://en.wikipedia.org/wiki/Endianness

The above source code will output 34 12 78 56 bc 9a. The first 2 bytes (34 12) represent the first integer, etc. The above source code encodes integers in little endian format.

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

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

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

startActivityForResult() from a Fragment and finishing child Activity, doesn't call onActivityResult() in Fragment

just try this:

_x000D_
_x000D_
//don't call getActivity()
getActivity().startActivityForResult(intent, REQ_CODE);

//just call 
startActivityForResult(intent, REQ_CODE);
//directly from fragment
_x000D_
_x000D_
_x000D_

Converting milliseconds to a date (jQuery/JavaScript)

_x000D_
_x000D_
var time = new Date().getTime(); // get your number
var date = new Date(time); // create Date object

console.log(date.toString()); // result: Wed Jan 12 2011 12:42:46 GMT-0800 (PST)
_x000D_
_x000D_
_x000D_

regular expression for DOT

[+*?.] Most special characters have no meaning inside the square brackets. This expression matches any of +, *, ? or the dot.

WebDriver - wait for element using Java

This is how I do it in my code.

WebDriverWait wait = new WebDriverWait(webDriver, timeoutInSeconds);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id<locator>));

or

wait.until(ExpectedConditions.elementToBeClickable(By.id<locator>));

to be precise.

See also:

RestSharp simple complete example

Changing

RestResponse response = client.Execute(request);

to

IRestResponse response = client.Execute(request);

worked for me.

How to scroll to bottom in a ScrollView on activity startup

This works for me:

scrollview.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        scrollview.post(new Runnable() {
            public void run() {
                scrollview.fullScroll(View.FOCUS_DOWN);
            }
        });
    }
});

Create ul and li elements in javascript.

Try out below code snippet:

 var list = [];
 var text;

function update() {
    console.log(list);    

    for (var i = 0; i < list.length; i++) {
       console.log( i );
       var letters;
       var ul = document.getElementById("list");
       var li = document.createElement("li");

       li.appendChild(document.createTextNode(list[i]));
       ul.appendChild(li);

       letters += "<li>"  + list[i] + "</li>";
    }

 document.getElementById("list").innerHTML = letters;

}

function myFunction() {
    text = prompt("enter TODO");  
    list.push(text);
    update();
}   

How to change pivot table data source in Excel?

Just figured it out-click anywhere in the table, then go to the tabs at the top of the page and select Options-from there you'll see a Change Data Source selection.

Listen to port via a Java socket

You need to use a ServerSocket. You can find an explanation here.

Android SDK Setup under Windows 7 Pro 64 bit

Windows 7 isn't a supported platform as far as I know. I use the SDK on 64-bit Ubuntu 9.10 and it works fine, though I did have to install the ia32libs or libcurses bombed every time. That was Eclipse related.

The SDK sys reqs makes it clear whatever platform you run, you must be able to run 32-bit code.

set height of imageview as matchparent programmatically

imageView.getLayoutParams().height= ViewGroup.LayoutParams.MATCH_PARENT;

Unable to ping vmware guest from another vmware guest

I have been able to ping from VMs and the host by setting the VM's network settings to "Bridged" mode. This, in short, places them all on the same physical network. This coupled with your static IP addresses should do the trick.

How to increase memory limit for PHP over 2GB?

I had the same problem with commandline php even when ini_set("memory_limit", "-1"); was set, so the limit is in php not from apache.

You should check if you are using the 64bit version of php.

Look at this question about Checking if code is running on 64-bit PHP to find out what php you are using.

I think your php is compiled in 32 bit.

How to split a string by spaces in a Windows batch file?

The following code will split a string with an arbitrary number of substrings:

@echo off
setlocal ENABLEDELAYEDEXPANSION

REM Set a string with an arbitrary number of substrings separated by semi colons
set teststring=The;rain;in;spain

REM Do something with each substring
:stringLOOP
    REM Stop when the string is empty
    if "!teststring!" EQU "" goto END

    for /f "delims=;" %%a in ("!teststring!") do set substring=%%a

        REM Do something with the substring - 
        REM we just echo it for the purposes of demo
        echo !substring!

REM Now strip off the leading substring
:striploop
    set stripchar=!teststring:~0,1!
    set teststring=!teststring:~1!

    if "!teststring!" EQU "" goto stringloop

    if "!stripchar!" NEQ ";" goto striploop

    goto stringloop
)

:END
endlocal

Strange PostgreSQL "value too long for type character varying(500)"

Character varying is different than text. Try running

ALTER TABLE product_product ALTER COLUMN code TYPE text;

That will change the column type to text, which is limited to some very large amount of data (you would probably never actually hit it.)

How do I use JDK 7 on Mac OSX?

As of April 27th there is an offical Oracle release of Java SE 7u4. Download the disk image and run the installer - then see the Mac readme.

How to get the list of all installed color schemes in Vim?

Looking at my system's menu.vim (look for 'Color Scheme submenu') and @chappar's answer, I came up with the following function:

" Returns the list of available color schemes
function! GetColorSchemes()
   return uniq(sort(map(
   \  globpath(&runtimepath, "colors/*.vim", 0, 1),  
   \  'fnamemodify(v:val, ":t:r")'
   \)))
endfunction

It does the following:

  1. Gets the list of available color scheme scripts under all runtime paths (globpath, runtimepath)
  2. Maps the script paths to their base names (strips parent dirs and extension) (map, fnamemodify)
  3. Sorts and removes duplicates (uniq, sort)

Then to use the function I do something like this:

let s:schemes = GetColorSchemes()
if index(s:schemes, 'solarized') >= 0
   colorscheme solarized
elseif index(s:schemes, 'darkblue') >= 0
   colorscheme darkblue
endif

Which means I prefer the 'solarized' and then the 'darkblue' schemes; if none of them is available, do nothing.

How to select all elements with a particular ID in jQuery?

Your document should not contain two divs with the same id. This is invalid HTML, and as a result, the underlying DOM API does not support it.

From the HTML standard:

id = name [CS] This attribute assigns a name to an element. This name must be unique in a document.

You can either assign different ids to each div and select them both using $('#id1, #id2). Or assign the same class to both elements (.cls for example), and use $('.cls') to select them both.

Why is the GETDATE() an invalid identifier

SYSDATE and GETDATE perform identically.

SYSDATE is compatible with Oracle syntax, and GETDATE is compatible with Microsoft SQL Server syntax.

Shell - How to find directory of some command?

An alternative to type -a is command -V

Since most of the times I am interested in the first result only, I also pipe from head. This way the screen will not flood with code in case of a bash function.

command -V lshw | head -n1

How to make multiple divs display in one line but still retain width?

Flex is the better way. Just try..

display: flex;

Multi-Line Comments in Ruby?

Despite the existence of =begin and =end, the normal and a more correct way to comment is to use #'s on each line. If you read the source of any ruby library, you will see that this is the way multi-line comments are done in almost all cases.

get list of packages installed in Anaconda

For script creation at Windows cmd or powershell prompt:

C:\ProgramData\Anaconda3\Scripts\activate.bat C:\ProgramData\Anaconda3
conda list
pip list

Re-doing a reverted merge in Git

Let's assume you have such history

---o---o---o---M---W---x-------x-------*
              /                      
      ---A---B

Where A, B failed commits and W - is revert of M

So before I start fixing found problems I do cherry-pick of W commit to my branch

git cherry-pick -x W

Then I revert W commit on my branch

git revert W 

After I can continue fixing.

The final history could look like:

---o---o---o---M---W---x-------x-------*
              /                       /     
      ---A---B---W---W`----------C---D

When I send a PR it will clearly shows that PR is undo revert and adds some new commits.

MySQL Delete all rows from table and reset ID to zero

Do not delete, use truncate:

Truncate table XXX

The table handler does not remember the last used AUTO_INCREMENT value, but starts counting from the beginning. This is true even for MyISAM and InnoDB, which normally do not reuse sequence values.

Source.

slideToggle JQuery right to left

I know it's been a year since this was asked, but just for people that are going to visit this page I am posting my solution.

By using what @Aldi Unanto suggested here is a more complete answer:

  jQuery('.show_hide').click(function(e) {
    e.preventDefault();
    if (jQuery('.slidingDiv').is(":visible") ) {
      jQuery('.slidingDiv').stop(true,true).hide("slide", { direction: "left" }, 200);
    } else {
      jQuery('.slidingDiv').stop(true,true).show("slide", { direction: "left" }, 200);
    }
  });

First I prevent the link from doing anything on click. Then I add a check if the element is visible or not. When visible I hide it. When hidden I show it. You can change direction to left or right and duration from 200 ms to anything you like.

Edit: I have also added

.stop(true,true)

in order to clearQueue and jumpToEnd. Read about jQuery stop here

What to do with "Unexpected indent" in python?

This error can also occur when pasting something into the Python interpreter (terminal/console).

Note that the interpreter interprets an empty line as the end of an expression, so if you paste in something like

def my_function():
    x = 3

    y = 7

the interpreter will interpret the empty line before y = 7 as the end of the expression, i.e. that you're done defining your function, and the next line - y = 7 will have incorrect indentation because it is a new expression.

Pure css close button

I become frustrated trying to implement something that looked consistent in all browsers and went with an svg button which can be styled with css.

html

<svg>
    <circle cx="12" cy="12" r="11" stroke="black" stroke-width="2" fill="white" />
    <path stroke="black" stroke-width="4" fill="none" d="M6.25,6.25,17.75,17.75" />
    <path stroke="black" stroke-width="4" fill="none" d="M6.25,17.75,17.75,6.25" />
</svg>

css

svg {
    cursor: pointer;
    height: 24px;
    width: 24px;
}
svg > circle {
    stroke: black;
    fill: white;
}
svg > path {
    stroke: black;
}
svg:hover > circle {
    fill: red;
}
svg:hover > path {
    stroke: white;
}

http://jsfiddle.net/purves/5exav2m7/

How to avoid the "Circular view path" exception with Spring MVC test

@Controller ? @RestController

I had the same issue and I noticed that my controller was also annotated with @Controller. Replacing it with @RestController solved the issue. Here is the explanation from Spring Web MVC:

@RestController is a composed annotation that is itself meta-annotated with @Controller and @ResponseBody indicating a controller whose every method inherits the type-level @ResponseBody annotation and therefore writes directly to the response body vs view resolution and rendering with an HTML template.

Excel: VLOOKUP that returns true or false?

You can use:

=IF(ISERROR(VLOOKUP(lookup value,table array,column no,FALSE)),"FALSE","TRUE")

How to get current user who's accessing an ASP.NET application?

The best practice is to check the Identity.IsAuthenticated Property first and then get the usr.UserName like this:

string userName = string.Empty;

if (System.Web.HttpContext.Current != null && 
    System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
{
    System.Web.Security.MembershipUser usr = Membership.GetUser();
    if (usr != null)
    {  
        userName = usr.UserName;
    }
}

How to plot a function curve in R

I did some searching on the web, and this are some ways that I found:

The easiest way is using curve without predefined function

curve(x^2, from=1, to=50, , xlab="x", ylab="y")

enter image description here

You can also use curve when you have a predfined function

eq = function(x){x*x}
curve(eq, from=1, to=50, xlab="x", ylab="y")

enter image description here

If you want to use ggplot,

library("ggplot2")
eq = function(x){x*x}
ggplot(data.frame(x=c(1, 50)), aes(x=x)) + 
  stat_function(fun=eq)

enter image description here

Simple JavaScript login form validation

Add a property to the form method="post".

Like this:

<form name="loginform" method="post">

How do I select the parent form based on which submit button is clicked?

I found this answer when searching for how to find the form of an input element. I wanted to add a note because there is now a better way than using:

var form = $(this).parents('form:first');

I'm not sure when it was added to jQuery but the closest() method does exactly what's needed more cleanly than using parents(). With closest the code can be changed to this:

var form = $(this).closest('form');

It traverses up and finds the first element which matches what you are looking for and stops there, so there's no need to specify :first.

How to create a file in Ruby

Try using "w+" as the write mode instead of just "w":

File.open("out.txt", "w+") { |file| file.write("boo!") }

Rails has_many with alias name

Give this a shot:

has_many :jobs, foreign_key: "user_id", class_name: "Task"

Note, that :as is used for polymorphic associations.

When do I need to use a semicolon vs a slash in Oracle SQL?

Almost all Oracle deployments are done through SQL*Plus (that weird little command line tool that your DBA uses). And in SQL*Plus a lone slash basically means "re-execute last SQL or PL/SQL command that I just executed".

See

http://ss64.com/ora/syntax-sqlplus.html

Rule of thumb would be to use slash with things that do BEGIN .. END or where you can use CREATE OR REPLACE.

For inserts that need to be unique use

INSERT INTO my_table ()
SELECT <values to be inserted>
FROM dual
WHERE NOT EXISTS (SELECT 
                  FROM my_table
                  WHERE <identify data that you are trying to insert>)

Bootstrap: Use .pull-right without having to hardcode a negative margin-top

Float elements will be rendered at the line they are normally in the layout. To fix this, you have two choices:

Move the header and the p after the login box:

<div class='container'>
    <div class='hero-unit'>

        <div id='login-box' class='pull-right control-group'>
            <div class='clearfix'>
                <input type='text' placeholder='Username' />
            </div>
            <div class='clearfix'>
                <input type='password' placeholder='Password' />
            </div>
            <button type='button' class='btn btn-primary'>Log in</button>
        </div>

        <h2>Welcome</h2>

        <p>Please log in</p>

    </div>
</div>

Or enclose the left block in a pull-left div, and add a clearfix at the bottom

<div class='container'>
    <div class='hero-unit'>

        <div class="pull-left">

          <h2>Welcome</h2>

          <p>Please log in</p>

        </div>

        <div id='login-box' class='pull-right control-group'>
            <div class='clearfix'>
                <input type='text' placeholder='Username' />
            </div>
            <div class='clearfix'>
                <input type='password' placeholder='Password' />
            </div>
            <button type='button' class='btn btn-primary'>Log in</button>
        </div>

        <div class="clearfix"></div>

    </div>
</div>

How to automatically import data from uploaded CSV or XLS file into Google Sheets

(Mar 2017) The accepted answer is not the best solution. It relies on manual translation using Apps Script, and the code may not be resilient, requiring maintenance. If your legacy system autogenerates CSV files, it's best they go into another folder for temporary processing (importing [uploading to Google Drive & converting] to Google Sheets files).

My thought is to let the Drive API do all the heavy-lifting. The Google Drive API team released v3 at the end of 2015, and in that release, insert() changed names to create() so as to better reflect the file operation. There's also no more convert flag -- you just specify MIMEtypes... imagine that!

The documentation has also been improved: there's now a special guide devoted to uploads (simple, multipart, and resumable) that comes with sample code in Java, Python, PHP, C#/.NET, Ruby, JavaScript/Node.js, and iOS/Obj-C that imports CSV files into Google Sheets format as desired.

Below is one alternate Python solution for short files ("simple upload") where you don't need the apiclient.http.MediaFileUpload class. This snippet assumes your auth code works where your service endpoint is DRIVE with a minimum auth scope of https://www.googleapis.com/auth/drive.file.

# filenames & MIMEtypes
DST_FILENAME = 'inventory'
SRC_FILENAME = DST_FILENAME + '.csv'
SHT_MIMETYPE = 'application/vnd.google-apps.spreadsheet'
CSV_MIMETYPE = 'text/csv'

# Import CSV file to Google Drive as a Google Sheets file
METADATA = {'name': DST_FILENAME, 'mimeType': SHT_MIMETYPE}
rsp = DRIVE.files().create(body=METADATA, media_body=SRC_FILENAME).execute()
if rsp:
    print('Imported %r to %r (as %s)' % (SRC_FILENAME, DST_FILENAME, rsp['mimeType']))

Better yet, rather than uploading to My Drive, you'd upload to one (or more) specific folder(s), meaning you'd add the parent folder ID(s) to METADATA. (Also see the code sample on this page.) Finally, there's no native .gsheet "file" -- that file just has a link to the online Sheet, so what's above is what you want to do.

If not using Python, you can use the snippet above as pseudocode to port to your system language. Regardless, there's much less code to maintain because there's no CSV parsing. The only thing remaining is to blow away the CSV file temp folder your legacy system wrote to.

Insert auto increment primary key to existing table

suppose you don't have column for auto increment like id, no, then you can add using following query:

ALTER TABLE table_name ADD id int NOT NULL AUTO_INCREMENT primary key FIRST

If you've column, then alter to auto increment using following query:

 ALTER TABLE table_name MODIFY column_name datatype(length) AUTO_INCREMENT PRIMARY KEY

Jenkins: Is there any way to cleanup Jenkins workspace?

not allowed to comment, therefore:

The answer from Upen works just fine, but not if you have Jenkins Pipeline Jobs mixed with Freestyle Jobs. There is no such Method as DoWipeWorkspace on Pipeline Jobs. So I modified the Script in order to skip those:

import hudson.model.*
import org.jenkinsci.plugins.workflow.job.WorkflowJob

// For each project
for(item in Hudson.instance.items) {
  // check that job is not building
  if(!item.isBuilding() && !(item instanceof WorkflowJob))
  {
    println("Wiping out workspace of job "+item.name)
    item.doDoWipeOutWorkspace()
  }
  else {
    println("Skipping job "+item.name+", currently building")
  }
}

you could also filter by Job Names if required: item.getDisplayName().toLowerCase().contains("release")

How to use vertical align in bootstrap

http://jsfiddle.net/b9chris/zN39r/

HTML:

<div class="item row">
    <div class="col-xs-12 col-sm-6"><h4>This is some text.</h4></div>
    <div class="col-xs-12 col-sm-6"><h4>This is some more.</h4></div>
</div>

CSS:

div.item div h4 {
    height: 60px;
    vertical-align: middle;    
    display: table-cell;
}

Important notes:

  • The vertical-align: middle; display: table-cell; must be applied to a tag that has no Bootstrap classes applied; it cannot be a col-*, a row, etc.
  • This can't be done without this extra, possibly pointless tag in your HTML, unfortunately.
  • The backgrounds are unnecessary - they're just there for demo purposes. So, you don't need to apply any special rules to the row or col-* tags.
  • It is important to notice the inner tag does not stretch to 100% of the width of its parent; in our scenario this didn't matter but it may to you. If it does, you end up with something closer to some of the other answers here:

http://jsfiddle.net/b9chris/zN39r/1/

CSS:

div.item div {
    background: #fdd;
    table-layout: fixed;
    display: table;
}
div.item div h4 {
    height: 60px;
    vertical-align: middle;    
    display: table-cell;
    background: #eee;
}

Notice the added table-layout and display properties on the col-* tags. This must be applied to the tag(s) that have col-* applied; it won't help on other tags.

SecurityError: Blocked a frame with origin from accessing a cross-origin frame

  • Open the start menu
  • Type windows+R or open "Run
  • Execute the following command.

chrome.exe --user-data-dir="C://Chrome dev session" --disable-web-security

Input and Output binary streams using JERSEY?

Here's another example. I'm creating a QRCode as a PNG via a ByteArrayOutputStream. The resource returns a Response object, and the stream's data is the entity.

To illustrate the response code handling, I've added handling of cache headers (If-modified-since, If-none-matches, etc).

@Path("{externalId}.png")
@GET
@Produces({"image/png"})
public Response getAsImage(@PathParam("externalId") String externalId, 
        @Context Request request) throws WebApplicationException {

    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    // do something with externalId, maybe retrieve an object from the
    // db, then calculate data, size, expirationTimestamp, etc

    try {
        // create a QRCode as PNG from data     
        BitMatrix bitMatrix = new QRCodeWriter().encode(
                data, 
                BarcodeFormat.QR_CODE, 
                size, 
                size
        );
        MatrixToImageWriter.writeToStream(bitMatrix, "png", stream);

    } catch (Exception e) {
        // ExceptionMapper will return HTTP 500 
        throw new WebApplicationException("Something went wrong …")
    }

    CacheControl cc = new CacheControl();
    cc.setNoTransform(true);
    cc.setMustRevalidate(false);
    cc.setNoCache(false);
    cc.setMaxAge(3600);

    EntityTag etag = new EntityTag(HelperBean.md5(data));

    Response.ResponseBuilder responseBuilder = request.evaluatePreconditions(
            updateTimestamp,
            etag
    );
    if (responseBuilder != null) {
        // Preconditions are not met, returning HTTP 304 'not-modified'
        return responseBuilder
                .cacheControl(cc)
                .build();
    }

    Response response = Response
            .ok()
            .cacheControl(cc)
            .tag(etag)
            .lastModified(updateTimestamp)
            .expires(expirationTimestamp)
            .type("image/png")
            .entity(stream.toByteArray())
            .build();
    return response;
}   

Please don't beat me up in case stream.toByteArray() is a no-no memory wise :) It works for my <1KB PNG files...

jQuery: find element by text

Yes, use the jQuery contains selector.

How do I set the driver's python version in spark?

In case you only want to change the python version for current task, you can use following pyspark start command:

    PYSPARK_DRIVER_PYTHON=/home/user1/anaconda2/bin/python PYSPARK_PYTHON=/usr/local/anaconda2/bin/python pyspark --master ..

Bootstrap footer at the bottom of the page

In my case for Bootstrap4:

<body class="d-flex flex-column min-vh-100">
    <div class="wrapper flex-grow-1"></div>
    <footer></footer>
</body>

console.log not working in Angular2 Component (Typescript)

Also try to update your browser because Angular need latest browser. check: https://angular.io/guide/browser-support

I fixed console.log issue after updating latest browser.

CSS rule to apply only if element has BOTH classes

Below applies to all tags with the following two classes

.abc.xyz {  
  width: 200px !important;
}

applies to div tags with the following two classes

div.abc.xyz {  
  width: 200px !important;
}

If you wanted to modify this using jQuery

$(document).ready(function() {
  $("div.abc.xyz").width("200px");
});

Python 3 sort a dict by its values

To sort dictionary, we could make use of operator module. Here is the operator module documentation.

import operator                             #Importing operator module
dc =  {"aa": 3, "bb": 4, "cc": 2, "dd": 1}  #Dictionary to be sorted

dc_sort = sorted(dc.items(),key = operator.itemgetter(1),reverse = True)
print dc_sort

Output sequence will be a sorted list :

[('bb', 4), ('aa', 3), ('cc', 2), ('dd', 1)]

If we want to sort with respect to keys, we can make use of

dc_sort = sorted(dc.items(),key = operator.itemgetter(0),reverse = True)

Output sequence will be :

[('dd', 1), ('cc', 2), ('bb', 4), ('aa', 3)]

Is it possible to get only the first character of a String?

Use ld.charAt(0). It will return the first char of the String.

With ld.substring(0, 1), you can get the first character as String.

Opening XML page shows "This XML file does not appear to have any style information associated with it."

This XML file does not appear to have any style information associated with it. The document tree is shown below.

You will get this error in the client side when the client (the webbrowser) for some reason interprets the HTTP response content as text/xml instead of text/html and the parsed XML tree doesn't have any XML-stylesheet. In other words, the webbrowser incorrectly parsed the retrieved HTTP response content as XML instead of as HTML due to the wrong or missing HTTP response content type.

In case of JSF/Facelets files which have the default extension of .xhtml, that can in turn happen if the HTTP request hasn't invoked the FacesServlet and thus it wasn't able to parse the Facelets file and generate the desired HTML output based on the XHTML source code. Firefox is then merely guessing the HTTP response content type based on the .xhtml file extension which is in your Firefox configuration apparently by default interpreted as text/xml.

You need to make sure that the HTTP request URL, as you see in browser's address bar, matches the <url-pattern> of the FacesServlet as registered in webapp's web.xml, so that it will be invoked and be able to generate the desired HTML output based on the XHTML source code. If it's for example *.jsf, then you need to open the page by /some.jsf instead of /some.xhtml. Alternatively, you can also just change the <url-pattern> to *.xhtml. This way you never need to fiddle with virtual URLs.

See also:


Note thus that you don't actually need a XML stylesheet. This all was just misinterpretation by the webbrowser while trying to do its best to make something presentable out of the retrieved HTTP response content. It should actually have retrieved the properly generated HTML output, Firefox surely knows precisely how to deal with HTML content.

What are the advantages and disadvantages of recursion?

Recursion means a function calls repeatedly

It uses system stack to accomplish it's task. As stack uses LIFO approach and when a function is called the controlled is moved to where function is defined which has it is stored in memory with some address, this address is stored in stack

Secondly, it reduces a time complexity of a program.

Though bit off-topic,a bit related. Must read. : Recursion vs Iteration

Error: Cannot find module html

Use

res.sendFile()

instead of

res.render().

What your trying to do is send a whole file.

This worked for me.

how to loop through rows columns in excel VBA Macro

This one is similar to @Wilhelm's solution. The loop automates based on a range created by evaluating the populated date column. This was slapped together based strictly on the conversation here and screenshots.

Please note: This assumes that the headers will always be on the same row (row 8). Changing the first row of data (moving the header up/down) will cause the range automation to break unless you edit the range block to take in the header row dynamically. Other assumptions include that VOL and CAPACITY formula column headers are named "Vol" and "Cap" respectively.

Sub Loop3()

Dim dtCnt As Long
Dim rng As Range
Dim frmlas() As String

Application.ScreenUpdating = False

'The following code block sets up the formula output range
dtCnt = Sheets("Loop").Range("A1048576").End(xlUp).Row              'lowest date column populated
endHead = Sheets("Loop").Range("XFD8").End(xlToLeft).Column         'right most header populated
Set rng = Sheets("Loop").Range(Cells(9, 2), Cells(dtCnt, endHead))  'assigns range for automation

ReDim frmlas(1)      'array assigned to formula strings
    'VOL column formula
frmlas(0) = "VOL FORMULA"
    'CAPACITY column formula
frmlas(1) = "CAP FORMULA"

For i = 1 To rng.Columns.count
If rng(0, i).Value = "Vol" Then         'checks for volume formula column
    For j = 1 To rng.Rows.count
        rng(j, i).Formula= frmlas(0)    'inserts volume formula
    Next j
ElseIf rng(0, i).Value = "Cap" Then     'checks for capacity formula column
    For j = 1 To rng.Rows.count
        rng(j, i).Formula = frmlas(1)   'inserts capacity formula
    Next j
End If
Next i

Application.ScreenUpdating = True

End Sub

What's the pythonic way to use getters and setters?

Try this: Python Property

The sample code is:

class C(object):
    def __init__(self):
        self._x = None

    @property
    def x(self):
        """I'm the 'x' property."""
        print("getter of x called")
        return self._x

    @x.setter
    def x(self, value):
        print("setter of x called")
        self._x = value

    @x.deleter
    def x(self):
        print("deleter of x called")
        del self._x


c = C()
c.x = 'foo'  # setter called
foo = c.x    # getter called
del c.x      # deleter called

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". error

You haven't specify version in your maven dependency file may be thats why it is not picking the latest jar
As well as you need another deppendency with slf4j-log4j12 artifact id.
Include this in your pom file

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

Let me know if error is still not resolved
I also recomend you to see this link

Not able to access adb in OS X through Terminal, "command not found"

I couldn't get the stupid path working so I created an alias for abd

alias abd ="~/Library/Android/sdk/platform-tools/adb"

works fine.

use Lodash to sort array of object by value

You can use lodash sortBy (https://lodash.com/docs/4.17.4#sortBy).

Your code could be like:

const myArray = [  
   {  
      "id":25,
      "name":"Anakin Skywalker",
      "createdAt":"2017-04-12T12:48:55.000Z",
      "updatedAt":"2017-04-12T12:48:55.000Z"
   },
   {  
      "id":1,
      "name":"Luke Skywalker",
      "createdAt":"2017-04-12T11:25:03.000Z",
      "updatedAt":"2017-04-12T11:25:03.000Z"
   }
]

const myOrderedArray = _.sortBy(myArray, o => o.name)

How to prevent Browser cache on Angular 2 site?

Found a way to do this, simply add a querystring to load your components, like so:

@Component({
  selector: 'some-component',
  templateUrl: `./app/component/stuff/component.html?v=${new Date().getTime()}`,
  styleUrls: [`./app/component/stuff/component.css?v=${new Date().getTime()}`]
})

This should force the client to load the server's copy of the template instead of the browser's. If you would like it to refresh only after a certain period of time you could use this ISOString instead:

new Date().toISOString() //2016-09-24T00:43:21.584Z

And substring some characters so that it will only change after an hour for example:

new Date().toISOString().substr(0,13) //2016-09-24T00

Hope this helps

Why doesn't os.path.join() work in this case?

Try combo of split("/") and * for strings with existing joins.

import os

home = '/home/build/test/sandboxes/'
todaystr = '042118'
new = '/new_sandbox/'

os.path.join(*home.split("/"), todaystr, *new.split("/"))


How it works...

split("/") turns existing path into list: ['', 'home', 'build', 'test', 'sandboxes', '']

* in front of the list breaks out each item of list its own parameter

How to use the ProGuard in Android Studio?

Here is Some of Most Common Proguard Rules that you need to add in proguard-rules.pro file in Android Sutdio.

ButterKnife

 -keep class butterknife.** { *; }
 -dontwarn butterknife.internal.**
 -keep class **$$ViewBinder { *; }
 -keepclasseswithmembernames class * {
        @butterknife.* <fields>;
  }
 -keepclasseswithmembernames class * {
        @butterknife.* <methods>;
  }

Retrofit

 -dontwarn retrofit.**
 -keep class retrofit.** { *; }
 -keepattributes Signature
 -keepattributes Exceptions

OkHttp3

 -keepattributes Signature
 -keepattributes *Annotation*
 -keep class okhttp3.** { *; }
 -keep interface okhttp3.** { *; }
 -dontwarn okhttp3.** 
 -keep class sun.misc.Unsafe { *; }
 -dontwarn java.nio.file.*
 -dontwarn org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement 

Gson

 -keep class sun.misc.Unsafe { *; }
 -keep class com.google.gson.stream.** { *; }

Code obfuscation

-keepclassmembers class com.yourname.models** { <fields>; }

random number generator between 0 - 1000 in c#

Have you tried this

Random integer between 0 and 1000(1000 not included):

Random random = new Random();
int randomNumber = random.Next(0, 1000);

Loop it as many times you want

What causes signal 'SIGILL'?

Make sure that all functions with non-void return type have a return statement.

While some compilers automatically provide a default return value, others will send a SIGILL or SIGTRAP at runtime when trying to leave a function without a return value.

What's the fastest way to convert String to Number in JavaScript?

A fast way to convert strings to an integer is to use a bitwise or, like so:

x | 0

While it depends on how it is implemented, in theory it should be relatively fast (at least as fast as +x) since it will first cast x to a number and then perform a very efficient or.

PHP substring extraction. Get the string before the first '/' or the whole string

You can also use this one line solution

list($substring) = explode("/", $string);

Transform char array into String

Visit https://www.arduino.cc/en/Reference/StringConstructor to solve the problem easily.

This worked for me:

char yyy[6];

String xxx;

yyy[0]='h';

yyy[1]='e';

yyy[2]='l';

yyy[3]='l';

yyy[4]='o';

yyy[5]='\0';

xxx=String(yyy);

Auto highlight text in a textbox control

If you need to do this for a large number of textboxes (in Silverlight or WPF), then you can use the technique used in the blog post: http://dnchannel.blogspot.com/2010/01/silverlight-3-auto-select-text-in.html. It uses Attached Properties and Routed Events.

python paramiko ssh

###### Use paramiko to connect to LINUX platform############
import paramiko

ip='server ip'
port=22
username='username'
password='password'
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip,port,username,password)

--------Connection Established-----------------------------

######To run shell commands on remote connection###########
import paramiko

ip='server ip'
port=22
username='username'
password='password'
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip,port,username,password)


stdin,stdout,stderr=ssh.exec_command(cmd)
outlines=stdout.readlines()
resp=''.join(outlines)
print(resp) # Output 

Display an array in a readable/hierarchical format

For single arrays you can use implode, it has a cleaner result to print.

<?php
$msg = array('msg1','msg2','msg3');
echo implode('<br />',$msg);
echo '<br />----------------------<br/>';

echo nl2br(implode("\n",$msg));
echo '<br />----------------------<br/>';
?>

For multidimensional arrays you need to combine with some sort of loop.

<?php
$msgs[] = $msg;
$msgs[] = $msg;
$msgs[] = $msg;
$msgs[] = $msg;
$msgs[] = $msg;
foreach($msgs as $msg) {
    echo implode('<br />',$msg);
    echo '<br />----------------------<br/>';
}
?>

How to link C++ program with Boost using CMake

Here is my take:

cmake_minimum_required(VERSION 3.15)

project(TryOuts LANGUAGES CXX)

find_package(Boost QUIET REQUIRED COMPONENTS program_options)

if(NOT Boost_FOUND)
    message(FATAL_ERROR "Boost Not found")
endif()

add_executable(helloworld main.cpp)

target_link_libraries(helloworld PUBLIC Boost::program_options)

TypeScript and field initializers

Update

Since writing this answer, better ways have come up. Please see the other answers below that have more votes and a better answer. I cannot remove this answer since it's marked as accepted.


Old answer

There is an issue on the TypeScript codeplex that describes this: Support for object initializers.

As stated, you can already do this by using interfaces in TypeScript instead of classes:

interface Name {
    first: string;
    last: string;
}
class Person {
    name: Name;
    age: number;
}

var bob: Person = {
    name: {
        first: "Bob",
        last: "Smith",
    },
    age: 35,
};

Django: Calling .update() on a single model instance retrieved by .get()?

if you want only to update model if exist (without create it):

Model.objects.filter(id = 223).update(field1 = 2)

mysql query:

UPDATE `model` SET `field1` = 2 WHERE `model`.`id` = 223

How do I fix the npm UNMET PEER DEPENDENCY warning?

Today available Angular 2 rc.7, and I had a similar problem with [email protected] UNMET PEER DEPENDENCY.

If you, like me, simply replaced @angular/...rc.6 to @angular/...rc.7 - it's not enough. Because, for example, @angular/router has no rc.6 version.

In this case, better review package.json in Quick start

Why can't I have abstract static methods in C#?

Static methods are not instantiated as such, they're just available without an object reference.

A call to a static method is done through the class name, not through an object reference, and the Intermediate Language (IL) code to call it will call the abstract method through the name of the class that defined it, not necessarily the name of the class you used.

Let me show an example.

With the following code:

public class A
{
    public static void Test()
    {
    }
}

public class B : A
{
}

If you call B.Test, like this:

class Program
{
    static void Main(string[] args)
    {
        B.Test();
    }
}

Then the actual code inside the Main method is as follows:

.entrypoint
.maxstack 8
L0000: nop 
L0001: call void ConsoleApplication1.A::Test()
L0006: nop 
L0007: ret 

As you can see, the call is made to A.Test, because it was the A class that defined it, and not to B.Test, even though you can write the code that way.

If you had class types, like in Delphi, where you can make a variable referring to a type and not an object, you would have more use for virtual and thus abstract static methods (and also constructors), but they aren't available and thus static calls are non-virtual in .NET.

I realize that the IL designers could allow the code to be compiled to call B.Test, and resolve the call at runtime, but it still wouldn't be virtual, as you would still have to write some kind of class name there.

Virtual methods, and thus abstract ones, are only useful when you're using a variable which, at runtime, can contain many different types of objects, and you thus want to call the right method for the current object you have in the variable. With static methods you need to go through a class name anyway, so the exact method to call is known at compile time because it can't and won't change.

Thus, virtual/abstract static methods are not available in .NET.

Adding item to Dictionary within loop

In your current code, what Dictionary.update() does is that it updates (update means the value is overwritten from the value for same key in passed in dictionary) the keys in current dictionary with the values from the dictionary passed in as the parameter to it (adding any new key:value pairs if existing) . A single flat dictionary does not satisfy your requirement , you either need a list of dictionaries or a dictionary with nested dictionaries.

If you want a list of dictionaries (where each element in the list would be a diciotnary of a entry) then you can make case_list as a list and then append case to it (instead of update) .

Example -

case_list = []
for entry in entries_list:
    case = {'key1': entry[0], 'key2': entry[1], 'key3':entry[2] }
    case_list.append(case)

Or you can also have a dictionary of dictionaries with the key of each element in the dictionary being entry1 or entry2 , etc and the value being the corresponding dictionary for that entry.

case_list = {}
for entry in entries_list:
    case = {'key1': value, 'key2': value, 'key3':value }
    case_list[entryname] = case  #you will need to come up with the logic to get the entryname.

How do I get the selected element by name and then get the selected value from a dropdown using jQuery?

To add to the answers here, ensure there's no space between the select and [name...

Wrong:

'select [name=' + name + ']'
       ^

Right:

'select[name=' + name + ']'

Angular - Use pipes in services and components

Yes, it is possible by using a simple custom pipe. Advantage of using custom pipe is if we need to update the date format in future, we can go and update a single file.

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

@Pipe({
    name: 'dateFormatPipe',
})
export class dateFormatPipe implements PipeTransform {
    transform(value: string) {
       var datePipe = new DatePipe("en-US");
        value = datePipe.transform(value, 'MMM-dd-yyyy');
        return value;
    }
}

{{currentDate | dateFormatPipe }}

You can always use this pipe anywhere , component, services etc

For example:

export class AppComponent {
  currentDate : any;
  newDate : any;
  constructor(){
    this.currentDate = new Date().getTime();
    let dateFormatPipeFilter = new dateFormatPipe();
    this.newDate = dateFormatPipeFilter.transform(this.currentDate);
    console.log(this.newDate);
}

Don't forget to import dependencies.

import { Component } from '@angular/core';
import {dateFormatPipe} from './pipes'

Custom Pipe examples and more info

JPA OneToMany and ManyToOne throw: Repeated column in mapping for entity column (should be mapped with insert="false" update="false")

I am not really sure about your question (the meaning of "empty table" etc, or how mappedBy and JoinColumn were not working).

I think you were trying to do a bi-directional relationships.

First, you need to decide which side "owns" the relationship. Hibernate is going to setup the relationship base on that side. For example, assume I make the Post side own the relationship (I am simplifying your example, just to keep things in point), the mapping will look like:

(Wish the syntax is correct. I am writing them just by memory. However the idea should be fine)

public class User{
    @OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
    private List<Post> posts;
}


public class Post {
    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="user_id")
    private User user;
}

By doing so, the table for Post will have a column user_id which store the relationship. Hibernate is getting the relationship by the user in Post (Instead of posts in User. You will notice the difference if you have Post's user but missing User's posts).

You have mentioned mappedBy and JoinColumn is not working. However, I believe this is in fact the correct way. Please tell if this approach is not working for you, and give us a bit more info on the problem. I believe the problem is due to something else.


Edit:

Just a bit extra information on the use of mappedBy as it is usually confusing at first. In mappedBy, we put the "property name" in the opposite side of the bidirectional relationship, not table column name.

Creating an array of objects in Java

Here is the clear example of creating array of 10 employee objects, with a constructor that takes parameter:

public class MainClass
{  
    public static void main(String args[])
    {
        System.out.println("Hello, World!");
        //step1 : first create array of 10 elements that holds object addresses.
        Emp[] employees = new Emp[10];
        //step2 : now create objects in a loop.
        for(int i=0; i<employees.length; i++){
            employees[i] = new Emp(i+1);//this will call constructor.
        }
    }
}

class Emp{
    int eno;
    public Emp(int no){
        eno = no;
        System.out.println("emp constructor called..eno is.."+eno);
    }
}

Questions every good PHP Developer should be able to answer

Admittedly, I stole this question from somewhere else (can't remember where I read it any more) but thought it was funny:

Q: What is T_PAAMAYIM_NEKUDOTAYIM?
A: Its the scope resolution operator (double colon)

An experienced PHP'er immediately knows what it means. Less experienced (and not Hebrew) developers may want to read this.

But more serious questions now:


Q: What is the cause of this warning: 'Warning: Cannot modify header information - headers already sent', and what is a good practice to prevent it?
A: Cause: body data was sent, causing headers to be sent too.
Prevention: Be sure to execute header specific code first before you output any body data. Be sure you haven't accidentally sent out whitespace or any other characters.


Q: What is wrong with this query: "SELECT * FROM table WHERE id = $_POST[ 'id' ]"?
A: 1. It is vulnarable to SQL injection. Never use user input directly in queries. Sanitize it first. Preferebly use prepared statements (PDO) 2. Don't select all columns (*), but specify every single column. This is predominantly ment to prevent queries hogging up memory when for instance a BLOB column is added at some point in the future.


Q: What is wrong with this if statement: if( !strpos( $haystack, $needle ) ...?
A: strpos returns the index position of where it first found the $needle, which could be 0. Since 0 also resolves to false the solution is to use strict comparison: if( false !== strpos( $haystack, $needle )...


Q: What is the preferred way to write this if statement, and why?
if( 5 == $someVar ) or if( $someVar == 5 )
A: The former, as it prevents accidental assignment of 5 to $someVar when you forget to use 2 equalsigns ($someVar = 5), and will cause an error, the latter won't.


Q: Given this code:

function doSomething( &$arg )
{
    $return = $arg;
    $arg += 1;
    return $return;
}

$a = 3;
$b = doSomething( $a );

...what is the value of $a and $b after the function call and why?
A: $a is 4 and $b is 3. The former because $arg is passed by reference, the latter because the return value of the function is a copy of (not a reference to) the initial value of the argument.


OOP specific

Q: What is the difference between public, protected and private in a class definition?
A: public makes a class member available to "everyone", protected makes the class member available to only itself and derived classes, private makes the class member only available to the class itself.


Q: What is wrong with this code:

class SomeClass
{
    protected $_someMember;

    public function __construct()
    {
        $this->_someMember = 1;
    }

    public static function getSomethingStatic()
    {
        return $this->_someMember * 5; // here's the catch
    }
}

A: Static methods don't have access to $this, because static methods can be executed without instantiating a class.


Q: What is the difference between an interface and an abstract class?
A: An interface defines a contract between an implementing class is and an object that calls the interface. An abstract class pre-defines certain behaviour for classes that will extend it. To a certain degree this can also be considered a contract, since it garantuees certain methods to exist.


Q: What is wrong with classes that predominantly define getters and setters, that map straight to it's internal members, without actually having methods that execute behaviour?
A: This might be a code smell since the object acts as an ennobled array, without much other use.


Q: Why is PHP's implementation of the use of interfaces sub-optimal?
A: PHP doesn't allow you to define the expected return type of the method's, which essentially renders interfaces pretty useless. :-P

Unsigned keyword in C++

You can read about the keyword unsigned in the C++ Reference.

There are two different types in this matter, signed and un-signed. The default for integers is signed which means that they can have negative values.

On a 32-bit system an integer is 32 Bit which means it can contain a value of ~4 billion.

And when it is signed, this means you need to split it, leaving -2 billion to +2 billion.

When it is unsigned however the value cannot contain any negative numbers, so for integers this would mean 0 to +4 billion.

There is a bit more informationa bout this on Wikipedia.

How can I debug a .BAT script?

I don't know of anyway to step through the execution of a .bat file but you can use echo and pause to help with debugging.

ECHO
Will echo a message in the batch file. Such as ECHO Hello World will print Hello World on the screen when executed. However, without @ECHO OFF at the beginning of the batch file you'll also get "ECHO Hello World" and "Hello World." Finally, if you'd just like to create a blank line, type ECHO. adding the period at the end creates an empty line.

PAUSE
Prompt the user to press any key to continue.

Source: Batch File Help

@workmad3: answer has more good tips for working with the echo command.

Another helpful resource... DDB: DOS Batch File Tips

Spell Checker for Python

Try jamspell - it works pretty well for automatic spelling correction:

import jamspell

corrector = jamspell.TSpellCorrector()
corrector.LoadLangModel('en.bin')

corrector.FixFragment('Some sentnec with error')
# u'Some sentence with error'

corrector.GetCandidates(['Some', 'sentnec', 'with', 'error'], 1)
# ('sentence', 'senate', 'scented', 'sentinel')

Add/delete row from a table

I suggest using jQuery. What you are doing right now is easy to achieve without jQuery, but as you will want new features and more functionality, jQuery will save you a lot of time. I would also like to mention that you shouldn't have multiple DOM elements with the same ID in one document. In such case use class attribute.

html:

<table id="dsTable">
  <tr>
     <td> Relationship Type </td>
     <td> Date of Birth </td>
     <td> Gender </td>
  </tr>
  <tr>
     <td> Spouse </td>
     <td> 1980-22-03 </td>
     <td> female </td>
     <td> <input type="button" class="addDep" value="Add"/></td>
     <td> <input type="button" class="deleteDep" value="Delete"/></td>
  </tr>
   <tr>
     <td> Child </td>
     <td> 2008-23-06 </td>
     <td> female </td>
     <td> <input type="button" class="addDep" value="Add"/></td>
     <td> <input type="button" class="deleteDep" value="Delete"/></td>
  </tr>
</table>

javascript:

$('body').on('click', 'input.deleteDep', function() {
   $(this).parents('tr').remove();  
});

Remember that you need to reference jQuery:

<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>

Here a working jsfiddle example: http://jsfiddle.net/p9dey/1/

Pass a string parameter in an onclick function

If you are using ASP.NET you can use JavaScript:

HTML

<input type='button' value='test' onclick='javascript: EditSelectedOptionName(x,y)' />"

JavaScript

function EditSelectedOptionName(id, name) {
    console.log(id);
    console.log(name);
}

How to convert milliseconds into a readable date?

Building on lonesomeday's example (upvote that answer not this one), I ran into this output:

undefined NaN, NaN

_x000D_
_x000D_
var datetime = '1324339200000'; //LOOK HERE_x000D_
_x000D_
function prettyDate(date) {_x000D_
  var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',_x000D_
                'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];_x000D_
_x000D_
  return months[date.getUTCMonth()] + ' ' + date.getUTCDate() + ', ' + date.getUTCFullYear();_x000D_
}_x000D_
_x000D_
console.log(prettyDate(new Date(datetime))); //AND HERE
_x000D_
_x000D_
_x000D_

The cause was using a string as input. To fix it, prefix the string with a plus sign:

prettyDate(new Date(+datetime));

_x000D_
_x000D_
var datetime = '1324339200000';_x000D_
_x000D_
function prettyDate(date) {_x000D_
  var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',_x000D_
                'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];_x000D_
_x000D_
  return months[date.getUTCMonth()] + ' ' + date.getUTCDate() + ', ' + date.getUTCFullYear();_x000D_
}_x000D_
_x000D_
console.log(prettyDate(new Date(+datetime))); //HERE
_x000D_
_x000D_
_x000D_

To add Hours/Minutes to the output:

_x000D_
_x000D_
var datetime = '1485010730253';_x000D_
_x000D_
function prettyDate(date) {_x000D_
  var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',_x000D_
                'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];_x000D_
_x000D_
  return months[date.getUTCMonth()] +' '+ date.getUTCDate()+ ', '+ date.getUTCHours() +':'+ date.getUTCMinutes();_x000D_
}_x000D_
_x000D_
console.log(prettyDate(new Date(+datetime)));
_x000D_
_x000D_
_x000D_

Closing a file after File.Create

The reason is because a FileStream is returned from your method to create a file. You should return the FileStream into a variable or call the close method directly from it after the File.Create.

It is a best practice to let the using block help you implement the IDispose pattern for a task like this. Perhaps what might work better would be:

if(!File.Exists(myPath)){
   using(FileStream fs = File.Create(myPath))
   using(StreamWriter writer = new StreamWriter(fs)){
      // do your work here
   }
}

Difference Between ViewResult() and ActionResult()

In the Controller , one could use the below syntax

public ViewResult EditEmployee() {
    return View();
}

public ActionResult EditEmployee() {
    return View();
}

In the above example , only the return type varies . one returns ViewResult whereas the other one returns ActionResult.

ActionResult is an abstract class . It can accept:

ViewResult , PartialViewResult, EmptyResult , RedirectResult , RedirectToRouteResult , JsonResult , JavaScriptResult , ContentResult, FileContentResult , FileStreamResult , FilePathResult etc.

The ViewResult is a subclass of ActionResult.

How does String substring work in Swift

I am new in Swift 3, but looking the String (index) syntax for analogy I think that index is like a "pointer" constrained to string and Int can help as an independent object. Using the base + offset syntax , then we can get the i-th character from string with the code bellow:

let s = "abcdefghi"
let i = 2
print (s[s.index(s.startIndex, offsetBy:i)])
// print c

For a range of characters ( indexes) from string using String (range) syntax we can get from i-th to f-th characters with the code bellow:

let f = 6
print (s[s.index(s.startIndex, offsetBy:i )..<s.index(s.startIndex, offsetBy:f+1 )])
//print cdefg

For a substring (range) from a string using String.substring (range) we can get the substring using the code bellow:

print (s.substring (with:s.index(s.startIndex, offsetBy:i )..<s.index(s.startIndex, offsetBy:f+1 ) ) )
//print cdefg

Notes:

  1. The i-th and f-th begin with 0.

  2. To f-th, I use offsetBY: f + 1, because the range of subscription use ..< (half-open operator), not include the f-th position.

  3. Of course must include validate errors like invalid index.

How do I use MySQL through XAMPP?

XAMPP Apache + MariaDB + PHP + Perl (X -any OS)

  • After successful installation execute xampp-control.exe in XAMPP folder
  • Start Apache and MySQL enter image description here

  • Open browser and in url type localhost or 127.0.0.1

  • then you are welcomed with dashboard

By default your port is listing with 80.If you want you can change it to your desired port number in httpd.conf file.(If port 80 is already using with other app then you have to change it).

For example you changed port number 80 to 8090 then you can run as 'localhost:8090' or '127.0.0.1:8090'

How to completely uninstall Visual Studio 2010?

Put in your CD or mount your ISO. Run the setup program from the command prompt using the flags /uninstall /force

I actually had ran into this issue the other day and it worked wonders. =)

MySQL set current date in a DATETIME field on insert

Since MySQL 5.6.X you can do this:

ALTER TABLE `schema`.`users` 
CHANGE COLUMN `created` `created` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ;

That way your column will be updated with the current timestamp when a new row is inserted, or updated.

If you're using MySQL Workbench, you can just put CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP in the DEFAULT value field, like so:

enter image description here

http://dev.mysql.com/doc/relnotes/mysql/5.6/en/news-5-6-5.html

Running Python in PowerShell?

Go to Python Website/dowloads/windows. Download Windows x86-64 embeddable zip file. 2. Open Windows Explorer

open zipped folder python-3.7.0 In the windows toolbar with the Red flair saying “Compressed Folder Tool” Press “Extract” button on the tool bar with “File” “Home “Share” “View” Select Extract all Extraction process is not covered yet Once extracted save onto SDD or fastest memory device. Not usb. HDD is fine. SDD Users/butte/ProgramFiles blah blah ooooor D:\Python Or Hook up to your cloud 3. Click your User Icon in the Windows tool bar.

Search environment variable Proceed with progressing with “Environment Variables” button press Under the “user variables” table select “New..” After the Canvas of Information Add Python in Variable Name Select the “D:\Python\python-3.7.0-embed-amd64\python.exe;” click ok Under the “System Variables” label and in the Canvas the first row has a value marked “Path” Select “Edit” when “Path” is highlighted. Select “New” Enter D:\Python\python-3.7.0-embed-amd click ok Ok Save and double check Open Power Shell python --help

python --version

Source to tutorial https://thedishbunnybitch.com/2018/08/11/installing-python-on-windows-10-for-powershell/

How can I update npm on Windows?

this is best tool to maintain version of NODE.Js i NVM

Node Version Manager (nvm) for Windows but for Windows, with an installer. Download Now! This has always been a node version manager, not an io.js manager, so there is no back-support for io.js. However, node 4+ is supported. enter image description here

Java output formatting for Strings

     @Override
     public String toString() {
          return String.format("%15s /n %15d /n %15s /n %15s", name, age, Occupation, status);
     }

Setting UILabel text to bold

Use attributed string:

// Define attributes
let labelFont = UIFont(name: "HelveticaNeue-Bold", size: 18)
let attributes :Dictionary = [NSFontAttributeName : labelFont]

// Create attributed string
var attrString = NSAttributedString(string: "Foo", attributes:attributes)
label.attributedText = attrString

You need to define attributes.

Using attributed string you can mix colors, sizes, fonts etc within one text

Hive: how to show all partitions of a table?

CLI has some limit when ouput is displayed. I suggest to export output into local file:

$hive -e 'show partitions table;' > partitions

How to view UTF-8 Characters in VIM or Gvim

If Japanese people come here, please add the following lines to your ~/.vimrc

set encoding=utf-8
set fileencodings=iso-2022-jp,euc-jp,sjis,utf-8
set fileformats=unix,dos,mac

Error: org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'text/plain;charset=UTF-8' not supported

Building on what is mentioned in the comments, the simplest solution would be:

@RequestMapping(method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public Collection<BudgetDTO> updateConsumerBudget(@RequestBody SomeDto someDto) throws GeneralException, ParseException {

    //whatever

}

class SomeDto {

   private List<WhateverBudgerPerDateDTO> budgetPerDate;


  //getters setters
}

The solution assumes that the HTTP request you are creating actually has

Content-Type:application/json instead of text/plain

What is the difference between single and double quotes in SQL?

The difference lies in their usage. The single quotes are mostly used to refer a string in WHERE, HAVING and also in some built-in SQL functions like CONCAT, STRPOS, POSITION etc.

When you want to use an alias that has space in between then you can use double quotes to refer to that alias.

For example

(select account_id,count(*) "count of" from orders group by 1)sub 

Here is a subquery from an orders table having account_id as Foreign key that I am aggregating to know how many orders each account placed. Here I have given one column any random name as "count of" for sake of purpose.

Now let's write an outer query to display the rows where "count of" is greater than 20.

select "count of" from 
(select account_id,count(*) "count of" from orders group by 1)sub where "count of" >20;

You can apply the same case to Common Table expressions also.

Cannot catch toolbar home button click event

In my case I had to put the icon using:

toolbar.setNavigationIcon(R.drawable.ic_my_home);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);

And then listen to click events with default onOptionsItemSelected and android.R.id.home id

Pushing an existing Git repository to SVN

If you don't have to use any specific SVN and you are using GitHub you can use their SVN connector.

More information is here: Collaborating on GitHub with Subversion

Why do I get an UnsupportedOperationException when trying to remove an element from a List?

Replace

List<String> list=Arrays.asList(split);

to

List<String> list = New ArrayList<>();
list.addAll(Arrays.asList(split));

or

List<String> list = new ArrayList<>(Arrays.asList(split));

or

List<String> list = new ArrayList<String>(Arrays.asList(split));

or (Better for Remove elements)

List<String> list = new LinkedList<>(Arrays.asList(split));

How to make popup look at the centre of the screen?

These are the changes to make:

CSS:

#container {
    width: 100%;
    height: 100%;
    top: 0;
    position: absolute;
    visibility: hidden;
    display: none;
    background-color: rgba(22,22,22,0.5); /* complimenting your modal colors */
}
#container:target {
    visibility: visible;
    display: block;
}
.reveal-modal {
    position: relative;
    margin: 0 auto;
    top: 25%;
}
    /* Remove the left: 50% */

HTML:

<a href="#container">Reveal</a>
<div id="container">
    <div id="exampleModal" class="reveal-modal">
    ........
    <a href="#">Close Modal</a>
    </div>
</div>

JSFiddle - Updated with CSS only

How to find out line-endings in a text file?

In the bash shell, try cat -v <filename>. This should display carriage-returns for windows files.

(This worked for me in rxvt via Cygwin on Windows XP).

Editor's note: cat -v visualizes \r (CR) chars. as ^M. Thus, line-ending \r\n sequences will display as ^M at the end of each output line. cat -e will additionally visualize \n, namely as $. (cat -et will additionally visualize tab chars. as ^I.)

What's the difference between using "let" and "var"?

I think the terms and most of the examples are a bit overwhelming, The main issue i had personally with the difference is understanding what a "Block" is. At some point i realized, a block would be any curly brackets except for IF statement. an opening bracket { of a function or loop will define a new block, anything defined with let within it, will not be available after the closing bracket } of the same thing (function or loop); With that in mind, it was easier to understand:

_x000D_
_x000D_
let msg = "Hello World";_x000D_
_x000D_
function doWork() { // msg will be available since it was defined above this opening bracket!_x000D_
  let friends = 0;_x000D_
  console.log(msg);_x000D_
_x000D_
  // with VAR though:_x000D_
  for (var iCount2 = 0; iCount2 < 5; iCount2++) {} // iCount2 will be available after this closing bracket!_x000D_
  console.log(iCount2);_x000D_
  _x000D_
    for (let iCount1 = 0; iCount1 < 5; iCount1++) {} // iCount1 will not be available behind this closing bracket, it will return undefined_x000D_
  console.log(iCount1);_x000D_
  _x000D_
} // friends will no be available after this closing bracket!_x000D_
doWork();_x000D_
console.log(friends);
_x000D_
_x000D_
_x000D_

Rails - Could not find a JavaScript runtime?

On the windows platform, I met that problem too The solution for me is just add

C:\Windows\System32

to the PATH

and restart the computer.

How can I make a ComboBox non-editable in .NET?

for winforms .NET change DropDownStyle to DropDownList from Combobox property

Get a timestamp in C in microseconds?

You need to add in the seconds, too:

unsigned long time_in_micros = 1000000 * tv.tv_sec + tv.tv_usec;

Note that this will only last for about 232/106 =~ 4295 seconds, or roughly 71 minutes though (on a typical 32-bit system).

Adding git branch on the Bash command prompt

parse_git_branch() {
    git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}
export PS1='\[\e]0;\w\a\]\n\[\e[32m\]\u@\h \[\e[33m\]\w\[\e[0m\]$(parse_git_branch)\n\$ '

Java :Add scroll into text area

The Easiest way to implement scrollbar using java swing is as below :

  1. Navigate to Design view
  2. right click on textArea
  3. Select surround with JScrollPane

How do I use CSS with a ruby on rails application?

Have you tried putting it in your public folder? Whenever I have images or the like that I need to reference externally, I put it all there.

Hibernate error: ids for this class must be manually assigned before calling save():

Here is what I did to solve just by 2 ways:

  1. make ID column as int type

  2. if you are using autogenerate in ID dont assing value in the setter of ID. If your mapping the some then sometimes autogenetated ID is not concedered. (I dont know why)

  3. try using @GeneratedValue(strategy=GenerationType.SEQUENCE) if possible

Oracle Age calculation from Date of birth and Today

SELECT 
TRUNC((SYSDATE - TO_DATE(DOB, 'YYYY-MM-DD'))/ 365.25) AS AGE_TODAY FROM DUAL;

This is easy and straight to the point.

Java: Calling a super method which calls an overridden method

class SuperClass
{
    public void method1()
    {
        System.out.println("superclass method1");
        SuperClass se=new SuperClass();
        se.method2();
    }

    public void method2()
    {
        System.out.println("superclass method2");
    }
}


class SubClass extends SuperClass
{
    @Override
    public void method1()
    {
        System.out.println("subclass method1");
        super.method1();
    }

    @Override
    public void method2()
    {
        System.out.println("subclass method2");
    }
}

calling

SubClass mSubClass = new SubClass();
mSubClass.method1();

outputs

subclass method1
superclass method1
superclass method2

Visual Studio Copy Project

I use Visual Studio 2013 where Project > Export Template is not an option. Here is what I use to clone a project.

From your solution: File > Export Template > select project to make template from, note save path

Download and install VS 2013 SDK Here

Create new VSIX project under Extensibility

From the VSIXManifest Dialog select the Assets tab

Fill in the Author textbox

Choose "Project Template" for Type and Browse to add the exported template (saved at path you noted in step 1)

Save and build the VSIX project. Go to the VSIX project's .../bin/Debug folder and double click to run the .vsix file

Start new instance of Visual Studio and you should see your template under whatever project type your template is. Create a new project from your template

You will have to re-add any dll references

Java: how can I split an ArrayList in multiple small ArrayLists?

You need to know the chunk size by which you're dividing your list. Say you have a list of 108 entries and you need a chunk size of 25. Thus you will end up with 5 lists:

  • 4 having 25 entries each;
  • 1 (the fifth) having 8 elements.

Code:

public static void main(String[] args) {

        List<Integer> list = new ArrayList<Integer>();
        for (int i=0; i<108; i++){
            list.add(i);
        }
        int size= list.size();
        int j=0;
                List< List<Integer> > splittedList = new ArrayList<List<Integer>>()  ;
                List<Integer> tempList = new ArrayList<Integer>();
        for(j=0;j<size;j++){
            tempList.add(list.get(j));
        if((j+1)%25==0){
            // chunk of 25 created and clearing tempList
            splittedList.add(tempList);
            tempList = null;
            //intializing it again for new chunk 
            tempList = new ArrayList<Integer>();
        }
        }
        if(size%25!=0){
            //adding the remaining enteries 
            splittedList.add(tempList);
        }
        for (int k=0;k<splittedList.size(); k++){
            //(k+1) because we started from k=0
            System.out.println("Chunk number: "+(k+1)+" has elements = "+splittedList.get(k).size());
        }
    }

Assigning multiple styles on an HTML element

You needed to do it like this:

_x000D_
_x000D_
<h2 style="text-align: center;font-family: Tahoma">TITLE</h2>
_x000D_
_x000D_
_x000D_

Hope it helped.

Is it possible to open developer tools console in Chrome on Android phone?

Please do yourself a favor and just hit the easy button:

download Web Inspector (Open Source) from the Play store.

A CAVEAT: ATTOW, console output does not accept rest params! I.e. if you have something like this:

console.log('one', 'two', 'three');

you will only see

one

logged to the console. You'll need to manually wrap the params in an Array and join, like so:

console.log([ 'one', 'two', 'three' ].join(' '));

to see the expected output.

But the app is open source! A patch may be imminent! The patcher could even be you!

javax.xml.bind.JAXBException: Class *** nor any of its super class is known to this context

This errors occurs when we use same method name for Jaxb2Marshaller for exemple:

    @Bean
    public Jaxb2Marshaller marshallerClient() {
        Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
        // this package must match the package in the <generatePackage> specified in
        // pom.xml
        marshaller.setContextPath("library.io.github.walterwhites.loans");

        return marshaller;
    }

And on other file

    @Bean
    public Jaxb2Marshaller marshallerClient() {
        Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
        // this package must match the package in the <generatePackage> specified in
        // pom.xml
        marshaller.setContextPath("library.io.github.walterwhites.client");

        return marshaller;
    }

Even It's different class, you should named them differently

jQuery Determine if a matched class has a given id

Check if element's ID is exist

_x000D_
_x000D_
if ($('#id').attr('id') == 'id')_x000D_
{_x000D_
  //OK_x000D_
}
_x000D_
_x000D_
_x000D_

When to use Task.Delay, when to use Thread.Sleep?

The biggest difference between Task.Delay and Thread.Sleep is that Task.Delay is intended to run asynchronously. It does not make sense to use Task.Delay in synchronous code. It is a VERY bad idea to use Thread.Sleep in asynchronous code.

Normally you will call Task.Delay() with the await keyword:

await Task.Delay(5000);

or, if you want to run some code before the delay:

var sw = new Stopwatch();
sw.Start();
Task delay = Task.Delay(5000);
Console.WriteLine("async: Running for {0} seconds", sw.Elapsed.TotalSeconds);
await delay;

Guess what this will print? Running for 0.0070048 seconds. If we move the await delay above the Console.WriteLine instead, it will print Running for 5.0020168 seconds.

Let's look at the difference with Thread.Sleep:

class Program
{
    static void Main(string[] args)
    {
        Task delay = asyncTask();
        syncCode();
        delay.Wait();
        Console.ReadLine();
    }

    static async Task asyncTask()
    {
        var sw = new Stopwatch();
        sw.Start();
        Console.WriteLine("async: Starting");
        Task delay = Task.Delay(5000);
        Console.WriteLine("async: Running for {0} seconds", sw.Elapsed.TotalSeconds);
        await delay;
        Console.WriteLine("async: Running for {0} seconds", sw.Elapsed.TotalSeconds);
        Console.WriteLine("async: Done");
    }

    static void syncCode()
    {
        var sw = new Stopwatch();
        sw.Start();
        Console.WriteLine("sync: Starting");
        Thread.Sleep(5000);
        Console.WriteLine("sync: Running for {0} seconds", sw.Elapsed.TotalSeconds);
        Console.WriteLine("sync: Done");
    }
}

Try to predict what this will print...

async: Starting
async: Running for 0.0070048 seconds
sync: Starting
async: Running for 5.0119008 seconds
async: Done
sync: Running for 5.0020168 seconds
sync: Done

Also, it is interesting to notice that Thread.Sleep is far more accurate, ms accuracy is not really a problem, while Task.Delay can take 15-30ms minimal. The overhead on both functions is minimal compared to the ms accuracy they have (use Stopwatch Class if you need something more accurate). Thread.Sleep still ties up your Thread, Task.Delay release it to do other work while you wait.

Adding a y-axis label to secondary y-axis in matplotlib

I don't have access to Python right now, but off the top of my head:

fig = plt.figure()

axes1 = fig.add_subplot(111)
# set props for left y-axis here

axes2 = axes1.twinx()   # mirror them
axes2.set_ylabel(...)

Ignoring a class property in Entity Framework 4.1 Code First

As of EF 5.0, you need to include the System.ComponentModel.DataAnnotations.Schema namespace.

SQL - How to find the highest number in a column?

If you are using AUTOINCREMENT, use:

SELECT LAST\_INSERT\_ID();

Assumming that you are using Mysql: http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html

Postgres handles this similarly via the currval(sequence_name) function.

Note that using MAX(ID) is not safe, unless you lock the table, since it's possible (in a simplified case) to have another insert that occurs before you call MAX(ID) and you lose the id of the first insert. The functions above are session based so if another session inserts you still get the ID that you inserted.

Static method in a generic class?

You can't use a class's generic type parameters in static methods or static fields. The class's type parameters are only in scope for instance methods and instance fields. For static fields and static methods, they are shared among all instances of the class, even instances of different type parameters, so obviously they cannot depend on a particular type parameter.

It doesn't seem like your problem should require using the class's type parameter. If you describe what you are trying to do in more detail, maybe we can help you find a better way to do it.

Configure Apache .conf for Alias

Sorry not sure what was going on this worked in the end:

<VirtualHost *> 
    ServerName example.com
    DocumentRoot /var/www/html/mjp

    Alias /ncn "/var/www/html/ncn"

    <Directory "/var/www/html/ncn">
        Options None
        AllowOverride None
        Order allow,deny
        Allow from all
    </Directory>
</VirtualHost>

Travel/Hotel API's?

Check out api.hotelsbase.org - its a free xml hotel api No images as of yet though

How to set multiple commands in one yaml file with Kubernetes?

command: ["/bin/sh","-c"]
args: ["command one; command two && command three"]

Explanation: The command ["/bin/sh", "-c"] says "run a shell, and execute the following instructions". The args are then passed as commands to the shell. In shell scripting a semicolon separates commands, and && conditionally runs the following command if the first succeed. In the above example, it always runs command one followed by command two, and only runs command three if command two succeeded.

Alternative: In many cases, some of the commands you want to run are probably setting up the final command to run. In this case, building your own Dockerfile is the way to go. Look at the RUN directive in particular.

ActionController::InvalidAuthenticityToken

If you have done a rake rails:update or otherwise recently changed your config/initializers/session_store.rb, this may be a symptom of old cookies in the browser. Hopefully this is done in dev/test (it was for me), and you can just clear all browser cookies related to the domain in question.

If this is in production, and you changed key, consider changing it back to use the old cookies (<- just speculation).

Replace image src location using CSS

Here is another dirty hack :)

.application-title > img {
display: none;
}

.application-title::before {
content: url(path/example.jpg);
}

return value after a promise

Use a pattern along these lines:

function getValue(file) {
  return lookupValue(file);
}

getValue('myFile.txt').then(function(res) {
  // do whatever with res here
});

(although this is a bit redundant, I'm sure your actual code is more complicated)

How to use java.net.URLConnection to fire and handle HTTP requests?

You can also use JdkRequest from jcabi-http (I'm a developer), which does all this work for you, decorating HttpURLConnection, firing HTTP requests and parsing responses, for example:

String html = new JdkRequest("http://www.google.com").fetch().body();

Check this blog post for more info: http://www.yegor256.com/2014/04/11/jcabi-http-intro.html

Access files in /var/mobile/Containers/Data/Application without jailbreaking iPhone

If this is your app, if you connect the device to your computer, you can use the "Devices" option on Xcode's "Window" menu and then download the app's data container to your computer. Just select your app from the list of installed apps, and click on the "gear" icon and choose "Download Container".

enter image description here

Once you've downloaded it, right click on the file in the Finder and choose "Show Package Contents".

Can't operator == be applied to generic types in C#?

"...by default == behaves as described above for both predefined and user-defined reference types."

Type T is not necessarily a reference type, so the compiler can't make that assumption.

However, this will compile because it is more explicit:

    bool Compare<T>(T x, T y) where T : class
    {
        return x == y;
    }

Follow up to additional question, "But, in case I'm using a reference type, would the the == operator use the predefined reference comparison, or would it use the overloaded version of the operator if a type defined one?"

I would have thought that == on the Generics would use the overloaded version, but the following test demonstrates otherwise. Interesting... I'd love to know why! If someone knows please share.

namespace TestProject
{
 class Program
 {
    static void Main(string[] args)
    {
        Test a = new Test();
        Test b = new Test();

        Console.WriteLine("Inline:");
        bool x = a == b;
        Console.WriteLine("Generic:");
        Compare<Test>(a, b);

    }


    static bool Compare<T>(T x, T y) where T : class
    {
        return x == y;
    }
 }

 class Test
 {
    public static bool operator ==(Test a, Test b)
    {
        Console.WriteLine("Overloaded == called");
        return a.Equals(b);
    }

    public static bool operator !=(Test a, Test b)
    {
        Console.WriteLine("Overloaded != called");
        return a.Equals(b);
    }
  }
}

Output

Inline: Overloaded == called

Generic:

Press any key to continue . . .

Follow Up 2

I do want to point out that changing my compare method to

    static bool Compare<T>(T x, T y) where T : Test
    {
        return x == y;
    }

causes the overloaded == operator to be called. I guess without specifying the type (as a where), the compiler can't infer that it should use the overloaded operator... though I'd think that it would have enough information to make that decision even without specifying the type.

How do I sort a list of datetime or date objects?

You're getting None because list.sort() it operates in-place, meaning that it doesn't return anything, but modifies the list itself. You only need to call a.sort() without assigning it to a again.

There is a built in function sorted(), which returns a sorted version of the list - a = sorted(a) will do what you want as well.

How to pass prepareForSegue: an object

My solution is similar.

// In destination class: 
var AddressString:String = String()

// In segue:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
   if (segue.identifier == "seguetobiddetailpagefromleadbidder")
    {
        let secondViewController = segue.destinationViewController as! BidDetailPage
        secondViewController.AddressString = pr.address as String
    }
}

Add new row to dataframe, at specific row-index, not appended?

for example you want to add rows of variable 2 to variable 1 of a data named "edges" just do it like this

allEdges <- data.frame(c(edges$V1,edges$V2))

Is there a difference between x++ and ++x in java?

When considering what the computer actually does...

++x: load x from memory, increment, use, store back to memory.

x++: load x from memory, use, increment, store back to memory.

Consider: a = 0 x = f(a++) y = f(++a)

where function f(p) returns p + 1

x will be 1 (or 2)

y will be 2 (or 1)

And therein lies the problem. Did the author of the compiler pass the parameter after retrieval, after use, or after storage.

Generally, just use x = x + 1. It's way simpler.

Swift 2: Call can throw, but it is not marked with 'try' and the error is not handled

When calling a function that is declared with throws in Swift, you must annotate the function call site with try or try!. For example, given a throwing function:

func willOnlyThrowIfTrue(value: Bool) throws {
  if value { throw someError }
}

this function can be called like:

func foo(value: Bool) throws {
  try willOnlyThrowIfTrue(value)
}

Here we annotate the call with try, which calls out to the reader that this function may throw an exception, and any following lines of code might not be executed. We also have to annotate this function with throws, because this function could throw an exception (i.e., when willOnlyThrowIfTrue() throws, then foo will automatically rethrow the exception upwards.

If you want to call a function that is declared as possibly throwing, but which you know will not throw in your case because you're giving it correct input, you can use try!.

func bar() {
  try! willOnlyThrowIfTrue(false)
}

This way, when you guarantee that code won't throw, you don't have to put in extra boilerplate code to disable exception propagation.

try! is enforced at runtime: if you use try! and the function does end up throwing, then your program's execution will be terminated with a runtime error.

Most exception handling code should look like the above: either you simply propagate exceptions upward when they occur, or you set up conditions such that otherwise possible exceptions are ruled out. Any clean up of other resources in your code should occur via object destruction (i.e. deinit()), or sometimes via defered code.

func baz(value: Bool) throws {

  var filePath = NSBundle.mainBundle().pathForResource("theFile", ofType:"txt")
  var data = NSData(contentsOfFile:filePath)

  try willOnlyThrowIfTrue(value)

  // data and filePath automatically cleaned up, even when an exception occurs.
}

If for whatever reason you have clean up code that needs to run but isn't in a deinit() function, you can use defer.

func qux(value: Bool) throws {
  defer {
    print("this code runs when the function exits, even when it exits by an exception")
  }

  try willOnlyThrowIfTrue(value)
}

Most code that deals with exceptions simply has them propagate upward to callers, doing cleanup on the way via deinit() or defer. This is because most code doesn't know what to do with errors; it knows what went wrong, but it doesn't have enough information about what some higher level code is trying to do in order to know what to do about the error. It doesn't know if presenting a dialog to the user is appropriate, or if it should retry, or if something else is appropriate.

Higher level code, however, should know exactly what to do in the event of any error. So exceptions allow specific errors to bubble up from where they initially occur to the where they can be handled.

Handling exceptions is done via catch statements.

func quux(value: Bool) {
  do {
    try willOnlyThrowIfTrue(value)
  } catch {
    // handle error
  }
}

You can have multiple catch statements, each catching a different kind of exception.

  do {
    try someFunctionThatThowsDifferentExceptions()
  } catch MyErrorType.errorA {
    // handle errorA
  } catch MyErrorType.errorB {
    // handle errorB
  } catch {
    // handle other errors
  }

For more details on best practices with exceptions, see http://exceptionsafecode.com/. It's specifically aimed at C++, but after examining the Swift exception model, I believe the basics apply to Swift as well.

For details on the Swift syntax and error handling model, see the book The Swift Programming Language (Swift 2 Prerelease).

How to make image hover in css?

You're setting the background of the image to another image. Which is fine, but the foreground (SRC attribute of the IMG) still overlays everything else.

.nkhome{
    margin-left:260px;
    top:170px;
    position:absolute;
}
.nkhome a {
    background:url(Images/btnhome.png);
    display:block; /* Necessary, since A is not a block element */
    width:59px;
    height:59px;
}
.nkhome a:hover {
    background:url(Images/btnhomeh.png);
}


<div class="nkhome">
    <a href="Home.html"></a>
</div>

What is the difference between the GNU Makefile variable assignments =, ?=, := and +=?

In the above answers, it is important to understand what is meant by "values are expanded at declaration/use time". Giving a value like *.c does not entail any expansion. It is only when this string is used by a command that it will maybe trigger some globbing. Similarly, a value like $(wildcard *.c) or $(shell ls *.c) does not entail any expansion and is completely evaluated at definition time even if we used := in the variable definition.

Try the following Makefile in directory where you have some C files:

VAR1 = *.c
VAR2 := *.c
VAR3 = $(wildcard *.c)
VAR4 := $(wildcard *.c)
VAR5 = $(shell ls *.c)
VAR6 := $(shell ls *.c)

all :
    touch foo.c
    @echo "now VAR1 = \"$(VAR1)\"" ; ls $(VAR1)
    @echo "now VAR2 = \"$(VAR2)\"" ; ls $(VAR2)
    @echo "now VAR3 = \"$(VAR3)\"" ; ls $(VAR3)
    @echo "now VAR4 = \"$(VAR4)\"" ; ls $(VAR4)
    @echo "now VAR5 = \"$(VAR5)\"" ; ls $(VAR5)
    @echo "now VAR6 = \"$(VAR6)\"" ; ls $(VAR6)
    rm -v foo.c

Running make will trigger a rule that creates an extra (empty) C file, called foo.c but none of the 6 variables has foo.c in its value.

Installing Git on Eclipse

egit was included in Indigo (2011) and should be there in all future Eclipse versions after that.

Just go to ![(Help->Install New Software)]

Then Work with: --All Available Sites--

Then type egit underneath and wait (may take a while) ! Then click the checkbox and install.

JAX-RS — How to return JSON and HTTP status code together?

I found it very useful to build also a json message with repeated code, like this:

@POST
@Consumes("application/json")
@Produces("application/json")
public Response authUser(JsonObject authData) {
    String email = authData.getString("email");
    String password = authData.getString("password");
    JSONObject json = new JSONObject();
    if (email.equalsIgnoreCase(user.getEmail()) && password.equalsIgnoreCase(user.getPassword())) {
        json.put("status", "success");
        json.put("code", Response.Status.OK.getStatusCode());
        json.put("message", "User " + authData.getString("email") + " authenticated.");
        return Response.ok(json.toString()).build();
    } else {
        json.put("status", "error");
        json.put("code", Response.Status.NOT_FOUND.getStatusCode());
        json.put("message", "User " + authData.getString("email") + " not found.");
        return Response.status(Response.Status.NOT_FOUND).entity(json.toString()).build();
    }
}

Path of assets in CSS files in Symfony 2

I had the same problem and I just tried using the following as a workaround. Seems to work so far. You can even create a dummy template that just contains references to all those static assets.

{% stylesheets
    output='assets/fonts/glyphicons-halflings-regular.ttf'
    'bundles/bootstrap/fonts/glyphicons-halflings-regular.ttf'
%}{% endstylesheets %}

Notice the omission of any output which means nothing shows up on the template. When I run assetic:dump the files are copied over to the desired location and the css includes work as expected.

TypeError: only integer scalar arrays can be converted to a scalar index with 1D numpy indices array

Another case that could cause this error is

>>> np.ndindex(np.random.rand(60,60))
TypeError: only integer scalar arrays can be converted to a scalar index

Using the actual shape will fix it.

>>> np.ndindex(np.random.rand(60,60).shape)
<numpy.ndindex object at 0x000001B887A98880>

Java: How to stop thread?

You can create a boolean field and check it inside run:

public class Task implements Runnable {

   private volatile boolean isRunning = true;

   public void run() {

     while (isRunning) {
         //do work
     }
   }

   public void kill() {
       isRunning = false;
   }

}

To stop it just call

task.kill();

This should work.

How to print in C

printf is a fair bit more complicated than that. You have to supply a format string, and then the variables to apply to the format string. If you just supply one variable, C will assume that is the format string and try to print out all the bytes it finds in it until it hits a terminating nul (0x0).

So if you just give it an integer, it will merrily march through memory at the location your integer is stored, dumping whatever garbage is there to the screen, until it happens to come across a byte containing 0.

For a Java programmer, I'd imagine this is a rather rude introduction to C's lack of type checking. Believe me, this is only the tip of the iceberg. This is why, while I applaud your desire to expand your horizons by learning C, I highly suggest you do whatever you can to avoid writing real programs in it.

(This goes for everyone else reading this too.)

CentOS: Copy directory to another directory

As I understand, you want to recursively copy test directory into /home/server/ path...

This can be done as:

-cp -rf /home/server/folder/test/* /home/server/

Hope this helps

Insert Data Into Temp Table with Query

Fastest way to do this is using "SELECT INTO" command e.g.

SELECT * INTO #TempTableName
FROM....

This will create a new table, you don't have to create it in advance.

How to wait in bash for several subprocesses to finish and return exit code !=0 when any subprocess ends with code !=0?

I've just been modifying a script to background and parallelise a process.

I did some experimenting (on Solaris with both bash and ksh) and discovered that 'wait' outputs the exit status if it's not zero , or a list of jobs that return non-zero exit when no PID argument is provided. E.g.

Bash:

$ sleep 20 && exit 1 &
$ sleep 10 && exit 2 &
$ wait
[1]-  Exit 2                  sleep 20 && exit 2
[2]+  Exit 1                  sleep 10 && exit 1

Ksh:

$ sleep 20 && exit 1 &
$ sleep 10 && exit 2 &
$ wait
[1]+  Done(2)                  sleep 20 && exit 2
[2]+  Done(1)                  sleep 10 && exit 1

This output is written to stderr, so a simple solution to the OPs example could be:

#!/bin/bash

trap "rm -f /tmp/x.$$" EXIT

for i in `seq 0 9`; do
  doCalculations $i &
done

wait 2> /tmp/x.$$
if [ `wc -l /tmp/x.$$` -gt 0 ] ; then
  exit 1
fi

While this:

wait 2> >(wc -l)

will also return a count but without the tmp file. This might also be used this way, for example:

wait 2> >(if [ `wc -l` -gt 0 ] ; then echo "ERROR"; fi)

But this isn't very much more useful than the tmp file IMO. I couldn't find a useful way to avoid the tmp file whilst also avoiding running the "wait" in a subshell, which wont work at all.

How do I write a correct micro-benchmark in Java?

Make sure you somehow use results which are computed in benchmarked code. Otherwise your code can be optimized away.

How to throw an exception in C?

This question is super old, but I just stumbled across it and thought I'd share a technique: divide by zero, or dereference a null pointer.

The question is simply "how to throw", not how to catch, or even how to throw a specific type of exception. I had a situation ages ago where we needed to trigger an exception from C to be caught in C++. Specifically, we had occasional reports of "pure virtual function call" errors, and needed to convince the C runtime's _purecall function to throw something. So we added our own _purecall function that divided by zero, and boom, we got an exception that we could catch on C++, and even use some stack fun to see where things went wrong.

Convert Swift string to array

Martin R answer is the best approach, and as he said, because String conforms the SquenceType protocol, you can also enumerate a string, getting each character on each iteration.

let characters = "Hello"
var charactersArray: [Character] = []

for (index, character) in enumerate(characters) {
    //do something with the character at index
    charactersArray.append(character)
}

println(charactersArray)

How do I get a specific range of numbers from rand()?

The naive way to do it is:

int myRand = rand() % 66; // for 0-65

This will likely be a very slightly non-uniform distribution (depending on your maximum value), but it's pretty close.

To explain why it's not quite uniform, consider this very simplified example:
Suppose RAND_MAX is 4 and you want a number from 0-2. The possible values you can get are shown in this table:

rand()   |  rand() % 3
---------+------------
0        |  0
1        |  1
2        |  2
3        |  0

See the problem? If your maximum value is not an even divisor of RAND_MAX, you'll be more likely to choose small values. However, since RAND_MAX is generally 32767, the bias is likely to be small enough to get away with for most purposes.

There are various ways to get around this problem; see here for an explanation of how Java's Random handles it.

nullable object must have a value

I got this message when trying to access values of a null valued object.

sName = myObj.Name;

this will produce error. First you should check if object not null

if(myObj != null)
  sName = myObj.Name;

This works.

Spring jUnit Testing properties file

As for the testing, you should use from Spring 4.1 which will overwrite the properties defined in other places:

@TestPropertySource("classpath:application-test.properties")

Test property sources have higher precedence than those loaded from the operating system's environment or Java system properties as well as property sources added by the application like @PropertySource

grabbing first row in a mysql query only

You didn't specify how the order is determined, but this will give you a rank value in MySQL:

SELECT t.*,
       @rownum := @rownum +1 AS rank
  FROM TBL_FOO t
  JOIN (SELECT @rownum := 0) r
 WHERE t.name = 'sarmen'

Then you can pick out what rows you want, based on the rank value.

django admin - add custom form fields that are not part of the model

It it possible to do in the admin, but there is not a very straightforward way to it. Also, I would like to advice to keep most business logic in your models, so you won't be dependent on the Django Admin.

Maybe it would be easier (and maybe even better) if you have the two seperate fields on your model. Then add a method on your model that combines them.

For example:

class MyModel(models.model):

    field1 = models.CharField(max_length=10)
    field2 = models.CharField(max_length=10)

    def combined_fields(self):
        return '{} {}'.format(self.field1, self.field2)

Then in the admin you can add the combined_fields() as a readonly field:

class MyModelAdmin(models.ModelAdmin):

    list_display = ('field1', 'field2', 'combined_fields')
    readonly_fields = ('combined_fields',)

    def combined_fields(self, obj):
        return obj.combined_fields()

If you want to store the combined_fields in the database you could also save it when you save the model:

def save(self, *args, **kwargs):
    self.field3 = self.combined_fields()
    super(MyModel, self).save(*args, **kwargs)

How to pick a new color for each plotted line within a figure in matplotlib?

I don't know if you can automatically change the color, but you could exploit your loop to generate different colors:

for i in range(20):
   ax1.plot(x, y, color = (0, i / 20.0, 0, 1)

In this case, colors will vary from black to 100% green, but you can tune it if you want.

See the matplotlib plot() docs and look for the color keyword argument.

If you want to feed a list of colors, just make sure that you have a list big enough and then use the index of the loop to select the color

colors = ['r', 'b', ...., 'w']

for i in range(20):
   ax1.plot(x, y, color = colors[i])

Why am I seeing "TypeError: string indices must be integers"?

data is a dict object. So, iterate over it like this:

Python 2

for key, value in data.iteritems():
    print key, value

Python 3

for key, value in data.items():
    print(key, value)

Why would one omit the close tag?

There are 2 possible use of php code:

  1. PHP code such as class definition or function definition
  2. Use PHP as a template language (i.e. in views)

in case 1. the closing tag is totally unusefull, also I would like to see just 1 (one) php open tag and NO (zero) closing tag in such a case. This is a good practice as it make code clean and separate logic from presentation. For presentation case (2.) some found it is natural to close all tags (even the PHP-processed ones), that leads to confution, as the PHP has in fact 2 separate use case, that should not be mixed: logic/calculus and presentation

How do I retrieve query parameters in Spring Boot?

To accept both @PathVariable and @RequestParam in the same /user endpoint:

@GetMapping(path = {"/user", "/user/{data}"})
public void user(@PathVariable(required=false,name="data") String data,
                 @RequestParam(required=false) Map<String,String> qparams) {
    qparams.forEach((a,b) -> {
        System.out.println(String.format("%s -> %s",a,b));
    }
  
    if (data != null) {
        System.out.println(data);
    }
}

Testing with curl:

  • curl 'http://localhost:8080/user/books'
  • curl 'http://localhost:8080/user?book=ofdreams&name=nietzsche'

Open a file with Notepad in C#

this will open the file with the default windows program (notepad if you haven't changed it);

Process.Start(@"c:\myfile.txt")

OpenCV in Android Studio

This worked for me and was as easy as adding a gradle dependancy:

https://bintray.com/seesaa/maven/opencv#

https://github.com/seesaa/opencv-android

The one caveat being that I had to use a hardware debugging device as arm emulators were running too slow for me (as AVD Manager says they will), and, as described at the repo README, this version does not include x86 or x86_64 support.

It seems to build and the suggested test:

static {
    OpenCVLoader.initDebug();
}

spits out a bunch of output that looks about right to me.

Using CMake to generate Visual Studio C++ project files

As Alex says, it works very well. The only tricky part is to remember to make any changes in the cmake files, rather than from within Visual Studio. So on all platforms, the workflow is similar to if you'd used plain old makefiles.

But it's fairly easy to work with, and I've had no issues with cmake generating invalid files or anything like that, so I wouldn't worry too much.