Programs & Examples On #Polymodel

Create a branch in Git from another branch

If you like the method in the link you've posted, have a look at Git Flow.

It's a set of scripts he created for that workflow.

But to answer your question:

$ git checkout -b myFeature dev

Creates MyFeature branch off dev. Do your work and then

$ git commit -am "Your message"

Now merge your changes to dev without a fast-forward

$ git checkout dev
$ git merge --no-ff myFeature

Now push changes to the server

$ git push origin dev
$ git push origin myFeature

And you'll see it how you want it.

Is there a command line utility for rendering GitHub flavored Markdown?

I found a website that will do this for you: http://tmpvar.com/markdown.html. Paste in your Markdown, and it'll display it for you. It seems to work just fine!

However, it doesn't seem to handle the syntax highlighting option for code; that is, the ~~~ruby feature doesn't work. It just prints 'ruby'.

Converting a datetime string to timestamp in Javascript

For those of us using non-ISO standard date formats, like civilian vernacular 01/01/2001 (mm/dd/YYYY), including time in a 12hour date format with am/pm marks, the following function will return a valid Date object:

function convertDate(date) {

    // # valid js Date and time object format (YYYY-MM-DDTHH:MM:SS)
    var dateTimeParts = date.split(' ');

    // # this assumes time format has NO SPACE between time and am/pm marks.
    if (dateTimeParts[1].indexOf(' ') == -1 && dateTimeParts[2] === undefined) {

        var theTime = dateTimeParts[1];

        // # strip out all except numbers and colon
        var ampm = theTime.replace(/[0-9:]/g, '');

        // # strip out all except letters (for AM/PM)
        var time = theTime.replace(/[[^a-zA-Z]/g, '');

        if (ampm == 'pm') {

            time = time.split(':');

            // # if time is 12:00, don't add 12
            if (time[0] == 12) {
                time = parseInt(time[0]) + ':' + time[1] + ':00';
            } else {
                time = parseInt(time[0]) + 12 + ':' + time[1] + ':00';
            }

        } else { // if AM

            time = time.split(':');

            // # if AM is less than 10 o'clock, add leading zero
            if (time[0] < 10) {
                time = '0' + time[0] + ':' + time[1] + ':00';
            } else {
                time = time[0] + ':' + time[1] + ':00';
            }
        }
    }
    // # create a new date object from only the date part
    var dateObj = new Date(dateTimeParts[0]);

    // # add leading zero to date of the month if less than 10
    var dayOfMonth = (dateObj.getDate() < 10 ? ("0" + dateObj.getDate()) : dateObj.getDate());

    // # parse each date object part and put all parts together
    var yearMoDay = dateObj.getFullYear() + '-' + (dateObj.getMonth() + 1) + '-' + dayOfMonth;

    // # finally combine re-formatted date and re-formatted time!
    var date = new Date(yearMoDay + 'T' + time);

    return date;
}

Usage:

date = convertDate('11/15/2016 2:00pm');

Moment.js: Date between dates

In versions 2.9+ there is an isBetween function, but it's exclusive:

var compareDate = moment("15/02/2013", "DD/MM/YYYY");
var startDate   = moment("12/01/2013", "DD/MM/YYYY");
var endDate     = moment("15/01/2013", "DD/MM/YYYY");

// omitting the optional third parameter, 'units'
compareDate.isBetween(startDate, endDate); //false in this case

There is an inclusive workaround ...
x.isBetween(a, b) || x.isSame(a) || x.isSame(b)

... which is logically equivalent to
!(x.isBefore(a) || x.isAfter(b))


In version 2.13 the isBetween function has a fourth optional parameter, inclusivity.

Use it like this:

target.isBetween(start, finish, 'days', '()') // default exclusive
target.isBetween(start, finish, 'days', '(]') // right inclusive
target.isBetween(start, finish, 'days', '[)') // left inclusive
target.isBetween(start, finish, 'days', '[]') // all inclusive

More units to consider: years, months, days, hours, minutes, seconds, milliseconds

Note: units are still optional. Use null as the third argument to disregard units in which case milliseconds is the default granularity.

Visit the Official Docs

How to uninstall Apache with command line

On Windows 8.1 I had to run cmd.exe as administrator (even though I was logged in as admin). Otherwise I got an error when trying to execute: httpd.exe -k uninstall

Error: C:\Program Files\Apache\bin>(OS 5)Access is denied. : AH00373: Apache2.4: OpenS ervice failed

MD5 hashing in Android

Here is Kotlin version from @Andranik answer. We need to change getBytes to toByteArray (don't need to add charset UTF-8 because the default charset of toByteArray is UTF-8) and cast array[i] to integer

fun String.md5(): String? {
    try {
        val md = MessageDigest.getInstance("MD5")
        val array = md.digest(this.toByteArray())
        val sb = StringBuffer()
        for (i in array.indices) {
            sb.append(Integer.toHexString(array[i].toInt() and 0xFF or 0x100).substring(1, 3))
        }
        return sb.toString()
    } catch (e: java.security.NoSuchAlgorithmException) {
    } catch (ex: UnsupportedEncodingException) {
    }
    return null
}

Hope it help

Assign output of os.system to a variable and prevent it from being displayed on the screen

From "Equivalent of Bash Backticks in Python", which I asked a long time ago, what you may want to use is popen:

os.popen('cat /etc/services').read()

From the docs for Python 3.6,

This is implemented using subprocess.Popen; see that class’s documentation for more powerful ways to manage and communicate with subprocesses.


Here's the corresponding code for subprocess:

import subprocess

proc = subprocess.Popen(["cat", "/etc/services"], stdout=subprocess.PIPE, shell=True)
(out, err) = proc.communicate()
print "program output:", out

Delete all rows in table

I would suggest using TRUNCATE TABLE, it's quicker and uses less resources than DELETE FROM xxx

Here's the related MSDN article

Convert string with comma to integer

Some more convenient

"1,1200.00".gsub(/[^0-9]/,'') 

it makes "1 200 200" work properly aswell

How do I set vertical space between list items?

Add a margin to your li tags. That will create space between the li and you can use line-height to set the spacing to the text within the li tags.

Internet Explorer 11 disable "display intranet sites in compatibility view" via meta tag not working

This problem is generally caused by the website/intranet URL being placed in one of:

  • Compatibility Mode List
  • Internet Explorer Intranet Zone
    (with Display intranet sites in Compatibility View setting enabled)
  • Enterprise Mode List

On corporate networks, these compatibility view settings are often controlled centrally via group policy. In your case, Enterprise Mode appears to be the culprit.

IE 11 Enterprise Mode

Unfortunately setting META X-UA-Compatible will not override this.

For End-Users

Sometimes the only way for end-users to override this is to press F12 and change the Document Mode under the Emulation Tab. However this setting is not permanent and may revert once Developer Tools is closed.

You can also try to exclude your site from the Intranet zone. But the list of domains which belong to the Intranet zone is usually also controlled by the group policy, so the chance of this working is slim.

To see the list of domains that belong to the Intranet zone, go to:

Tools -> Internet Options -> Security -> Sites -> Advanced

If the list contains your subdomain and is greyed out, then you will not be able to override compatibility view until your network admin allows it.

You really need to contact your network administrator to allow changing the compatibility view settings in the group policy.

For Network Admins

Loading the website with Developer Tools open (F12) will often report the reason that IE is switching to an older mode.

All 3 settings mentioned above are generally controlled via Group Policy, although can sometimes be overridden on user machines.

If Enterprise Mode is the issue (as appears to be the case for the original poster), the following two articles might be helpful:

Fatal error: Call to undefined function: ldap_connect()

If you are a Windows user, this is a common error when you use XAMPP since LDAP is not enabled by default.

You can follow this steps to make sure LDAP works in your XAMPP:

  • [Your Drive]:\xampp\php\php.ini: In this file uncomment the following line:

     extension=php_ldap.dll
    
  • Move the file: libsasl.dll, from [Your Drive]:\xampp\php to [Your Drive]:\xampp\apache\bin (Note: moving the file is needed only for XAMPP prior to version: 5.6.28)

  • Restart Apache.

  • You can now use functions of the LDAP Module!

If you use Linux:

For php5:

sudo apt-get install php5-ldap

For php7:

sudo apt-get install php7.0-ldap

If you are using the latest version of PHP you can do

sudo apt-get install php-ldap

running the above command should do the trick.

if for any reason it doesn't work check your php.ini configuration to enable ldap, remove the semicolon before extension=ldap to uncomment, save and restart Apache

How can you encode a string to Base64 in JavaScript?

I have re-wrote by hand, these encoding and decoding methods with the exception of the hexadecimal one into a modular format for cross-platform / browser compatibility and also with real private scoping, and uses btoa and atob if they exist due to speed rather than utilize its own encoding:

https://gist.github.com/Nijikokun/5192472

Usage:

base64.encode(/* String */);
base64.decode(/* String */);

utf8.encode(/* String */);
utf8.decode(/* String */);

Convert a python 'type' object to a string

In case you want to use str() and a custom str method. This also works for repr.

class TypeProxy:
    def __init__(self, _type):
        self._type = _type

    def __call__(self, *args, **kwargs):
        return self._type(*args, **kwargs)

    def __str__(self):
        return self._type.__name__

    def __repr__(self):
        return "TypeProxy(%s)" % (repr(self._type),)

>>> str(TypeProxy(str))
'str'
>>> str(TypeProxy(type("")))
'str'

How can I convert a date to GMT?

Based on the accepted answer and the second highest scoring answer both are not perfect according to the comment so I mixed both to get something perfect:

_x000D_
_x000D_
var date = new Date(); //Current timestamp_x000D_
date = date.toGMTString(); _x000D_
//Based on the time zone where the date was created_x000D_
console.log(date);_x000D_
_x000D_
/*based on the comment getTimezoneOffset returns an offset based _x000D_
on the date it is called on, and the time zone of the computer the code is_x000D_
 running on. It does not supply the offset passed in when constructing a _x000D_
date from a string. */_x000D_
_x000D_
date = new Date(date); //will convert to present timestamp offset_x000D_
date = new Date(date.getTime() + (date.getTimezoneOffset() * 60 * 1000)); _x000D_
console.log(date);
_x000D_
_x000D_
_x000D_

How to display activity indicator in middle of the iphone screen?

You can set the position like this

        UIActivityIndicatorView *activityView = 
[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
activityView.frame = CGRectMake(120, 230, 50, 50);
[self.view addSubview:activityView];

Accordingly change the frame size.....

Check whether a table contains rows or not sql server 2005

Like Other said you can use something like that:

IF NOT EXISTS (SELECT 1 FROM Table)
  BEGIN 
    --Do Something
  END 
ELSE
  BEGIN
    --Do Another Thing
  END

Getting selected value of a combobox

The problem you have with the SelectedValue is not converting into integer. This is the main problem so usinge the following code snippet will help you:

int selectedValue;
bool parseOK = Int32.TryParse(cmb.SelectedValue.ToString(), out selectedValue);

How to get response body using HttpURLConnection, when code other than 2xx is returned?

Wrong method was used for errors, here is the working code:

BufferedReader br = null;
if (100 <= conn.getResponseCode() && conn.getResponseCode() <= 399) {
    br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
} else {
    br = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
}

When would you use the Builder Pattern?

For a multi-threaded problem, we needed a complex object to be built up for each thread. The object represented the data being processed, and could change depending on the user input.

Could we use a factory instead? Yes

Why didn't we? Builder makes more sense I guess.

Factories are used for creating different types of objects that are the same basic type (implement the same interface or base class).

Builders build the same type of object over and over, but the construction is dynamic so it can be changed at runtime.

Pressed <button> selector

Maybe :active over :focus with :hover will help! Try

button {
background:lime;
}

button:hover {
background:green;
}

button:focus {
background:gray;
}

button:active {
background:red;
}

Then:

<button onkeydown="alerted_of_key_pressed()" id="button" title="Test button" href="#button">Demo</button>

Then:

<!--JAVASCRIPT-->
<script>
function alerted_of_key_pressed() { alert("You pressed a key when hovering over this button.") }
</script>
 Sorry about that last one. :) I was just showing you a cool function! 
Wait... did I just emphasize a code block? This is cool!!!

Database development mistakes made by application developers

Poor Performance Caused by Correlated Subqueries

Most of the time you want to avoid correlated subqueries. A subquery is correlated if, within the subquery, there is a reference to a column from the outer query. When this happens, the subquery is executed at least once for every row returned and could be executed more times if other conditions are applied after the condition containing the correlated subquery is applied.

Forgive the contrived example and the Oracle syntax, but let's say you wanted to find all the employees that have been hired in any of your stores since the last time the store did less than $10,000 of sales in a day.

select e.first_name, e.last_name
from employee e
where e.start_date > 
        (select max(ds.transaction_date)
         from daily_sales ds
         where ds.store_id = e.store_id and
               ds.total < 10000)

The subquery in this example is correlated to the outer query by the store_id and would be executed for every employee in your system. One way that this query could be optimized is to move the subquery to an inline-view.

select e.first_name, e.last_name
from employee e,
     (select ds.store_id,
             max(s.transaction_date) transaction_date
      from daily_sales ds
      where ds.total < 10000
      group by s.store_id) dsx
where e.store_id = dsx.store_id and
      e.start_date > dsx.transaction_date

In this example, the query in the from clause is now an inline-view (again some Oracle specific syntax) and is only executed once. Depending on your data model, this query will probably execute much faster. It would perform better than the first query as the number of employees grew. The first query could actually perform better if there were few employees and many stores (and perhaps many of stores had no employees) and the daily_sales table was indexed on store_id. This is not a likely scenario but shows how a correlated query could possibly perform better than an alternative.

I've seen junior developers correlate subqueries many times and it usually has had a severe impact on performance. However, when removing a correlated subquery be sure to look at the explain plan before and after to make sure you are not making the performance worse.

How to explain callbacks in plain english? How are they different from calling one function from another function?

I'm stunned to see so many intelligent people failing to stress the reality that the word "callback" has come to be used in two inconsistent ways.

Both ways involve the customization of a function by passing additional functionality (a function definition, anonymous or named) to an existing function. ie.

customizableFunc(customFunctionality)

If the custom functionality is simply plugged into the code block, you have customized the function, like so.

    customizableFucn(customFunctionality) {
      var data = doSomthing();
      customFunctionality(data);
      ...
    }

Though this kind of injected functionality is often called a "callback", there is nothing contingent about it. A very obvious example is the forEach method in which a custom function is supplied as an argument to be applied to each element in an array to modify the array.

But this is fundamentally distinct from the use of "callback" functions for asynchronous programming, as in AJAX or node.js or simply in assigning functionality to user interaction events (like mouse clicks). In this case, the whole idea is to wait for a contingent event to occur before executing the custom functionality. This is obvious in the case of user interaction, but is also important in i/o (input/output) processes that can take time, like reading files from disk. This is where the term "callback" makes the most obvious sense. Once an i/o process is started (like asking for a file to be read from disk or a server to return data from an http request) an asynchronous program doesn't wait around for it to finish. It can go ahead with whatever tasks are scheduled next, and only respond with the custom functionality after it has been notified that the read file or http request is completed (or that it failed) and that the data is available to the custom functionality. It's like calling a business on the phone and leaving your "callback" number, so they can call you when someone is available to get back to you. That's better than hanging on the line for who knows how long and not being able to attend to other affairs.

Asynchronous use inherently involves some means of listening for the desired event (e.g, the completion of the i/o process) so that, when it occurs (and only when it occurs) the custom "callback" functionality is executed. In the obvious AJAX example, when the data actually arrives from the server, the "callback" function is triggered to use that data to modify the DOM and therefore redraw the browser window to that extent.

To recap. Some people use the word "callback" to refer to any kind of custom functionality that can be injected into an existing function as an argument. But, at least to me, the most appropriate use of the word is where the injected "callback" function is used asynchronously -- to be executed only upon the occurrence of an event that it is waiting to be notified of.

CSS rotation cross browser with jquery.animate()

To do this cross browser including IE7+, you will need to expand the plugin with a transformation matrix. Since vendor prefix is done in jQuery from jquery-1.8+ I will leave that out for the transform property.

$.fn.animateRotate = function(endAngle, options, startAngle)
{
    return this.each(function()
    {
        var elem = $(this), rad, costheta, sintheta, matrixValues, noTransform = !('transform' in this.style || 'webkitTransform' in this.style || 'msTransform' in this.style || 'mozTransform' in this.style || 'oTransform' in this.style),
            anims = {}, animsEnd = {};
        if(typeof options !== 'object')
        {
            options = {};
        }
        else if(typeof options.extra === 'object')
        {
            anims = options.extra;
            animsEnd = options.extra;
        }
        anims.deg = startAngle;
        animsEnd.deg = endAngle;
        options.step = function(now, fx)
        {
            if(fx.prop === 'deg')
            {
                if(noTransform)
                {
                    rad = now * (Math.PI * 2 / 360);
                    costheta = Math.cos(rad);
                    sintheta = Math.sin(rad);
                    matrixValues = 'M11=' + costheta + ', M12=-'+ sintheta +', M21='+ sintheta +', M22='+ costheta;
                    $('body').append('Test ' + matrixValues + '<br />');
                    elem.css({
                        'filter': 'progid:DXImageTransform.Microsoft.Matrix(sizingMethod=\'auto expand\','+matrixValues+')',
                        '-ms-filter': 'progid:DXImageTransform.Microsoft.Matrix(sizingMethod=\'auto expand\','+matrixValues+')'
                    });
                }
                else
                {
                    elem.css({
                        //webkitTransform: 'rotate('+now+'deg)',
                        //mozTransform: 'rotate('+now+'deg)',
                        //msTransform: 'rotate('+now+'deg)',
                        //oTransform: 'rotate('+now+'deg)',
                        transform: 'rotate('+now+'deg)'
                    });
                }
            }
        };
        if(startAngle)
        {
            $(anims).animate(animsEnd, options);
        }
        else
        {
            elem.animate(animsEnd, options);
        }
    });
};

Note: The parameters options and startAngle are optional, if you only need to set startAngle use {} or null for options.

Example usage:

var obj = $(document.createElement('div'));
obj.on("click", function(){
    obj.stop().animateRotate(180, {
        duration: 250,
        complete: function()
        {
            obj.animateRotate(0, {
                duration: 250
            });
        }
    });
});
obj.text('Click me!');
obj.css({cursor: 'pointer', position: 'absolute'});
$('body').append(obj);

See also this jsfiddle for a demo.

Update: You can now also pass extra: {} in the options. This will make you able to execute other animations simultaneously. For example:

obj.animateRotate(90, {extra: {marginLeft: '100px', opacity: 0.5}});

This will rotate the element 90 degrees, and move it to the right with 100px and make it semi-transparent all at the same time during the animation.

jQuery : select all element with custom attribute

As described by the link I've given in comment, this

$('p[MyTag]').each(function(index) {
  document.write(index + ': ' + $(this).text() + "<br>");});

works (playable example).

Changing one character in a string

Like other people have said, generally Python strings are supposed to be immutable.

However, if you are using CPython, the implementation at python.org, it is possible to use ctypes to modify the string structure in memory.

Here is an example where I use the technique to clear a string.

Mark data as sensitive in python

I mention this for the sake of completeness, and this should be your last resort as it is hackish.

Pagination using MySQL LIMIT, OFFSET

If you want to keep it simple go ahead and try this out.

$page_number = mysqli_escape_string($con, $_GET['page']);
$count_per_page = 20;
$next_offset = $page_number * $count_per_page;
$cat =mysqli_query($con, "SELECT * FROM categories LIMIT $count_per_page OFFSET $next_offset");
while ($row = mysqli_fetch_array($cat))
        $count = $row[0];

The rest is up to you. If you have result comming from two tables i suggest you try a different approach.

How to see log files in MySQL?

In my (I have LAMP installed) /etc/mysql/my.cnf file I found following, commented lines in [mysqld] section:

general_log_file        = /var/log/mysql/mysql.log
general_log             = 1

I had to open this file as superuser, with terminal:

sudo geany /etc/mysql/my.cnf

(I prefer to use Geany instead of gedit or VI, it doesn't matter)

I just uncommented them & save the file then restart MySQL with

sudo service MySQL restart

Run several queries, open the above file (/var/log/mysql/mysql.log) and the log was there :)

Can't start Eclipse - Java was started but returned exit code=13

I had a similar error after installing Java 8 on my Windows 7 system, 64 bit system.

Changing environment variables, etc. did not help. So I tried to remove the Java Update 8, but that too did not help. Downloading and installing the 64-bit version of Java 8 SDK fixed my problem. I hope this helps.

What's the proper way to "go get" a private repository?

All of the above did not work for me. Cloning the repo was working correctly but I was still getting an unrecognized import error.

As it stands for Go v1.13, I found in the doc that we should use the GOPRIVATE env variable like so:

$ GOPRIVATE=github.com/ORGANISATION_OR_USER_NAME go get -u github.com/ORGANISATION_OR_USER_NAME/REPO_NAME

How to read strings from a Scanner in a Java console application?

What you can do is use delimeter as new line. Till you press enter key you will be able to read it as string.

Scanner sc = new Scanner(System.in);
sc.useDelimiter(System.getProperty("line.separator"));

Hope this helps.

How can I get phone serial number (IMEI)

Here is the code:-

telephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);


    deviceId = telephonyManager.getDeviceId(); 
    Log.d(TAG, "getDeviceId() " + deviceId);



    phoneType = telephonyManager.getPhoneType();
    Log.d(TAG, "getPhoneType () " + phoneType);

Is it possible to dynamically compile and execute C# code fragments?

Found this useful - ensures the compiled Assembly references everything you currently have referenced, since there's a good chance you wanted the C# you're compiling to use some classes etc in the code that's emitting this:

(string code is the dynamic C# being compiled)

        var refs = AppDomain.CurrentDomain.GetAssemblies();
        var refFiles = refs.Where(a => !a.IsDynamic).Select(a => a.Location).ToArray();
        var cSharp = (new Microsoft.CSharp.CSharpCodeProvider()).CreateCompiler();
        var compileParams = new System.CodeDom.Compiler.CompilerParameters(refFiles);
        compileParams.GenerateInMemory = true;
        compileParams.GenerateExecutable = false;

        var compilerResult = cSharp.CompileAssemblyFromSource(compileParams, code);
        var asm = compilerResult.CompiledAssembly;

In my case I was emitting a class, whose name was stored in a string, className, which had a single public static method named Get(), that returned with type StoryDataIds. Here's what calling that method looks like:

        var tempType = asm.GetType(className);
        var ids = (StoryDataIds)tempType.GetMethod("Get").Invoke(null, null);

Warning: Compilation can be surprisingly, extremely slow. A small, relatively simple 10-line chunk of code compiles at normal priority in 2-10 seconds on our relatively fast server. You should never tie calls to CompileAssemblyFromSource() to anything with normal performance expectations, like a web request. Instead, proactively compile code you need on a low-priority thread and have a way of dealing with code that requires that code to be ready, until it's had a chance to finish compiling. For example you could use it in a batch job process.

C++ undefined reference to defined function

You need to compile and link all your source files together:

g++ main.c function_file.c

for loop in Python

The answer is good, but for the people that want this with range(), the form to do is:

range(end):

>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

range(start,end):

 >>> list(range(1, 11))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

range(start,end, step):

 >>> list(range(0, 30, 5))
[0, 5, 10, 15, 20, 25]

How to remove element from ArrayList by checking its value?

Just use myList.remove(myObject).

It uses the equals method of the class. See http://docs.oracle.com/javase/6/docs/api/java/util/List.html#remove(java.lang.Object)

BTW, if you have more complex things to do, you should check out the guava library that has dozen of utility to do that with predicates and so on.

Update query using Subquery in Sql Server

because you are just learning I suggest you practice converting a SELECT joins to UPDATE or DELETE joins. First I suggest you generate a SELECT statement joining these two tables:

SELECT *
FROM    tempDataView a
        INNER JOIN tempData b
            ON a.Name = b.Name

Then note that we have two table aliases a and b. Using these aliases you can easily generate UPDATE statement to update either table a or b. For table a you have an answer provided by JW. If you want to update b, the statement will be:

UPDATE  b
SET     b.marks = a.marks
FROM    tempDataView a
        INNER JOIN tempData b
            ON a.Name = b.Name

Now, to convert the statement to a DELETE statement use the same approach. The statement below will delete from a only (leaving b intact) for those records that match by name:

DELETE a
FROM    tempDataView a
        INNER JOIN tempData b
            ON a.Name = b.Name

You can use the SQL Fiddle created by JW as a playground

How can I see the entire HTTP request that's being sent by my Python application?

r = requests.get('https://api.github.com', auth=('user', 'pass'))

r is a response. It has a request attribute which has the information you need.

r.request.allow_redirects  r.request.headers          r.request.register_hook
r.request.auth             r.request.hooks            r.request.response
r.request.cert             r.request.method           r.request.send
r.request.config           r.request.params           r.request.sent
r.request.cookies          r.request.path_url         r.request.session
r.request.data             r.request.prefetch         r.request.timeout
r.request.deregister_hook  r.request.proxies          r.request.url
r.request.files            r.request.redirect         r.request.verify

r.request.headers gives the headers:

{'Accept': '*/*',
 'Accept-Encoding': 'identity, deflate, compress, gzip',
 'Authorization': u'Basic dXNlcjpwYXNz',
 'User-Agent': 'python-requests/0.12.1'}

Then r.request.data has the body as a mapping. You can convert this with urllib.urlencode if they prefer:

import urllib
b = r.request.data
encoded_body = urllib.urlencode(b)

depending on the type of the response the .data-attribute may be missing and a .body-attribute be there instead.

How to find and replace string?

Not exactly that, but std::string has many replace overloaded functions.

Go through this link to see explanation of each, with examples as to how they're used.

Also, there are several versions of string::find functions (listed below) which you can use in conjunction with string::replace.

  • find
  • rfind
  • find_first_of
  • find_last_of
  • find_first_not_of
  • find_last_not_of

Also, note that there are several versions of replace functions available from <algorithm> which you can also use (instead of string::replace):

  • replace
  • replace_if
  • replace_copy
  • replace_copy_if

Write to custom log file from a Bash script

If you see the man page of logger:

$ man logger

LOGGER(1) BSD General Commands Manual LOGGER(1)

NAME logger — a shell command interface to the syslog(3) system log module

SYNOPSIS logger [-isd] [-f file] [-p pri] [-t tag] [-u socket] [message ...]

DESCRIPTION Logger makes entries in the system log. It provides a shell command interface to the syslog(3) system log module.

It Clearly says that it will log to system log. If you want to log to file, you can use ">>" to redirect to log file.

Resolving javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed Error?

For me didn't work the recognized solution from this post: https://stackoverflow.com/a/9619478/4507034.

Instead, I managed to solve the problem by importing the certification to my machine trusted certifications.

Steps:

  1. Go to the URL (eg. https://localhost:8443/yourpath) where the certification is not working.
  2. Export the certification as described in the mentioned post.
  3. On your windows machine open: Manage computer certificates
  4. Go to Trusted Root Certification Authorities -> Certificates
  5. Import here your your_certification_name.cer file.

NullInjectorError: No provider for AngularFirestore

I had the same issue while adding firebase to my Ionic App. To fix the issue I followed these steps:

npm install @angular/fire firebase --save

In my app/app.module.ts:

...
import { AngularFireModule } from '@angular/fire';
import { environment } from '../environments/environment';
import { AngularFirestoreModule, SETTINGS } from '@angular/fire/firestore';

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [
    BrowserModule, 
    AppRoutingModule,
    AngularFireModule.initializeApp(environment.firebase),
    AngularFirestoreModule
  ],
  providers: [
    { provide: SETTINGS, useValue: {} }
  ],
  bootstrap: [AppComponent]
})

Previously we used FirestoreSettingsToken instead of SETTINGS. But that bug got resolved, now we use SETTINGS. (link)

In my app/services/myService.ts I imported as:

import { AngularFirestore } from "@angular/fire/firestore";

For some reason vscode was importing it as "@angular/fire/firestore/firestore";I After changing it for "@angular/fire/firestore"; the issue got resolved!

How to check if a file exists in Go?

As mentioned in other answers, it is possible to construct the required behaviour / errors from using different flags with os.OpenFile. In fact, os.Create is just a sensible-defaults shorthand for doing so:

// Create creates or truncates the named file. If the file already exists,
// it is truncated. If the file does not exist, it is created with mode 0666
// (before umask). If successful, methods on the returned File can
// be used for I/O; the associated file descriptor has mode O_RDWR.
// If there is an error, it will be of type *PathError.
func Create(name string) (*File, error) {
    return OpenFile(name, O_RDWR|O_CREATE|O_TRUNC, 0666)
}

You should combine these flags yourself to get the behaviour you are interested in:

// Flags to OpenFile wrapping those of the underlying system. Not all
// flags may be implemented on a given system.
const (
    // Exactly one of O_RDONLY, O_WRONLY, or O_RDWR must be specified.
    O_RDONLY int = syscall.O_RDONLY // open the file read-only.
    O_WRONLY int = syscall.O_WRONLY // open the file write-only.
    O_RDWR   int = syscall.O_RDWR   // open the file read-write.
    // The remaining values may be or'ed in to control behavior.
    O_APPEND int = syscall.O_APPEND // append data to the file when writing.
    O_CREATE int = syscall.O_CREAT  // create a new file if none exists.
    O_EXCL   int = syscall.O_EXCL   // used with O_CREATE, file must not exist.
    O_SYNC   int = syscall.O_SYNC   // open for synchronous I/O.
    O_TRUNC  int = syscall.O_TRUNC  // truncate regular writable file when opened.
)

Depending on what you pick, you will get different errors.

Here's an example where I wish to open a file for writing, but I will only truncate an existing file if the user has said that is OK:

var f *os.File
if truncateWhenExists {
    // O_TRUNC - truncate regular writable file when opened.
    if f, err = os.OpenFile(filepath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644); err != nil {
        log.Fatalln("failed to force-open file, err:", err)
    }
} else {
    // O_EXCL - used with O_CREATE, file must not exist
    if f, err = os.OpenFile(filepath, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0644); err != nil {
        log.Fatalln("failed to open file, err:", err) 
   }
}

How do I use shell variables in an awk script?

You could pass in the command-line option -v with a variable name (v) and a value (=) of the environment variable ("${v}"):

% awk -vv="${v}" 'BEGIN { print v }'
123test

Or to make it clearer (with far fewer vs):

% environment_variable=123test
% awk -vawk_variable="${environment_variable}" 'BEGIN { print awk_variable }'
123test

Load external css file like scripts in jquery which is compatible in ie also

Here is a function that will load CSS files with a success or failure callback. The failure callback will be called just once, if one or more resources fail to load. I think this approach is better than some of the other solutions because inserting a element into the DOM with an HREF causes an additional browser request (albeit, the request will likely come from cache, depending on response headers).

function loadCssFiles(urls, successCallback, failureCallback) {

    $.when.apply($,
        $.map(urls, function(url) {
            return $.get(url, function(css) {
                $("<style>" + css + "</style>").appendTo("head");
            });
        })
    ).then(function() {
        if (typeof successCallback === 'function') successCallback();
    }).fail(function() {
        if (typeof failureCallback === 'function') failureCallback();
    });

}

Usage as so:

loadCssFiles(["https://test.com/style1.css", "https://test.com/style2.css",],
    function() {
    alert("All resources loaded");
}, function() {
    alert("One or more resources failed to load");
});

Here is another function that will load both CSS and javascript files:

function loadJavascriptAndCssFiles(urls, successCallback, failureCallback) {

    $.when.apply($,
        $.map(urls, function(url) {
            if(url.endsWith(".css")) {
                return $.get(url, function(css) {
                    $("<style>" + css + "</style>").appendTo("head");
                });
            } else {
                return $.getScript(url);
            }
        })
    ).then(function() {
        if (typeof successCallback === 'function') successCallback();
    }).fail(function() {
        if (typeof failureCallback === 'function') failureCallback();
    });

}

Most efficient way to concatenate strings in JavaScript?

Three years past since this question was answered but I will provide my answer anyway :)

Actually, accepted answer is not fully correct. Jakub's test uses hardcoded string which allows JS engine to optimize code execution (Google's V8 is really good in this stuff!). But as soon as you use completely random strings (here is JSPerf) then string concatenation will be on a second place.

How can I get a list of users from active directory?

PrincipalContext for browsing the AD is ridiculously slow (only use it for .ValidateCredentials, see below), use DirectoryEntry instead and .PropertiesToLoad() so you only pay for what you need.

Filters and syntax here: https://social.technet.microsoft.com/wiki/contents/articles/5392.active-directory-ldap-syntax-filters.aspx

Attributes here: https://docs.microsoft.com/en-us/windows/win32/adschema/attributes-all

using (var root = new DirectoryEntry($"LDAP://{Domain}"))
{
    using (var searcher = new DirectorySearcher(root))
    {
        // looking for a specific user
        searcher.Filter = $"(&(objectCategory=person)(objectClass=user)(sAMAccountName={username}))";
        // I only care about what groups the user is a memberOf
        searcher.PropertiesToLoad.Add("memberOf");

        // FYI, non-null results means the user was found
        var results = searcher.FindOne();

        var properties = results?.Properties;
        if (properties?.Contains("memberOf") == true)
        {
            // ... iterate over all the groups the user is a member of
        }
    }
}

Clean, simple, fast. No magic, no half-documented calls to .RefreshCache to grab the tokenGroups or to .Bind or .NativeObject in a try/catch to validate credentials.

For authenticating the user:

using (var context = new PrincipalContext(ContextType.Domain))
{
    return context.ValidateCredentials(username, password);
}

Environment variable to control java.io.tmpdir?

It isn't an environment variable, but still gives you control over the temp dir:

-Djava.io.tmpdir

ex.:

java -Djava.io.tmpdir=/mytempdir

Converting Go struct to JSON

Related issue:

I was having trouble converting struct to JSON, sending it as response from Golang, then, later catch the same in JavaScript via Ajax.

Wasted a lot of time, so posting solution here.

In Go:

// web server

type Foo struct {
    Number int    `json:"number"`
    Title  string `json:"title"`
}

foo_marshalled, err := json.Marshal(Foo{Number: 1, Title: "test"})
fmt.Fprint(w, string(foo_marshalled)) // write response to ResponseWriter (w)

In JavaScript:

// web call & receive in "data", thru Ajax/ other

var Foo = JSON.parse(data);
console.log("number: " + Foo.number);
console.log("title: " + Foo.title);

JQuery datepicker language

Try Adding this

$('input[name="daterangepicker"]').daterangepicker({

   "locale": {
    "firstDay" :1 // 0 Tuesday - 6 - Monday between
         }});

It must be completed within the locale object of the defined daterangepicker. detailed information can be found here.

Quick way to clear all selections on a multiselect enabled <select> with jQuery?

You can pass an empty array to unselect all the selection. Here goes an example. From documentation

val() allows you to pass an array of element values. This is useful when working on a jQuery object containing elements like , , and s inside of a . In this case, the inputs and the options having a value that matches one of the elements of the array will be checked or selected while those having a value that doesn't match one of the elements of the array will be unchecked or unselected, depending on the type.

_x000D_
_x000D_
$('.clearAll').on('click', function() {_x000D_
  $('.dropdown').val([]);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<select class="dropdown" multiple>_x000D_
  <option value="volvo">Volvo</option>_x000D_
  <option value="saab">Saab</option>_x000D_
  <option value="opel">Opel</option>_x000D_
  <option value="audi">Audi</option>_x000D_
</select>_x000D_
_x000D_
<button class='clearAll'>Clear All Selection</button>
_x000D_
_x000D_
_x000D_

How to make a redirection on page load in JSF 1.x

you should use action instead of actionListener:

<h:commandLink id="close" action="#{bean.close}" value="Close" immediate="true" 
                                   />

and in close method you right something like:

public String close() {
   return "index?faces-redirect=true";
}

where index is one of your pages(index.xhtml)

Of course, all this staff should be written in our original page, not in the intermediate. And inside the close() method you can use the parameters to dynamically choose where to redirect.

Project with path ':mypath' could not be found in root project 'myproject'

It's not enough to have just compile project("xy") dependency. You need to configure root project to include all modules (or to call them subprojects but that might not be correct word here).

Create a settings.gradle file in the root of your project and add this:

include ':progressfragment'

to that file. Then sync Gradle and it should work.

Also one interesting side note: If you add ':unexistingProject' in settings.gradle (project that you haven't created yet), Gradle will create folder for this project after sync (at least in Android studio this is how it behaves). So, to avoid errors with settings.gradle when you create project from existing files, first add that line to file, sync and then put existing code in created folder. Unwanted behavior arising from this might be that if you delete the project folder and then sync folder will come back empty because Gradle sync recreated it since it is still listed in settings.gradle.

error LNK2005, already defined?

Assuming you want 'k' to be a different value in different .cpp files (hence declaring it twice), try changing both files to

namespace {
    int k;
}

This guarantees that the name 'k' uniquely identifies 'k' across translation units. The old version static int k; is deprecated.

If you want them to point to the same value, change one to extern int k;.

Python: convert string from UTF-8 to Latin-1

Can you provide more details about what you are trying to do? In general, if you have a unicode string, you can use encode to convert it into string with appropriate encoding. Eg:

>>> a = u"\u00E1"
>>> type(a)
<type 'unicode'>
>>> a.encode('utf-8')
'\xc3\xa1'
>>> a.encode('latin-1')
'\xe1'

2 ways for "ClearContents" on VBA Excel, but 1 work fine. Why?

It is because you haven't qualified Cells(1, 1) with a worksheet object, and the same holds true for Cells(10, 2). For the code to work, it should look something like this:

Dim ws As Worksheet

Set ws = Sheets("SheetName")
Range(ws.Cells(1, 1), ws.Cells(10, 2)).ClearContents

Alternately:

With Sheets("SheetName")
    Range(.Cells(1, 1), .Cells(10, 2)).ClearContents
End With

EDIT: The Range object will inherit the worksheet from the Cells objects when the code is run from a standard module or userform. If you are running the code from a worksheet code module, you will need to qualify Range also, like so:

ws.Range(ws.Cells(1, 1), ws.Cells(10, 2)).ClearContents

or

With Sheets("SheetName")
    .Range(.Cells(1, 1), .Cells(10, 2)).ClearContents
End With

How to convert from Hex to ASCII in JavaScript?

An optimized version of the implementation of the reverse function proposed by @michieljoris (according to the comments of @Beterraba and @Mala):

_x000D_
_x000D_
function a2hex(str) {_x000D_
  var hex = '';_x000D_
  for (var i = 0, l = str.length; i < l; i++) {_x000D_
    var hexx = Number(str.charCodeAt(i)).toString(16);_x000D_
    hex += (hexx.length > 1 && hexx || '0' + hexx);_x000D_
  }_x000D_
  return hex;_x000D_
}_x000D_
alert(a2hex('2460')); // display 32343630
_x000D_
_x000D_
_x000D_

How to prove that a problem is NP complete?

You need to reduce an NP-Complete problem to the problem you have. If the reduction can be done in polynomial time then you have proven that your problem is NP-complete, if the problem is already in NP, because:

It is not easier than the NP-complete problem, since it can be reduced to it in polynomial time which makes the problem NP-Hard.

See the end of http://www.ics.uci.edu/~eppstein/161/960312.html for more.

Disable F5 and browser refresh using JavaScript

Use this for modern browsers:

function my_onkeydown_handler( event ) {
    switch (event.keyCode) {
        case 116 : // 'F5'
            event.preventDefault();
            event.keyCode = 0;
            window.status = "F5 disabled";
            break;
    }
}
document.addEventListener("keydown", my_onkeydown_handler);

PDO mysql: How to know if insert was successful

If an update query executes with values that match the current database record then $stmt->rowCount() will return 0 for no rows were affected. If you have an if( rowCount() == 1 ) to test for success you will think the updated failed when it did not fail but the values were already in the database so nothing change.

$stmt->execute();
if( $stmt ) return "success";

This did not work for me when I tried to update a record with a unique key field that was violated. The query returned success but another query returns the old field value.

Best way to check if a drop down list contains a value?

If 0 is your default value, you can just use a simple assignment:

ddlCustomerNumber.SelectedValue = GetCustomerNumberCookie().ToString();

This automatically selects the proper list item, if the DDL contains the value of the cookie. If it doesn't contain it, this call won't change the selection, so it stays at the default selection. If the latter one is the same as value 0, then it's the perfect solution for you.

I use this mechanism quite a lot and find it very handy.

How to solve COM Exception Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))?

It looks like whichever program or process you're trying to initialize either isn't installed on your machine, has a damaged installation or needs to be registered.

Either install it, repair it (via Add/Remove Programs) or register it (via Regsvr32.exe).

You haven't provided enough information for us to help you any more than this.

How to set the style -webkit-transform dynamically using JavaScript?

If you want to do it via setAttribute you would change the style attribute like so:

element.setAttribute('style','transform:rotate(90deg); -webkit-transform: rotate(90deg)') //etc

This would be helpful if you want to reset all other inline style and only set your needed style properties' values again, BUT in most cases you may not want that. That's why everybody advised to use this:

element.style.transform = 'rotate(90deg)';
element.style.webkitTransform = 'rotate(90deg)';

The above is equivalent to

element.style['transform'] = 'rotate(90deg)';
element.style['-webkit-transform'] = 'rotate(90deg)';

Reading RFID with Android phones

A UHF RFID reader option for both Android and iOS is available from a company called U Grok It.

It is just UHF, which is "non-NFC enabled Android", if that's what you meant. My apologies if you meant an NFC reader for Android devices that don't have an NFC reader built-in.

Their reader has a range up to 7 meters (~21 feet). It connects via the audio port, not bluetooth, which has the advantage of pairing instantly, securely, and with way less of a power draw.

They have a free native SDK for Android, iOS, Cordova, and Xamarin, as well as an Android keyboard wedge.

Javascript: formatting a rounded number to N decimals

There's always a better way for doing things.

var number = 51.93999999999761;

I would like to get four digits precision: 51.94

just do:

number.toPrecision(4);

the result will be: 51.94

How to test my servlet using JUnit

I find Selenium tests more useful with integration or functional (end-to-end) testing. I am working with trying to use org.springframework.mock.web, but I am not very far along. I am attaching a sample controller with a jMock test suite.

First, the Controller:

package com.company.admin.web;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

import com.company.admin.domain.PaymentDetail;
import com.company.admin.service.PaymentSearchService;
import com.company.admin.service.UserRequestAuditTrail;
import com.company.admin.web.form.SearchCriteria;

/**
 * Controls the interactions regarding to the refunds.
 * 
 * @author slgelma
 *
 */
@Controller
@SessionAttributes({"user", "authorization"})
public class SearchTransactionController {

    public static final String SEARCH_TRANSACTION_PAGE = "searchtransaction";

    private PaymentSearchService searchService;
    //private Validator searchCriteriaValidator;
    private UserRequestAuditTrail notifications;

    @Autowired
    public void setSearchService(PaymentSearchService searchService) {
        this.searchService = searchService;
    }

    @Autowired
    public void setNotifications(UserRequestAuditTrail notifications) {
        this.notifications = notifications;
    }

    @RequestMapping(value="/" + SEARCH_TRANSACTION_PAGE)
    public String setUpTransactionSearch(Model model) {
        SearchCriteria searchCriteria = new SearchCriteria();
        model.addAttribute("searchCriteria", searchCriteria);
        notifications.transferTo(SEARCH_TRANSACTION_PAGE);
        return SEARCH_TRANSACTION_PAGE;
    }

    @RequestMapping(value="/" + SEARCH_TRANSACTION_PAGE, method=RequestMethod.POST, params="cancel")
    public String cancelSearch() {
        notifications.redirectTo(HomeController.HOME_PAGE);
        return "redirect:/" + HomeController.HOME_PAGE;
    }

    @RequestMapping(value="/" + SEARCH_TRANSACTION_PAGE, method=RequestMethod.POST, params="execute")
    public String executeSearch(
            @ModelAttribute("searchCriteria") @Valid SearchCriteria searchCriteria,
            BindingResult result, Model model,
            SessionStatus status) {
        //searchCriteriaValidator.validate(criteria, result);
        if (result.hasErrors()) {
            notifications.transferTo(SEARCH_TRANSACTION_PAGE);
            return SEARCH_TRANSACTION_PAGE;
        } else {
            PaymentDetail payment = 
                searchService.getAuthorizationFor(searchCriteria.geteWiseTransactionId());
            if (payment == null) {
                ObjectError error = new ObjectError(
                        "eWiseTransactionId", "Transaction not found");
                result.addError(error);
                model.addAttribute("searchCriteria", searchCriteria);
                notifications.transferTo(SEARCH_TRANSACTION_PAGE);
                return SEARCH_TRANSACTION_PAGE;
            } else {
                model.addAttribute("authorization", payment);
                notifications.redirectTo(PaymentDetailController.PAYMENT_DETAIL_PAGE);
                return "redirect:/" + PaymentDetailController.PAYMENT_DETAIL_PAGE;
            }
        }
    }

}

Next, the test:

    package test.unit.com.company.admin.web;

    import static org.hamcrest.Matchers.containsString;
    import static org.hamcrest.Matchers.equalTo;
    import static org.junit.Assert.assertThat;

    import org.jmock.Expectations;
    import org.jmock.Mockery;
    import org.jmock.integration.junit4.JMock;
    import org.jmock.integration.junit4.JUnit4Mockery;
    import org.junit.Before;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.ui.Model;
    import org.springframework.validation.BindingResult;
    import org.springframework.validation.ObjectError;
    import org.springframework.web.bind.support.SessionStatus;

    import com.company.admin.domain.PaymentDetail;
    import com.company.admin.service.PaymentSearchService;
    import com.company.admin.service.UserRequestAuditTrail;
    import com.company.admin.web.HomeController;
    import com.company.admin.web.PaymentDetailController;
    import com.company.admin.web.SearchTransactionController;
    import com.company.admin.web.form.SearchCriteria;

    /**
     * Tests the behavior of the SearchTransactionController.
     * @author slgelma
     *
     */
    @RunWith(JMock.class)
    public class SearchTransactionControllerTest {

        private final Mockery context = new JUnit4Mockery(); 
        private final SearchTransactionController controller = new SearchTransactionController();
        private final PaymentSearchService searchService = context.mock(PaymentSearchService.class);
        private final UserRequestAuditTrail notifications = context.mock(UserRequestAuditTrail.class);
        private final Model model = context.mock(Model.class);


        /**
         * @throws java.lang.Exception
         */
        @Before
        public void setUp() throws Exception {
            controller.setSearchService(searchService);
            controller.setNotifications(notifications);
        }

        @Test
        public void setUpTheSearchForm() {

            final String target = SearchTransactionController.SEARCH_TRANSACTION_PAGE;

            context.checking(new Expectations() {{
                oneOf(model).addAttribute(
                        with(any(String.class)), with(any(Object.class)));
                oneOf(notifications).transferTo(with(any(String.class)));
            }});

            String nextPage = controller.setUpTransactionSearch(model);
            assertThat("Controller is not requesting the correct form", 
                    target, equalTo(nextPage));
        }

        @Test
        public void cancelSearchTest() {

            final String target = HomeController.HOME_PAGE;

            context.checking(new Expectations(){{
                never(model).addAttribute(with(any(String.class)), with(any(Object.class)));
                oneOf(notifications).redirectTo(with(any(String.class)));
            }});

            String nextPage = controller.cancelSearch();
            assertThat("Controller is not requesting the correct form", 
                    nextPage, containsString(target));
        }

        @Test
        public void executeSearchWithNullTransaction() {

            final String target = SearchTransactionController.SEARCH_TRANSACTION_PAGE;

            final SearchCriteria searchCriteria = new SearchCriteria();
            searchCriteria.seteWiseTransactionId(null);

            final BindingResult result = context.mock(BindingResult.class);
            final SessionStatus status = context.mock(SessionStatus.class);

            context.checking(new Expectations() {{
                allowing(result).hasErrors(); will(returnValue(true));
                never(model).addAttribute(with(any(String.class)), with(any(Object.class)));
                never(searchService).getAuthorizationFor(searchCriteria.geteWiseTransactionId());
                oneOf(notifications).transferTo(with(any(String.class)));
            }});

            String nextPage = controller.executeSearch(searchCriteria, result, model, status);
            assertThat("Controller is not requesting the correct form", 
                    target, equalTo(nextPage));
        }

        @Test
        public void executeSearchWithEmptyTransaction() {

            final String target = SearchTransactionController.SEARCH_TRANSACTION_PAGE;

            final SearchCriteria searchCriteria = new SearchCriteria();
            searchCriteria.seteWiseTransactionId("");

            final BindingResult result = context.mock(BindingResult.class);
            final SessionStatus status = context.mock(SessionStatus.class);

            context.checking(new Expectations() {{
                allowing(result).hasErrors(); will(returnValue(true));
                never(model).addAttribute(with(any(String.class)), with(any(Object.class)));
                never(searchService).getAuthorizationFor(searchCriteria.geteWiseTransactionId());
                oneOf(notifications).transferTo(with(any(String.class)));
            }});

            String nextPage = controller.executeSearch(searchCriteria, result, model, status);
            assertThat("Controller is not requesting the correct form", 
                    target, equalTo(nextPage));
        }

        @Test
        public void executeSearchWithTransactionNotFound() {

            final String target = SearchTransactionController.SEARCH_TRANSACTION_PAGE;
            final String badTransactionId = "badboy"; 
            final PaymentDetail transactionNotFound = null;

            final SearchCriteria searchCriteria = new SearchCriteria();
            searchCriteria.seteWiseTransactionId(badTransactionId);

            final BindingResult result = context.mock(BindingResult.class);
            final SessionStatus status = context.mock(SessionStatus.class);

            context.checking(new Expectations() {{
                allowing(result).hasErrors(); will(returnValue(false));
                atLeast(1).of(model).addAttribute(with(any(String.class)), with(any(Object.class)));
                oneOf(searchService).getAuthorizationFor(with(any(String.class)));
                    will(returnValue(transactionNotFound));
                oneOf(result).addError(with(any(ObjectError.class)));
                oneOf(notifications).transferTo(with(any(String.class)));
            }});

            String nextPage = controller.executeSearch(searchCriteria, result, model, status);
            assertThat("Controller is not requesting the correct form", 
                    target, equalTo(nextPage));
        }

        @Test
        public void executeSearchWithTransactionFound() {

            final String target = PaymentDetailController.PAYMENT_DETAIL_PAGE;
            final String goodTransactionId = "100000010";
            final PaymentDetail transactionFound = context.mock(PaymentDetail.class);

            final SearchCriteria searchCriteria = new SearchCriteria();
            searchCriteria.seteWiseTransactionId(goodTransactionId);

            final BindingResult result = context.mock(BindingResult.class);
            final SessionStatus status = context.mock(SessionStatus.class);

            context.checking(new Expectations() {{
                allowing(result).hasErrors(); will(returnValue(false));
                atLeast(1).of(model).addAttribute(with(any(String.class)), with(any(Object.class)));
                oneOf(searchService).getAuthorizationFor(with(any(String.class)));
                    will(returnValue(transactionFound));
                oneOf(notifications).redirectTo(with(any(String.class)));
            }});

            String nextPage = controller.executeSearch(searchCriteria, result, model, status);
            assertThat("Controller is not requesting the correct form", 
                    nextPage, containsString(target));
        }

    }

I hope this might help.

How to measure time taken between lines of code in python?

I was looking for a way how to output a formatted time with minimal code, so here is my solution. Many people use Pandas anyway, so in some cases this can save from additional library imports.

import pandas as pd
start = pd.Timestamp.now()
# code
print(pd.Timestamp.now()-start)

Output:

0 days 00:05:32.541600

I would recommend using this if time precision is not the most important, otherwise use time library:

%timeit pd.Timestamp.now() outputs 3.29 µs ± 214 ns per loop

%timeit time.time() outputs 154 ns ± 13.3 ns per loop

Get min and max value in PHP Array

How about without using predefined function like min or max ?

$arr = [4,5,6,7,8,2,9,1];
$val = $arr[0];
$n = count($arr);

for($i=1;$i<$n;$i++) {
if($val<$arr[$i]) {
    $val = $val;        
} else {
    $val = $arr[$i];
}
}
print($val);

?>

jQuery and TinyMCE: textarea value doesn't submit

I used:

var save_and_add = function(){
    tinyMCE.triggerSave();
    $('.new_multi_text_block_item').submit();
};

This is all you need to do.

Received fatal alert: handshake_failure through SSLHandshakeException

I meet the same problem today with OkHttp client to GET a https based url. It was caused by Https protocol version and Cipher method mismatch between server side and client side.

1) check your website https Protocol version and Cipher method.

openssl>s_client -connect your_website.com:443 -showcerts

You will get many detail info, the key info is listed as follows:

SSL-Session:
    Protocol  : TLSv1
    Cipher    : RC4-SHA
2) config your http client, for example, in OkHttp client case:
@Test()
public void testHttpsByOkHttp() {
    ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
            .tlsVersions(TlsVersion.TLS_1_0) //protocol version
            .cipherSuites(
                    CipherSuite.TLS_RSA_WITH_RC4_128_SHA, //cipher method
                    CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
                    CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
                    CipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256)
            .build();

    OkHttpClient client = new OkHttpClient();
    client.setConnectionSpecs(Collections.singletonList(spec));
    Request request = new Request.Builder().url("https://your_website.com/").build();
    try {
        Response response = client.newCall(request).execute();
        if(response.isSuccessful()){
            logger.debug("result= {}", response.body().string());
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

This will get what we want.

Compare two folders which has many files inside contents

diff -r will do this, telling you both if any files have been added or deleted, and what's changed in the files that have been modified.

Insert string in beginning of another string

Other answers explain how to insert a string at the beginning of another String or StringBuilder (or StringBuffer).

However, strictly speaking, you cannot insert a string into the beginning of another one. Strings in Java are immutable1.

When you write:

String s = "Jam";
s = "Hello " + s;

you are actually causing a new String object to be created that is the concatenation of "Hello " and "Jam". You are not actually inserting characters into an existing String object at all.


1 - It is technically possible to use reflection to break abstraction on String objects and mutate them ... even though they are immutable by design. But it is a really bad idea to do this. Unless you know that a String object was created explicitly via new String(...) it could be shared, or it could share internal state with other String objects. Finally, the JVM spec clearly states that the behavior of code that uses reflection to change a final is undefined. Mutation of String objects is dangerous.

Differences between time complexity and space complexity?

Yes, this is definitely possible. For example, sorting n real numbers requires O(n) space, but O(n log n) time. It is true that space complexity is always a lowerbound on time complexity, as the time to initialize the space is included in the running time.

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

SLF4j is an abstraction for various logging frameworks. Hence apart from having slf4j you need to include any of your logging framework like log4j or logback (etc) in your classpath.
To have an idea refer the First Baby Step in http://logback.qos.ch/manual/introduction.html

How can I right-align text in a DataGridView column?

<DataGridTextColumn Header="Quantity" Binding="{Binding Quantity}" >
  <DataGridTextColumn.ElementStyle>
    <Style TargetType="{x:Type TextBlock}">
       <Setter Property="HorizontalAlignment" Value="Right" />
    </Style>
  </DataGridTextColumn.ElementStyle>
</DataGridTextColumn>

add title attribute from css

You can't. CSS is a presentation language. It isn't designed to add content (except for the very trivial with :before and :after).

Pandas index column title or name

The solution for multi-indexes is inside jezrael's cyclopedic answer, but it took me a while to find it so I am posting a new answer:

df.index.names gives the names of a multi-index (as a Frozenlist).

get an element's id

You need to check if is a string to avoid getting a child element

var getIdFromDomObj = function(domObj){
   var id = domObj.id;
   return typeof id  === 'string' ? id : false;
};

Insert ellipsis (...) into HTML tag if content too wide

Just in case y'all end up here in 2013 - here is a pure css approach I found here: http://css-tricks.com/snippets/css/truncate-string-with-ellipsis/

.truncate {
  width: 250px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

It works well.

How to change the scrollbar color using css

Your css will only work in IE browser. And the css suggessted by hayk.mart will olny work in webkit browsers. And by using different css hacks you can't style your browsers scroll bars with a same result.

So, it is better to use a jQuery/Javascript plugin to achieve a cross browser solution with a same result.

Solution:

By Using jScrollPane a jQuery plugin, you can achieve a cross browser solution

See This Demo

SELECT where row value contains string MySQL

SELECT * FROM Accounts WHERE Username LIKE '%$query%'

but it's not suggested. use PDO

Implement division with bit-wise operator

I assume we are discussing division of integers.

Consider that I got two number 1502 and 30, and I wanted to calculate 1502/30. This is how we do this:

First we align 30 with 1501 at its most significant figure; 30 becomes 3000. And compare 1501 with 3000, 1501 contains 0 of 3000. Then we compare 1501 with 300, it contains 5 of 300, then compare (1501-5*300) with 30. At so at last we got 5*(10^1) = 50 as the result of this division.

Now convert both 1501 and 30 into binary digits. Then instead of multiplying 30 with (10^x) to align it with 1501, we multiplying (30) in 2 base with 2^n to align. And 2^n can be converted into left shift n positions.

Here is the code:

int divide(int a, int b){
    if (b != 0)
        return;

    //To check if a or b are negative.
    bool neg = false;
    if ((a>0 && b<0)||(a<0 && b>0))
        neg = true;

    //Convert to positive
    unsigned int new_a = (a < 0) ? -a : a;
    unsigned int new_b = (b < 0) ? -b : b;

    //Check the largest n such that b >= 2^n, and assign the n to n_pwr
    int n_pwr = 0;
    for (int i = 0; i < 32; i++)
    {
        if (((1 << i) & new_b) != 0)
            n_pwr = i;
    }

    //So that 'a' could only contain 2^(31-n_pwr) many b's,
    //start from here to try the result
    unsigned int res = 0;
    for (int i = 31 - n_pwr; i >= 0; i--){
        if ((new_b << i) <= new_a){
            res += (1 << i);
            new_a -= (new_b << i);
        }
    }

    return neg ? -res : res;
}

Didn't test it, but you get the idea.

Remove or adapt border of frame of legend using matplotlib

When plotting a plot using matplotlib:

How to remove the box of the legend?

plt.legend(frameon=False)

How to change the color of the border of the legend box?

leg = plt.legend()
leg.get_frame().set_edgecolor('b')

How to remove only the border of the box of the legend?

leg = plt.legend()
leg.get_frame().set_linewidth(0.0)

How to retrieve the LoaderException property?

Using Quick Watch in Visual Studio you can access the LoaderExceptions from ViewDetails of the thrown exception like this:

($exception).LoaderExceptions

Why is Git better than Subversion?

Easy Git has a nice page comparing actual usage of Git and SVN which will give you an idea of what things Git can do (or do more easily) compared to SVN. (Technically, this is based on Easy Git, which is a lightweight wrapper on top of Git.)

Convert tabs to spaces in Notepad++

I did not read all of the answers, but I did not find the answer I was looking for.

I use Python and don't want to do find/replace or 'blank operations' each time I want to compile code...

So the best solution for me is that it happens on the fly!

Here is the simple solution I found:

Go to:

  1. Menu Settings -> Preferences
  2. Choose Tab Settings
  3. Choose your language type (e.g. Python)
  4. Select checkbox 'Use default value'
  5. Select checkbox 'Replace by space'

Enter image description here

How to set up file permissions for Laravel?

Add to composer.json

"scripts": {
    "post-install-cmd": [
      "chgrp -R www-data storage bootstrap/cache",
      "chmod -R ug+rwx storage bootstrap/cache"
    ]
}

After composer install

jQuery AJAX form data serialize using PHP

Try this

 $(document).ready(function(){
    var form=$("#myForm");
    $("#smt").click(function(){
    $.ajax({
            type:"POST",
            url:form.attr("action"),
            data:$("#myForm input").serialize(),//only input
            success: function(response){
                console.log(response);  
            }
        });
    });
    });

javac option to compile all java files under a given directory recursively

If your shell supports it, would something like this work ?

javac com/**/*.java 

If your shell does not support **, then maybe

javac com/*/*/*.java

works (for all packages with 3 components - adapt for more or less).

Length of array in function argument

First, a better usage to compute number of elements when the actual array declaration is in scope is:

sizeof array / sizeof array[0]

This way you don't repeat the type name, which of course could change in the declaration and make you end up with an incorrect length computation. This is a typical case of don't repeat yourself.

Second, as a minor point, please note that sizeof is not a function, so the expression above doesn't need any parenthesis around the argument to sizeof.

Third, C doesn't have references so your usage of & in a declaration won't work.

I agree that the proper C solution is to pass the length (using the size_t type) as a separate argument, and use sizeof at the place the call is being made if the argument is a "real" array.

Note that often you work with memory returned by e.g. malloc(), and in those cases you never have a "true" array to compute the size off of, so designing the function to use an element count is more flexible.

json and empty array

"location" : null // this is not really an array it's a null object
"location" : []   // this is an empty array

It looks like this API returns null when there is no location defined - instead of returning an empty array, not too unusual really - but they should tell you if they're going to do this.

Should a 502 HTTP status code be used if a proxy receives no response at all?

Yes. Empty or incomplete headers or response body typically caused by broken connections or server side crash can cause 502 errors if accessed via a gateway or proxy.

For more information about the network errors

https://en.wikipedia.org/wiki/List_of_HTTP_status_codes

How do I change the background color with JavaScript?

AJAX is getting data from the server using Javascript and XML in an asynchronous fashion. Unless you want to download the colour code from the server, that's not what you're really aiming for!

But otherwise you can set the CSS background with Javascript. If you're using a framework like jQuery, it'll be something like this:

$('body').css('background', '#ccc');

Otherwise, this should work:

document.body.style.background = "#ccc";

How do I handle the window close event in Tkinter?

i say a lot simpler way would be using the break command, like

import tkinter as tk
win=tk.Tk
def exit():
    break
btn= tk.Button(win, text="press to exit", command=exit)
win.mainloop()

OR use sys.exit()

import tkinter as tk
import sys
win=tk.Tk
def exit():
    sys.exit
btn= tk.Button(win, text="press to exit", command=exit)
win.mainloop()

How do I create a user account for basic authentication?

I know this is a really old question but I wanted to add a bit of explanation that I discovered the hard way (this is n00b information).

"Basic Authentication" shares the same accounts that you have on your local computer or network. If you leave the domain and realm empty, local accounts are what are actually being used. So to add a new account you follow the exact process you would for adding a normal new user account to your local computer (as answered by JoshM or shown here). If you enter a domain and realm you can create network accounts in your local active directory and these are what will be used to log the user in and out.

Because it has been around for so long, basic authentication is generally compatible with any browser/system out there but it does have to major flaws:

  • user and password are sent in the clear (except over SSL)
  • you need to have a user account for each user or client

For more information about basic authentication or user accounts see the following MSDN page.

Normalizing a list of numbers in Python

How long is the list you're going to normalize?

def psum(it):
    "This function makes explicit how many calls to sum() are done."
    print "Another call!"
    return sum(it)

raw = [0.07,0.14,0.07]
print "How many calls to sum()?"
print [ r/psum(raw) for r in raw]

print "\nAnd now?"
s = psum(raw)
print [ r/s for r in raw]

# if one doesn't want auxiliary variables, it can be done inside
# a list comprehension, but in my opinion it's quite Baroque    
print "\nAnd now?"
print [ r/s  for s in [psum(raw)] for r in raw]

Output

# How many calls to sum()?
# Another call!
# Another call!
# Another call!
# [0.25, 0.5, 0.25]
# 
# And now?
# Another call!
# [0.25, 0.5, 0.25]
# 
# And now?
# Another call!
# [0.25, 0.5, 0.25]

Selecting only numeric columns from a data frame

The library PCAmixdata has functon splitmix that splits quantitative(Numerical data) and qualitative (Categorical data) of a given dataframe "YourDataframe" as shown below:

install.packages("PCAmixdata")
library(PCAmixdata)
split <- splitmix(YourDataframe)
X1 <- split$X.quanti(Gives numerical columns in the dataset) 
X2 <- split$X.quali (Gives categorical columns in the dataset)

How to make a shape with left-top round rounded corner and left-bottom rounded corner?

This bug is filed here. This is a bug of android devices having API level less than 12. You've to put correct versions of your layouts in drawable-v12 folder which will be used for API level 12 or higher. And an erroneous version(corners switched/reversed) of the same layout will be put in the default drawable folder which will be used by the devices having API level less than 12.

For example: I had to design a button with rounded corner at bottom-right.

In 'drawable' folder - button.xml: I had to make bottom-left corner rounded.

<shape>
    <corners android:bottomLeftRadius="15dp"/>
</shape>

In 'drawable-v12' folder - button.xml: Correct version of the layout was placed here to be used for API level 12 or higher.

<shape>
    <corners android:bottomLeftRadius="15dp"/>
</shape>

What are -moz- and -webkit-?

These are the vendor-prefixed properties offered by the relevant rendering engines (-webkit for Chrome, Safari; -moz for Firefox, -o for Opera, -ms for Internet Explorer). Typically they're used to implement new, or proprietary CSS features, prior to final clarification/definition by the W3.

This allows properties to be set specific to each individual browser/rendering engine in order for inconsistencies between implementations to be safely accounted for. The prefixes will, over time, be removed (at least in theory) as the unprefixed, the final version, of the property is implemented in that browser.

To that end it's usually considered good practice to specify the vendor-prefixed version first and then the non-prefixed version, in order that the non-prefixed property will override the vendor-prefixed property-settings once it's implemented; for example:

.elementClass {
    -moz-border-radius: 2em;
    -ms-border-radius: 2em;
    -o-border-radius: 2em;
    -webkit-border-radius: 2em;
    border-radius: 2em;
}

Specifically, to address the CSS in your question, the lines you quote:

-webkit-column-count: 3;
-webkit-column-gap: 10px;
-webkit-column-fill: auto;
-moz-column-count: 3;
-moz-column-gap: 10px;
-moz-column-fill: auto;

Specify the column-count, column-gap and column-fill properties for Webkit browsers and Firefox.

References:

DataGrid get selected rows' column values

Solution based on Tonys answer:

        DataGrid dg = sender as DataGrid;
        User row = (User)dg.SelectedItems[0];
        Console.WriteLine(row.UserID);

Pip install Matplotlib error with virtualenv

To reduce the required packages to install you just need

apt-get install -y \
    libfreetype6-dev \
    libxft-dev && \
    pip install matplotlib

and you will get the following packages locally installed

Collecting matplotlib
  Downloading matplotlib-2.2.0-cp35-cp35m-manylinux1_x86_64.whl (12.5MB)
Collecting pytz (from matplotlib)
  Downloading pytz-2018.3-py2.py3-none-any.whl (509kB)
Collecting python-dateutil>=2.1 (from matplotlib)
  Downloading python_dateutil-2.6.1-py2.py3-none-any.whl (194kB)
Collecting pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 (from matplotlib)
  Downloading pyparsing-2.2.0-py2.py3-none-any.whl (56kB)
Requirement already satisfied: six>=1.10 in /opt/conda/envs/pytorch-py35/lib/python3.5/site-packages (from matplotlib)
Collecting cycler>=0.10 (from matplotlib)
  Downloading cycler-0.10.0-py2.py3-none-any.whl
Collecting kiwisolver>=1.0.1 (from matplotlib)
  Downloading kiwisolver-1.0.1-cp35-cp35m-manylinux1_x86_64.whl (949kB)
Requirement already satisfied: numpy>=1.7.1 in /opt/conda/envs/pytorch-py35/lib/python3.5/site-packages (from matplotlib)
Requirement already satisfied: setuptools in /opt/conda/envs/pytorch-py35/lib/python3.5/site-packages/setuptools-27.2.0-py3.5.egg (from kiwisolver>=1.0.1->matplotlib)
Installing collected packages: pytz, python-dateutil, pyparsing, cycler, kiwisolver, matplotlib
Successfully installed cycler-0.10.0 kiwisolver-1.0.1 matplotlib-2.2.0 pyparsing-2.2.0 python-dateutil-2.6.1 pytz-2018.3

Display PNG image as response to jQuery AJAX request

You'll need to send the image back base64 encoded, look at this: http://php.net/manual/en/function.base64-encode.php

Then in your ajax call change the success function to this:

$('.div_imagetranscrits').html('<img src="data:image/png;base64,' + data + '" />');

Delayed rendering of React components

Depends on your use case.

If you want to do some animation of children blending in, use the react animation add-on: https://facebook.github.io/react/docs/animation.html Otherwise, make the rendering of the children dependent on props and add the props after some delay.

I wouldn't delay in the component, because it will probably haunt you during testing. And ideally, components should be pure.

How to get twitter bootstrap modal to close (after initial launch)

Add the class hide to the modal

<!-- Modal Demo -->
<div class="modal hide" id ="myModal" aria-hidden="true" >

Javascript Code

 <!-- Use this to hide the modal necessary for loading and closing the modal-->
 <script>
     $(function(){
         $('#closeModal').click(function(){
              $('#myModal').modal('hide');
          });
      });
 </script>

 <!-- Use this to load the modal necessary for loading and closing the modal-->
 <script>
     $(function () {
         $('#myModal').modal('show');
     });
  </script>

How to split a string, but also keep the delimiters?

Fast answer: use non physical bounds like \b to split. I will try and experiment to see if it works (used that in PHP and JS).

It is possible, and kind of work, but might split too much. Actually, it depends on the string you want to split and the result you need. Give more details, we will help you better.

Another way is to do your own split, capturing the delimiter (supposing it is variable) and adding it afterward to the result.

My quick test:

String str = "'ab','cd','eg'";
String[] stra = str.split("\\b");
for (String s : stra) System.out.print(s + "|");
System.out.println();

Result:

'|ab|','|cd|','|eg|'|

A bit too much... :-)

php error: Class 'Imagick' not found

For all to those having problems with this i did this tutorial:

How to install Imagemagick and Php module Imagick on ubuntu?

i did this 7 simple steps:

Update libraries, and packages

apt-get update

Remove obsolete things

apt-get autoremove

For the libraries of ImageMagick

apt-get install libmagickwand-dev

for the core class Imagick

apt-get install imagemagick

For create the binaries, and conections in beetween

pecl install imagick

Append the extension to your php.ini

echo "extension=imagick.so" >> /etc/php5/apache2/php.ini

Restart Apache

service apache2 restart

I found a problem. PHP searches for .so files in a folder called /usr/lib/php5/20100525, and the imagick.so is stored in a folder called /usr/lib/php5/20090626. So you have to copy the file to that folder.

How to get the onclick calling object?

I think the best way is to use currentTarget property instead of target property.

The currentTarget read-only property of the Event interface identifies the current target for the event, as the event traverses the DOM. It always refers to the element to which the event handler has been attached, as opposed to Event.target, which identifies the element on which the event occurred.


For example:

<a href="#"><span class="icon"></span> blah blah</a>

Javascript:

a.addEventListener('click', e => {
    e.currentTarget; // always returns "a" element
    e.target; // may return "a" or "span"
})

Shell script to set environment variables

You need to run the script as source or the shorthand .

source ./myscript.sh

or

. ./myscript.sh

This will run within the existing shell, ensuring any variables created or modified by the script will be available after the script completes.

Running the script just using the filename will execute the script in a separate subshell.

FlutterError: Unable to load asset

Encountered the same issue with a slightly different code. In my case, I was using a "assets" folder subdivided into sub-folders for assets (sprites, audio, UI).

My code was simply at first in pubspec.yaml- alternative would be to detail every single file.

flutter:

  assets:
    - assets

Indentation and flutter clean was not enough to fix it. The files in the sub-folders were not loading by flutter. It seems like flutter needs to be "taken by the hand" and not looking at sub-folders without explicitly asking it to look at them. This worked for me:

flutter:

  assets:
    - assets/sprites/
    - assets/audio/
    - assets/UI/

So I had to detail each folder and each sub-folder that contains assets (mp3, jpg, etc). Doing so made the app work and saved me tons of time as the only solution detailed above would require me to manually list 30+ assets while the code here is just a few lines and easier to maintain.

Escaping ampersand character in SQL string

In order to escape & you can try following ways:-

  1. set scan off
  2. set define off
  3. set escape on then replace & by/&
  4. replace & by &&

One of them should work atleast.

Additionally if you are using PL/SQL developer then there is & icon in bottom of sql window please go there and disable it. Note in older version this option is not present.

Also make sure set define off is written in very beginning of the script.

ETag vs Header Expires

Another summary:

You need to use both. ETags are a "server side" information. Expires are a "Client side" caching.

  • Use ETags except if you have a load-balanced server. They are safe and will let clients know they should get new versions of your server files every time you change something on your side.

  • Expires must be used with caution, as if you set a expiration date far in the future but want to change one of the files immediatelly (a JS file for instance), some users may not get the modified version until a long time!

Creating a chart in Excel that ignores #N/A or blank cells

just wanted to put my 2cents in about this issue...

I had a similar need where i was pulling data from another table via INDEX/MATCH, and it was difficult to distinguish between a real 0 value vs. a 0 value because of no match (for example for a column chart that shows the progress of values over the 12 months and where we are only in february but the rest of the months data is not available yet and the column chart still showed 0's everywhere for Mar to Dec)

What i ended up doing is create a new series and plot this new series on the graph as a line chart and then i hid the line chart by choosing not to display the line in the options and i put the data labels on top, the formula for the values for this new series was something like :

=IF(LEN([@[column1]])=0,NA(),[@[column1]])

I used LEN as a validation because ISEMPTY/ISBLANK didn't work because the result of the INDEX/MATCH always returned something other than a blank even though i had put a "" after the IFERROR...

On the line chart the error value NA() makes it so that the value isn't displayed ...so this worked out for me...

I guess it's a bit difficult to follow this procedure without pictures, but i hope it paints some kind of picture to allow you to use a workaround if you have a similar case like mine

Phone validation regex

Try this

\+?\(?([0-9]{3})\)?[-.]?\(?([0-9]{3})\)?[-.]?\(?([0-9]{4})\)?

It matches the following cases

  • +123-(456)-(7890)
  • +123.(456).(7890)
  • +(123).(456).(7890)
  • +(123)-(456)-(7890)
  • +123(456)(7890)
  • +(123)(456)(7890)
  • 123-(456)-(7890)
  • 123.(456).(7890)
  • (123).(456).(7890)
  • (123)-(456)-(7890)
  • 123(456)(7890)
  • (123)(456)(7890)

For further explanation on the pattern CLICKME

How to bind DataTable to Datagrid

I'd do it this way:

grid1.DataContext = dt.AsEnumerable().Where(x => x < 10).AsEnumerable().CopyToDataTable().AsDataView();

and do whatever query i want between the two AsEnumerable(). If you don't need space for query, you can just do directly this:

grid1.DataContext = dt.AsDataView();

Mysql: Select all data between two dates

IF YOU CAN AVOID IT.. DON'T DO IT

Databases aren't really designed for this, you are effectively trying to create data (albeit a list of dates) within a query.

For anyone who has an application layer above the DB query the simplest solution is to fill in the blank data there.

You'll more than likely be looping through the query results anyway and can implement something like this:

loop_date = start_date

while (loop_date <= end_date){

  if(loop_date in db_data) {
    output db_data for loop_date
  }
  else {
    output default_data for loop_date
  }

  loop_date = loop_date + 1 day
}

The benefits of this are reduced data transmission; simpler, easier to debug queries; and no worry of over-flowing the calendar table.

How do browser cookie domains work?

Although there is the RFC 2965 (Set-Cookie2, had already obsoleted RFC 2109) that should define the cookie nowadays, most browsers don’t fully support that but just comply to the original specification by Netscape.

There is a distinction between the Domain attribute value and the effective domain: the former is taken from the Set-Cookie header field and the latter is the interpretation of that attribute value. According to the RFC 2965, the following should apply:

  • If the Set-Cookie header field does not have a Domain attribute, the effective domain is the domain of the request.
  • If there is a Domain attribute present, its value will be used as effective domain (if the value does not start with a . it will be added by the client).

Having the effective domain it must also domain-match the current requested domain for being set; otherwise the cookie will be revised. The same rule applies for choosing the cookies to be sent in a request.


Mapping this knowledge onto your questions, the following should apply:

  • Cookie with Domain=.example.com will be available for www.example.com
  • Cookie with Domain=.example.com will be available for example.com
  • Cookie with Domain=example.com will be converted to .example.com and thus will also be available for www.example.com
  • Cookie with Domain=example.com will not be available for anotherexample.com
  • www.example.com will be able to set cookie for example.com
  • www.example.com will not be able to set cookie for www2.example.com
  • www.example.com will not be able to set cookie for .com

And to set and read a cookie for/by www.example.com and example.com, set it for .www.example.com and .example.com respectively. But the first (.www.example.com) will only be accessible for other domains below that domain (e.g. foo.www.example.com or bar.www.example.com) where .example.com can also be accessed by any other domain below example.com (e.g. foo.example.com or bar.example.com).

Android Canvas: drawing too large bitmap

I also had this issue when i was trying to add a splash screen to the android app through the launch_backgrgound.xml . the issue was the resolution. it was too high so the images memory footprint exploded and caused the app to crash hence the reason for this error. so just resize your image using a site called nativescript image builder so i got the ldpi,mdpi and all the rest and it worked fine for me.

Where is adb.exe in windows 10 located?

Open a cmd window and type where adb.exe

For me

D:\android-sdk_r24.4.1-windows\android-sdk-windows\platform-tools\adb.exe

Reading in double values with scanf in c

Use the %lf format specifier to read a double:

double a;
scanf("%lf",&a);

Wikipedia has a decent reference for available format specifiers.

You'll need to use the %lf format specifier to print out the results as well:

printf("%lf %lf",a,b);

Python speed testing - Time Difference - milliseconds

Here is a custom function that mimic's Matlab's/Octave's tic toc functions.

Example of use:

time_var = time_me(); # get a variable with the current timestamp

... run operation ...

time_me(time_var); # print the time difference (e.g. '5 seconds 821.12314 ms')

Function :

def time_me(*arg):
    if len(arg) != 0: 
        elapsedTime = time.time() - arg[0];
        #print(elapsedTime);
        hours = math.floor(elapsedTime / (60*60))
        elapsedTime = elapsedTime - hours * (60*60);
        minutes = math.floor(elapsedTime / 60)
        elapsedTime = elapsedTime - minutes * (60);
        seconds = math.floor(elapsedTime);
        elapsedTime = elapsedTime - seconds;
        ms = elapsedTime * 1000;
        if(hours != 0):
            print ("%d hours %d minutes %d seconds" % (hours, minutes, seconds)) 
        elif(minutes != 0):
            print ("%d minutes %d seconds" % (minutes, seconds))
        else :
            print ("%d seconds %f ms" % (seconds, ms))
    else:
        #print ('does not exist. here you go.');
        return time.time()

create unique id with javascript

    const generateUniqueId = () => 'id_' + Date.now() + String(Math.random()).substr(2);

    // if u want to check for collision
    const arr = [];
    const checkForCollision = () => {
      for (let i = 0; i < 10000; i++) {
        const el = generateUniqueId();
        if (arr.indexOf(el) > -1) {
          alert('COLLISION FOUND');
        }
        arr.push(el);
      }
    };

Allow user to select camera or gallery for image

As per David Manpearl answer
https://stackoverflow.com/a/12347567/7226732

we just need to modify onActivityResult() like

 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        if (requestCode == YOUR_SELECT_PICTURE_REQUEST_CODE) {
            final boolean isCamera;
            if (data.getExtras() == null) {
                isCamera = true;
            } else {
                final String action = data.getAction();
                if (action == null) {
                    isCamera = false;
                } else {
                    isCamera = action.equals(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                }
            }
            Uri selectedImageUri;
            if (isCamera) {
                selectedImageUri = fileUri;
                try {
                    Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImageUri);
                    Toast.makeText(CreateWaterType.this, "Image Saved!", Toast.LENGTH_SHORT).show();
                    image_view.setImageBitmap(bitmap);

                } catch (IOException e) {
                    e.printStackTrace();
                    Toast.makeText(CreateWaterType.this, "Failed!", Toast.LENGTH_SHORT).show();
                }

            } else {
                selectedImageUri = data == null ? null : data.getData();
                try {
                    Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImageUri);

                    Toast.makeText(CreateWaterType.this, "Image Saved!", Toast.LENGTH_SHORT).show();
                    image_view.setImageBitmap(bitmap);

                } catch (IOException e) {
                    e.printStackTrace();
                    Toast.makeText(CreateWaterType.this, "Failed!", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }
}

and set the capture or pick images in image view.

Counting null and non-null values in a single query

Here are two solutions:

Select count(columnname) as countofNotNulls, count(isnull(columnname,1))-count(columnname) AS Countofnulls from table name

OR

Select count(columnname) as countofNotNulls, count(*)-count(columnname) AS Countofnulls from table name

When should I use semicolons in SQL Server?

Personal opinion: Use them only where they are required. (See TheTXI's answer above for the required list.)

Since the compiler doesn't require them, you can put them all over, but why? The compiler won't tell you where you forgot one, so you'll end up with inconsistent use.

[This opinion is specific to SQL Server. Other databases may have more-stringent requirements. If you're writing SQL to run on multiple databases, your requirements may vary.]

tpdi stated above, "in a script, as you're sending more than one statement, you need it." That's actually not correct. You don't need them.

PRINT 'Semicolons are optional'
PRINT 'Semicolons are optional'
PRINT 'Semicolons are optional';
PRINT 'Semicolons are optional';

Output:

Semicolons are optional
Semicolons are optional
Semicolons are optional
Semicolons are optional

How do I change the string representation of a Python class?

The closest equivalent to Java's toString is to implement __str__ for your class. Put this in your class definition:

def __str__(self):
     return "foo"

You may also want to implement __repr__ to aid in debugging.

See here for more information:

Use of "global" keyword in Python

Global makes the variable "Global"

def out():
    global x
    x = 1
    print(x)
    return


out()

print (x)

This makes 'x' act like a normal variable outside the function. If you took the global out then it would give an error since it cannot print a variable inside a function.

def out():
     # Taking out the global will give you an error since the variable x is no longer 'global' or in other words: accessible for other commands
    x = 1
    print(x)
    return


out()

print (x)

Import Package Error - Cannot Convert between Unicode and Non Unicode String Data Type

Not sure if this is a best practice with SSIS but sometimes I find their tools are a bit clunky when you want to do this type of activity.

Instead of using their components you can convert the data within your query

Instead of doing

SELECT myField = myNvarchar20Field
FROM myTable

You could do

SELECT myField = CONVERT(VARCHAR(20),myNvarchar20Field)
FROM myTable

Conditional replacement of values in a data.frame

The R-inferno, or the basic R-documentation will explain why using df$* is not the best approach here. From the help page for "[" :

"Indexing by [ is similar to atomic vectors and selects a list of the specified element(s). Both [[ and $ select a single element of the list. The main difference is that $ does not allow computed indices, whereas [[ does. x$name is equivalent to x[["name", exact = FALSE]]. Also, the partial matching behavior of [[ can be controlled using the exact argument. "

I recommend using the [row,col] notation instead. Example:

Rgames: foo   
         x    y z  
   [1,] 1e+00 1 0  
   [2,] 2e+00 2 0  
   [3,] 3e+00 1 0  
   [4,] 4e+00 2 0  
   [5,] 5e+00 1 0  
   [6,] 6e+00 2 0  
   [7,] 7e+00 1 0  
   [8,] 8e+00 2 0  
   [9,] 9e+00 1 0  
   [10,] 1e+01 2 0  
Rgames: foo<-as.data.frame(foo)

Rgames: foo[foo$y==2,3]<-foo[foo$y==2,1]
Rgames: foo
       x y     z
1  1e+00 1 0e+00
2  2e+00 2 2e+00
3  3e+00 1 0e+00
4  4e+00 2 4e+00
5  5e+00 1 0e+00
6  6e+00 2 6e+00
7  7e+00 1 0e+00
8  8e+00 2 8e+00
9  9e+00 1 0e+00
10 1e+01 2 1e+01

How do you convert between 12 hour time and 24 hour time in PHP?

// 24-hour time to 12-hour time 
$time_in_12_hour_format  = date("g:i a", strtotime("13:30"));

// 12-hour time to 24-hour time 
$time_in_24_hour_format  = date("H:i", strtotime("1:30 PM"));

Python: Find in list

If you want to find one element or None use default in next, it won't raise StopIteration if the item was not found in the list:

first_or_default = next((x for x in lst if ...), None)

How can I use jQuery to move a div across the screen

Just a quick little function I drummed up that moves DIVs from their current spot to a target spot, one pixel step at a time. I tried to comment as best as I could, but the part you're interested in, is in example 1 and example 2, right after [$(function() { // jquery document.ready]. Put your bounds checking code there, and then exit the interval if conditions are met. Requires jQuery.

First the Demo: http://jsfiddle.net/pnYWY/

First the DIVs...

<style>
  .moveDiv {
    position:absolute;
    left:20px;
    top:20px;
    width:10px;
    height:10px;
    background-color:#ccc;
  }

  .moveDivB {
    position:absolute;
    left:20px;
    top:20px;
    width:10px;
    height:10px;
    background-color:#ccc;
  }
</style>


<div class="moveDiv"></div>
<div class="moveDivB"></div>

example 1) Start

// first animation (fire right away)
var myVar = setInterval(function(){
    $(function() { // jquery document.ready

        // returns true if it just took a step
        // returns false if the div has arrived
        if( !move_div_step(55,25,'.moveDiv') )
        {
            // arrived...
            console.log('arrived'); 
            clearInterval(myVar);
        }

    });
},50); // set speed here in ms for your delay

example 2) Delayed Start

// pause and then fire an animation..
setTimeout(function(){
    var myVarB = setInterval(function(){
        $(function() { // jquery document.ready
            // returns true if it just took a step
            // returns false if the div has arrived
            if( !move_div_step(25,55,'.moveDivB') )
            {
                // arrived...
                console.log('arrived'); 
                clearInterval(myVarB);
            }
        });
    },50); // set speed here in ms for your delay
},5000);// set speed here for delay before firing

Now the Function:

function move_div_step(xx,yy,target) // takes one pixel step toward target
{
    // using a line algorithm to move a div one step toward a given coordinate.
    var div_target = $(target);

    // get current x and current y
    var x = div_target.position().left; // offset is relative to document; position() is relative to parent;
    var y = div_target.position().top;

    // if x and y are = to xx and yy (destination), then div has arrived at it's destination.
    if(x == xx && y == yy)
        return false;

    // find the distances travelled
    var dx = xx - x;
    var dy = yy - y;

    // preventing time travel
    if(dx < 0)          dx *= -1;
    if(dy < 0)          dy *= -1;

    // determine speed of pixel travel...
    var sx=1, sy=1;

    if(dx > dy)         sy = dy/dx;
    else if(dy > dx)    sx = dx/dy;

    // find our one...
    if(sx == sy) // both are one..
    {
        if(x <= xx) // are we going forwards?
        {
            x++; y++;
        }
        else  // .. we are going backwards.
        {
            x--; y--;
        }       
    }
    else if(sx > sy) // x is the 1
    {
        if(x <= xx) // are we going forwards..?
            x++;
        else  // or backwards?
            x--;

        y += sy;
    }
    else if(sy > sx) // y is the 1 (eg: for every 1 pixel step in the y dir, we take 0.xxx step in the x
    {
        if(y <= yy) // going forwards?
            y++;
        else  // .. or backwards?
            y--;

        x += sx;
    }

    // move the div
    div_target.css("left", x);
    div_target.css("top",  y);

    return true;
}  // END :: function move_div_step(xx,yy,target)

Remove all special characters, punctuation and spaces from string

Python 2.*

I think just filter(str.isalnum, string) works

In [20]: filter(str.isalnum, 'string with special chars like !,#$% etcs.')
Out[20]: 'stringwithspecialcharslikeetcs'

Python 3.*

In Python3, filter( ) function would return an itertable object (instead of string unlike in above). One has to join back to get a string from itertable:

''.join(filter(str.isalnum, string)) 

or to pass list in join use (not sure but can be fast a bit)

''.join([*filter(str.isalnum, string)])

note: unpacking in [*args] valid from Python >= 3.5

Change the color of a bullet in a html list?

You can use Jquery if you have lots of pages and don't need to go and edit the markup your self.

here is a simple example:

$("li").each(function(){
var content = $(this).html();
var myDiv = $("<div />")
myDiv.css("color", "red"); //color of text.
myDiv.html(content);
$(this).html(myDiv).css("color", "yellow"); //color of bullet
});

Assign command output to variable in batch file

A method has already been devised, however this way you don't need a temp file.

for /f "delims=" %%i in ('command') do set output=%%i

However, I'm sure this has its own exceptions and limitations.

How to add a ListView to a Column in Flutter?

Expanded Widget increases it’s size as much as it can with the space available Since ListView essentially has an infinite height it will cause an error.

 Column(
  children: <Widget>[
    Flexible(
      child: ListView(...),
    )
  ],
)

Here we should use Flexible widget as it will only take the space it required as Expanded take full screen even if there are not enough widgets to render on full screen.

How do I make a semi transparent background?

This is simple and sort. Use hsla css function like below

.transparent {
   background-color: hsla(0,0%,4%,.4);
}

JavaScript inside an <img title="<a href='#' onClick='alert('Hello World!')>The Link</a>" /> possible?

no, you can't do that, but you can use event handlers to change the title:

<img src="foo.jpg" onmouseover="this.title='it is now ' + new Date()" /> 

Hibernate dialect for Oracle Database 11g?

According to supported databases, Oracle 11g is not officially supported. Although, I believe you shouldn't have any problems using org.hibernate.dialect.OracleDialect.

Finding the path of the program that will execute from the command line in Windows

As the thread mentioned in the comment, get-command in powershell can also work it out. For example, you can type get-command npm and the output is as below:

enter image description here

How to get Java Decompiler / JD / JD-Eclipse running in Eclipse Helios

Steps to add the Java Decompiler in Eclipse :

  1. Open Eclipse IDE.
  2. Click Help->Eclipse Marketplace Wizard
  3. In Search tab find the JD (JD is keyword to get the Eclipse Class Decompiler)
  4. Select the Eclipse Class Decompiler
  5. Click on Install.
  6. Restart Eclipse and check

Force GUI update from UI Thread

I've just stumbled over the same problem and found some interesting information and I wanted to put in my two cents and add it here.

First of all, as others have already mentioned, long-running operations should be done by a thread, which can be a background worker, an explicit thread, a thread from the threadpool or (since .Net 4.0) a task: Stackoverflow 570537: update-label-while-processing-in-windows-forms, so that the UI keeps responsive.

But for short tasks there is no real need for threading although it doesn't hurt of course.

I have created a winform with one button and one label to analyze this problem:

System::Void button1_Click(System::Object^  sender, System::EventArgs^  e)
{
  label1->Text = "Start 1";
  label1->Update();
  System::Threading::Thread::Sleep(5000); // do other work
}

My analysis was stepping over the code (using F10) and seeing what happened. And after reading this article Multithreading in WinForms I have found something interesting. The article says at the bottom of the first page, that the UI thread can not repaint the UI until the currently executed function finishes and the window is marked by Windows as "not responding" instead after a while. I have also noticed that on my test application from above while stepping through it, but only in certain cases.

(For the following test it is important to not have Visual Studio set to fullscreen, you must be able to see your little application window at the same time next to it, You must not have to switch between the Visual Studio window for debugging and your application window to see what happens. Start the application, set a breakpoint at label1->Text ..., put the application window beside the VS window and place the mouse cursor over the VS window.)

  1. When I click once on VS after app start (to put the focues there and enable stepping) and step through it WITHOUT moving the mouse, the new text is set and the label is updated in the update() function. This means, the UI is repainted obviously.

  2. When I step over the first line, then move the mouse around a lot and click somewhere, then step further, the new text is likely set and the update() function is called, but the UI is not updated/repainted and the old text remains there until the button1_click() function finishes. Instead of repainting, the window is marked as "not responsive"! It also doesn't help to add this->Update(); to update the whole form.

  3. Adding Application::DoEvents(); gives the UI a chance to update/repaint. Anyway you have to take care that the user can not press buttons or perform other operations on the UI that are not permitted!! Therefore: Try to avoid DoEvents()!, better use threading (which I think is quite simple in .Net).
    But (@Jagd, Apr 2 '10 at 19:25) you can omit .refresh() and .invalidate().

My explanations is as following: AFAIK winform still uses the WINAPI function. Also MSDN article about System.Windows.Forms Control.Update method refers to WINAPI function WM_PAINT. The MSDN article about WM_PAINT states in its first sentence that the WM_PAINT command is only sent by the system when the message queue is empty. But as the message queue is already filled in the 2nd case, it is not send and thus the label and the application form are not repainted.

<>joke> Conclusion: so you just have to keep the user from using the mouse ;-) <>/joke>

How to unsubscribe to a broadcast event in angularJS. How to remove function registered via $on

Looking at most of the replies, they seem overly complicated. Angular has built in mechanisms to unregister.

Use the deregistration function returned by $on :

// Register and get a handle to the listener
var listener = $scope.$on('someMessage', function () {
    $log.log("Message received");
});

// Unregister
$scope.$on('$destroy', function () {
    $log.log("Unregistering listener");
    listener();
});

Annotation @Transactional. How to rollback?

Just throw any RuntimeException from a method marked as @Transactional.

By default all RuntimeExceptions rollback transaction whereas checked exceptions don't. This is an EJB legacy. You can configure this by using rollbackFor() and noRollbackFor() annotation parameters:

@Transactional(rollbackFor=Exception.class)

This will rollback transaction after throwing any exception.

The transaction log for the database is full

I had this error once and it ended up being the server's hard drive that run out of disk space.

Display the current time and date in an Android application

Try the below code:

SimpleDateFormat dateFormat = new SimpleDateFormat(
                                    "yyyy/MM/dd HH:mm:ss");

Calendar cal = Calendar.getInstance();
System.out.println("time => " + dateFormat.format(cal.getTime()));

String time_str = dateFormat.format(cal.getTime());

String[] s = time_str.split(" ");

for (int i = 0; i < s.length; i++) {
     System.out.println("date  => " + s[i]);
}

int year_sys = Integer.parseInt(s[0].split("/")[0]);
int month_sys = Integer.parseInt(s[0].split("/")[1]);
int day_sys = Integer.parseInt(s[0].split("/")[2]);

int hour_sys = Integer.parseInt(s[1].split(":")[0]);
int min_sys = Integer.parseInt(s[1].split(":")[1]);

System.out.println("year_sys  => " + year_sys);
System.out.println("month_sys  => " + month_sys);
System.out.println("day_sys  => " + day_sys);

System.out.println("hour_sys  => " + hour_sys);
System.out.println("min_sys  => " + min_sys);

Locate current file in IntelliJ

There is no direct shortcut for such operation in IntelliJ IDEA 14 but you can install the plugin and set it the keyboard shortcut to the function that called "Scroll From Source" in keymap settings.

enter image description here

In which conda environment is Jupyter executing?

I have tried every method mentioned above and nothing worked, except installing jupyter in the new environment.

to activate the new environment conda activate new_env replace 'new_env' with your environment name.

next install jupyter 'pip install jupyter'

you can also install jupyter by going to anaconda navigator and selecting the right environment, and installing jupyter notebook from Home tab

How do you create a Spring MVC project in Eclipse?

  1. step 1: create a new "Dynamic Web Project" in eclipse.
  2. step 2: right click on the created project.
  3. step 3: click on "configure" option.
  4. step 4: click on "convert to maven project".

here is more detailed information -> [1]: https://crunchify.com/simplest-spring-mvc-hello-world-example-tutorial-spring-model-view-controller-tips/

Set a path variable with spaces in the path in a Windows .cmd file or batch file

I always place the path in double quotes when I am creating a .bat file. (I just added the PAUSE so it wont close the screen.)

For example:

"C:\Program Files\PageTech\PCLReader64_131\PCLReader64.exe"
PAUSE

Finding moving average from data points in Python

There is a problem with the accepted answer. I think we need to use "valid" instead of "same" here - return numpy.convolve(interval, window, 'same') .

As an Example try out the MA of this data-set = [1,5,7,2,6,7,8,2,2,7,8,3,7,3,7,3,15,6] - the result should be [4.2,5.4,6.0,5.0,5.0,5.2,5.4,4.4,5.4,5.6,5.6,4.6,7.0,6.8], but having "same" gives us an incorrect output of [2.6,3.0,4.2,5.4,6.0,5.0,5.0,5.2,5.4,4.4,5.4,5.6,5.6, 4.6,7.0,6.8,6.2,4.8]

Rusty code to try this out -:

result=[]
dataset=[1,5,7,2,6,7,8,2,2,7,8,3,7,3,7,3,15,6]
window_size=5
for index in xrange(len(dataset)):
    if index <=len(dataset)-window_size :
        tmp=(dataset[index]+ dataset[index+1]+ dataset[index+2]+ dataset[index+3]+ dataset[index+4])/5.0
        result.append(tmp)
    else:
      pass

result==movingaverage(y, window_size) 

Try this with valid & same and see whether the math makes sense.

See also -: http://sentdex.com/sentiment-analysisbig-data-and-python-tutorials-algorithmic-trading/how-to-chart-stocks-and-forex-doing-your-own-financial-charting/calculate-simple-moving-average-sma-python/

npm ERR cb() never called

Try

sudo npm cache clean --force

More info refer: https://reactgo.com/npm-err-cb-never-called/

C++ STL Vectors: Get iterator from index?

Or you can use std::advance

vector<int>::iterator i = L.begin();
advance(i, 2);

Uncaught ReferenceError: <function> is not defined at HTMLButtonElement.onclick

Place your script inside the body tag

<body>
  // Rest of html
  <script>
  function hideButton() {
    $(".loading").hide();
  }
function showButton() {
  $(".loading").show();
}
</script> 
< /body>

If you check this JSFIDDLE and click on javascript, you will see the load Type body is selected

List all environment variables from the command line

As mentioned in other answers, you can use set to list all the environment variables or use

set [environment_variable] to get a specific variable with its value.

set [environment_variable]= can be used to remove a variable from the workspace.

Getting the length of two-dimensional array

use

   System.out.print( nir[0].length);

look at this for loop which print the content of the 2 dimension array the second loop iterate over the column in each row

for(int row =0 ; row < ntr.length; ++row)
 for(int column =0; column<ntr[row].length;++column)
    System.out.print(ntr[row][column]);

Count number of cells with any value (string or number) in a column in Google Docs Spreadsheet

The SUBTOTAL function can be used if you want to get the count respecting any filters you use on the page.

=SUBTOTAL(103, A1:A200)

will help you get count of non-empty rows, respecting filters.

103 - is similar to COUNTA, but ignores empty rows and also respects filters.

Reference : SUBTOTAL function

varbinary to string on SQL Server

For a VARBINARY(MAX) column, I had to use NVARCHAR(MAX):

cast(Content as nvarchar(max))

Or

CONVERT(NVARCHAR(MAX), Content, 0)
VARCHAR(MAX) didn't show the entire value

How to change the remote a branch is tracking?

git fetch origin
git checkout --track -b local_branch_name origin/branch_name

or

git fetch
git checkout -b local_branch_name origin/branch_name

How can I hash a password in Java?

You can use the Shiro library's (formerly JSecurity) implementation of what is described by OWASP.

It also looks like the JASYPT library has a similar utility.

How to move the layout up when the soft keyboard is shown android

Try this in the android manifest file corresponding to the activity.

<activity android:windowSoftInputMode="adjustPan"> </activity>

IOError: [Errno 22] invalid mode ('r') or filename: 'c:\\Python27\test.txt'

\t is a tab character. Use a raw string instead:

test_file=open(r'c:\Python27\test.txt','r')

or double the slashes:

test_file=open('c:\\Python27\\test.txt','r')

or use forward slashes instead:

test_file=open('c:/Python27/test.txt','r')

'Access denied for user 'root'@'localhost' (using password: NO)'

when trying to run this command i got the same error

sudo mysqladmin create asteriskcdrdba

i simply add a few lines to the code

-u root -p

and pressed the enter key. i then typed my password and hit enter. Linux liked my command as nothing more was displayed

so maybe try

sudo <your command here> -u <username> -p

after that hit enter and enter your password

Java - Change int to ascii

In fact in the last answer String strAsciiTab = Character.toString((char) iAsciiValue); the essential part is (char)iAsciiValue which is doing the job (Character.toString useless)

Meaning the first answer was correct actually char ch = (char) yourInt;

if in yourint=49 (or 0x31), ch will be '1'

File to byte[] in Java

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;

File file = getYourFile();
Path path = file.toPath();
byte[] data = Files.readAllBytes(path);

C: convert double to float, preserving decimal point precision

A float generally has about 7 digits of precision, regardless of the position of the decimal point. So if you want 5 digits of precision after the decimal, you'll need to limit the range of the numbers to less than somewhere around +/-100.

Fatal error in launcher: Unable to create process using ""C:\Program Files (x86)\Python33\python.exe" "C:\Program Files (x86)\Python33\pip.exe""

On Windows I had solved this problem in the following way :

1) uninstalled Python

2) navigated to C:\Users\MyName\AppData\Local\Programs(your should turn on hidden files visibility Show hidden files instruction)

3) deleted 'Python' folder

4) installed Python

Import CSV file with mixed data types

For the case when you know how many columns of data there will be in your CSV file, one simple call to textscan like Amro suggests will be your best solution.

However, if you don't know a priori how many columns are in your file, you can use a more general approach like I did in the following function. I first used the function fgetl to read each line of the file into a cell array. Then I used the function textscan to parse each line into separate strings using a predefined field delimiter and treating the integer fields as strings for now (they can be converted to numeric values later). Here is the resulting code, placed in a function read_mixed_csv:

function lineArray = read_mixed_csv(fileName, delimiter)

  fid = fopen(fileName, 'r');         % Open the file
  lineArray = cell(100, 1);           % Preallocate a cell array (ideally slightly
                                      %   larger than is needed)
  lineIndex = 1;                      % Index of cell to place the next line in
  nextLine = fgetl(fid);              % Read the first line from the file
  while ~isequal(nextLine, -1)        % Loop while not at the end of the file
    lineArray{lineIndex} = nextLine;  % Add the line to the cell array
    lineIndex = lineIndex+1;          % Increment the line index
    nextLine = fgetl(fid);            % Read the next line from the file
  end
  fclose(fid);                        % Close the file

  lineArray = lineArray(1:lineIndex-1);              % Remove empty cells, if needed
  for iLine = 1:lineIndex-1                          % Loop over lines
    lineData = textscan(lineArray{iLine}, '%s', ...  % Read strings
                        'Delimiter', delimiter);
    lineData = lineData{1};                          % Remove cell encapsulation
    if strcmp(lineArray{iLine}(end), delimiter)      % Account for when the line
      lineData{end+1} = '';                          %   ends with a delimiter
    end
    lineArray(iLine, 1:numel(lineData)) = lineData;  % Overwrite line data
  end

end

Running this function on the sample file content from the question gives this result:

>> data = read_mixed_csv('myfile.csv', ';')

data = 

  Columns 1 through 7

    '04'    'abc'    'def'    'ghj'    'klm'    ''            ''        
    ''      ''       ''       ''       ''       'Test'        'text'    
    ''      ''       ''       ''       ''       'asdfhsdf'    'dsafdsag'

  Columns 8 through 10

    ''          ''    ''
    '0xFF'      ''    ''
    '0x0F0F'    ''    ''

The result is a 3-by-10 cell array with one field per cell where missing fields are represented by the empty string ''. Now you can access each cell or a combination of cells to format them as you like. For example, if you wanted to change the fields in the first column from strings to integer values, you could use the function str2double as follows:

>> data(:, 1) = cellfun(@(s) {str2double(s)}, data(:, 1))

data = 

  Columns 1 through 7

    [  4]    'abc'    'def'    'ghj'    'klm'    ''            ''        
    [NaN]    ''       ''       ''       ''       'Test'        'text'    
    [NaN]    ''       ''       ''       ''       'asdfhsdf'    'dsafdsag'

  Columns 8 through 10

    ''          ''    ''
    '0xFF'      ''    ''
    '0x0F0F'    ''    ''

Note that the empty fields results in NaN values.

What exactly does Perl's "bless" do?

For example, if you can be confident that any Bug object is going to be a blessed hash, you can (finally!) fill in the missing code in the Bug::print_me method:

 package Bug;
 sub print_me
 {
     my ($self) = @_;
     print "ID: $self->{id}\n";
     print "$self->{descr}\n";
     print "(Note: problem is fatal)\n" if $self->{type} eq "fatal";
 }

Now, whenever the print_me method is called via a reference to any hash that's been blessed into the Bug class, the $self variable extracts the reference that was passed as the first argument and then the print statements access the various entries of the blessed hash.

What are unit tests, integration tests, smoke tests, and regression tests?

Unit Testing: It always performs by developer after their development done to find out issue from their testing side before they make any requirement ready for QA.

Integration Testing: It means tester have to verify module to sub module verification when some data/function output are drive to one module to other module. Or in your system if using third party tool which using your system data for integrate.

Smoke Testing: tester performed to verify system for high-level testing and trying to find out show stopper bug before changes or code goes live.

Regression Testing: Tester performed regression for verification of existing functionality due to changes implemented in system for newly enhancement or changes in system.

How to use AND in IF Statement

If you are simply looking for the occurrence of "Miami" or "Florida" inside a string (since you put * at both ends), it's probably better to use the InStr function instead of Like. Not only are the results more predictable, but I believe you'll get better performance.

Also, VBA is not short-circuited so when you use the AND keyword, it will test both sides of the AND, regardless if the first test failed or not. In VBA, it is more optimal to use 2 if-statements in these cases, that way you aren't checking for "Florida" if you don't find "Miami".

The other advice I have is that a for-each loop is faster than a for-loop. Using .offset, you can achieve the same thing, but with better effeciency. Of course there are even better ways (like variant arrays), but those will add a layer of complexity not needed in this example.

Here is some sample code:

Sub test()

Application.ScreenUpdating = False
Dim lastRow As Long
Dim cell As Range
lastRow = Range("A" & Rows.Count).End(xlUp).Row

For Each cell In Range("A1:A" & lastRow)
    If InStr(1, cell.Value, "Miami") <> 0 Then
        If InStr(1, cell.Offset(, 3).Value, "Florida") <> 0 Then
            cell.Offset(, 2).Value = "BA"
        End If
    End If
Next

Application.ScreenUpdating = True
End Sub

I hope you find some of this helpful, and keep at it with VBA! ^^

How do I select an element that has a certain class?

The CSS :first-child selector allows you to target an element that is the first child element within its parent.

element:first-child { style_properties }
table:first-child { style_properties }

Form/JavaScript not working on IE 11 with error DOM7011

I had a similar problem on Internet Explorer, and got the same error number. The culprit was an HTML comment. I know it sounds unbelievable, so here is the story.

I saw a series of 6 articles on the Internet. I liked them, so I decided to download the 6 Web-Pages and store them on my Hard Drive. At the top of each page, was a couple of HTML <a> Tags, that would allow you to go to the next article or the previous article. So I changed the href attribute to point to the next folder on my Hard Drive, instead of the next URL on the Internet.

After all of the links had been re-directed, the Browser refused to display any of the Web-Pages when I clicked on the Links. The message in the Console was the Error Number that was mentioned at the top of this page.

However, the real problem was a Comment. Whenever you download a Web-Page using Google Chrome, the Chrome Browser inserts a Comment at the very top of the page that includes the URL of the location that you got the Web-Page from. After I removed the Comment at the top of each one of the 6 Pages, all of the Links worked fine ( although I continued to get the same Error Message in the Console. )

How to round the minute of a datetime object

From the best answer I modified to an adapted version using only datetime objects, this avoids having to do the conversion to seconds and makes the calling code more readable:

def roundTime(dt=None, dateDelta=datetime.timedelta(minutes=1)):
    """Round a datetime object to a multiple of a timedelta
    dt : datetime.datetime object, default now.
    dateDelta : timedelta object, we round to a multiple of this, default 1 minute.
    Author: Thierry Husson 2012 - Use it as you want but don't blame me.
            Stijn Nevens 2014 - Changed to use only datetime objects as variables
    """
    roundTo = dateDelta.total_seconds()

    if dt == None : dt = datetime.datetime.now()
    seconds = (dt - dt.min).seconds
    # // is a floor division, not a comment on following line:
    rounding = (seconds+roundTo/2) // roundTo * roundTo
    return dt + datetime.timedelta(0,rounding-seconds,-dt.microsecond)

Samples with 1 hour rounding & 15 minutes rounding:

print roundTime(datetime.datetime(2012,12,31,23,44,59),datetime.timedelta(hour=1))
2013-01-01 00:00:00

print roundTime(datetime.datetime(2012,12,31,23,44,49),datetime.timedelta(minutes=15))
2012-12-31 23:30:00

How to pass a parameter to Vue @click event handler

Just use a normal Javascript expression, no {} or anything necessary:

@click="addToCount(item.contactID)"

if you also need the event object:

@click="addToCount(item.contactID, $event)"

Representing EOF in C code?

There is the constant EOF of type int, found in stdio.h. There is no equivalent character literal specified by any standard.

Sort an ArrayList based on an object field

Modify the DataNode class so that it implements Comparable interface.

public int compareTo(DataNode o)
{
     return(degree - o.degree);
}

then just use

Collections.sort(nodeList);

$(document).ready(function() is not working

You only get this error if jQuery is not correctly loaded, you can check with firebug what url its trying to load so you can see if your relative path is wrong.

Also, on a separate note, you can use $(function(){ as a shorthand to $(document).ready(function(){

How to use Ajax.ActionLink?

@Ajax.ActionLink requires jQuery AJAX Unobtrusive library. You can download it via nuget:

Install-Package Microsoft.jQuery.Unobtrusive.Ajax

Then add this code to your View:

@Scripts.Render("~/Scripts/jquery.unobtrusive-ajax.min.js")

Is it possible to declare a public variable in vba and assign a default value?

Little-Known Fact:
A named range can refer to a value instead of specific cells.

This could be leveraged to act like a "global variable", plus you can refer to the value from VBA and in a worksheet cell, and the assigned value will even persist after closing & re-opening the workbook!


  • To "declare" the name myVariable and assign it a value of 123:

    ThisWorkbook.Names.Add "myVariable", 123
    
  • To retrieve the value (for example to display the value in a MsgBox):

      MsgBox [myVariable]
    
  • Alternatively, you could refer to the name with a string: (identical result as square brackets)

    MsgBox Evaluate("myVariable")
    
  • To use the value on a worksheet just use it's name in your formula as-is:

    =myVariable
    
  • In fact, you could even store function expressions: (sort of like in JavaScript)
    (Admittedly, I can't actually think of a situation where this would be beneficial - but I don't use them in JS either.)

    ThisWorkbook.Names.Add "myDay", "=if(isodd(day(today())),""on day"",""off day"")"
    

Square brackets are just a shortcut for the Evaluate method. I've heard that using them is considered messy or "hacky", but I've had no issues and their use in Excel is supported by Microsoft.

There is probably also a way use the Range function to refer to these names, but I don't see any advantage so I didn't look very deeply into it.


More info:

Django DateField default options

This should do the trick:

models.DateTimeField(_("Date"), auto_now_add = True)

How to get an object's property's value by property name?

You can get a property by name using the Select-Object cmdlet and specifying the property name(s) that you're interested in. Note that this doesn't simply return the raw value for that property; instead you get something that still behaves like an object.

[PS]> $property = (Get-Process)[0] | Select-Object -Property Name

[PS]> $property

Name
----
armsvc

[PS]> $property.GetType().FullName
System.Management.Automation.PSCustomObject

In order to use the value for that property, you will still need to identify which property you are after, even if there is only one property:

[PS]> $property.Name
armsvc

[PS]> $property -eq "armsvc"
False

[PS]> $property.Name -eq "armsvc"
True

[PS]> $property.Name.GetType().FullName
System.String

As per other answers here, if you want to use a single property within a string, you need to evaluate the expression (put brackets around it) and prefix with a dollar sign ($) to declare the expression dynamically as a variable to be inserted into the string:

[PS]> "The first process in the list is: $($property.Name)"
The first process in the list is: armsvc

Quite correctly, others have answered this question by recommending the -ExpandProperty parameter for the Select-Object cmdlet. This bypasses some of the headache by returning the value of the property specified, but you will want to use different approaches in different scenarios.

-ExpandProperty <String>

Specifies a property to select, and indicates that an attempt should be made to expand that property

https://technet.microsoft.com/en-us/library/hh849895.aspx

[PS]> (Get-Process)[0] | Select-Object -ExpandProperty Name
armsvc

docker unauthorized: authentication required - upon push with successful login

The problem newbies face is that we tend to treat docker hub repository just like a maven repository and think that it might contain many a different files, folders and other contents.

A docker repository on the other hand is just a single image, it does not contain anything else. It can hold different versions of the same image, but its going to contain just one image.

So, name your repository on docker hub the same name as the image you want to push into it, and use your dockerhub username as prefix. For eg, if your username is myusername and your image name is docker-whale , make sure to name your dockerhub repository as docker-whale and use the below commands to tag and push your image to repository:

docker logout                                   # to make sure you're logged out and not cause any clashes
docker tag <imageId> myusername/docker-whale    # use :1.0.0 for specific version, default is 'latest'
docker login --username=myusername              # use the username/pwd to login to docker hub
docker push myusername/docker-whale             # use :1.0.0 for pushing specific version, default is 'latest'

How to replace local branch with remote branch entirely in Git?

The selected answer is absolutely correct, however it did not leave me with the latest commit/pushes ...

So for me:

git reset --hard dev/jobmanager-tools
git pull  ( did not work as git was not sure what branch i wanted)

Since I know I want to temporarily set my upstream branch for a few weeks to a specific branch ( same as the one i switched to / checked out earlier and did a hard reset on )

So AFTER reset

git branch --set-upstream-to=origin/dev/jobmanager-tools
git pull
git status    ( says--> on branch  dev/jobmanager-tools 

How to debug PDO database queries?

almost nothing was said about error displaying except check error logs, but there's a rather helpful functionality:

<?php
/* Provoke an error -- bogus SQL syntax */
$stmt = $dbh->prepare('bogus sql');
if (!$stmt) {
    echo "\PDO::errorInfo():\n";
    print_r($dbh->errorInfo());
}
?>

(source link)

it is clear that this code can be modified to be used as exception message or any other kind of error handling

HTML combo box with option to type an entry

    <html>
<head>
    <title></title>
    <script src="jquery-3.1.0.js"></script>
    <script>
        $(function () {
            $('#selectnumber').change(function(){
                alert('.val() = ' + $('#selectnumber').val() + '  AND  html() = ' + $('#selectnumber option:selected').html() + '  AND .text() = ' + $('#selectnumber option:selected').text());
            })
        });
    </script>
</head>
<body>
       <div>
        <select id="selectnumber">
            <option value="1">one</option>
            <option value="2">two</option>
            <option value="3">three</option>
            <option value="4">four</option>
        </select>

    </div>
   </body>
</html>

Click to see OutPut Screen

Thanks...:)

Reading HTML content from a UIWebView

Note that the NSString stringWithContentsOfURL will report a totally different user-agent string than the UIWebView making the same request. So if your server is user-agent aware, and sending back different html depending on who is asking for it, you may not get correct results this way.

Also note that the @"document.body.innerHTML" mentioned above will only display what is in the body tag. If you use @"document.all[0].innerHTML" you will get both head and body. Which is still not the complete contents of the UIWebView, since it will not get back the !doctype or html tags, but it is a lot closer.

What does %~dp0 mean, and how does it work?

%~dp0 expands to current directory path of the running batch file.

To get clear understanding, let's create a batch file in a directory.

C:\script\test.bat

with contents:

@echo off
echo %~dp0

When you run it from command prompt, you will see this result:

C:\script\

Hide div if screen is smaller than a certain width

I have the almost the same situation as yours; that if the screen width is less than the my specified width it should hide the div. This is the jquery code I used that worked for me.

$(window).resize(function() {

  if ($(this).width() < 1024) {

    $('.divIWantedToHide').hide();

  } else {

    $('.divIWantedToHide').show();

    }

});

Running Node.Js on Android

J2V8 is best solution of your problem. It's run Nodejs application on jvm(java and android).

J2V8 is Java Bindings for V8, But Node.js integration is available in J2V8 (version 4.4.0)

Github : https://github.com/eclipsesource/J2V8

Example : http://eclipsesource.com/blogs/2016/07/20/running-node-js-on-the-jvm/

How do I convert datetime.timedelta to minutes, hours in Python?

Another alternative for this (older) question:

import datetime
import pytz
import time

pacific=pytz.timezone('US/Pacific')
now=datetime.datetime.now()
# pacific.dst(now).total_seconds() yields 3600 secs. [aka 1 hour]
time.strftime("%-H", time.gmtime(pacific.dst(now).total_seconds()))
'1'

The above is a good way to tell if your current time zone is actually in daylight savings time or not. (It provides an offset of 0 or 1.) Anyway, the real work is being done by time.strftime("%H:%M:%S", time.gmtime(36901)) which does work on the output of gmtime().

>>> time.strftime("%H:%M:%S",time.gmtime(36901))  # secs = 36901
'10:15:01'

And, that's it! (NOTE: Here's a link to format specifiers for time.strftime(). ...)

String to object in JS

I implemented a solution in a few lines of code which works quite reliably.

Having an HTML element like this where I want to pass custom options:

<div class="my-element"
    data-options="background-color: #dadada; custom-key: custom-value;">
</div>

a function parses the custom options and return an object to use that somewhere:

function readCustomOptions($elem){
    var i, len, option, options, optionsObject = {};

    options = $elem.data('options');
    options = (options || '').replace(/\s/g,'').split(';');
    for (i = 0, len = options.length - 1; i < len; i++){
        option = options[i].split(':');
        optionsObject[option[0]] = option[1];
    }
    return optionsObject;
}

console.log(readCustomOptions($('.my-element')));

How do I execute a Shell built-in command with a C function?

You can use the excecl command

int execl(const char *path, const char *arg, ...);

Like shown here

#include <stdio.h>
#include <unistd.h>
#include <dirent.h>

int main (void) {

   return execl ("/bin/pwd", "pwd", NULL);

}

The second argument will be the name of the process as it will appear in the process table.

Alternatively, you can use the getcwd() function to get the current working directory:

#include <stdio.h>
#include <unistd.h>
#include <dirent.h>
#define MAX 255

int main (void) {
char wd[MAX];
wd[MAX-1] = '\0';

if(getcwd(wd, MAX-1) == NULL) {
  printf ("Can not get current working directory\n");
}
else {
  printf("%s\n", wd);
}
  return 0;
}

ClassCastException, casting Integer to Double

This means that your ArrayList has integers in some elements. The casting should work unless there's an integer in one of your elements.

One way to make sure that your arraylist has no integers is by declaring it as a Doubles array.

    ArrayList<Double> marks = new ArrayList<Double>();

How do I use a PriorityQueue?

Just pass appropriate Comparator to the constructor:

PriorityQueue(int initialCapacity, Comparator<? super E> comparator)

The only difference between offer and add is the interface they belong to. offer belongs to Queue<E>, whereas add is originally seen in Collection<E> interface. Apart from that both methods do exactly the same thing - insert the specified element into priority queue.

Inserting multiple rows in a single SQL query?

If you are inserting into a single table, you can write your query like this (maybe only in MySQL):

INSERT INTO table1 (First, Last)
VALUES
    ('Fred', 'Smith'),
    ('John', 'Smith'),
    ('Michael', 'Smith'),
    ('Robert', 'Smith');

How can I make a checkbox readonly? not disabled?

In my case, i only needed it within certain conditions, and to be done easily in HTML:

<input type="checkbox" [style.pointer-events]="(condition == true) ? 'none' : 'auto'"> 

Or in case you need this consistently:

<input type="checkbox" style="pointer-events: none;">