Programs & Examples On #Carryflag

Compare 2 JSON objects

Simply parsing the JSON and comparing the two objects is not enough because it wouldn't be the exact same object references (but might be the same values).

You need to do a deep equals.

From http://threebit.net/mail-archive/rails-spinoffs/msg06156.html - which seems the use jQuery.

Object.extend(Object, {
   deepEquals: function(o1, o2) {
     var k1 = Object.keys(o1).sort();
     var k2 = Object.keys(o2).sort();
     if (k1.length != k2.length) return false;
     return k1.zip(k2, function(keyPair) {
       if(typeof o1[keyPair[0]] == typeof o2[keyPair[1]] == "object"){
         return deepEquals(o1[keyPair[0]], o2[keyPair[1]])
       } else {
         return o1[keyPair[0]] == o2[keyPair[1]];
       }
     }).all();
   }
});

Usage:

var anObj = JSON.parse(jsonString1);
var anotherObj= JSON.parse(jsonString2);

if (Object.deepEquals(anObj, anotherObj))
   ...

How to access full source of old commit in BitBucket?

Search it for a long time, and finally, I found how to do it:)

Please check this image which illustrates steps. enter image description here

What is the best way to ensure only one instance of a Bash script is running?

from with your script:

ps -ef | grep $0 | grep $(whoami)

Detecting Back Button/Hash Change in URL

Another great implementation is balupton's jQuery History which will use the native onhashchange event if it is supported by the browser, if not it will use an iframe or interval appropriately for the browser to ensure all the expected functionality is successfully emulated. It also provides a nice interface to bind to certain states.

Another project worth noting as well is jQuery Ajaxy which is pretty much an extension for jQuery History to add ajax to the mix. As when you start using ajax with hashes it get's quite complicated!

c++ boost split string

The problem is somewhere else in your code, because this works:

string line("test\ttest2\ttest3");
vector<string> strs;
boost::split(strs,line,boost::is_any_of("\t"));

cout << "* size of the vector: " << strs.size() << endl;    
for (size_t i = 0; i < strs.size(); i++)
    cout << strs[i] << endl;

and testing your approach, which uses a vector iterator also works:

string line("test\ttest2\ttest3");
vector<string> strs;
boost::split(strs,line,boost::is_any_of("\t"));

cout << "* size of the vector: " << strs.size() << endl;
for (vector<string>::iterator it = strs.begin(); it != strs.end(); ++it)
{
    cout << *it << endl;
}

Again, your problem is somewhere else. Maybe what you think is a \t character on the string, isn't. I would fill the code with debugs, starting by monitoring the insertions on the vector to make sure everything is being inserted the way its supposed to be.

Output:

* size of the vector: 3
test
test2
test3

How to reduce the image file size using PIL

The main image manager in PIL is PIL's Image module.

from PIL import Image
import math

foo = Image.open("path\\to\\image.jpg")
x, y = foo.size
x2, y2 = math.floor(x-50), math.floor(y-20)
foo = foo.resize((x2,y2),Image.ANTIALIAS)
foo.save("path\\to\\save\\image_scaled.jpg",quality=95)

You can add optimize=True to the arguments of you want to decrease the size even more, but optimize only works for JPEG's and PNG's. For other image extensions, you could decrease the quality of the new saved image. You could change the size of the new image by just deleting a bit of code and defining the image size and you can only figure out how to do this if you look at the code carefully. I defined this size:

x, y = foo.size
x2, y2 = math.floor(x-50), math.floor(y-20)

just to show you what is (almost) normally done with horizontal images. For vertical images you might do:

x, y = foo.size
x2, y2 = math.floor(x-20), math.floor(y-50)

. Remember, you can still delete that bit of code and define a new size.

What's the best way to convert a number to a string in JavaScript?

Method toFixed() will also solves the purpose.

var n = 8.434332;
n.toFixed(2)  // 8.43

img src SVG changing the styles with CSS

I suggest to select your color , and go to this pen https://codepen.io/sosuke/pen/Pjoqqp it will convert HEX to css filter eg:#64D7D6

equal

filter: invert(88%) sepia(21%) saturate(935%) hue-rotate(123deg) brightness(85%) contrast(97%);

the final snippet

_x000D_
_x000D_
.filterit{
width:270px;
filter: invert(88%) sepia(21%) saturate(935%) hue-rotate(123deg) brightness(85%) contrast(97%);
}
_x000D_
<img src="https://www.flaticon.com/svg/static/icons/svg/1389/1389029.svg"
class="filterit

/>
_x000D_
_x000D_
_x000D_

Url decode UTF-8 in Python

The data is UTF-8 encoded bytes escaped with URL quoting, so you want to decode, with urllib.parse.unquote(), which handles decoding from percent-encoded data to UTF-8 bytes and then to text, transparently:

from urllib.parse import unquote

url = unquote(url)

Demo:

>>> from urllib.parse import unquote
>>> url = 'example.com?title=%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%B2%D0%B0%D1%8F+%D0%B7%D0%B0%D1%89%D0%B8%D1%82%D0%B0'
>>> unquote(url)
'example.com?title=????????+??????'

The Python 2 equivalent is urllib.unquote(), but this returns a bytestring, so you'd have to decode manually:

from urllib import unquote

url = unquote(url).decode('utf8')

How to send a correct authorization header for basic authentication

You can include the user and password as part of the URL:

http://user:[email protected]/index.html

see this URL, for more

HTTP Basic Authentication credentials passed in URL and encryption

of course, you'll need the username password, it's not 'Basic hashstring.

hope this helps...

Exception 'open failed: EACCES (Permission denied)' on Android

Add android:requestLegacyExternalStorage="true" to the Android Manifest It's worked with Android 10 (Q) at SDK 29+
or After migrating Android X.

 <application
    android:name=".MyApplication"
    android:allowBackup="true"
    android:hardwareAccelerated="true"
    android:icon=""
    android:label=""
    android:largeHeap="true"
    android:supportsRtl=""
    android:theme=""
    android:requestLegacyExternalStorage="true">

Javascript Date: next month

Instead, try:

var now = new Date();
current = new Date(now.getFullYear(), now.getMonth()+1, 1);

How to retrieve the hash for the current commit in Git?

git show-ref --head --hash head

If you're going for speed though, the approach mentioned by Deestan

cat .git/refs/heads/<branch-name>

is significantly faster than any other method listed here so far.

How to convert characters to HTML entities using plain JavaScript

I fixed my problem by using encodeURIComponent() instead of escape().

This might be the fix for you if the problem happens when sending your string in a URL.

Try this with the phrase ("hi & % ‘")

escape() returns

"hi%20%26%20%25%20%u2018"

Notice the %u2018 isn't very url friendly and can break the rest of the query string.

encodeURI() returns

"hi%20&%20%25%20%E2%80%98"

Notice the ampersand is still there.

encodeURIComponent() returns

"hi%20%26%20%25%20%E2%80%98"

Finally, all of our characters are properly encoded.

How can I search sub-folders using glob.glob module?

You can use Formic with Python 2.6

import formic
fileset = formic.FileSet(include="**/*.txt", directory="C:/Users/sam/Desktop/")

Disclosure - I am the author of this package.

Stripping non printable characters from a string in python

You could try setting up a filter using the unicodedata.category() function:

import unicodedata
printable = {'Lu', 'Ll'}
def filter_non_printable(str):
  return ''.join(c for c in str if unicodedata.category(c) in printable)

See Table 4-9 on page 175 in the Unicode database character properties for the available categories

jQuery & CSS - Remove/Add display:none

So, let me give you sample code:

<div class="news">
Blah, blah, blah. I'm hidden.
</div>

<a class="trigger">Hide/Show News</a>

The link will be the trigger to show the div when clicked. So your Javascript will be:

$('.trigger').click(function() {
   $('.news').toggle();
});

You're almost always better off letting jQuery handle the styling for hiding and showing elements.

Edit: I see people above are recommending using .show and .hide for this. .toggle allows you to do both with just one effect. So that's cool.

Changing background color of ListView items on Android

Simple code to change all in layout of item (custom listview extends baseadapter):

lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {

            RelativeLayout layout=(RelativeLayout) arg1.findViewById(R.id.rel_cell_left);
            layout.setBackgroundColor(Color.YELLOW);



        }
    });

How to bundle vendor scripts separately and require them as needed with Webpack?

In case you're interested in bundling automatically your scripts separately from vendors ones:

var webpack = require('webpack'),
    pkg     = require('./package.json'),  //loads npm config file
    html    = require('html-webpack-plugin');

module.exports = {
  context : __dirname + '/app',
  entry   : {
    app     : __dirname + '/app/index.js',
    vendor  : Object.keys(pkg.dependencies) //get npm vendors deps from config
  },
  output  : {
    path      : __dirname + '/dist',
    filename  : 'app.min-[hash:6].js'
  },
  plugins: [
    //Finally add this line to bundle the vendor code separately
    new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.min-[hash:6].js'),
    new html({template : __dirname + '/app/index.html'})
  ]
};

You can read more about this feature in official documentation.

Indirectly referenced from required .class file

I was getting this error:

The type com.ibm.portal.state.exceptions.StateException cannot be resolved. It is indirectly referenced from required .class files

Doing the following fixed it for me:

Properties -> Java build path -> Libraries -> Server Library[wps.base.v61]unbound -> Websphere Portal v6.1 on WAS 7 -> Finish -> OK

Removing time from a Date object?

Another way to work out here is to use java.sql.Date as sql Date doesn't have time associated with it, whereas java.util.Date always have a timestamp. Whats catching point here is java.sql.Date extends java.util.Date, therefore java.util.Date variable can be a reference to java.sql.Date(without time) and to java.util.Date of course(with timestamp).

Python threading.timer - repeat function every 'n' seconds

In the interest of providing a correct answer using Timer as the OP requested, I'll improve upon swapnil jariwala's answer:

from threading import Timer


class InfiniteTimer():
    """A Timer class that does not stop, unless you want it to."""

    def __init__(self, seconds, target):
        self._should_continue = False
        self.is_running = False
        self.seconds = seconds
        self.target = target
        self.thread = None

    def _handle_target(self):
        self.is_running = True
        self.target()
        self.is_running = False
        self._start_timer()

    def _start_timer(self):
        if self._should_continue: # Code could have been running when cancel was called.
            self.thread = Timer(self.seconds, self._handle_target)
            self.thread.start()

    def start(self):
        if not self._should_continue and not self.is_running:
            self._should_continue = True
            self._start_timer()
        else:
            print("Timer already started or running, please wait if you're restarting.")

    def cancel(self):
        if self.thread is not None:
            self._should_continue = False # Just in case thread is running and cancel fails.
            self.thread.cancel()
        else:
            print("Timer never started or failed to initialize.")


def tick():
    print('ipsem lorem')

# Example Usage
t = InfiniteTimer(0.5, tick)
t.start()

Get last n lines of a file, similar to tail

Here is my answer. Pure python. Using timeit it seems pretty fast. Tailing 100 lines of a log file that has 100,000 lines:

>>> timeit.timeit('tail.tail(f, 100, 4098)', 'import tail; f = open("log.txt", "r");', number=10)
0.0014600753784179688
>>> timeit.timeit('tail.tail(f, 100, 4098)', 'import tail; f = open("log.txt", "r");', number=100)
0.00899195671081543
>>> timeit.timeit('tail.tail(f, 100, 4098)', 'import tail; f = open("log.txt", "r");', number=1000)
0.05842900276184082
>>> timeit.timeit('tail.tail(f, 100, 4098)', 'import tail; f = open("log.txt", "r");', number=10000)
0.5394978523254395
>>> timeit.timeit('tail.tail(f, 100, 4098)', 'import tail; f = open("log.txt", "r");', number=100000)
5.377126932144165

Here is the code:

import os


def tail(f, lines=1, _buffer=4098):
    """Tail a file and get X lines from the end"""
    # place holder for the lines found
    lines_found = []

    # block counter will be multiplied by buffer
    # to get the block size from the end
    block_counter = -1

    # loop until we find X lines
    while len(lines_found) < lines:
        try:
            f.seek(block_counter * _buffer, os.SEEK_END)
        except IOError:  # either file is too small, or too many lines requested
            f.seek(0)
            lines_found = f.readlines()
            break

        lines_found = f.readlines()

        # we found enough lines, get out
        # Removed this line because it was redundant the while will catch
        # it, I left it for history
        # if len(lines_found) > lines:
        #    break

        # decrement the block counter to get the
        # next X bytes
        block_counter -= 1

    return lines_found[-lines:]

How to fix Cannot find module 'typescript' in Angular 4?

This should do the trick,

npm install -g typescript

How do I print colored output to the terminal in Python?

You can try this with python 3:

from termcolor import colored
print(colored('Hello, World!', 'green', 'on_red'))

If you are using windows operating system, the above code may not work for you. Then you can try this code:

from colorama import init
from termcolor import colored

# use Colorama to make Termcolor work on Windows too
init()

# then use Termcolor for all colored text output
print(colored('Hello, World!', 'green', 'on_red'))

Hope that helps.

CSS: how do I create a gap between rows in a table?

If none of the other answers are satisfactory, you could always just create an empty row and style it with CSS appropriately to be transparent.

Is JVM ARGS '-Xms1024m -Xmx2048m' still useful in Java 8?

What I know is one reason when “GC overhead limit exceeded” error is thrown when 2% of the memory is freed after several GC cycles

By this error your JVM is signalling that your application is spending too much time in garbage collection. so the little amount GC was able to clean will be quickly filled again thus forcing GC to restart the cleaning process again.

You should try changing the value of -Xmx and -Xms.

How to run Gulp tasks sequentially one after the other

Try this hack :-) Gulp v3.x Hack for Async bug

I tried all of the "official" ways in the Readme, they didn't work for me but this did. You can also upgrade to gulp 4.x but I highly recommend you don't, it breaks so much stuff. You could use a real js promise, but hey, this is quick, dirty, simple :-) Essentially you use:

var wait = 0; // flag to signal thread that task is done
if(wait == 0) setTimeout(... // sleep and let nodejs schedule other threads

Check out the post!

How to put an image next to each other

You don't need the div's.

HTML:

<div class="nav3" style="height:705px;">
    <a href="http://www.facebook.com/" class="icons"><img src="images/facebook.png"></a>
    <a href="https://twitter.com" class="icons"><img src="images/twitter.png"></a>
</div>

CSS:

.nav3 {
    background-color: #E9E8C7;
    height: auto;
    width: 150px;
    float: left;
    padding-left: 20px;
    font-family: Arial, Helvetica, sans-serif;
    font-size: 12px;
    color: #333333;
    padding-top: 20px;
    padding-right: 20px;
}

.icons{
    display:inline-block;
    width: 64px; 
    height: 64px; 
   }

 a.icons:hover {
     background: #C93;
 }

See this fiddle

Python dictionary: Get list of values for list of keys

Try this:

mydict = {'one': 1, 'two': 2, 'three': 3}
mykeys = ['three', 'one'] # if there are many keys, use a set

[mydict[k] for k in mykeys]
=> [3, 1]

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

How can I search an array in VB.NET?

It's not exactly clear how you want to search the array. Here are some alternatives:

Find all items containing the exact string "Ra" (returns items 2 and 3):

Dim result As String() = Array.FindAll(arr, Function(s) s.Contains("Ra"))

Find all items starting with the exact string "Ra" (returns items 2 and 3):

Dim result As String() = Array.FindAll(arr, Function(s) s.StartsWith("Ra"))

Find all items containing any case version of "ra" (returns items 0, 2 and 3):

Dim result As String() = Array.FindAll(arr, Function(s) s.ToLower().Contains("ra"))

Find all items starting with any case version of "ra" (retuns items 0, 2 and 3):

Dim result As String() = Array.FindAll(arr, Function(s) s.ToLower().StartsWith("ra"))

-

If you are not using VB 9+ then you don't have anonymous functions, so you have to create a named function.

Example:

Function ContainsRa(s As String) As Boolean
   Return s.Contains("Ra")
End Function

Usage:

Dim result As String() = Array.FindAll(arr, ContainsRa)

Having a function that only can compare to a specific string isn't always very useful, so to be able to specify a string to compare to you would have to put it in a class to have somewhere to store the string:

Public Class ArrayComparer

   Private _compareTo As String

   Public Sub New(compareTo As String)
      _compareTo = compareTo
   End Sub

   Function Contains(s As String) As Boolean
      Return s.Contains(_compareTo)
   End Function

   Function StartsWith(s As String) As Boolean
      Return s.StartsWith(_compareTo)
   End Function

End Class

Usage:

Dim result As String() = Array.FindAll(arr, New ArrayComparer("Ra").Contains)

How to get selected option using Selenium WebDriver with Java

Completing the answer:

String selectedOption = new Select(driver.findElement(By.xpath("Type the xpath of the drop-down element"))).getFirstSelectedOption().getText();

Assert.assertEquals("Please select any option...", selectedOption);

Remove leading and trailing spaces?

Expand your one liner into multiple lines. Then it becomes easy:

f.write(re.split("Tech ID:|Name:|Account #:",line)[-1])

parts = re.split("Tech ID:|Name:|Account #:",line)
wanted_part = parts[-1]
wanted_part_stripped = wanted_part.strip()
f.write(wanted_part_stripped)

Cross-browser window resize event - JavaScript / jQuery

hope it will help in jQuery

define a function first, if there is an existing function skip to next step.

 function someFun() {
 //use your code
 }

browser resize use like these.

 $(window).on('resize', function () {
    someFun();  //call your function.
 });

Java; String replace (using regular expressions)?

class Replacement 
{
    public static void main(String args[])
    {
        String Main = "5 * x^3 - 6 * x^1 + 1";
        String replaced = Main.replaceAll("(?m)(:?\\d+) \\* x\\^(:?\\d+)", "$1x<sup>$2</sup>");
        System.out.println(replaced);
    }
}

Regex Match all characters between two strings

for a quick search in VIM, you could use at Vim Control prompt: /This is.*\_.*sentence

How do I connect to mongodb with node.js (and authenticate)?

Here is new may to authenticate from "admin" and then switch to your desired DB for further operations:

   var MongoClient = require('mongodb').MongoClient;
var Db = require('mongodb').Db, Server = require('mongodb').Server ,
    assert = require('assert');

var user = 'user';
var password = 'password';

MongoClient.connect('mongodb://'+user+':'+password+'@localhost:27017/opsdb',{native_parser:true, authSource:'admin'}, function(err,db){
    if(err){
        console.log("Auth Failed");
        return;
    }
    console.log("Connected");
    db.collection("cols").find({loc:{ $eq: null } }, function(err, docs) {
        docs.each(function(err, doc) {
          if(doc) {
            console.log(doc['_id']);
          }
        });
    });

    db.close();

}); 

Check if a string contains a string in C++

From so many answers in this website I didn't find out a clear answer so in 5-10 minutes I figured it out the answer myself. But this can be done in two cases:

  1. Either you KNOW the position of the sub-string you search for in the string
  2. Either you don't know the position and search for it, char by char...

So, let's assume we search for the substring "cd" in the string "abcde", and we use the simplest substr built-in function in C++

for 1:

#include <iostream>
#include <string>

    using namespace std;
int i;

int main()
{
    string a = "abcde";
    string b = a.substr(2,2);    // 2 will be c. Why? because we start counting from 0 in a string, not from 1.

    cout << "substring of a is: " << b << endl;
    return 0;
}

for 2:

#include <iostream>
#include <string>

using namespace std;
int i;

int main()
{
    string a = "abcde";

    for (i=0;i<a.length(); i++)
    {
        if (a.substr(i,2) == "cd")
        {
        cout << "substring of a is: " << a.substr(i,2) << endl;    // i will iterate from 0 to 5 and will display the substring only when the condition is fullfilled 
        }
    }
    return 0;
}

CORS header 'Access-Control-Allow-Origin' missing

This happens generally when you try access another domain's resources.

This is a security feature for avoiding everyone freely accessing any resources of that domain (which can be accessed for example to have an exact same copy of your website on a pirate domain).

The header of the response, even if it's 200OK do not allow other origins (domains, port) to access the ressources.

You can fix this problem if you are the owner of both domains:

Solution 1: via .htaccess

To change that, you can write this in the .htaccess of the requested domain file:

    <IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
    </IfModule>

If you only want to give access to one domain, the .htaccess should look like this:

    <IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin 'https://my-domain.tdl'
    </IfModule>

Solution 2: set headers the correct way

If you set this into the response header of the requested file, you will allow everyone to access the ressources:

Access-Control-Allow-Origin : *

OR

Access-Control-Allow-Origin : http://www.my-domain.com

Peace and code ;)

Shell - How to find directory of some command?

The Korn shell, ksh, offers the whence built-in, which identifies other shell built-ins, macros, etc. The which command is more portable, however.

Requested bean is currently in creation: Is there an unresolvable circular reference?

Spring uses an special logic for resolving this kind of circular dependencies with singleton beans. But this won't apply to other scopes. There is no elegant way of breaking this circular dependency, but a clumsy option could be this one:

@Component("bean1")
@Scope("view")
public class Bean1 {

    @Autowired
    private Bean2 bean2;

    @PostConstruct
    public void init() {
        bean2.setBean1(this);
    }
}

@Component("bean2")
@Scope("view")
public class Bean2 {

    private Bean1 bean1;

    public void setBean1(Bean1 bean1) {
        this.bean1 = bean1;
    }
}

Anyway, circular dependencies are usually a symptom of bad design. You would think again if there is some better way of defining your class dependencies.

How do I remove all null and empty string values from an object?

According to Alexis King answer, here is a plain JavaScript version.

_x000D_
_x000D_
function cleanUp(obj) {_x000D_
    for (var attrKey in obj) {_x000D_
        var attrValue = obj[attrKey];_x000D_
        if (attrValue === null || attrValue === "") {_x000D_
            delete obj[attrKey];_x000D_
        } else if (Object.prototype.toString.call(attrValue) === "[object Object]") {_x000D_
            cleanUp(attrValue);_x000D_
        } else if (Array.isArray(attrValue)) {_x000D_
            attrValue.forEach(function (arrayValue) {_x000D_
                cleanUp(arrayValue);_x000D_
            });_x000D_
        }_x000D_
    }_x000D_
}
_x000D_
_x000D_
_x000D_

How to extract or unpack an .ab file (Android Backup file)

As per https://android.stackexchange.com/a/78183/239063 you can run a one line command in Linux to add in an appropriate tar header to extract it.

( printf "\x1f\x8b\x08\x00\x00\x00\x00\x00" ; tail -c +25 backup.ab ) | tar xfvz -

Replace backup.ab with the path to your file.

How do I call one constructor from another in Java?

I will tell you an easy way

There are two types of constructors:

  1. Default constructor
  2. Parameterized constructor

I will explain in one Example

class ConstructorDemo 
{
      ConstructorDemo()//Default Constructor
      {
         System.out.println("D.constructor ");
      }

      ConstructorDemo(int k)//Parameterized constructor
      {
         this();//-------------(1)
         System.out.println("P.Constructor ="+k);       
      }

      public static void main(String[] args) 
      {
         //this(); error because "must be first statement in constructor
         new ConstructorDemo();//-------(2)
         ConstructorDemo g=new ConstructorDemo(3);---(3)    
       }
   }                  

In the above example I showed 3 types of calling

  1. this() call to this must be first statement in constructor
  2. This is Name less Object. this automatically calls the default constructor. 3.This calls the Parameterized constructor.

Note: this must be the first statement in the constructor.

What is the Auto-Alignment Shortcut Key in Eclipse?

Ctrl+Shift+F to invoke the Auto Formatter

Ctrl+I to indent the selected part (or all) of you code.

Select From all tables - MySQL

Improve to @inno answer

delimiter //

DROP PROCEDURE IF EXISTS get_product;  
CREATE PROCEDURE get_product()
BEGIN
   DECLARE i VARCHAR(100); 
   DECLARE cur1 CURSOR FOR SELECT DISTINCT table_name FROM information_schema.columns WHERE COLUMN_NAME IN ('Product');
   OPEN cur1;

   read_loop: LOOP
       FETCH cur1 INTO i;
    
       SELECT i; -- printing table name
    
       SET @s = CONCAT('select * from ', i, ' where Product like %XYZ%'); 
       PREPARE stmt1 FROM @s;
       EXECUTE stmt1;
       DEALLOCATE PREPARE stmt1;

   END LOOP read_loop;

   CLOSE cur1;
END//

delimiter ;

call get_product();

How do you check "if not null" with Eloquent?

If you want to search deleted record (Soft Deleted Record), do't user Eloquent Model Query. Instead use Db::table query e.g Instead of using Below:

$stu = Student::where('rollNum', '=', $rollNum . '-' . $nursery)->first();

Use:

$stu = DB::table('students')->where('rollNum', '=', $newRollNo)->first();

Does a `+` in a URL scheme/host/path represent a space?

  • Percent encoding in the path section of a URL is expected to be decoded, but
  • any + characters in the path component is expected to be treated literally.

To be explicit: + is only a special character in the query component.

https://tools.ietf.org/html/rfc3986

Is there a C# case insensitive equals operator?

if (StringA.ToUpperInvariant() == StringB.ToUpperInvariant()) {

People report ToUpperInvariant() is faster than ToLowerInvariant().

HTML5 tag for horizontal line break

Instead of using <hr>, you can one of the border of the enclosing block and display it as a horizontal line.

Here is a sample code:

The HTML:

<div class="title_block">
    <h3>This is a header.</h3>
</div>
<p>Here is some sample paragraph text.<br>
This demonstrates that a horizontal line goes between the title and the paragraph.</p>

The CSS:

.title_block {
    border-bottom: 1px solid #ddd;
    padding-bottom: 5px;
    margin-bottom: 5px;
}

Getting time elapsed in Objective-C

For anybody coming here looking for a getTickCount() implementation for iOS, here is mine after putting various sources together.

Previously I had a bug in this code (I divided by 1000000 first) which was causing some quantisation of the output on my iPhone 6 (perhaps this was not an issue on iPhone 4/etc or I just never noticed it). Note that by not performing that division first, there is some risk of overflow if the numerator of the timebase is quite large. If anybody is curious, there is a link with much more information here: https://stackoverflow.com/a/23378064/588476

In light of that information, maybe it is safer to use Apple's function CACurrentMediaTime!

I also benchmarked the mach_timebase_info call and it takes approximately 19ns on my iPhone 6, so I removed the (not threadsafe) code which was caching the output of that call.

#include <mach/mach.h>
#include <mach/mach_time.h>

uint64_t getTickCount(void)
{
    mach_timebase_info_data_t sTimebaseInfo;
    uint64_t machTime = mach_absolute_time();

    // Convert to milliseconds
    mach_timebase_info(&sTimebaseInfo);
    machTime *= sTimebaseInfo.numer;
    machTime /= sTimebaseInfo.denom;
    machTime /= 1000000; // convert from nanoseconds to milliseconds

    return machTime;
}

Do be aware of the potential risk of overflow depending on the output of the timebase call. I suspect (but do not know) that it might be a constant for each model of iPhone. on my iPhone 6 it was 125/3.

The solution using CACurrentMediaTime() is quite trivial:

uint64_t getTickCount(void)
{
    double ret = CACurrentMediaTime();
    return ret * 1000;
}

Convert JSON string to array of JSON objects in Javascript

As Luca indicated, add extra [] to your string and use the code below:

var myObject = eval('(' + myJSONtext + ')');

to test it you can use the snippet below.

var s =" [{'id':1,'name':'Test1'},{'id':2,'name':'Test2'}]";
var myObject = eval('(' + s + ')');
for (i in myObject)
{
   alert(myObject[i]["name"]);
}

hope it helps..

Android - implementing startForeground for a service?

Solution for Oreo 8.1

I've encountered some problems such as RemoteServiceException because of invalid channel id with most recent versions of Android. This is how i solved it:

Activity:

override fun onCreate(savedInstanceState: Bundle?) {
    val intent = Intent(this, BackgroundService::class.java)

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        startForegroundService(intent)
    } else {
        startService(intent)
    }
}

BackgroundService:

override fun onCreate() {
    super.onCreate()
    startForeground()
}

private fun startForeground() {

    val service = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    val channelId =
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                createNotificationChannel()
            } else {
                // If earlier version channel ID is not used
                // https://developer.android.com/reference/android/support/v4/app/NotificationCompat.Builder.html#NotificationCompat.Builder(android.content.Context)
                ""
            }

    val notificationBuilder = NotificationCompat.Builder(this, channelId )
    val notification = notificationBuilder.setOngoing(true)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setPriority(PRIORITY_MIN)
            .setCategory(Notification.CATEGORY_SERVICE)
            .build()
    startForeground(101, notification)
}


@RequiresApi(Build.VERSION_CODES.O)
private fun createNotificationChannel(): String{
    val channelId = "my_service"
    val channelName = "My Background Service"
    val chan = NotificationChannel(channelId,
            channelName, NotificationManager.IMPORTANCE_HIGH)
    chan.lightColor = Color.BLUE
    chan.importance = NotificationManager.IMPORTANCE_NONE
    chan.lockscreenVisibility = Notification.VISIBILITY_PRIVATE
    val service = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    service.createNotificationChannel(chan)
    return channelId
}

JAVA EQUIVALENT

public class YourService extends Service {

    // Constants
    private static final int ID_SERVICE = 101;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);
        return START_STICKY;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        // do stuff like register for BroadcastReceiver, etc.

        // Create the Foreground Service
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        String channelId = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ? createNotificationChannel(notificationManager) : "";
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId);
        Notification notification = notificationBuilder.setOngoing(true)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setPriority(PRIORITY_MIN)
                .setCategory(NotificationCompat.CATEGORY_SERVICE)
                .build();

        startForeground(ID_SERVICE, notification);
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private String createNotificationChannel(NotificationManager notificationManager){
        String channelId = "my_service_channelid";
        String channelName = "My Foreground Service";
        NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH);
        // omitted the LED color
        channel.setImportance(NotificationManager.IMPORTANCE_NONE);
        channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
        notificationManager.createNotificationChannel(channel);
        return channelId;
    }
}

Why can't I set text to an Android TextView?

The code should instead be something like this:

TextView text = (TextView) findViewById(R.id.this_is_the_id_of_textview);
text.setText("test");

How to right-align and justify-align in Markdown?

I used

<p align='right'>Farhan Khan</p>

and it worked for me on Google Colaboratory. Funnily enough it does not work anywhere else?

How can I check if an InputStream is empty without reading from it?

No, you can't. InputStream is designed to work with remote resources, so you can't know if it's there until you actually read from it.

You may be able to use a java.io.PushbackInputStream, however, which allows you to read from the stream to see if there's something there, and then "push it back" up the stream (that's not how it really works, but that's the way it behaves to client code).

How to change MenuItem icon in ActionBar programmatically

Lalith's answer is correct.

You may also try this approach:

button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            invalidateOptionsMenu();
        }
    });

 @Override
 public boolean onPrepareOptionsMenu(Menu menu) {

    MenuItem settingsItem = menu.findItem(R.id.action_settings);
    // set your desired icon here based on a flag if you like
    settingsItem.setIcon(ContextCompat.getDrawable(this, R.drawable.ic_launcher)); 

    return super.onPrepareOptionsMenu(menu);
 }

Support for the experimental syntax 'classProperties' isn't currently enabled

yarn add --dev @babel/plugin-proposal-class-properties

or

npm install @babel/plugin-proposal-class-properties --save-dev .babelrc

SQLAlchemy IN clause

With the expression API, which based on the comments is what this question is asking for, you can use the in_ method of the relevant column.

To query

SELECT id, name FROM user WHERE id in (123,456)

use

myList = [123, 456]
select = sqlalchemy.sql.select([user_table.c.id, user_table.c.name], user_table.c.id.in_(myList))
result = conn.execute(select)
for row in result:
    process(row)

This assumes that user_table and conn have been defined appropriately.

How to stop docker under Linux

The output of ps aux looks like you did not start docker through systemd/systemctl.

It looks like you started it with:

sudo dockerd -H gridsim1103:2376

When you try to stop it with systemctl, nothing should happen as the resulting dockerd process is not controlled by systemd. So the behavior you see is expected.

The correct way to start docker is to use systemd/systemctl:

systemctl enable docker
systemctl start docker

After this, docker should start on system start.

EDIT: As you already have the docker process running, simply kill it by pressing CTRL+C on the terminal you started it. Or send a kill signal to the process.

How to set a Javascript object values dynamically?

You can get the property the same way as you set it.

foo = {
 bar: "value"
}

You set the value foo["bar"] = "baz";

To get the value foo["bar"]

will return "baz".

What is a "slug" in Django?

The term 'slug' comes from the world of newspaper production.

It's an informal name given to a story during the production process. As the story winds its path from the beat reporter (assuming these even exist any more?) through to editor through to the "printing presses", this is the name it is referenced by, e.g., "Have you fixed those errors in the 'kate-and-william' story?".

Some systems (such as Django) use the slug as part of the URL to locate the story, an example being www.mysite.com/archives/kate-and-william.

Even Stack Overflow itself does this, with the GEB-ish(a) self-referential https://stackoverflow.com/questions/427102/what-is-a-slug-in-django/427201#427201, although you can replace the slug with blahblah and it will still find it okay.

It may even date back earlier than that, since screenplays had "slug lines" at the start of each scene, which basically sets the background for that scene (where, when, and so on). It's very similar in that it's a precis or preamble of what follows.

On a Linotype machine, a slug was a single line piece of metal which was created from the individual letter forms. By making a single slug for the whole line, this greatly improved on the old character-by-character compositing.

Although the following is pure conjecture, an early meaning of slug was for a counterfeit coin (which would have to be pressed somehow). I could envisage that usage being transformed to the printing term (since the slug had to be pressed using the original characters) and from there, changing from the 'piece of metal' definition to the 'story summary' definition. From there, it's a short step from proper printing to the online world.


(a) "Godel Escher, Bach", by one Douglas Hofstadter, which I (at least) consider one of the great modern intellectual works. You should also check out his other work, "Metamagical Themas".

Escape a string for a sed replace pattern

If the case happens to be that you are generating a random password to pass to sed replace pattern, then you choose to be careful about which set of characters in the random string. If you choose a password made by encoding a value as base64, then there is is only character that is both possible in base64 and is also a special character in sed replace pattern. That character is "/", and is easily removed from the password you are generating:

# password 32 characters log, minus any copies of the "/" character.
pass=`openssl rand -base64 32 | sed -e 's/\///g'`;

Ctrl+click doesn't work in Eclipse Juno

If you're working on a large project and are working with a repository, you could just have the file opened via the wrong project, I just had two instances of the file open, where one was the one where I couldn't do Ctrl + click, while on the other file I could Ctrl + click on it successfully.

How to install SQL Server Management Studio 2012 (SSMS) Express?

Easiest way to install MSSQL 2012 MS SQL INSTALLATION

Here i am showing the easiest way to install ms sql 2012.

My opinion is the installation will be easier with windows 8.1 rather than windows 7.

This is my personnal opinion only.

We can install in windows 7 as well.

The steps to be followed:

Download any one of the link using the following URL

http://www.microsoft.com/en-us/download/details.aspx?id=43351

SQLEXPRWT_x86_ENU.exe or SQLEXPRWT_x64_ENU.exe

http://www.microsoft.com/en-us/download/details.aspx?id=42299

SQLEXPRWT_x86_ENU.exe or SQLEXPRWT_x64_ENU.exe

Right click on .exe file and run it

We should leave everything default while installing.

During installation, there will be 2 options:

1)If you are New user,then click on new sql-server stand alone application.

2)If you have already MS SQL application then you can upgrade by using the other option.

Then accept the Licence terms and click Next.

Now you will move on to Product Updates and press next then Setup support rules.

After this Feature selection.According to me we can check all the boxes except localdb.

Next it will take you to Instance Configuration where you should select Named Instance as

"SQLEXPRESS".

Then go to Server Configuration and press next.

Now Database engine configuration:

Authentication Mode:we can click on any one that is windows authentication mode or mixed.

Windows authentication mode (default for windows).

Mixed authentication mode:then should create username and password.

Then move on Error reporting,we can move further by clicking next to install process.

Finally we can see the Complete windows by showing the products added .

We can close and run the MSSQL server.

I hope it's useful.

Regards

Ramya

how to bypass Access-Control-Allow-Origin?

Okay, but you all know that the * is a wildcard and allows cross site scripting from every domain?

You would like to send multiple Access-Control-Allow-Origin headers for every site that's allowed to - but unfortunately its officially not supported to send multiple Access-Control-Allow-Origin headers, or to put in multiple origins.

You can solve this by checking the origin, and sending back that one in the header, if it is allowed:

$origin = $_SERVER['HTTP_ORIGIN'];
$allowed_domains = [
    'http://mysite1.com',
    'https://www.mysite2.com',
    'http://www.mysite2.com',
];

if (in_array($origin, $allowed_domains)) {
    header('Access-Control-Allow-Origin: ' . $origin);
}

Thats much safer. You might want to edit the matching and change it to a manual function with some regex, or something like that. At least this will only send back 1 header, and you will be sure its the one that the request came from. Please do note that all HTTP headers can be spoofed, but this header is for the client's protection. Don't protect your own data with those values. If you want to know more, read up a bit on CORS and CSRF.

Why is it safer?

Allowing access from other locations then your own trusted site allows for session highjacking. I'm going to go with a little example - image Facebook allows a wildcard origin - this means that you can make your own website somewhere, and make it fire AJAX calls (or open iframes) to facebook. This means you can grab the logged in info of the facebook of a visitor of your website. Even worse - you can script POST requests and post data on someone's facebook - just while they are browsing your website.

Be very cautious when using the ACAO headers!

Android: why setVisibility(View.GONE); or setVisibility(View.INVISIBLE); do not work

I see quite a few things wrong. For starters, you don't have your magic button defined and there is no event handler for it.

Also you shouldn't use:

dp2.setVisibility(View.GONE);
dp2.setVisibility(View.INVISIBLE); 

Use only one of the two. From Android documentation:

View.GONE This view is invisible, and it doesn't take any space for layout purposes.

View.INVISIBLE This view is invisible, but it still takes up space for layout purposes.

In your example, you are overriding the View.GONE assignment with the View.INVISIBLE one.


Try replacing:

final DatePicker dp2 = new DatePicker(this)

with:

DatePicker dp2 = (DatePicker) findViewById(R.id.datePick2);  

Similarly for other widgets:

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        LinearLayout ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.VERTICAL);

        final DatePicker dp2 = new DatePicker(this);
        final Button btn2 = new Button(this);
        final Button magicButton = new Button(this);
        final TextView txt2 = new TextView(TestActivity.this);

        dp2.setVisibility(View.GONE);
        btn2.setVisibility(View.GONE);
        btn2.setText("set Date");

        btn2.setOnClickListener(new View.OnClickListener() {
            public void onClick(View arg0) {
                txt2.setText("You selected "
                    + dp2.getDayOfMonth() + "/" + (dp2.getMonth() + 1) 
                    + "/" + dp2.getYear());
            }
        });

        magicButton.setText("Magic Button");
        magicButton.setOnClickListener(new View.OnClickListener()    
            public void onClick(View arg0) {
                dp2.setVisibility(View.VISIBLE);
                btn2.setVisibility(View.VISIBLE);
            }
        });

    ll.addView(dp2);
    ll.addView(btn2);
    ll.addView(magicButton);
    ll.addView(txt2);

    setContentView(ll);
}

Unstaged changes left after git reset --hard

I had the same problem. I did git reset --hard HEAD but still every time I did git status I was seeing some files as modified.

My solution was relatively simple. I just closed my IDE (here it was Xcode) and close my command line (here it was terminal on my Mac OS) and tried it again and it worked .

Yet I was never able to find what originated the problem.

What's the yield keyword in JavaScript?

To give a complete answer: yield is working similar to return, but in a generator.

As for the commonly given example, this works as follows:

function *squareGen(x) {
    var i;
    for (i = 0; i < x; i++) {
        yield i*i;
    }
}

var gen = squareGen(3);

console.log(gen.next().value); // prints 0
console.log(gen.next().value); // prints 1
console.log(gen.next().value); // prints 4

But theres also a second purpose of the yield keyword. It can be used to send values to the generator.

To clarify, a small example:

function *sendStuff() {
    y = yield (0);
    yield y*y;
}

var gen = sendStuff();

console.log(gen.next().value); // prints 0
console.log(gen.next(2).value); // prints 4

This works, as the value 2 is assigned to y, by sending it to the generator, after it stopped at the first yield (which returned 0).

This enables us to to some really funky stuff. (look up coroutine)

How do I execute multiple SQL Statements in Access' Query Editor?

create a macro like this

Option Compare Database

Sub a()

DoCmd.RunSQL "DELETE * from TABLENAME where CONDITIONS"

DoCmd.RunSQL "DELETE * from TABLENAME where CONDITIONS"

End Sub

How do I draw a grid onto a plot in Python?

Here is a small example how to add a matplotlib grid in Gtk3 with Python 2 (not working in Python 3):

#!/usr/bin/env python
#-*- coding: utf-8 -*-

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from matplotlib.figure import Figure
from matplotlib.backends.backend_gtk3agg import FigureCanvasGTK3Agg as FigureCanvas

win = Gtk.Window()
win.connect("delete-event", Gtk.main_quit)
win.set_title("Embedding in GTK3")

f = Figure(figsize=(1, 1), dpi=100)
ax = f.add_subplot(111)
ax.grid()

canvas = FigureCanvas(f)
canvas.set_size_request(400, 400)
win.add(canvas)

win.show_all()
Gtk.main()

enter image description here

Exporting the values in List to excel

the one easy way to do it is to open Excel create sheet containing test data you want to export then say to excel save as xml open the xml see the xml format excel is expecting and generate it by head replacing the test data with export data

SpreadsheetML Markup Spec

@lan this is xml fo a simle execel file with one column value i genereted with office 2003 this format is for office 2003 and above

<?xml version="1.0"?>
<?mso-application progid="Excel.Sheet"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
 xmlns:o="urn:schemas-microsoft-com:office:office"
 xmlns:x="urn:schemas-microsoft-com:office:excel"
 xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
 xmlns:html="http://www.w3.org/TR/REC-html40">
 <DocumentProperties xmlns="urn:schemas-microsoft-com:office:office">
  <Author>Dancho</Author>
  <LastAuthor>Dancho</LastAuthor>
  <Created>2010-02-05T10:15:54Z</Created>
  <Company>cc</Company>
  <Version>11.9999</Version>
 </DocumentProperties>
 <ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel">
  <WindowHeight>13800</WindowHeight>
  <WindowWidth>24795</WindowWidth>
  <WindowTopX>480</WindowTopX>
  <WindowTopY>105</WindowTopY>
  <ProtectStructure>False</ProtectStructure>
  <ProtectWindows>False</ProtectWindows>
 </ExcelWorkbook>
 <Styles>
  <Style ss:ID="Default" ss:Name="Normal">
   <Alignment ss:Vertical="Bottom"/>
   <Borders/>
   <Font/>
   <Interior/>
   <NumberFormat/>
   <Protection/>
  </Style>
 </Styles>
 <Worksheet ss:Name="Sheet1">
  <Table ss:ExpandedColumnCount="1" ss:ExpandedRowCount="6" x:FullColumns="1"
   x:FullRows="1">
   <Row>
    <Cell><Data ss:Type="String">Value1</Data></Cell>
   </Row>
   <Row>
    <Cell><Data ss:Type="String">Value2</Data></Cell>
   </Row>
   <Row>
    <Cell><Data ss:Type="String">Value3</Data></Cell>
   </Row>
   <Row>
    <Cell><Data ss:Type="String">Value4</Data></Cell>
   </Row>
   <Row>
    <Cell><Data ss:Type="String">Value5</Data></Cell>
   </Row>
   <Row>
    <Cell><Data ss:Type="String">Value6</Data></Cell>
   </Row>
  </Table>
  <WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">
   <Selected/>
   <Panes>
    <Pane>
     <Number>3</Number>
     <ActiveRow>5</ActiveRow>
    </Pane>
   </Panes>
   <ProtectObjects>False</ProtectObjects>
   <ProtectScenarios>False</ProtectScenarios>
  </WorksheetOptions>
 </Worksheet>
 <Worksheet ss:Name="Sheet2">
  <WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">
   <ProtectObjects>False</ProtectObjects>
   <ProtectScenarios>False</ProtectScenarios>
  </WorksheetOptions>
 </Worksheet>
 <Worksheet ss:Name="Sheet3">
  <WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">
   <ProtectObjects>False</ProtectObjects>
   <ProtectScenarios>False</ProtectScenarios>
  </WorksheetOptions>
 </Worksheet>
</Workbook>

Adding three months to a date in PHP

The following should work, but you may need to change the format:

echo date('l F jS, Y (m-d-Y)', strtotime('+3 months', strtotime($DateToAdjust)));

PHPExcel Make first row bold

You can try

$objPHPExcel->getActiveSheet()->getStyle(1)->getFont()->setBold(true);

Functional, Declarative, and Imperative Programming

I think that your taxonomy is incorrect. There are two opposite types imperative and declarative. Functional is just a subtype of declarative. BTW, wikipedia states the same fact.

Google Gson - deserialize list<class> object? (generic type)

public static final <T> List<T> getList(final Class<T[]> clazz, final String json)
{
    final T[] jsonToObject = new Gson().fromJson(json, clazz);

    return Arrays.asList(jsonToObject);
}

Example:

getList(MyClass[].class, "[{...}]");

java.math.BigInteger cannot be cast to java.lang.Long

You need to add an alias for the count to your query and then use the addScalar() method as the default for list() method in Hibernate seams to be BigInteger for numeric SQL types. Here is an example:

List<Long> sqlResult = session.createSQLQuery("SELECT column AS num FROM table")
    .addScalar("num", StandardBasicTypes.LONG).list();

Problem in running .net framework 4.0 website on iis 7.0

After mapping of Application follow these steps

Open IIS Click on Applications Pools Double click on website Change Manage pipeline mode to "classic" click Ok.

Ow change .Net Framework Version to Lower version

Then click Ok

How to load URL in UIWebView in Swift?

import UIKit

class ViewController: UIViewController{

@IBOutlet weak var webView: UIWebView!



override func viewDidLoad() {
   super.viewDidLoad()
       //Func Gose Here 
      loadUrl()

   } 
 func loadUrl(){

   let url = URL(string: "Url which you want to load(www.google.com)")
   let requestObj = URLRequest(url: url! as URL)
   webView.load(requestObj)
 }

}

Is there a command to restart computer into safe mode?

My first answer!

This will set the safemode switch:

bcdedit /set {current} safeboot minimal 

with networking:

bcdedit /set {current} safeboot network

then reboot the machine with

shutdown /r

to put back in normal mode via dos:

bcdedit /deletevalue {current} safeboot

What are the most useful Intellij IDEA keyboard shortcuts?

These are some of my most used keyboard short cuts

Syntax aware selection in the editor selects a word at the caret and then selects expanding areas of the source code. For example, it may select a method name, then the expression that calls this method, then the whole statement, then the containing block, etc.: Ctrl+W

Basic Code Completion, to complete methods, keywords etc.: Ctrl+Space

Go to Declaration. Use this to navigate to the declaration of a class, method or variable used somewhere in the code: Ctrl+B

Introduce Variable Refactoring, to create a variable from an expression. This expression may even be incomplete or contain errors. Since version 8, IDEA intelligently selects a likely expression when no text is selected: Ctrl+Alt+V

Go to Class, to quickly open any class in the editor: Ctrl+N

To open any file, not just classes: Ctrl+Shift+N

Comment/Uncomment current line or selection: Ctrl+/ and Ctrl+Shift+/

Quick JavaDoc Popup to show the JavaDoc of the method or class at the text cursor: Ctrl+Q (Ctrl+J on Mac OS X)

Smart Type Completion to complete an expression with a method call or variable with a type suitable in the current Context: Ctrl+Shift+Space

Rename refactoring to rename any identifier. Can look in comments, text files and across different languages too: Shift+F6

Select in Popup to quickly select the currently edited element (class, file, method or field) in any view (Project View, Structure View or other): Alt+F1

Highlight Usages in File. Position the text cursor on any identifier without selecting any text and it will show all places in the file where that variable, method etc. is used. Use it on a throws, try or catch keyword to show all places where the exception is thrown. Use it on the implements keyword to highlight the methods of the implemented interface: Ctrl+Shift+F7

Received an invalid column length from the bcp client for colid 6

I just stumbled upon this and using @b_stil's snippet, I was able to figure the culprit column. And on futher investigation, I figured i needed to trim the column just like @Liji Chandran suggested but I was using IExcelDataReader and I couldn't figure out an easy way to validate and trim each of my 160 columns.

Then I stumbled upon this class, (ValidatingDataReader) class from CSVReader.

Interesting thing about this class is that it gives you the source and destination columns data length, the culprit row and even the column value that's causing the error.

All I did was just trim all (nvarchar, varchar, char and nchar) columns.

I just changed my GetValue method to this:

 object IDataRecord.GetValue(int i)
    {
        object columnValue = reader.GetValue(i);

        if (i > -1 && i < lookup.Length)
        {
            DataRow columnDef = lookup[i];
            if
            (
                (
                    (string)columnDef["DataTypeName"] == "varchar" ||
                    (string)columnDef["DataTypeName"] == "nvarchar" ||
                    (string)columnDef["DataTypeName"] == "char" ||
                    (string)columnDef["DataTypeName"] == "nchar"
                ) &&
                (
                    columnValue != null &&
                    columnValue != DBNull.Value
                )
            )
            {
                string stringValue = columnValue.ToString().Trim();

                columnValue = stringValue;


                if (stringValue.Length > (int)columnDef["ColumnSize"])
                {
                    string message =
                        "Column value \"" + stringValue.Replace("\"", "\\\"") + "\"" +
                        " with length " + stringValue.Length.ToString("###,##0") +
                        " from source column " + (this as IDataRecord).GetName(i) +
                        " in record " + currentRecord.ToString("###,##0") +
                        " does not fit in destination column " + columnDef["ColumnName"] +
                        " with length " + ((int)columnDef["ColumnSize"]).ToString("###,##0") +
                        " in table " + tableName +
                        " in database " + databaseName +
                        " on server " + serverName + ".";

                    if (ColumnException == null)
                    {
                        throw new Exception(message);
                    }
                    else
                    {
                        ColumnExceptionEventArgs args = new ColumnExceptionEventArgs();

                        args.DataTypeName = (string)columnDef["DataTypeName"];
                        args.DataType = Type.GetType((string)columnDef["DataType"]);
                        args.Value = columnValue;
                        args.SourceIndex = i;
                        args.SourceColumn = reader.GetName(i);
                        args.DestIndex = (int)columnDef["ColumnOrdinal"];
                        args.DestColumn = (string)columnDef["ColumnName"];
                        args.ColumnSize = (int)columnDef["ColumnSize"];
                        args.RecordIndex = currentRecord;
                        args.TableName = tableName;
                        args.DatabaseName = databaseName;
                        args.ServerName = serverName;
                        args.Message = message;

                        ColumnException(args);

                        columnValue = args.Value;
                    }
                }



            }
        }

        return columnValue;
    }

Hope this helps someone

No converter found capable of converting from type to type

Return ABDeadlineType from repository:

public interface ABDeadlineTypeRepository extends JpaRepository<ABDeadlineType, Long> {
    List<ABDeadlineType> findAllSummarizedBy();
}

and then convert to DeadlineType. Manually or use mapstruct.

Or call constructor from @Query annotation:

public interface DeadlineTypeRepository extends JpaRepository<ABDeadlineType, Long> {

    @Query("select new package.DeadlineType(a.id, a.code) from ABDeadlineType a ")
    List<DeadlineType> findAllSummarizedBy();
}

Or use @Projection:

@Projection(name = "deadline", types = { ABDeadlineType.class })
public interface DeadlineType {

    @Value("#{target.id}")
    String getId();

    @Value("#{target.code}")
    String getText();

}

Update: Spring can work without @Projection annotation:

public interface DeadlineType {
    String getId();    
    String getText();
}

How to append data to a json file?

You aren't ever writing anything to do with the data you read in. Do you want to be adding the data structure in feeds to the new one you're creating?

Or perhaps you want to open the file in append mode open(filename, 'a') and then add your string, by writing the string produced by json.dumps instead of using json.dump - but nneonneo points out that this would be invalid json.

Could not find com.android.tools.build:gradle:3.0.0-alpha1 in circle ci

I did this:

click SDk Manager:

enter image description here

Change in updates to Canary Channel, check and update it...

enter image description here

After go in build.gradle and change the compile version to 26.0.0-beta2:

enter image description here

After go in gradle/build.gradle and change dependencies classpath 'com.android.tools.build:gradle:3.0.0-alpha7':

enter image description here

After sync the project... It works to me! I hope I've helped... tks!

JavaScript file upload size validation

I use one main Javascript function that I had found at Mozilla Developer Network site https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications, along with another function with AJAX and changed according to my needs. It receives a document element id regarding the place in my html code where I want to write the file size.

<Javascript>

function updateSize(elementId) {
    var nBytes = 0,
    oFiles = document.getElementById(elementId).files,
    nFiles = oFiles.length;

    for (var nFileId = 0; nFileId < nFiles; nFileId++) {
        nBytes += oFiles[nFileId].size;
    }
    var sOutput = nBytes + " bytes";
    // optional code for multiples approximation
    for (var aMultiples = ["K", "M", "G", "T", "P", "E", "Z", "Y"], nMultiple = 0, nApprox = nBytes / 1024; nApprox > 1; nApprox /= 1024, nMultiple++) {
        sOutput = " (" + nApprox.toFixed(3) + aMultiples[nMultiple] + ")";
    }

    return sOutput;
}
</Javascript>

<HTML>
<input type="file" id="inputFileUpload" onchange="uploadFuncWithAJAX(this.value);" size="25">
</HTML>

<Javascript with XMLHttpRequest>
document.getElementById('spanFileSizeText').innerHTML=updateSize("inputFileUpload");
</XMLHttpRequest>

Cheers

Fit cell width to content

Setting

max-width:100%;
white-space:nowrap;

will solve your problem.

How To Raise Property Changed events on a Dependency Property?

I question the logic of raising a PropertyChanged event on the second property when it's the first property that's changing. If the second properties value changes then the PropertyChanged event could be raised there.

At any rate, the answer to your question is you should implement INotifyPropertyChange. This interface contains the PropertyChanged event. Implementing INotifyPropertyChanged lets other code know that the class has the PropertyChanged event, so that code can hook up a handler. After implementing INotifyPropertyChange, the code that goes in the if statement of your OnPropertyChanged is:

if (PropertyChanged != null)
    PropertyChanged(new PropertyChangedEventArgs("MySecondProperty"));

How to free memory from char array in C

char arr[3] = "bo";

The arr takes the memory into the stack segment. which will be automatically free, if arr goes out of scope.

gitbash command quick reference

Git command Quick Reference

git [command] -help

Git command Manual Pages

git help [command]
git [command] --help

Autocomplete

git <tab>

Cheat Sheets

What's the difference between event.stopPropagation and event.preventDefault?

event.preventDefault(); Stops the default action of an element from happening.

event.stopPropagation(); Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

For example, if there is a link with a click method attached inside of a DIV or FORM that also has a click method attached, it will prevent the DIV or FORM click method from firing.

Best way to access a control on another form in Windows Forms?

I would handle this in the parent form. You can notify the other form that it needs to modify itself through an event.

Linux: where are environment variables stored?

Type "set" and you will get a list of all the current variables. If you want something to persist put it in ~/.bashrc or ~/.bash_profile (if you're using bash)

Serializing class instance to JSON

An approach which I have been using in my Flask app to serialize Class instance to JSON response.

Github project for reference

from json import JSONEncoder
import json
from typing import List

class ResponseEncoder(JSONEncoder):
    def default(self, o):
        return o.__dict__

class ListResponse:
    def __init__(self, data: List):
        self.data = data
        self.count = len(data)

class A:
    def __init__(self, message: str):
        self.message = message

class B:
    def __init__(self, record: A):
        self.record = record

class C:
    def __init__(self, data: B):
        self.data = data

Now create an instance of A, B, C then encode.

data_a = A('Test Data')
data_b = B(data_a)
data_c = C(data_b)

response = ResponseEncoder().encode(data_c)
json_response = json.loads(response)

Output

{
    "data": {
        "record": {
            "message": "Test Data"
        }
    }
}

For list type response

records = ['One', 'Two', 'Three']
list_response = ListResponse(records)
response = ResponseEncoder().encode(list_response)
json_response = json.loads(response)

Output

{
    "data": [
        "One",
        "Two",
        "Three"
    ],
    "count": 3
}

Using Exit button to close a winform program

Used Following Code

System.Windows.Forms.Application.Exit( ) 

OSError: [Errno 8] Exec format error

If you think the space before and after "=" is mandatory, try it as separate item in the list.

Out = subprocess.Popen(['/usr/local/bin/script', 'hostname', '=', 'actual server name', '-p', 'LONGLIST'],shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)

SQL Server default character encoding

I think this is worthy of a separate answer: although internally unicode data is stored as UTF-16 in Sql Server this is the Little Endian flavour, so if you're calling the database from an external system, you probably need to specify UTF-16LE.

Finish all activities at a time

You can store a boolean flag to represent if all activities should be finished or not (more preferred in your shared preferences) then onStart() method of each activity should have something like:

SharedPreferences pref=PreferenceManager.getDefaultSharedPreferences(this);
boolean needToDestroyFlag=pref.getBoolean("destroyFlag", false);
if(needToDestroyFlag)
{
    finish();
}else
{
    //...
}

Obviously you can set this flag like below when ever you need to finish all activities (in the current activity) after doing so you can call finish() method on current activity that will result to terminate current activity and pop activities from stack up one by one, the onStart() method of each one executes and causes to terminate it:

SharedPreferences.Editor editor=PreferenceManager.getDefaultSharedPreferences(this).edit();
editor.putBoolean("destroyFlag", true);
editor.apply();

If you use the method that @letsnurture suggested, you'll be faced with the question asked by @gumuruh.

How to check if a file exists in Ansible?

You can use Ansible stat module to register the file, and when module to apply the condition.

- name: Register file
      stat:
        path: "/tmp/test_file"
      register: file_path

- name: Create file if it doesn't exists
      file: 
        path: "/tmp/test_file"
        state: touch
      when: file_path.stat.exists == False

How to pass arguments within docker-compose?

This can now be done as of docker-compose v2+ as part of the build object;

docker-compose.yml

version: '2'
services:
    my_image_name:
        build:
            context: . #current dir as build context
            args:
                var1: 1
                var2: c

See the docker compose docs.

In the above example "var1" and "var2" will be sent to the build environment.

Note: any env variables (specified by using the environment block) which have the same name as args variable(s) will override that variable.

How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?

this is my simple implementation for ASYNC requests with jQuery. I hope this help anyone.

var queueUrlsForRemove = [
    'http://dev-myurl.com/image/1', 
    'http://dev-myurl.com/image/2',
    'http://dev-myurl.com/image/3',
];

var queueImagesDelete = function(){

    deleteImage( queueUrlsForRemove.splice(0,1), function(){
        if (queueUrlsForRemove.length > 0) {
            queueImagesDelete();
        }
    });

}

var deleteImage = function(url, callback) {
    $.ajax({
        url: url,
        method: 'DELETE'
    }).done(function(response){
        typeof(callback) == 'function' ? callback(response) : null;
    });
}

queueImagesDelete();

Sorting an array of objects by property values

for string sorting in case some one needs it,

_x000D_
_x000D_
const dataArr = {_x000D_
_x000D_
  "hello": [{_x000D_
    "id": 114,_x000D_
    "keyword": "zzzzzz",_x000D_
    "region": "Sri Lanka",_x000D_
    "supportGroup": "administrators",_x000D_
    "category": "Category2"_x000D_
  }, {_x000D_
    "id": 115,_x000D_
    "keyword": "aaaaa",_x000D_
    "region": "Japan",_x000D_
    "supportGroup": "developers",_x000D_
    "category": "Category2"_x000D_
  }]_x000D_
_x000D_
};_x000D_
const sortArray = dataArr['hello'];_x000D_
_x000D_
console.log(sortArray.sort((a, b) => {_x000D_
  if (a.region < b.region)_x000D_
    return -1;_x000D_
  if (a.region > b.region)_x000D_
    return 1;_x000D_
  return 0;_x000D_
}));
_x000D_
_x000D_
_x000D_

How do you create a dropdownlist from an enum in ASP.NET MVC?

Here is a better encapsulated solution:

https://www.spicelogic.com/Blog/enum-dropdownlistfor-asp-net-mvc-5

Say here is your model:

enter image description here

Sample Usage:

enter image description here

Generated UI: enter image description here

And generated HTML

enter image description here

The Helper Extension Source Code snap shot:

enter image description here

You can download the sample project from the link I provided.

EDIT: Here's the code:

public static class EnumEditorHtmlHelper
{
    /// <summary>
    /// Creates the DropDown List (HTML Select Element) from LINQ 
    /// Expression where the expression returns an Enum type.
    /// </summary>
    /// <typeparam name="TModel">The type of the model.</typeparam>
    /// <typeparam name="TProperty">The type of the property.</typeparam>
    /// <param name="htmlHelper">The HTML helper.</param>
    /// <param name="expression">The expression.</param>
    /// <returns></returns>
    public static MvcHtmlString DropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,
        Expression<Func<TModel, TProperty>> expression) 
        where TModel : class
    {
        TProperty value = htmlHelper.ViewData.Model == null 
            ? default(TProperty) 
            : expression.Compile()(htmlHelper.ViewData.Model);
        string selected = value == null ? String.Empty : value.ToString();
        return htmlHelper.DropDownListFor(expression, createSelectList(expression.ReturnType, selected));
    }

    /// <summary>
    /// Creates the select list.
    /// </summary>
    /// <param name="enumType">Type of the enum.</param>
    /// <param name="selectedItem">The selected item.</param>
    /// <returns></returns>
    private static IEnumerable<SelectListItem> createSelectList(Type enumType, string selectedItem)
    {
        return (from object item in Enum.GetValues(enumType)
                let fi = enumType.GetField(item.ToString())
                let attribute = fi.GetCustomAttributes(typeof (DescriptionAttribute), true).FirstOrDefault()
                let title = attribute == null ? item.ToString() : ((DescriptionAttribute) attribute).Description
                select new SelectListItem
                  {
                      Value = item.ToString(), 
                      Text = title, 
                      Selected = selectedItem == item.ToString()
                  }).ToList();
    }
}

Check difference in seconds between two times

I use this to avoid negative interval.

var seconds = (date1< date2)? (date2- date1).TotalSeconds: (date1 - date2).TotalSeconds;

Postgres "psql not recognized as an internal or external command"

Make sure that the path actually leads to the executables. I'm using version 11 and it did not work until this was set as the path:

C:\Program Files\PostgreSQL\11\bin\bin

Maybe this is how version 11 is structured or I somehow botched the installation but I haven't had a problem since.

Remove privileges from MySQL database

The USAGE-privilege in mysql simply means that there are no privileges for the user 'phpadmin'@'localhost' defined on global level *.*. Additionally the same user has ALL-privilege on database phpmyadmin phpadmin.*.

So if you want to remove all the privileges and start totally from scratch do the following:

  • Revoke all privileges on database level:

    REVOKE ALL PRIVILEGES ON phpmyadmin.* FROM 'phpmyadmin'@'localhost';

  • Drop the user 'phpmyadmin'@'localhost'

    DROP USER 'phpmyadmin'@'localhost';

Above procedure will entirely remove the user from your instance, this means you can recreate him from scratch.

To give you a bit background on what described above: as soon as you create a user the mysql.user table will be populated. If you look on a record in it, you will see the user and all privileges set to 'N'. If you do a show grants for 'phpmyadmin'@'localhost'; you will see, the allready familliar, output above. Simply translated to "no privileges on global level for the user". Now your grant ALL to this user on database level, this will be stored in the table mysql.db. If you do a SELECT * FROM mysql.db WHERE db = 'nameofdb'; you will see a 'Y' on every priv.

Above described shows the scenario you have on your db at the present. So having a user that only has USAGE privilege means, that this user can connect, but besides of SHOW GLOBAL VARIABLES; SHOW GLOBAL STATUS; he has no other privileges.

Styling mat-select in Angular Material

Put your class name on the mat-form-field element. This works for all inputs.

What should be the values of GOPATH and GOROOT?

There is also a case where when we use go it compiles all the go files.

So lets say we had one file main.go and later we changed the current file to main_old.go and then added our new main.go file. Then when we build our app all the go files will get compiled. So the error that's happening might be due to compilation error in some other go files.

Google MAP API v3: Center & Zoom on displayed markers

In case you prefer more functional style:

// map - instance of google Map v3
// markers - array of Markers
var bounds = markers.reduce(function(bounds, marker) {
    return bounds.extend(marker.getPosition());
}, new google.maps.LatLngBounds());

map.setCenter(bounds.getCenter());
map.fitBounds(bounds);

No resource found that matches the given name: attr 'android:keyboardNavigationCluster'. when updating to Support Library 26.0.0

I had the same issue with my Ionic 2 project, all I did to resolved the issues was

  • Open "ionic_project_folder/platforms/android/project.properties"
  • Change target=android-25 to target=android-26
  • Run ionic build --release android

Hope this helps someone!

XCOPY switch to create specified directory if it doesn't exist?

I hate the PostBuild step, it allows for too much stuff to happen outside of the build tool's purview. I believe that its better to let MSBuild manage the copy process, and do the updating. You can edit the .csproj file like this:

  <Target Name="AfterBuild" Inputs="$(TargetPath)\**">
    <Copy SourceFiles="$(TargetPath)\**" DestinationFiles="$(SolutionDir)Prism4Demo.Shell\$(OutDir)Modules\**" OverwriteReadOnlyFiles="true"></Copy>
  </Target>

How do I fix an "Invalid license data. Reinstall is required." error in Visual C# 2010 Express?

I met the same problem yesterday.And I fixed already. Please follow the steps:

  • Run setup.exe again; Change or Remove Microsoft Visual Studio 2010; Upgrade license Key (Enter new license key); Complete.

GOOD LUCK !

catch specific HTTP error in python

Python 3

from urllib.error import HTTPError

Python 2

from urllib2 import HTTPError

Just catch HTTPError, handle it, and if it's not Error 404, simply use raise to re-raise the exception.

See the Python tutorial.

e.g. complete example for Pyhton 2

import urllib2
from urllib2 import HTTPError
try:
   urllib2.urlopen("some url")
except HTTPError as err:
   if err.code == 404:
       <whatever>
   else:
       raise

PHP post_max_size overrides upload_max_filesize

Your server configuration settings allows users to upload files upto 16MB (because you have set upload_max_filesize = 16Mb) but the post_max_size accepts post data upto 8MB only. This is why it throws an error.

Quoted from the official PHP site:

  1. To upload large files, post_max_size value must be larger than upload_max_filesize.

  2. memory_limit should be larger than post_max_size

You should always set your post_max_size value greater than the upload_max_filesize value.

Extending an Object in Javascript

PLEASE ADD REASON FOR DOWNVOTE

  • No need to use any external library to extend

  • In JavaScript, everything is an object (except for the three primitive datatypes, and even they are automatically wrapped with objects when needed). Furthermore, all objects are mutable.

Class Person in JavaScript

function Person(name, age) {
    this.name = name;
    this.age = age;
}
Person.prototype = {
    getName: function() {
        return this.name;
    },
    getAge: function() {
        return this.age;
    }
}

/* Instantiate the class. */
var alice = new Person('Alice', 93);
var bill = new Person('Bill', 30);

Modify a specific instance/object.

alice.displayGreeting = function() 
{
    alert(this.getGreeting());
}

Modify the class

Person.prototype.getGreeting = function() 
{
    return 'Hi ' + this.getName() + '!';
};

Or simply say : extend JSON and OBJECT both are same

var k = {
    name : 'jack',
    age : 30
}

k.gender = 'male'; /*object or json k got extended with new property gender*/

thanks to ross harmes , dustin diaz

How to update ruby on linux (ubuntu)?

On Ubuntu 12.04 (Precise Pangolin), I got this working with the following command:

sudo apt-get install ruby1.9.1
sudo apt-get install ruby1.9.3

How can I detect window size with jQuery?

Do you want to detect when the window has been resized?

You can use JQuery's resize to attach a handler.

Swift: Testing optionals for nil

var xyz : NSDictionary?

// case 1:
xyz = ["1":"one"]
// case 2: (empty dictionary)
xyz = NSDictionary() 
// case 3: do nothing

if xyz { NSLog("xyz is not nil.") }
else   { NSLog("xyz is nil.")     }

This test worked as expected in all cases. BTW, you do not need the brackets ().

Create multiple threads and wait all of them to complete

It depends which version of the .NET Framework you are using. .NET 4.0 made thread management a whole lot easier using Tasks:

class Program
{
    static void Main(string[] args)
    {
        Task task1 = Task.Factory.StartNew(() => doStuff());
        Task task2 = Task.Factory.StartNew(() => doStuff());
        Task task3 = Task.Factory.StartNew(() => doStuff());

        Task.WaitAll(task1, task2, task3);
                Console.WriteLine("All threads complete");
    }

    static void doStuff()
    {
        //do stuff here
    }
}

In previous versions of .NET you could use the BackgroundWorker object, use ThreadPool.QueueUserWorkItem(), or create your threads manually and use Thread.Join() to wait for them to complete:

static void Main(string[] args)
{
    Thread t1 = new Thread(doStuff);
    t1.Start();

    Thread t2 = new Thread(doStuff);
    t2.Start();

    Thread t3 = new Thread(doStuff);
    t3.Start();

    t1.Join();
    t2.Join();
    t3.Join();

    Console.WriteLine("All threads complete");
}

How to output numbers with leading zeros in JavaScript?

You could extend the Number object:

Number.prototype.pad = function(size) {
    var s = String(this);
    while (s.length < (size || 2)) {s = "0" + s;}
    return s;
}

Examples:

(9).pad();  //returns "09"

(7).pad(3);  //returns "007"

How do I make a batch file terminate upon encountering an error?

Check the errorlevel in an if statement, and then exit /b (exit the batch file only, not the entire cmd.exe process) for values other than 0.

same-executable-over-and-over.exe /with different "parameters"
if %errorlevel% neq 0 exit /b %errorlevel%

If you want the value of the errorlevel to propagate outside of your batch file

if %errorlevel% neq 0 exit /b %errorlevel%

but if this is inside a for it gets a bit tricky. You'll need something more like:

setlocal enabledelayedexpansion
for %%f in (C:\Windows\*) do (
    same-executable-over-and-over.exe /with different "parameters"
    if !errorlevel! neq 0 exit /b !errorlevel!
)

Edit: You have to check the error after each command. There's no global "on error goto" type of construct in cmd.exe/command.com batch. I've also updated my code per CodeMonkey, although I've never encountered a negative errorlevel in any of my batch-hacking on XP or Vista.

How can I get key's value from dictionary in Swift?

From Apple Docs

You can use subscript syntax to retrieve a value from the dictionary for a particular key. Because it is possible to request a key for which no value exists, a dictionary’s subscript returns an optional value of the dictionary’s value type. If the dictionary contains a value for the requested key, the subscript returns an optional value containing the existing value for that key. Otherwise, the subscript returns nil:

https://developer.apple.com/documentation/swift/dictionary

if let airportName = airports["DUB"] {
    print("The name of the airport is \(airportName).")
} else {
    print("That airport is not in the airports dictionary.")
}
// prints "The name of the airport is Dublin Airport."

Function to close the window in Tkinter

def exit(self):
    self.frame.destroy()
exit_btn=Button(self.frame,text='Exit',command=self.exit,activebackground='grey',activeforeground='#AB78F1',bg='#58F0AB',highlightcolor='red',padx='10px',pady='3px')
exit_btn.place(relx=0.45,rely=0.35)

This worked for me to destroy my Tkinter frame on clicking the exit button.

How to view the SQL queries issued by JPA?

JPA provider can set it for you - incase if someone doesn't want to control through JPA properties

public static JpaProperties properties() {
        final JpaProperties jpaProperties = new JpaProperties();
        jpaProperties.setShowSql(true);

pass parameter by link_to ruby on rails

You probably don't want to pass the car object as a parameter, try just passing car.id. What do you get when you inspect(params) after clicking "Add to cart"?

What is "loose coupling?" Please provide examples

Tightly coupled code relies on a concrete implementation. If I need a list of strings in my code and I declare it like this (in Java)

ArrayList<String> myList = new ArrayList<String>();

then I'm dependent on the ArrayList implementation.

If I want to change that to loosely coupled code, I make my reference an interface (or other abstract) type.

List<String> myList = new ArrayList<String>();

This prevents me from calling any method on myList that's specific to the ArrayList implementation. I'm limited to only those methods defined in the List interface. If I decide later that I really need a LinkedList, I only need to change my code in one place, where I created the new List, and not in 100 places where I made calls to ArrayList methods.

Of course, you can instantiate an ArrayList using the first declaration and restrain yourself from not using any methods that aren't part of the List interface, but using the second declaration makes the compiler keep you honest.

How to insert 1000 rows at a time

You can of course use a loop, or you can insert them in a single statement, e.g.

Insert into db
(names,email,password) 
Values
('abc','def','mypassword')
,('ghi','jkl','mypassword2')
,('mno','pqr','mypassword3')

It really depends where you're getting your data from.

If you use a loop, wrapping it in a transaction will make it a bit faster.

UPDATE

What if i want to insert unique names?

If you want to insert unique names, then you need to generate data with unique names. One way to do this is to use Visual Studio to generate test data.

jQuery move to anchor location on page load

Description

You can do this using jQuery's .scrollTop() and .offset() method

Check out my sample and this jsFiddle Demonstration

Sample

$(function() {
    $(document).scrollTop( $("#header").offset().top );  
});

More Information

Is Java "pass-by-reference" or "pass-by-value"?

I feel like arguing about "pass-by-reference vs pass-by-value" is not super-helpful.

If you say, "Java is pass-by-whatever (reference/value)", in either case, you're not provide a complete answer. Here's some additional information that will hopefully aid in understanding what's happening in memory.

Crash course on stack/heap before we get to the Java implementation: Values go on and off the stack in a nice orderly fashion, like a stack of plates at a cafeteria. Memory in the heap (also known as dynamic memory) is haphazard and disorganized. The JVM just finds space wherever it can, and frees it up as the variables that use it are no longer needed.

Okay. First off, local primitives go on the stack. So this code:

int x = 3;
float y = 101.1f;
boolean amIAwesome = true;

results in this:

primitives on the stack

When you declare and instantiate an object. The actual object goes on the heap. What goes on the stack? The address of the object on the heap. C++ programmers would call this a pointer, but some Java developers are against the word "pointer". Whatever. Just know that the address of the object goes on the stack.

Like so:

int problems = 99;
String name = "Jay-Z";

a b*7ch aint one!

An array is an object, so it goes on the heap as well. And what about the objects in the array? They get their own heap space, and the address of each object goes inside the array.

JButton[] marxBros = new JButton[3];
marxBros[0] = new JButton("Groucho");
marxBros[1] = new JButton("Zeppo");
marxBros[2] = new JButton("Harpo");

marx brothers

So, what gets passed in when you call a method? If you pass in an object, what you're actually passing in is the address of the object. Some might say the "value" of the address, and some say it's just a reference to the object. This is the genesis of the holy war between "reference" and "value" proponents. What you call it isn't as important as that you understand that what's getting passed in is the address to the object.

private static void shout(String name){
    System.out.println("There goes " + name + "!");
}

public static void main(String[] args){
    String hisName = "John J. Jingleheimerschmitz";
    String myName = hisName;
    shout(myName);
}

One String gets created and space for it is allocated in the heap, and the address to the string is stored on the stack and given the identifier hisName, since the address of the second String is the same as the first, no new String is created and no new heap space is allocated, but a new identifier is created on the stack. Then we call shout(): a new stack frame is created and a new identifier, name is created and assigned the address of the already-existing String.

la da di da da da da

So, value, reference? You say "potato".

session not created: This version of ChromeDriver only supports Chrome version 74 error with ChromeDriver Chrome using Selenium

This error message...

Selenium message:session not created: This version of ChromeDriver only supports Chrome version 74
  (Driver info: chromedriver=74.0.3729.6 (255758eccf3d244491b8a1317aa76e1ce10d57e9-refs/branch-heads/3729@{#29}),platform=Mac OS X 10.14.3 x86_64)

...implies that the ChromeDriver expects the Chrome Browser version to be 74.


Quick installation of the latest ChromeDriver

To install the latest version of ChromeDriver you can use:

  • Mac users with Homebrew: brew tap homebrew/cask && brew cask install chromedriver
  • Debian based Linux distros: sudo apt-get install chromium-chromedriver
  • Windows users with Chocolatey installed: choco install chromedriver

Analysis

Your main issue is the incompatibility between the version of the binaries you are using as follows:

Supports Chrome v74

  • You are using the currently released chrome=73.0

So there is a clear mismatch between the ChromeDriver v74.0.3729.6 and the Chrome Browser v73.0


Solution

  • Downgrade ChromeDriver to ChromeDriver v73.0.3683.68 level.
  • Keep Chrome version at Chrome v73 level. (as per ChromeDriver v73.0.3683.68 release notes)
  • Clean your Project Workspace through your IDE and Rebuild your project with required dependencies only.
  • If your base Web Client version is too old, then uninstall it and install a recent GA and released version of Web Client.
  • Execute your @Test.
  • Always invoke driver.quit() within tearDown(){} method to close & destroy the WebDriver and Web Client instances gracefully.

Reference

You can find a relevant detailed discussion in:

Checking version of angular-cli that's installed?

ng --version

ng--version output

Please take a look at the above image.

How to get next/previous record in MySQL?

All the above solutions require two database calls. The below sql code combine two sql statements into one.

select * from foo 
where ( 
        id = IFNULL((select min(id) from foo where id > 4),0) 
        or  id = IFNULL((select max(id) from foo where id < 4),0)
      )    

R : how to simply repeat a command?

It's not clear whether you're asking this because you are new to programming, but if that's the case then you should probably read this article on loops and indeed read some basic materials on programming.

If you already know about control structures and you want the R-specific implementation details then there are dozens of tutorials around, such as this one. The other answer uses replicate and colMeans, which is idiomatic when writing in R and probably blazing fast as well, which is important if you want 10,000 iterations.

However, one more general and (for beginners) straightforward way to approach problems of this sort would be to use a for loop.

> for (ii in 1:5) { + print(ii) + } [1] 1 [1] 2 [1] 3 [1] 4 [1] 5 > 

So in your case, if you just wanted to print the mean of your Tandem object 5 times:

for (ii in 1:5) {     Tandem <- sample(OUT, size = 815, replace = TRUE, prob = NULL)     TandemMean <- mean(Tandem)     print(TandemMean) } 

As mentioned above, replicate is a more natural way to deal with this specific problem using R. Either way, if you want to store the results - which is surely the case - you'll need to start thinking about data structures like vectors and lists. Once you store something you'll need to be able to access it to use it in future, so a little knowledge is vital.

set.seed(1234) OUT <- runif(100000, 1, 2) tandem <- list() for (ii in 1:10000) {     tandem[[ii]] <- mean(sample(OUT, size = 815, replace = TRUE, prob = NULL)) }  tandem[1] tandem[100] tandem[20:25] 

...creates this output:

> set.seed(1234) > OUT <- runif(100000, 1, 2) > tandem <- list() > for (ii in 1:10000) { +     tandem[[ii]] <- mean(sample(OUT, size = 815, replace = TRUE, prob = NULL)) + } >  > tandem[1] [[1]] [1] 1.511923  > tandem[100] [[1]] [1] 1.496777  > tandem[20:25] [[1]] [1] 1.500669  [[2]] [1] 1.487552  [[3]] [1] 1.503409  [[4]] [1] 1.501362  [[5]] [1] 1.499728  [[6]] [1] 1.492798  >  

Swift Beta performance: sorting arrays

func partition(inout list : [Int], low: Int, high : Int) -> Int {
    let pivot = list[high]
    var j = low
    var i = j - 1
    while j < high {
        if list[j] <= pivot{
            i += 1
            (list[i], list[j]) = (list[j], list[i])
        }
        j += 1
    }
    (list[i+1], list[high]) = (list[high], list[i+1])
    return i+1
}

func quikcSort(inout list : [Int] , low : Int , high : Int) {

    if low < high {
        let pIndex = partition(&list, low: low, high: high)
        quikcSort(&list, low: low, high: pIndex-1)
        quikcSort(&list, low: pIndex + 1, high: high)
    }
}

var list = [7,3,15,10,0,8,2,4]
quikcSort(&list, low: 0, high: list.count-1)

var list2 = [ 10, 0, 3, 9, 2, 14, 26, 27, 1, 5, 8, -1, 8 ]
quikcSort(&list2, low: 0, high: list2.count-1)

var list3 = [1,3,9,8,2,7,5]
quikcSort(&list3, low: 0, high: list3.count-1) 

This is my Blog about Quick Sort- Github sample Quick-Sort

You can take a look at Lomuto's partitioning algorithm in Partitioning the list. Written in Swift.

What exactly does the Access-Control-Allow-Credentials header do?

By default, CORS does not include cookies on cross-origin requests. This is different from other cross-origin techniques such as JSON-P. JSON-P always includes cookies with the request, and this behavior can lead to a class of vulnerabilities called cross-site request forgery, or CSRF.

In order to reduce the chance of CSRF vulnerabilities in CORS, CORS requires both the server and the client to acknowledge that it is ok to include cookies on requests. Doing this makes cookies an active decision, rather than something that happens passively without any control.

The client code must set the withCredentials property on the XMLHttpRequest to true in order to give permission.

However, this header alone is not enough. The server must respond with the Access-Control-Allow-Credentials header. Responding with this header to true means that the server allows cookies (or other user credentials) to be included on cross-origin requests.

You also need to make sure your browser isn't blocking third-party cookies if you want cross-origin credentialed requests to work.

Note that regardless of whether you are making same-origin or cross-origin requests, you need to protect your site from CSRF (especially if your request includes cookies).

Access maven properties defined in the pom

This can be done with standard java properties in combination with the maven-resource-plugin with enabled filtering on properties.

For more info see http://maven.apache.org/plugins/maven-resources-plugin/examples/filter.html

This will work for standard maven project as for plugin projects

Most simple code to populate JTable from ResultSet

The JTable constructor accepts two arguments 2dimension Object Array for the data, and String Array for the column names.

eg:

import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;

public class Test6 extends JFrame {

    public Test6(){     
        this.setSize(300,300);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Mpanel m = new Mpanel();
        this.add(m,BorderLayout.CENTER);        
    }


    class Mpanel extends JPanel {       

        JTable mTable;
        private Object[][] cells = {{"Vivek",10.00},{"Vishal",20.00}};
        private String[] columnNames = { "Planet", "Radius" };
        JScrollPane mScroll;

        public Mpanel(){
            this.setSize(150,150);
            this.setComponent();
        }

        public void setComponent(){
            mTable = new JTable(cells,columnNames);
            mTable.setAutoCreateRowSorter(true);
            mScroll = new JScrollPane(mTable);

            this.add(mScroll);
        }
    }

    public static void main(String[] args){     
        new Test6().setVisible(true);
    }
}

To enable extensions, verify that they are enabled in those .ini files - Vagrant/Ubuntu/Magento 2.0.2

ubuntu users try this

apt-get install php7.2 libapache2-mod-php7.2 php7.2-common php7.2-gd php7.2-mysql php7.2-curl php7.2-intl php7.2-xsl php7.2-mbstring php7.2-zip php7.2-bcmath php7.2-soap php-xdebug php-imagick

this is work for php 7.2 but you can change this 7.2 to 5.2 and run this command it is work.

Recommended way to embed PDF in HTML?

If you don't want to host PDF.JS on your own, you could try DocDroid. It is similar to the Google Drive PDF viewer but allows custom branding.

Hibernate vs JPA vs JDO - pros and cons of each?

Which would you suggest for a new project?

I would suggest neither! Use Spring DAO's JdbcTemplate together with StoredProcedure, RowMapper and RowCallbackHandler instead.

My own personal experience with Hibernate is that the time saved up-front is more than offset by the endless days you will spend down the line trying to understand and debug issues like unexpected cascading update behaviour.

If you are using a relational DB then the closer your code is to it, the more control you have. Spring's DAO layer allows fine control of the mapping layer, whilst removing the need for boilerplate code. Also, it integrates into Spring's transaction layer which means you can very easily add (via AOP) complicated transactional behaviour without this intruding into your code (of course, you get this with Hibernate too).

How to use BeanUtils.copyProperties?

As you can see in the below source code, BeanUtils.copyProperties internally uses reflection and there's additional internal cache lookup steps as well which is going to add cost wrt performance

 private static void copyProperties(Object source, Object target, @Nullable Class<?> editable,
                @Nullable String... ignoreProperties) throws BeansException {

            Assert.notNull(source, "Source must not be null");
            Assert.notNull(target, "Target must not be null");

            Class<?> actualEditable = target.getClass();
            if (editable != null) {
                if (!editable.isInstance(target)) {
                    throw new IllegalArgumentException("Target class [" + target.getClass().getName() +
                            "] not assignable to Editable class [" + editable.getName() + "]");
                }
                actualEditable = editable;
            }
            **PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);**
            List<String> ignoreList = (ignoreProperties != null ? Arrays.asList(ignoreProperties) : null);

            for (PropertyDescriptor targetPd : targetPds) {
                Method writeMethod = targetPd.getWriteMethod();
                if (writeMethod != null && (ignoreList == null || !ignoreList.contains(targetPd.getName()))) {
                    PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
                    if (sourcePd != null) {
                        Method readMethod = sourcePd.getReadMethod();
                        if (readMethod != null &&
                                ClassUtils.isAssignable(writeMethod.getParameterTypes()[0], readMethod.getReturnType())) {
                            try {
                                if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                                    readMethod.setAccessible(true);
                                }
                                Object value = readMethod.invoke(source);
                                if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                                    writeMethod.setAccessible(true);
                                }
                                writeMethod.invoke(target, value);
                            }
                            catch (Throwable ex) {
                                throw new FatalBeanException(
                                        "Could not copy property '" + targetPd.getName() + "' from source to target", ex);
                            }
                        }
                    }
                }
            }
        }

So it's better to use plain setters given the cost reflection

How to solve the memory error in Python

Assuming your example text is representative of all the text, one line would consume about 75 bytes on my machine:

In [3]: sys.getsizeof('usedfor zipper fasten_coat')
Out[3]: 75

Doing some rough math:

75 bytes * 8,000,000 lines / 1024 / 1024 = ~572 MB

So roughly 572 meg to store the strings alone for one of these files. Once you start adding in additional, similarly structured and sized files, you'll quickly approach your virtual address space limits, as mentioned in @ShadowRanger's answer.

If upgrading your python isn't feasible for you, or if it only kicks the can down the road (you have finite physical memory after all), you really have two options: write your results to temporary files in-between loading in and reading the input files, or write your results to a database. Since you need to further post-process the strings after aggregating them, writing to a database would be the superior approach.

How to move Jenkins from one PC to another

This worked for me to move from Ubuntu 12.04 (Jenkins ver. 1.628) to Ubuntu 16.04 (Jenkins ver. 1.651.2). I first installed Jenkins from the repositories.

  1. Stop both Jenkins servers
  2. Copy JENKINS_HOME (e.g. /var/lib/jenkins) from the old server to the new one. From a console in the new server:

    rsync -av username@old-server-IP:/var/lib/jenkins/ /var/lib/jenkins/

  3. Start your new Jenkins server

You might not need this, but I had to

  • Manage Jenkins and Reload Configuration from Disk.
  • Disconnect and connect all the slaves again.
  • Check that in the Configure System > Jenkins Location, the Jenkins URL is correctly assigned to the new Jenkins server.

Sun JSTL taglib declaration fails with "Can not find the tag library descriptor"

If you use Tomcat server I suggest you to put JSTL .jar file to the Tomcat lib folder. By doing this you will have an access to JSTL in all your web projects automatically (with taglib declaration in .jsp files of course).

How do I wait until Task is finished in C#?

I'm an async novice, so I can't tell you definitively what is happening here. I suspect that there's a mismatch in the method execution expectations, even though you are using tasks internally in the methods. I think you'd get the results you are expecting if you changed Print to return a Task<string>:

private static string Send(int id)
{
    Task<HttpResponseMessage> responseTask = client.GetAsync("aaaaa");
    Task<string> result;
    responseTask.ContinueWith(x => result = Print(x));
    result.Wait();
    responseTask.Wait(); // There's likely a better way to wait for both tasks without doing it in this awkward, consecutive way.
    return result.Result;
}

private static Task<string> Print(Task<HttpResponseMessage> httpTask)
{
    Task<string> task = httpTask.Result.Content.ReadAsStringAsync();
    string result = string.Empty;
    task.ContinueWith(t =>
    {
        Console.WriteLine("Result: " + t.Result);
        result = t.Result;
    });
    return task;
}

percentage of two int?

float percent = (n / (v * 1.0f)) *100

NSArray + remove item from array

As others suggested, NSMutableArray has methods to do so but sometimes you are forced to use NSArray, I'd use:

NSArray* newArray = [oldArray subarrayWithRange:NSMakeRange(1, [oldArray count] - 1)];

This way, the oldArray stays as it was but a newArray will be created with the first item removed.

Is there a way to make numbers in an ordered list bold?

A new ::marker pseudo-element selector has been added to CSS Pseudo-Elements Level 4, which makes styling list item numbers in bold as simple as

ol > li::marker {
  font-weight: bold;
}

It is currently supported by Firefox 68+, Chrome/Edge 86+, and Safari 11.1+.

What causes the error "_pickle.UnpicklingError: invalid load key, ' '."?

I had a similar error but with different context when I uploaded a *.p file to Google Drive. I tried to use it later in a Google Colab session, and got this error:

    1 with open("/tmp/train.p", mode='rb') as training_data:
----> 2     train = pickle.load(training_data)
UnpicklingError: invalid load key, '<'.

I solved it by compressing the file, upload it and then unzip on the session. It looks like the pickle file is not saved correctly when you upload/download it so it gets corrupted.

Checking if a textbox is empty in Javascript

your validation should be occur before your event suppose you are going to submit your form.

anyway if you want this on onchange, so here is code.

function valid(id)
{
    var textVal=document.getElementById(id).value;
    if (!textVal.match(/\S/)) 
    {
        alert("Field is blank");
        return false;
    } 
    else 
    {
        return true;
    }
 }

Split string based on regex

You could use a lookahead:

re.split(r'[ ](?=[A-Z]+\b)', input)

This will split at every space that is followed by a string of upper-case letters which end in a word-boundary.

Note that the square brackets are only for readability and could as well be omitted.

If it is enough that the first letter of a word is upper case (so if you would want to split in front of Hello as well) it gets even easier:

re.split(r'[ ](?=[A-Z])', input)

Now this splits at every space followed by any upper-case letter.

PowerShell says "execution of scripts is disabled on this system."

Set-ExecutionPolicy RemoteSigned

Executing this command in administrator mode in powershell will solve the problem.

Create a table without a header in Markdown

The following works well for me in GitHub. The first row is no longer bolded as it is not a header:

<table align="center">
    <tr>
        <td align="center"><img src="docs/img1.png?raw=true" alt="some text"></td>
        <td align="center">Some other text</td>
        <td align="center">More text</td>
    </tr>
    <tr>
        <td align="center"><img src="docs/img2.png?raw=true" alt="some text"></td>
        <td align="center">Some other text 2</td>
        <td align="center">More text 2</td>
    </tr>
</table>

Check a sample HTML table without a header here.

How to add new line into txt file

No new line:

File.AppendAllText("file.txt", DateTime.Now.ToString());

and then to get a new line after OK:

File.AppendAllText("file.txt", string.Format("{0}{1}", "OK", Environment.NewLine));

Java Error: illegal start of expression

public static int [] locations={1,2,3};

public static test dot=new test();

Declare the above variables above the main method and the code compiles fine.

public static void main(String[] args){

Change old commit message on Git

It says:

When you save and exit the editor, it will rewind you back to that last commit in that list and drop you on the command line with the following message:

$ git rebase -i HEAD~3
Stopped at 7482e0d... updated the gemspec to hopefully work better
You can amend the commit now, with

It does not mean:

type again git rebase -i HEAD~3

Try to not typing git rebase -i HEAD~3 when exiting the editor, and it should work fine.
(otherwise, in your particular situation, a git rebase -i --abort might be needed to reset everything and allow you to try again)


As Dave Vogt mentions in the comments, git rebase --continue is for going to the next task in the rebasing process, after you've amended the first commit.

Also, Gregg Lind mentions in his answer the reword command of git rebase:

By replacing the command "pick" with the command "edit", you can tell git rebase to stop after applying that commit, so that you can edit the files and/or the commit message, amend the commit, and continue rebasing.

If you just want to edit the commit message for a commit, replace the command "pick" with the command "reword", since Git1.6.6 (January 2010).

It does the same thing ‘edit’ does during an interactive rebase, except it only lets you edit the commit message without returning control to the shell. This is extremely useful.
Currently if you want to clean up your commit messages you have to:

$ git rebase -i next

Then set all the commits to ‘edit’. Then on each one:

# Change the message in your editor.
$ git commit --amend
$ git rebase --continue

Using ‘reword’ instead of ‘edit’ lets you skip the git-commit and git-rebase calls.

Android Studio : How to uninstall APK (or execute adb command) automatically before Run or Debug?

Use this cmd to display the packages in your device (for windows users)

adb shell pm list packages

then you can delete completely the package with the following cmd

adb uninstall com.example.myapp

How to remove focus without setting focus to another control?

  1. You can use View.clearFocus().

  2. Use View.requestFocus() called from onResume().

Android Studio Gradle DSL method not found: 'android()' -- Error(17,0)

Actually i tried many combinations nothing worked

but when i modified my application gradle file with following

 buildTypes {
        release {
            minifyEnabled false
        }
    }

By removing the Line

proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'

it worked Normally :)) cheers

Connect multiple devices to one device via Bluetooth

I don't think it's possible with bluetooth, but you could try looking into WiFi Peer-to-Peer,
which allows one-to-many connections.

bool to int conversion

You tagged your question [C] and [C++] at the same time. The results will be consistent between the languages, but the structure of the the answer is different for each of these languages.

In C language your examples has no relation to bool whatsoever (that applies to C99 as well). In C language relational operators do not produce bool results. Both 4 > 5 and 4 < 5 are expressions that produce results of type int with values 0 or 1. So, there's no "bool to int conversion" of any kind taking place in your examples in C.

In C++ relational operators do indeed produce bool results. bool values are convertible to int type, with true converting to 1 and false converting to 0. This is guaranteed by the language.

P.S. C language also has a dedicated boolean type _Bool (macro-aliased as bool), and its integral conversion rules are essentially the same as in C++. But nevertheless this is not relevant to your specific examples in C. Once again, relational operators in C always produce int (not bool) results regardless of the version of the language specification.

How to clean project cache in Intellij idea like Eclipse's clean?

Depending on the version you are running. It is basically the same just go to
File -> Invalidate caches, then restart Intellij
or
File -> Invalidate caches / Restart

The main difference is that in older versions you had to manually restart as cache files are not removed until you restart. The newer versions will ask if you also want to restart.

Older versions Newer Versions

As seen here on this official Jetbrains help page


You can also try delete caches manually in the system folder for your installed version. The location of this folder depends on your OS and version installed.

Windows Vista, 7, 8, 10
<SYSTEM DRIVE>\Users\<USER ACCOUNT NAME>\.<PRODUCT><VERSION>

Linux/Unix
~/.<PRODUCT><VERSION>

Mac OS
~/Library/Caches/<PRODUCT><VERSION>

Read this for more details on cache locations.

Python: How to get stdout after running os.system?

commands also works.

import commands
batcmd = "dir"
result = commands.getoutput(batcmd)
print result

It works on linux, python 2.7.

How to create a custom scrollbar on a div (Facebook style)

I solved this problem by adding another div as a sibling to the scrolling content div. It's height is set to the radius of the curved borders. There will be design issues if you have content that you want nudged to the very bottom, or text you want to flow into this new div, etc,. but for my UI this thin div is no problem.

The real trick is to have the following structure:

<div class="window">
 <div class="title">Some title text</div>
 <div class="content">Main content area</div>
 <div class="footer"></div>
</div>

Important CSS highlights:

  • Your CSS would define the content region with a height and overflow to allow the scrollbar(s) to appear.
  • The window class gets the same diameter corners as the title and footer
  • The drop shadow, if desired, is only given to the window class
  • The height of the footer div is the same as the radius of the bottom corners

Here's what that looks like:

Bottom right corner

Unsafe JavaScript attempt to access frame with URL

Crossframe-Scripting is not possible when the two frames have different domains -> Security.

See this: http://javascript.about.com/od/reference/a/frame3.htm

Now to answer your question: there is no solution or work around, you simply should check your website-design why there must be two frames from different domains that changes the url of the other one.

SQL Delete Records within a specific Range

if you use Sql Server

delete from Table where id between 79 and 296

After your edit : you now clarified that you want :

ID (>79 AND < 296)

So use this :

delete from Table where id > 79 and id < 296

How to add an element to Array and shift indexes?

Unless I'm missing something, the question is not about increasing the array size. In the example the array size remains the same. (Like a bit shift.) In this case, there is really no reason to create a new array or to copy it. This should do the trick:

static void addPos(int[] array, int pos, int value) {
    // initially set to value parameter so the first iteration, the value is replaced by it
    int prevValue = value;

    // Shift all elements to the right, starting at pos
    for (int i = pos; i < array.length; i++) {
        int tmp = prevValue;
        prevValue = array[i];
        array[i] = tmp;
    }
}
int[] a = {1, 2, 3, 4, 5, 6};
addPos(a, 4, 87);
// output: {1, 2, 3, 4, 87, 5}

can't access mysql from command line mac

Just do the following in your terminal:

echo $PATH

If your given path is not in that string, you have to add it like this: export PATH=$PATH:/usr/local/ or export PATH=$PATH:/usr/local/mysql/bin

Bad Request, Your browser sent a request that this server could not understand

I just deleted my stored cookies, site data, and cache from my browser... It worked. I'm using firefox...

Validating parameters to a Bash script

The sh solution by Brian Campbell, while noble and well executed, has a few problems, so I thought I'd provide my own bash solution.

The problems with the sh one:

  • The tilde in ~/foo doesn't expand to your homedirectory inside heredocs. And neither when it's read by the read statement or quoted in the rm statement. Which means you'll get No such file or directory errors.
  • Forking off grep and such for basic operations is daft. Especially when you're using a crappy shell to avoid the "heavy" weight of bash.
  • I also noticed a few quoting issues, for instance around a parameter expansion in his echo.
  • While rare, the solution cannot cope with filenames that contain newlines. (Almost no solution in sh can cope with them - which is why I almost always prefer bash, it's far more bulletproof & harder to exploit when used well).

While, yes, using /bin/sh for your hashbang means you must avoid bashisms at all costs, you can use all the bashisms you like, even on Ubuntu or whatnot when you're honest and put #!/bin/bash at the top.

So, here's a bash solution that's smaller, cleaner, more transparent, probably "faster", and more bulletproof.

[[ -d $1 && $1 != *[^0-9]* ]] || { echo "Invalid input." >&2; exit 1; }
rm -rf ~/foo/"$1"/bar ...
  1. Notice the quotes around $1 in the rm statement!
  2. The -d check will also fail if $1 is empty, so that's two checks in one.
  3. I avoided regular expressions for a reason. If you must use =~ in bash, you should be putting the regular expression in a variable. In any case, globs like mine are always preferable and supported in far more bash versions.

C++ vector of char array

In fact technically you can store C++ arrays in a vector, and it makes a lot of sense. Not directly, but by a simple workaround, wrapping in a class, will meet exactly all the requirements of a multidimensional array. As the question is already answered by anon. Some explanations steel needed. STL already provides std::array for these purposes.
Is an unpleasant surprise to fall in the trap of not understanding clearly the difference between arrays and pointers, between multidimensional arrays and arrays of arrays, and so on and so on. Vectors of vectors contains vectors as elements. Each element containing a copy of size, capacity and maybe other things, meanwhile the vector datas for elements will be placed in different random places in memory. But a vector of arrays will contain a contiguous segment of memory with all data, which is identical to multidimensional array. Also there is no good reason to keep the size of each array element while it is known to be the same for all elements. So, making a vector of array, you can't do it directly. But you can workaround it easily by wrapping the array in a class, and in this sample the memory will be identical to the memory of a bidimensional array. This approach is already widely used by many libraries. At low level it will be easily interoperable with APIs that are not C++ vector aware. So without using std::array it will look like this:

int main()
{
    struct ss
    {
        int a[5];
        int& operator[] (const int& i) { return a[i]; }
    } a{ 1,2,3,4,5 }, b{ 9,8,7,6,5 };

    vector<ss> v;
    v.resize(10);
    v[0] = a;
    v[1] = b;
    v.push_back(a); // will push to index 10, with reallocation
    v.push_back(b); // will push to index 11, with reallocation

    auto d = v.data();
    // cin >> v[1][3]; //input any element from stdin
    cout << "show two element: "<< v[1][2] <<":"<< v[1][3] << endl;
    return 0;
}

Since C++11 STL contains std::array for these purposes, so no need to reinvent it:

....
#include<array>
....
int main()
{
    vector<array<int, 5>> v;
    v.reserve(10);
    v.resize(2);
    v[0] = array<int, 5> {1, 2, 3, 4, 5};
    v[1] = array<int, 5> {9, 8, 7, 6, 5};
    v.emplace_back(array<int, 5>{ 7, 2, 53, 4, 5 });
    ///cin >> v[1][1];
    auto d = v.data();

Now look how looks in memory


Now, this is why vectors of vectors is not the answer. Supposing following code

int main()
{
    vector<vector<int>> vv = { { 1,2,3,4,5 }, { 9,8,7,6,5 } };
    auto dd = vv.data();
    return 0;
}

Guess what it looks like in the memory now

How to compile makefile using MinGW?

Please learn about automake and autoconf.

Makefile.am is processed by automake to generate a Makefile that is processed by make in order to build your sources.

http://www.gnu.org/software/automake/

Django: Redirect to previous page after login

This may not be a "best practice", but I've successfully used this before:

return HttpResponseRedirect(request.META.get('HTTP_REFERER','/'))

How to use TLS 1.2 in Java 6

After a few hours of playing with the Oracle JDK 1.6, I was able to make it work without any code change. The magic is done by Bouncy Castle to handle SSL and allow JDK 1.6 to run with TLSv1.2 by default. In theory, it could also be applied to older Java versions with eventual adjustments.

  1. Download the latest Java 1.6 version from the Java Archive Oracle website
  2. Uncompress it on your preferred path and set your JAVA_HOME environment variable
  3. Update the JDK with the latest Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files 6
  4. Download the Bounce Castle files bcprov-jdk15to18-165.jar and bctls-jdk15to18-165.jar and copy them into your ${JAVA_HOME}/jre/lib/ext folder
  5. Modify the file ${JAVA_HOME}/jre/lib/security/java.security commenting out the providers section and adding some extra lines
    # Original security providers (just comment it)
    # security.provider.1=sun.security.provider.Sun
    # security.provider.2=sun.security.rsa.SunRsaSign
    # security.provider.3=com.sun.net.ssl.internal.ssl.Provider
    # security.provider.4=com.sun.crypto.provider.SunJCE
    # security.provider.5=sun.security.jgss.SunProvider
    # security.provider.6=com.sun.security.sasl.Provider
    # security.provider.7=org.jcp.xml.dsig.internal.dom.XMLDSigRI
    # security.provider.8=sun.security.smartcardio.SunPCSC

    # Add the Bouncy Castle security providers with higher priority
    security.provider.1=org.bouncycastle.jce.provider.BouncyCastleProvider
    security.provider.2=org.bouncycastle.jsse.provider.BouncyCastleJsseProvider
    
    # Original security providers with different priorities
    security.provider.3=sun.security.provider.Sun
    security.provider.4=sun.security.rsa.SunRsaSign
    security.provider.5=com.sun.net.ssl.internal.ssl.Provider
    security.provider.6=com.sun.crypto.provider.SunJCE 
    security.provider.7=sun.security.jgss.SunProvider
    security.provider.8=com.sun.security.sasl.Provider
    security.provider.9=org.jcp.xml.dsig.internal.dom.XMLDSigRI
    security.provider.10=sun.security.smartcardio.SunPCSC

    # Here we are changing the default SSLSocketFactory implementation
    ssl.SocketFactory.provider=org.bouncycastle.jsse.provider.SSLSocketFactoryImpl

Just to make sure it's working let's make a simple Java program to download files from one URL using https.

import java.io.*;
import java.net.*;


public class DownloadWithHttps {

    public static void main(String[] args) {
        try {
            URL url = new URL(args[0]);
            System.out.println("File to Download: " + url);
            String filename = url.getFile();
            File f = new File(filename);
            System.out.println("Output File: " + f.getName());
            BufferedInputStream in = new BufferedInputStream(url.openStream());
            FileOutputStream fileOutputStream = new FileOutputStream(f.getName());
            int bytesRead;
            byte dataBuffer[] = new byte[1024];

            while ((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) {
                fileOutputStream.write(dataBuffer, 0, bytesRead);
            }
            fileOutputStream.close();

        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }
}

Now, just compile the DownloadWithHttps.java program and execute it with your Java 1.6


${JAVA_HOME}/bin/javac DownloadWithHttps.java
${JAVA_HOME}/bin/java DownloadWithHttps https://repo1.maven.org/maven2/org/apache/commons/commons-lang3/3.10/commons-lang3-3.10.jar

Important note for Windows users: This solution was tested in a Linux OS, if you are using Windows, please replace the ${JAVA_HOME} by %JAVA_HOME%.

In bash, how to store a return value in a variable?

Something like this could be used, and still maintaining meanings of return (to return control signals) and echo (to return information) and logging statements (to print debug/info messages).

v_verbose=1
v_verbose_f=""         # verbose file name
FLAG_BGPID=""

e_verbose() {
        if [[ $v_verbose -ge 0 ]]; then
                v_verbose_f=$(tempfile)
                tail -f $v_verbose_f &
                FLAG_BGPID="$!"
        fi
}

d_verbose() {
        if [[ x"$FLAG_BGPID" != "x" ]]; then
                kill $FLAG_BGPID > /dev/null
                FLAG_BGPID=""
                rm -f $v_verbose_f > /dev/null
        fi
}

init() {
        e_verbose

        trap cleanup SIGINT SIGQUIT SIGKILL SIGSTOP SIGTERM SIGHUP SIGTSTP
}

cleanup() {
        d_verbose
}

init

fun1() {
    echo "got $1" >> $v_verbose_f
    echo "got $2" >> $v_verbose_f
    echo "$(( $1 + $2 ))"
    return 0
}

a=$(fun1 10 20)
if [[ $? -eq 0 ]]; then
    echo ">>sum: $a"
else
    echo "error: $?"
fi
cleanup

In here, I'm redirecting debug messages to separate file, that is watched by tail, and if there is any changes then printing the change, trap is used to make sure that background process always ends.

This behavior can also be achieved using redirection to /dev/stderr, But difference can be seen at the time of piping output of one command to input of other command.

how to get files from <input type='file' .../> (Indirect) with javascript

Based on Ray Nicholus's answer :

inputElement.onchange = function(event) {
   var fileList = inputElement.files;
   //TODO do something with fileList.  
}

using this will also work :

inputElement.onchange = function(event) {
   var fileList = event.target.files;
   //TODO do something with fileList.  
}

is not JSON serializable

class CountryListView(ListView):
     model = Country

    def render_to_response(self, context, **response_kwargs):

         return HttpResponse(json.dumps(list(self.get_queryset().values_list('code', flat=True))),mimetype="application/json") 

fixed the problem

also mimetype is important.

javascript: detect scroll end

I could not get either of the above answers to work so here is a third option that works for me! (This is used with jQuery)

if (($(window).innerHeight() + $(window).scrollTop()) >= $("body").height()) {
    //do stuff
}

Hope this helps anyone!

Find specific string in a text file with VBS script

Wow, after few attempts I finally figured out how to deal with my text edits in vbs. The code works perfectly, it gives me the result I was expecting. Maybe it's not the best way to do this, but it does its job. Here's the code:

Option Explicit

Dim StdIn:  Set StdIn = WScript.StdIn
Dim StdOut: Set StdOut = WScript


Main()

Sub Main()

Dim objFSO, filepath, objInputFile, tmpStr, ForWriting, ForReading, count, text, objOutputFile, index, TSGlobalPath, foundFirstMatch
Set objFSO = CreateObject("Scripting.FileSystemObject")
TSGlobalPath = "C:\VBS\TestSuiteGlobal\Test suite Dispatch Decimal - Global.txt"
ForReading = 1
ForWriting = 2
Set objInputFile = objFSO.OpenTextFile(TSGlobalPath, ForReading, False)
count = 7
text=""
foundFirstMatch = false

Do until objInputFile.AtEndOfStream
    tmpStr = objInputFile.ReadLine
    If foundStrMatch(tmpStr)=true Then
        If foundFirstMatch = false Then
            index = getIndex(tmpStr)
            foundFirstMatch = true
            text = text & vbCrLf & textSubstitution(tmpStr,index,"true")
        End If
        If index = getIndex(tmpStr) Then
            text = text & vbCrLf & textSubstitution(tmpStr,index,"false")
        ElseIf index < getIndex(tmpStr) Then
            index = getIndex(tmpStr)
            text = text & vbCrLf & textSubstitution(tmpStr,index,"true")
        End If
    Else
        text = text & vbCrLf & textSubstitution(tmpStr,index,"false")
    End If
Loop
Set objOutputFile = objFSO.CreateTextFile("C:\VBS\NuovaProva.txt", ForWriting, true)
objOutputFile.Write(text)
End Sub


Function textSubstitution(tmpStr,index,foundMatch)
Dim strToAdd
strToAdd = "<tr><td><a href=" & chr(34) & "../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC" & CStr(index) & ".html" & chr(34) & ">Beginning_of_CF5.0_Features_TC" & CStr(index) & "</a></td></tr>"
If foundMatch = "false" Then
    textSubstitution = tmpStr
ElseIf foundMatch = "true" Then
    textSubstitution = strToAdd & vbCrLf & tmpStr
End If
End Function


Function getIndex(tmpStr)
Dim substrToFind, charAtPos, char1, char2
substrToFind = "<tr><td><a href=" & chr(34) & "../Test case "
charAtPos = len(substrToFind) + 1
char1 = Mid(tmpStr, charAtPos, 1)
char2 = Mid(tmpStr, charAtPos+1, 1)
If IsNumeric(char2) Then
    getIndex = CInt(char1 & char2)
Else
    getIndex = CInt(char1)
End If
End Function

Function foundStrMatch(tmpStr)
Dim substrToFind
substrToFind = "<tr><td><a href=" & chr(34) & "../Test case "
If InStr(tmpStr, substrToFind) > 0 Then
    foundStrMatch = true
Else
    foundStrMatch = false
End If
End Function

This is the original txt file

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <meta content="text/html; charset=UTF-8" http-equiv="content-type" />
  <title>Test Suite</title>
</head>
<body>
<table id="suiteTable" cellpadding="1" cellspacing="1" border="1" class="selenium"><tbody>
<tr><td><b>Test Suite</b></td></tr>
<tr><td><a href="../../Component/TC_Environment_setting">TC_Environment_setting</a></td></tr>
<tr><td><a href="../../Component/TC_Set_variables">TC_Set_variables</a></td></tr>
<tr><td><a href="../../Component/TC_Set_ID">TC_Set_ID</a></td></tr>
<tr><td><a href="../../Login/Log_in_Admin">Log_in_Admin</a></td></tr>
<tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../Test case 5 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 5 DD/contrD1">contrD1</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
<tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
<tr><td><a href="../Test case 5 DD/FormEND">FormEND</a></td></tr>
<tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../Test case 6 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 6 DD/contrD1">contrD1</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
<tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
<tr><td><a href="../Test case 5 DD/FormEND">FormEND</a></td></tr>
<tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../Test case 7 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../../Component/Controllo DeadLetter">Controllo DeadLetter</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
<tr><td><a href="../../Login/Logout_BAC">Logout_BAC</a></td></tr>
</tbody></table>
</body>
</html>

And this is the result I'm expecting

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <meta content="text/html; charset=UTF-8" http-equiv="content-type" />
  <title>Test Suite</title>
</head>
<body>
<table id="suiteTable" cellpadding="1" cellspacing="1" border="1" class="selenium"><tbody>
<tr><td><b>Test Suite</b></td></tr>
<tr><td><a href="../../Component/TC_Environment_setting">TC_Environment_setting</a></td></tr>
<tr><td><a href="../../Component/TC_Set_variables">TC_Set_variables</a></td></tr>
<tr><td><a href="../../Component/TC_Set_ID">TC_Set_ID</a></td></tr>
<tr><td><a href="../../Login/Log_in_Admin">Log_in_Admin</a></td></tr>
<tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC5.html">Beginning_of_CF5.0_Features_TC5</a></td></tr>
<tr><td><a href="../Test case 5 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 5 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 5 DD/contrD1">contrD1</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
<tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
<tr><td><a href="../Test case 5 DD/FormEND">FormEND</a></td></tr>
<tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC6.html">Beginning_of_CF5.0_Features_TC6</a></td></tr>
<tr><td><a href="../Test case 6 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 6 DD/contrD1">contrD1</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
<tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
<tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC7.html">Beginning_of_CF5.0_Features_TC7</a></td></tr>
<tr><td><a href="../Test case 7 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../../Component/Controllo DeadLetter">Controllo DeadLetter</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
<tr><td><a href="../../Login/Logout_BAC">Logout_BAC</a></td></tr>
</tbody></table>
</body>
</html>

How do you synchronise projects to GitHub with Android Studio?

Github with android studio

/*For New - Run these command in terminal*/
echo "# Your Repository" >> README.md
git init
git add README.md
git commit -m "first commit"
git remote add origin https://github.com/username/repository.git
git push -u origin master

/*For Exist - Run these command in terminal*/
git remote add origin https://github.com/username/repository.git
git push -u origin master
//git push -f origin master
//git push origin master --force

/*For Update - Run these command in terminal*/
git add .
git commit -m "your message"
git push

iOS / Android cross platform development

Cappuccino or PhoneGap.

Sometimes though trying to find a shortcut does not save you time or give you a comparable end product.

How to enable zoom controls and pinch zoom in a WebView?

Use these:

webview.getSettings().setBuiltInZoomControls(true);
webview.getSettings().setDisplayZoomControls(false);

How do I make jQuery wait for an Ajax call to finish before it returns?

It should wait until get request completed. After that I'll return get request body from where function is called.

function foo() {
    var jqXHR = $.ajax({
        url: url,
        type: 'GET',
        async: false,
    });
    return JSON.parse(jqXHR.responseText);  
}

Avoid Adding duplicate elements to a List C#

Use a HashSet<string> instead of a List<string>. It is prepared to perform a better performance because you don't need to provide checks for any items. The collection will manage it for you. That is the difference between a list and a set. For sample:

HashSet<string> set = new HashSet<string>();

set.Add("a");
set.Add("a");
set.Add("b");
set.Add("c");
set.Add("b");
set.Add("c");
set.Add("a");
set.Add("d");
set.Add("e");
set.Add("e");

var total = set.Count;

Total is 5 and the values are a, b, c, d, e.

The implemention of List<T> does not give you nativelly. You can do it, but you have to provide this control. For sample, this extension method:

public static class CollectionExtensions
{
    public static void AddItem<T>(this List<T> list, T item)
    {
       if (!list.Contains(item))
       {
          list.Add(item);
       }
    }
}

and use it:

var list = new List<string>();
list.AddItem(1);
list.AddItem(2);
list.AddItem(3);
list.AddItem(2);
list.AddItem(4);
list.AddItem(5);

Read each line of txt file to new array element

You were on the right track, but there were some problems with the code you posted. First of all, there was no closing bracket for the while loop. Secondly, $line_of_text would be overwritten with every loop iteration, which is fixed by changing the = to a .= in the loop. Third, you're exploding the literal characters '\n' and not an actual newline; in PHP, single quotes will denote literal characters, but double quotes will actually interpret escaped characters and variables.

    <?php
        $file = fopen("members.txt", "r");
        $i = 0;
        while (!feof($file)) {
            $line_of_text .= fgets($file);
        }
        $members = explode("\n", $line_of_text);
        fclose($file);
        print_r($members);
    ?>

Convert a number into a Roman Numeral in javaScript

function convertToRoman(num) {

var roNumerals = {
    M: Math.floor(num / 1000),
    CM: Math.floor(num % 1000 / 900),
    D: Math.floor(num % 1000 % 900 / 500),
    CD: Math.floor(num % 1000 % 900 % 500 / 400),
    C: Math.floor(num % 1000 % 900 % 500 % 400 / 100),
    XC: Math.floor(num % 1000 % 900 % 500 % 400 % 100 / 90),
    L: Math.floor(num % 1000 % 900 % 500 % 400 % 100 % 90 / 50),
    XL: Math.floor(num % 1000 % 900 % 500 % 400 % 100 % 90 % 50 / 40),
    X: Math.floor(num % 1000 % 900 % 500 % 400 % 100 % 90 % 50 % 40 / 10),
    IX: Math.floor(num % 1000 % 900 % 500 % 400 % 100 % 90 % 50 % 40 % 10 / 9),
    V: Math.floor(num % 1000 % 900 % 500 % 400 % 100 % 90 % 50 % 40 % 10 % 9 / 5),
    IV: Math.floor(num % 1000 % 900 % 500 % 400 % 100 % 90 % 50 % 40 % 10 % 9 % 5 / 4),
    I: Math.floor(num % 1000 % 900 % 500 % 400 % 100 % 90 % 50 % 40 % 10 % 9 % 5 % 4 / 1)
  };
  var roNuStr = "";

  for (var prop in roNumerals) {
    for (i = 0; i < roNumerals[prop]; i++) {
      roNuStr += prop;
    }

  }
  return roNuStr;
}

convertToRoman(9);

How to set viewport meta for iPhone that handles rotation properly?

I have come up with a slighly different approach that should work on cross platforms

http://www.jqui.net/tips-tricks/fixing-the-auto-scale-on-mobile-devices/

So far I have tested in on

Samsun galaxy 2

  • Samsung galaxy s
  • Samsung galaxy s2
  • Samsung galaxy Note (but had to change the css to 800px [see below]*)
  • Motorola
  • iPhone 4

    • @media screen and (max-width:800px) {

This is a massive lip forward with mobile development ...

Is there a RegExp.escape function in JavaScript?

There has only ever been and ever will be 12 meta characters that need to be escaped to be considered a literal.

It doesn't matter what is done with the escaped string, inserted into a balanced regex wrapper or appended. It doesn't matter.

Do a string replace using this

var escaped_string = oldstring.replace(/[\\^$.|?*+()[{]/g, '\\$&');

Raise an event whenever a property's value changed?

public event EventHandler ImageFullPath1Changed;

public string ImageFullPath1
{
    get
    {
        // insert getter logic
    }
    set
    {
        // insert setter logic       

        // EDIT -- this example is not thread safe -- do not use in production code
        if (ImageFullPath1Changed != null && value != _backingField)
            ImageFullPath1Changed(this, new EventArgs(/*whatever*/);
    }
}                        

That said, I completely agree with Ryan. This scenario is precisely why INotifyPropertyChanged exists.

I want to remove double quotes from a String

A one liner for the lazy people

var str = '"a string"';
str = str.replace(/^"|"$/g, '');

How to capture the android device screen content?

[Based on Android source code:]

At the C++ side, the SurfaceFlinger implements the captureScreen API. This is exposed over the binder IPC interface, returning each time a new ashmem area that contains the raw pixels from the screen. The actual screenshot is taken through OpenGL.

For the system C++ clients, the interface is exposed through the ScreenshotClient class, defined in <surfaceflinger_client/SurfaceComposerClient.h> for Android < 4.1; for Android > 4.1 use <gui/SurfaceComposerClient.h>

Before JB, to take a screenshot in a C++ program, this was enough:

ScreenshotClient ssc;
ssc.update();

With JB and multiple displays, it becomes slightly more complicated:

ssc.update(
    android::SurfaceComposerClient::getBuiltInDisplay(
        android::ISurfaceComposer::eDisplayIdMain));

Then you can access it:

do_something_with_raw_bits(ssc.getPixels(), ssc.getSize(), ...);

Using the Android source code, you can compile your own shared library to access that API, and then expose it through JNI to Java. To create a screen shot form your app, the app has to have the READ_FRAME_BUFFER permission. But even then, apparently you can create screen shots only from system applications, i.e. ones that are signed with the same key as the system. (This part I still don't quite understand, since I'm not familiar enough with the Android Permissions system.)

Here is a piece of code, for JB 4.1 / 4.2:

#include <utils/RefBase.h>
#include <binder/IBinder.h>
#include <binder/MemoryHeapBase.h>
#include <gui/ISurfaceComposer.h>
#include <gui/SurfaceComposerClient.h>

static void do_save(const char *filename, const void *buf, size_t size) {
    int out = open(filename, O_RDWR|O_CREAT, 0666);
    int len = write(out, buf, size);
    printf("Wrote %d bytes to out.\n", len);
    close(out);
}

int main(int ac, char **av) {
    android::ScreenshotClient ssc;
    const void *pixels;
    size_t size;
    int buffer_index;

    if(ssc.update(
        android::SurfaceComposerClient::getBuiltInDisplay(
            android::ISurfaceComposer::eDisplayIdMain)) != NO_ERROR ){
        printf("Captured: w=%d, h=%d, format=%d\n");
        ssc.getWidth(), ssc.getHeight(), ssc.getFormat());
        size = ssc.getSize();
        do_save(av[1], pixels, size);
    }
    else
        printf(" screen shot client Captured Failed");
    return 0;
}

Get the current user, within an ApiController action, without passing the userID as a parameter

Hint lies in Webapi2 auto generated account controller

Have this property with getter defined as

public string UserIdentity
        {
            get
            {
                var user = UserManager.FindByName(User.Identity.Name);
                return user;//user.Email
            }
        }

and in order to get UserManager - In WebApi2 -do as Romans (read as AccountController) do

public ApplicationUserManager UserManager
        {
            get { return HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>(); }
        }

This should be compatible in IIS and self host mode

How can I get Docker Linux container information from within the container itself?

I've found that in 17.09 there is a simplest way to do it within docker container:

$ cat /proc/self/cgroup | head -n 1 | cut -d '/' -f3
4de1c09d3f1979147cd5672571b69abec03d606afcc7bdc54ddb2b69dec3861c

Or like it has already been told, a shorter version with

$ cat /etc/hostname
4de1c09d3f19

Or simply:

$ hostname
4de1c09d3f19

How to add target="_blank" to JavaScript window.location?

I have created a function that allows me to obtain this feature:

function redirect_blank(url) {
  var a = document.createElement('a');
  a.target="_blank";
  a.href=url;
  a.click();
}