Programs & Examples On #Probability

Consider if your question would be better at stats.stackexchange.com. Probability touches upon uncertainty, random phenomena, random numbers, random variables, probability distributions, sampling, combinatorics.

Generate a random point within a circle (uniformly)

I am still not sure about the exact '(2/R2)×r' but what is apparent is the number of points required to be distributed in given unit 'dr' i.e. increase in r will be proportional to r2 and not r.

check this way...number of points at some angle theta and between r (0.1r to 0.2r) i.e. fraction of the r and number of points between r (0.6r to 0.7r) would be equal if you use standard generation, since the difference is only 0.1r between two intervals. but since area covered between points (0.6r to 0.7r) will be much larger than area covered between 0.1r to 0.2r, the equal number of points will be sparsely spaced in larger area, this I assume you already know, So the function to generate the random points must not be linear but quadratic, (since number of points required to be distributed in given unit 'dr' i.e. increase in r will be proportional to r2 and not r), so in this case it will be inverse of quadratic, since the delta we have (0.1r) in both intervals must be square of some function so it can act as seed value for linear generation of points (since afterwords, this seed is used linearly in sin and cos function), so we know, dr must be quadratic value and to make this seed quadratic, we need to originate this values from square root of r not r itself, I hope this makes it little more clear.

How to calculate probability in a normal distribution given mean & standard deviation?

Scipy.stats is a great module. Just to offer another approach, you can calculate it directly using

import math
def normpdf(x, mean, sd):
    var = float(sd)**2
    denom = (2*math.pi*var)**.5
    num = math.exp(-(float(x)-float(mean))**2/(2*var))
    return num/denom

This uses the formula found here: http://en.wikipedia.org/wiki/Normal_distribution#Probability_density_function

to test:

>>> normpdf(7,5,5)  
0.07365402806066466
>>> norm(5,5).pdf(7)
0.073654028060664664

Find the similarity metric between two strings

Here's what i thought of:

import string

def match(a,b):
    a,b = a.lower(), b.lower()
    error = 0
    for i in string.ascii_lowercase:
            error += abs(a.count(i) - b.count(i))
    total = len(a) + len(b)
    return (total-error)/total

if __name__ == "__main__":
    print(match("pple inc", "Apple Inc."))

Normalizing a list of numbers in Python

For ones who wanna use scikit-learn, you can use

from sklearn.preprocessing import normalize

x = [1,2,3,4]
normalize([x]) # array([[0.18257419, 0.36514837, 0.54772256, 0.73029674]])
normalize([x], norm="l1") # array([[0.1, 0.2, 0.3, 0.4]])
normalize([x], norm="max") # array([[0.25, 0.5 , 0.75, 1.]])

$(window).height() vs $(document).height

Well you seem to have mistaken them both for what they do.

$(window).height() gets you an unit-less pixel value of the height of the (browser) window aka viewport. With respect to the web browsers the viewport here is visible portion of the canvas(which often is smaller than the document being rendered).

$(document).height() returns an unit-less pixel value of the height of the document being rendered. However, if the actual document’s body height is less than the viewport height then it will return the viewport height instead.

Hope that clears things a little.

Get the second largest number in a list in linear time

This can be done in [N + log(N) - 2] time, which is slightly better than the loose upper bound of 2N (which can be thought of O(N) too).

The trick is to use binary recursive calls and "tennis tournament" algorithm. The winner (the largest number) will emerge after all the 'matches' (takes N-1 time), but if we record the 'players' of all the matches, and among them, group all the players that the winner has beaten, the second largest number will be the largest number in this group, i.e. the 'losers' group.

The size of this 'losers' group is log(N), and again, we can revoke the binary recursive calls to find the largest among the losers, which will take [log(N) - 1] time. Actually, we can just linearly scan the losers group to get the answer too, the time budget is the same.

Below is a sample python code:

def largest(L):
    global paris
    if len(L) == 1:
        return L[0]
    else:
        left = largest(L[:len(L)//2])
        right = largest(L[len(L)//2:])
        pairs.append((left, right))
        return max(left, right)

def second_largest(L):
    global pairs
    biggest = largest(L)
    second_L = [min(item) for item in pairs if biggest in item]

    return biggest, largest(second_L)  



if __name__ == "__main__":
    pairs = []
    # test array
    L = [2,-2,10,5,4,3,1,2,90,-98,53,45,23,56,432]    

    if len(L) == 0:
        first, second = None, None
    elif len(L) == 1:
        first, second = L[0], None
    else:
        first, second = second_largest(L)

    print('The largest number is: ' + str(first))
    print('The 2nd largest number is: ' + str(second))

How can I install a local gem?

Well, it's this my DRY installation:

  1. Look into a computer with already installed gems needed in the cache directory (by default: [Ruby Installation version]/lib/ruby/gems/[Ruby version]/cache)
  2. Copy all "*.gems files" to a computer without gems in own gem cache place (by default the same patron path of first step: [Ruby Installation version]/lib/ruby/gems/[Ruby version]/cache)
  3. In the console be located in the gems cache (cd [Ruby Installation version]/lib/ruby/gems/[Ruby version]/cache) and fire the gem install anygemwithdependencieshere (by example cucumber-2.99.0)

It's DRY because after install any gem, by default rubygems put the gem file in the cache gem directory and not make sense duplicate thats files, it's more easy if you want both computer has the same versions (or bloqued by paranoic security rules :v)

Edit: In some versions of ruby or rubygems, it don't work and fire alerts or error, you can put gems in other place but not get DRY, other alternative is using launch integrated command gem server and add the localhost url in gem sources, more information in: https://guides.rubygems.org/run-your-own-gem-server/

Replace whitespaces with tabs in linux

If you are talking about replacing all consecutive spaces on a line with a tab then tr -s '[:blank:]' '\t'.

[root@sysresccd /run/archiso/img_dev]# sfdisk -l -q -o Device,Start /dev/sda
Device         Start
/dev/sda1       2048
/dev/sda2     411648
/dev/sda3    2508800
/dev/sda4   10639360
/dev/sda5   75307008
/dev/sda6   96278528
/dev/sda7  115809778
[root@sysresccd /run/archiso/img_dev]# sfdisk -l -q -o Device,Start /dev/sda | tr -s '[:blank:]' '\t'
Device  Start
/dev/sda1       2048
/dev/sda2       411648
/dev/sda3       2508800
/dev/sda4       10639360
/dev/sda5       75307008
/dev/sda6       96278528
/dev/sda7       115809778

If you are talking about replacing all whitespace (e.g. space, tab, newline, etc.) then tr -s '[:space:]'.

[root@sysresccd /run/archiso/img_dev]# sfdisk -l -q -o Device,Start /dev/sda | tr -s '[:space:]' '\t'
Device  Start   /dev/sda1       2048    /dev/sda2       411648  /dev/sda3       2508800 /dev/sda4       10639360        /dev/sda5       75307008        /dev/sda6     96278528        /dev/sda7       115809778  

If you are talking about fixing a tab-damaged file then use expand and unexpand as mentioned in other answers.

Proper use of the IDisposable interface

I see a lot of answers have shifted to talk about using IDisposable for both managed and unmanaged resources. I'd suggest this article as one of the best explanations that I've found for how IDisposable should actually be used.

https://www.codeproject.com/Articles/29534/IDisposable-What-Your-Mother-Never-Told-You-About

For the actual question; should you use IDisposable to clean up managed objects that are taking up a lot of memory the short answer would be no. The reason is that once you Dispose of an IDisposable you should be letting it go out of scope. At that point any referenced child objects are also out of scope and will get collected.

The only real exception to this would be if you have a lot of memory tied up in managed objects and you've blocked that thread waiting for some operation to complete. If those objects where not going to be needed after that call completed then setting those references to null might allow the garbage collector to collect them sooner. But that scenario would represent bad code that needed to be refactored - not a use case of IDisposable.

How to navigate back to the last cursor position in Visual Studio Code?

I am on Mac OSX, so I can't answer for windows users:

I added a custom keymap entry and set it to Ctrl+? + Ctrl+?, while the original default is Ctrl+- and Ctrl+Shift+- (which translates to Ctrl+ß and Ctrl+Shift+ß on my german keyboard).

One can simply modify it in the user keymap settings:

{ "key": "ctrl+left",  "command": "workbench.action.navigateBack" },
{ "key": "ctrl+right", "command": "workbench.action.navigateForward" }

For the accepted answer I actually wonder :) Alt+? / Alt+? jumps wordwise for me (which is kinda standard in all editors). Did they really do this mapping for the windows version?

Regular expression for matching latitude/longitude coordinates?

^-?[0-9]{1,3}(?:\.[0-9]{1,10})?$

Regex breakdown:

^-?[0-9]{1,3}(?:\.[0-9]{1,10})?$

-? # accept negative values

^ # Start of string

[0-9]{1,3} # Match 1-3 digits (i. e. 0-999)

(?: # Try to match...

\. # a decimal point

[0-9]{1,10} # followed by one to 10 digits (i. e. 0-9999999999)

)? # ...optionally

$ # End of string

What does getActivity() mean?

Two likely definitions:

Check if a string contains a number

I'll make the @zyxue answer a bit more explicit:

RE_D = re.compile('\d')

def has_digits(string):
    res = RE_D.search(string)
    return res is not None

has_digits('asdf1')
Out: True

has_digits('asdf')
Out: False

which is the solution with the fastest benchmark from the solutions that @zyxue proposed on the answer.

Sleep Command in T-SQL?

Look at the WAITFOR command.

E.g.

-- wait for 1 minute
WAITFOR DELAY '00:01'

-- wait for 1 second
WAITFOR DELAY '00:00:01'

This command allows you a high degree of precision but is only accurate within 10ms - 16ms on a typical machine as it relies on GetTickCount. So, for example, the call WAITFOR DELAY '00:00:00:001' is likely to result in no wait at all.

Installing Oracle Instant Client

If you want to use SQL Server Management Studio, you want to install the full Oracle client, not the Instant Client. The full Oracle client is on the same download page as the Oracle database. Assuming that you are installing on a 64-bit version of Windows, I expect you want the "Oracle Database 11g Release 2 Client (11.2.0.1.0) for Microsoft Windows (x64)" download. This is several hundred MB rather than a couple of MB for the Instant Client.

How to solve error: "Clock skew detected"?

Simply go to the directory where the troubling file is, type touch * without quotes in the console, and you should be good.

Python - Convert a bytes array into JSON format

Your bytes object is almost JSON, but it's using single quotes instead of double quotes, and it needs to be a string. So one way to fix it is to decode the bytes to str and replace the quotes. Another option is to use ast.literal_eval; see below for details. If you want to print the result or save it to a file as valid JSON you can load the JSON to a Python list and then dump it out. Eg,

import json

my_bytes_value = b'[{\'Date\': \'2016-05-21T21:35:40Z\', \'CreationDate\': \'2012-05-05\', \'LogoType\': \'png\', \'Ref\': 164611595, \'Classe\': [\'Email addresses\', \'Passwords\'],\'Link\':\'http://some_link.com\'}]'

# Decode UTF-8 bytes to Unicode, and convert single quotes 
# to double quotes to make it valid JSON
my_json = my_bytes_value.decode('utf8').replace("'", '"')
print(my_json)
print('- ' * 20)

# Load the JSON to a Python list & dump it back out as formatted JSON
data = json.loads(my_json)
s = json.dumps(data, indent=4, sort_keys=True)
print(s)

output

[{"Date": "2016-05-21T21:35:40Z", "CreationDate": "2012-05-05", "LogoType": "png", "Ref": 164611595, "Classe": ["Email addresses", "Passwords"],"Link":"http://some_link.com"}]
- - - - - - - - - - - - - - - - - - - - 
[
    {
        "Classe": [
            "Email addresses",
            "Passwords"
        ],
        "CreationDate": "2012-05-05",
        "Date": "2016-05-21T21:35:40Z",
        "Link": "http://some_link.com",
        "LogoType": "png",
        "Ref": 164611595
    }
]

As Antti Haapala mentions in the comments, we can use ast.literal_eval to convert my_bytes_value to a Python list, once we've decoded it to a string.

from ast import literal_eval
import json

my_bytes_value = b'[{\'Date\': \'2016-05-21T21:35:40Z\', \'CreationDate\': \'2012-05-05\', \'LogoType\': \'png\', \'Ref\': 164611595, \'Classe\': [\'Email addresses\', \'Passwords\'],\'Link\':\'http://some_link.com\'}]'

data = literal_eval(my_bytes_value.decode('utf8'))
print(data)
print('- ' * 20)

s = json.dumps(data, indent=4, sort_keys=True)
print(s)

Generally, this problem arises because someone has saved data by printing its Python repr instead of using the json module to create proper JSON data. If it's possible, it's better to fix that problem so that proper JSON data is created in the first place.

How to post ASP.NET MVC Ajax form using JavaScript rather than submit button

Unfortunately triggering the onsubmit or submit events wont work in all browsers.

  • Works in IE and Chrome: #('form#ajaxForm')trigger('onsubmit');
  • Works in Firefox and Safari: #('form#ajaxForm')trigger('submit');

Also, if you trigger('submit') in Chrome or IE, it causes the entire page to be posted rather than doing an AJAX behavior.

What works for all browsers is removing the onsubmit event behavior and just calling submit() on the form itself.

<script type="text/javascript">
$(function() {

    $('form#ajaxForm').submit(function(event) { 
        eval($(this).attr('onsubmit')); return false; 
        });

    $('form#ajaxForm').find('a.submit-link').click( function() { 
        $'form#ajaxForm').submit();
        });

  }
</script>
  <% using (Ajax.BeginForm("Update", "Description", new { id = Model.Id },
     new AjaxOptions
     {
       UpdateTargetId = "DescriptionDiv",
       HttpMethod = "post"
     }, new { id = "ajaxForm" } )) {%>
   Description:
   <%= Html.TextBox("Description", Model.Description) %><br />
   <a href="#" class="submit-link">Save</a> 
<% } %>

Also, the link doesn't have to be contained within the form in order for this to work.

Convert Unix timestamp to a date string

As @TomMcKenzie says in a comment to another answer, date -r 123456789 is arguably a more common (i.e. more widely implemented) simple solution for times given as seconds since the Unix Epoch, but unfortunately there's no universal guaranteed portable solution.

The -d option on many types of systems means something entirely different than GNU Date's --date extension. Sadly GNU Date doesn't interpret -r the same as these other implementations. So unfortunately you have to know which version of date you're using, and many older Unix date commands don't support either option.

Even worse, POSIX date recognizes neither -d nor -r and provides no standard way in any command at all (that I know of) to format a Unix time from the command line (since POSIX Awk also lacks strftime()). (You can't use touch -t and ls because the former does not accept a time given as seconds since the Unix Epoch.)

Note though The One True Awk available direct from Brian Kernighan does now have the strftime() function built-in as well as a systime() function to return the current time in seconds since the Unix Epoch), so perhaps the Awk solution is the most portable.

Cant get text of a DropDownList in code - can get value but not text

Have a look here, this has a proof-of-concept page and demo you can use to get anything from the drop-down: asp:DropDownList Control Tutorial Page

How to run a subprocess with Python, wait for it to exit and get the full stdout as a string?

I'd try something like:

#!/usr/bin/python
from __future__ import print_function

import shlex
from subprocess import Popen, PIPE

def shlep(cmd):
    '''shlex split and popen
    '''
    parsed_cmd = shlex.split(cmd)
    ## if parsed_cmd[0] not in approved_commands:
    ##    raise ValueError, "Bad User!  No output for you!"
    proc = Popen(parsed_command, stdout=PIPE, stderr=PIPE)
    out, err = proc.communicate()
    return (proc.returncode, out, err)

... In other words let shlex.split() do most of the work. I would NOT attempt to parse the shell's command line, find pipe operators and set up your own pipeline. If you're going to do that then you'll basically have to write a complete shell syntax parser and you'll end up doing an awful lot of plumbing.

Of course this raises the question, why not just use Popen with the shell=True (keyword) option? This will let you pass a string (no splitting nor parsing) to the shell and still gather up the results to handle as you wish. My example here won't process any pipelines, backticks, file descriptor redirection, etc that might be in the command, they'll all appear as literal arguments to the command. Thus it is still safer then running with shell=True ... I've given a silly example of checking the command against some sort of "approved command" dictionary or set --- through it would make more sense to normalize that into an absolute path unless you intend to require that the arguments be normalized prior to passing the command string to this function.

Java: Clear the console

Try this: only works on console, not in NetBeans integrated console.

public static void cls(){
    try {

     if (System.getProperty("os.name").contains("Windows"))
         new ProcessBuilder("cmd", "/c", 
                  "cls").inheritIO().start().waitFor();
     else
         Runtime.getRuntime().exec("clear");
    } catch (IOException | InterruptedException ex) {}
}

Convert Existing Eclipse Project to Maven Project

Start from m2e 0.13.0 (if not earlier than), you can convert a Java project to Maven project from the context menu. Here is how:

  • Right click the Java project to pop up the context menu
  • Select Configure > Convert to Maven Project

Here is the detailed steps with screen shots.

Sublime Text 2 - Show file navigation in sidebar

Instead of opening a folder, try adding a folder by going to "Project" -> "Add Folder to Project..." which opens a Folder choosing dialog. This way the folder won't open in a new window and will be added to your current workspace.

If you then go to "Project" -> "Save Project As..." you can even save your current setup (cells setup, opened files, unsaved changes, etc...), this makes it easy to hotswitch between multiple projects without loosing control and unsaved changes which could be unsafe to be saved right now, but would be a loss if you just ditched them. (Just be sure to have the "hot_exit" setting set to true.)

And Ctrl + Alt + P (Linux and Windows) / Super + Ctrl + P (Mac) lets you switch between the saved projects.

This way you don't have to setup your editor every time you want to work on one of your projects.

Hint: Try http://sublime-text-unofficial-documentation.readthedocs.org/en/sublime-text-2/ which is a wonderful resource for beginners, it teaches you the ropes and shows you the power of your "new" editor, just start with the "Editing" chapter.

Is there a way to detect if an image is blurry?

Answers above elucidated many things, but I think it is useful to make a conceptual distinction.

What if you take a perfectly on-focus picture of a blurred image?

The blurring detection problem is only well posed when you have a reference. If you need to design, e.g., an auto-focus system, you compare a sequence of images taken with different degrees of blurring, or smoothing, and you try to find the point of minimum blurring within this set. I other words you need to cross reference the various images using one of the techniques illustrated above (basically--with various possible levels of refinement in the approach--looking for the one image with the highest high-frequency content).

How can I directly view blobs in MySQL Workbench

I'm not sure if this answers the question but if if you right click on the "blob" icon in the field (when viewing the table) there is an option to "Open Value in Editor". One of the tabs lets you view the blob. This is in ver. 5.2.34

Replace text inside td using jQuery having td containing other elements

Using text nodes in jquery is a particularly delicate endeavour and most operations are made to skip them altogether.

Instead of going through the trouble of carefully avoiding the wrong nodes, why not just wrap whatever you need to replace inside a <span> for instance:

<td><span class="replaceme">8: Tap on APN and Enter <B>www</B>.</span></td>

Then:

$('.replaceme').html('Whatever <b>HTML</b> you want here.');

Python: Making a beep noise

On Windows, if you want to just make the computer make a beep sound:

import winsound
frequency = 2500  # Set Frequency To 2500 Hertz
duration = 1000  # Set Duration To 1000 ms == 1 second
winsound.Beep(frequency, duration)

The winsound.Beep() can be used wherever you want the beep to occur.

Add button to a layout programmatically

This line:

layout = (LinearLayout) findViewById(R.id.statsviewlayout);

Looks for the "statsviewlayout" id in your current 'contentview'. Now you've set that here:

setContentView(new GraphTemperature(getApplicationContext()));

And i'm guessing that new "graphTemperature" does not set anything with that id.

It's a common mistake to think you can just find any view with findViewById. You can only find a view that is in the XML (or appointed by code and given an id).

The nullpointer will be thrown because the layout you're looking for isn't found, so

layout.addView(buyButton);

Throws that exception.

addition: Now if you want to get that view from an XML, you should use an inflater:

layout = (LinearLayout) View.inflate(this, R.layout.yourXMLYouWantToLoad, null);

assuming that you have your linearlayout in a file called "yourXMLYouWantToLoad.xml"

MS Access - execute a saved query by name in VBA

You can do it the following way:

DoCmd.OpenQuery "yourQueryName", acViewNormal, acEdit

OR

CurrentDb.OpenRecordset("yourQueryName")

Are there any HTTP/HTTPS interception tools like Fiddler for mac OS X?

I think the possibilities are less, but FireBug (addon of FireFox) has some network analysis tools, too.

Why does cURL return error "(23) Failed writing body"?

For me, it was permission issue. Docker run is called with a user profile but root is the user inside the container. The solution was to make curl write to /tmp since that has write permission for all users , not just root.

I used the -o option.

-o /tmp/file_to_download

Is there a short cut for going back to the beginning of a file by vi editor?

After opening a file using vi

1) You can press Shift + g to go the end of the file

and

2) Press g twice to go to the beginning of the file

NOTE : - g is case-sensitive (Thanks to @Ben for pointing it out)

AngularJS error: 'argument 'FirstCtrl' is not a function, got undefined'

This can happen if you have gulp misconfigured to add your angular app code more than once. In my case, this was in index.js, and it was adding it as part of the directory of js files (globbed in gulp) before and after my controller declarations. Once I added an exclusion for index.js not to be minified and injected the second time, my app began to work. Another tip if any of the solutions above don't address your problem.

How to style readonly attribute with CSS?

Note that textarea[readonly="readonly"] works if you set readonly="readonly" in HTML but it does NOT work if you set the readOnly-attribute to true or "readonly" via JavaScript.

For the CSS selector to work if you set readOnly with JavaScript you have to use the selector textarea[readonly].

Same behavior in Firefox 14 and Chrome 20.

To be on the safe side, i use both selectors.

textarea[readonly="readonly"], textarea[readonly] {
...
}

What's the difference between "end" and "exit sub" in VBA?

This is a bit outside the scope of your question, but to avoid any potential confusion for readers who are new to VBA: End and End Sub are not the same. They don't perform the same task.

End puts a stop to ALL code execution and you should almost always use Exit Sub (or Exit Function, respectively).

End halts ALL exectution. While this sounds tempting to do it also clears all global and static variables. (source)

See also the MSDN dox for the End Statement

When executed, the End statement resets allmodule-level variables and all static local variables in allmodules. To preserve the value of these variables, use the Stop statement instead. You can then resume execution while preserving the value of those variables.

Note The End statement stops code execution abruptly, without invoking the Unload, QueryUnload, or Terminate event, or any other Visual Basic code. Code you have placed in the Unload, QueryUnload, and Terminate events offorms andclass modules is not executed. Objects created from class modules are destroyed, files opened using the Open statement are closed, and memory used by your program is freed. Object references held by other programs are invalidated.

Nor is End Sub and Exit Sub the same. End Sub can't be called in the same way Exit Sub can be, because the compiler doesn't allow it.

enter image description here

This again means you have to Exit Sub, which is a perfectly legal operation:

Exit Sub
Immediately exits the Sub procedure in which it appears. Execution continues with the statement following the statement that called the Sub procedure. Exit Sub can be used only inside a Sub procedure.

Additionally, and once you get the feel for how procedures work, obviously, End Sub does not clear any global variables. But it does clear local (Dim'd) variables:

End Sub
Terminates the definition of this procedure.

Disabling Controls in Bootstrap

also you can use "readonly"

<select id="xxx" name="xxx" class="input-medium" readonly>

How do I convert a Python program to a runnable .exe Windows program?

For this you have two choices:

  • A downgrade to python 2.6. This is generally undesirable because it is backtracking and may nullify a small portion of your scripts
  • Your second option is to use some form of exe converter. I recommend pyinstaller as it seems to have the best results.

How to set timer in android?

I'm surprised that there is no answer that would mention solution with RxJava2. It is really simple and provides an easy way to setup timer in Android.

First you need to setup Gradle dependency, if you didn't do so already:

implementation "io.reactivex.rxjava2:rxjava:2.x.y"

(replace x and y with current version number)

Since we have just a simple, NON-REPEATING TASK, we can use Completable object:

Completable.timer(2, TimeUnit.SECONDS, Schedulers.computation())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(() -> {
            // Timer finished, do something...
        });

For REPEATING TASK, you can use Observable in a similar way:

Observable.interval(2, TimeUnit.SECONDS, Schedulers.computation())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(tick -> {
            // called every 2 seconds, do something...
        }, throwable -> {
            // handle error
        });

Schedulers.computation() ensures that our timer is running on background thread and .observeOn(AndroidSchedulers.mainThread()) means code we run after timer finishes will be done on main thread.

To avoid unwanted memory leaks, you should ensure to unsubscribe when Activity/Fragment is destroyed.

How do I calculate someone's age based on a DateTime type birthday?

I would simply do this:

DateTime birthDay = new DateTime(1990, 05, 23);
DateTime age = DateTime.Now - birthDay;

This way you can calculate the exact age of a person, down to the millisecond if you want.

Single huge .css file vs. multiple smaller specific .css files?

This is a hard one to answer. Both options have their pros and cons in my opinion.

I personally don't love reading through a single HUGE CSS file, and maintaining it is very difficult. On the other hand, splitting it out causes extra http requests which could potentially slow things down.

My opinion would be one of two things.

1) If you know that your CSS will NEVER change once you've built it, I'd build multiple CSS files in the development stage (for readability), and then manually combine them before going live (to reduce http requests)

2) If you know that you're going to change your CSS once in a while, and need to keep it readable, I would build separate files and use code (providing you're using some sort of programming language) to combine them at runtime build time (runtime minification/combination is a resource pig).

With either option I would highly recommend caching on the client side in order to further reduce http requests.

EDIT:
I found this blog that shows how to combine CSS at runtime using nothing but code. Worth taking a look at (though I haven't tested it myself yet).

EDIT 2:
I've settled on using separate files in my design time, and a build process to minify and combine. This way I can have separate (manageable) css while I develop and a proper monolithic minified file at runtime. And I still have my static files and less system overhead because I'm not doing compression/minification at runtime.

note: for you shoppers out there, I highly suggest using bundler as part of your build process. Whether you're building from within your IDE, or from a build script, bundler can be executed on Windows via the included exe or can be run on any machine that is already running node.js.

TypeError: Missing 1 required positional argument: 'self'

You need to instantiate a class instance here.

Use

p = Pump()
p.getPumps()

Small example -

>>> class TestClass:
        def __init__(self):
            print("in init")
        def testFunc(self):
            print("in Test Func")


>>> testInstance = TestClass()
in init
>>> testInstance.testFunc()
in Test Func

Using RegEx in SQL Server

Regular Expressions In SQL Server Databases Implementation Use

Regular Expression - Description
. Match any one character
* Match any character
+ Match at least one instance of the expression before
^ Start at beginning of line
$ Search at end of line
< Match only if word starts at this point
> Match only if word stops at this point
\n Match a line break
[] Match any character within the brackets
[^...] Matches any character not listed after the ^
[ABQ]% The string must begin with either the letters A, B, or Q and can be of any length
[AB][CD]% The string must have a length of two or more and which must begin with A or B and have C or D as the second character
[A-Z]% The string can be of any length and must begin with any letter from A to Z
[A-Z0-9]% The string can be of any length and must start with any letter from A to Z or numeral from 0 to 9
[^A-C]% The string can be of any length but cannot begin with the letters A to C
%[A-Z] The string can be of any length and must end with any of the letters from A to Z
%[%$#@]% The string can be of any length and must contain at least one of the special characters enclosed in the bracket

Android Design Support Library expandable Floating Action Button(FAB) menu

  • First create the menu layouts in the your Activity layout xml file. For e.g. a linear layout with horizontal orientation and include a TextView for label then a Floating Action Button beside the TextView.

  • Create the menu layouts as per your need and number.

  • Create a Base Floating Action Button and on its click of that change the visibility of the Menu Layouts.

Please check the below code for the reference and for more info checkout my project from github

Checkout project from Github

<android.support.constraint.ConstraintLayout
            android:id="@+id/activity_main"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            tools:context="com.app.fabmenu.MainActivity">

            <android.support.design.widget.FloatingActionButton
                android:id="@+id/baseFloatingActionButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="16dp"
                android:layout_marginEnd="16dp"
                android:layout_marginRight="16dp"
                android:clickable="true"
                android:onClick="@{FabHandler::onBaseFabClick}"
                android:tint="@android:color/white"
                app:fabSize="normal"
                app:layout_constraintBottom_toBottomOf="@+id/activity_main"
                app:layout_constraintRight_toRightOf="@+id/activity_main"
                app:srcCompat="@drawable/ic_add_black_24dp" />

            <LinearLayout
                android:id="@+id/shareLayout"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="12dp"
                android:layout_marginEnd="24dp"
                android:layout_marginRight="24dp"
                android:gravity="center_vertical"
                android:orientation="horizontal"
                android:visibility="invisible"
                app:layout_constraintBottom_toTopOf="@+id/createLayout"
                app:layout_constraintLeft_toLeftOf="@+id/createLayout"
                app:layout_constraintRight_toRightOf="@+id/activity_main">

                <TextView
                    android:id="@+id/shareLabelTextView"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginEnd="8dp"
                    android:layout_marginRight="8dp"
                    android:background="@drawable/shape_fab_label"
                    android:elevation="2dp"
                    android:fontFamily="sans-serif"
                    android:padding="5dip"
                    android:text="Share"
                    android:textColor="@android:color/white"
                    android:typeface="normal" />


                <android.support.design.widget.FloatingActionButton
                    android:id="@+id/shareFab"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:clickable="true"
                    android:onClick="@{FabHandler::onShareFabClick}"
                    android:tint="@android:color/white"
                    app:fabSize="mini"
                    app:srcCompat="@drawable/ic_share_black_24dp" />

            </LinearLayout>

            <LinearLayout
                android:id="@+id/createLayout"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="24dp"
                android:layout_marginEnd="24dp"
                android:layout_marginRight="24dp"
                android:gravity="center_vertical"
                android:orientation="horizontal"
                android:visibility="invisible"
                app:layout_constraintBottom_toTopOf="@+id/baseFloatingActionButton"
                app:layout_constraintRight_toRightOf="@+id/activity_main">

                <TextView
                    android:id="@+id/createLabelTextView"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginEnd="8dp"
                    android:layout_marginRight="8dp"
                    android:background="@drawable/shape_fab_label"
                    android:elevation="2dp"
                    android:fontFamily="sans-serif"
                    android:padding="5dip"
                    android:text="Create"
                    android:textColor="@android:color/white"
                    android:typeface="normal" />

                <android.support.design.widget.FloatingActionButton
                    android:id="@+id/createFab"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:clickable="true"
                    android:onClick="@{FabHandler::onCreateFabClick}"
                    android:tint="@android:color/white"
                    app:fabSize="mini"
                    app:srcCompat="@drawable/ic_create_black_24dp" />

            </LinearLayout>

        </android.support.constraint.ConstraintLayout>

These are the animations-

Opening animation of FAB Menu:

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true">
<scale
    android:duration="300"
    android:fromXScale="0"
    android:fromYScale="0"
    android:interpolator="@android:anim/linear_interpolator"
    android:pivotX="50%"
    android:pivotY="50%"
    android:toXScale="1"
    android:toYScale="1" />
<alpha
    android:duration="300"
    android:fromAlpha="0.0"
    android:interpolator="@android:anim/accelerate_interpolator"
    android:toAlpha="1.0" />

</set>

Closing animation of FAB Menu:

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true">
<scale
    android:duration="300"
    android:fromXScale="1"
    android:fromYScale="1"
    android:interpolator="@android:anim/linear_interpolator"
    android:pivotX="50%"
    android:pivotY="50%"
    android:toXScale="0.0"
    android:toYScale="0.0" />
<alpha
    android:duration="300"
    android:fromAlpha="1.0"
    android:interpolator="@android:anim/accelerate_interpolator"
    android:toAlpha="0.0" />
</set>

Then in my Activity I've simply used the animations above to show and hide the FAB menu :

Show Fab Menu:

  private void expandFabMenu() {

    ViewCompat.animate(binding.baseFloatingActionButton).rotation(45.0F).withLayer().setDuration(300).setInterpolator(new OvershootInterpolator(10.0F)).start();
    binding.createLayout.startAnimation(fabOpenAnimation);
    binding.shareLayout.startAnimation(fabOpenAnimation);
    binding.createFab.setClickable(true);
    binding.shareFab.setClickable(true);
    isFabMenuOpen = true;

}

Close Fab Menu:

private void collapseFabMenu() {

    ViewCompat.animate(binding.baseFloatingActionButton).rotation(0.0F).withLayer().setDuration(300).setInterpolator(new OvershootInterpolator(10.0F)).start();
    binding.createLayout.startAnimation(fabCloseAnimation);
    binding.shareLayout.startAnimation(fabCloseAnimation);
    binding.createFab.setClickable(false);
    binding.shareFab.setClickable(false);
    isFabMenuOpen = false;

}

Here is the the Activity class -

package com.app.fabmenu;

import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v4.view.ViewCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.OvershootInterpolator;

import com.app.fabmenu.databinding.ActivityMainBinding;

public class MainActivity extends AppCompatActivity {

private ActivityMainBinding binding;
private Animation fabOpenAnimation;
private Animation fabCloseAnimation;
private boolean isFabMenuOpen = false;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    binding = DataBindingUtil.setContentView(this,    R.layout.activity_main);
    binding.setFabHandler(new FabHandler());

    getAnimations();


}

private void getAnimations() {

    fabOpenAnimation = AnimationUtils.loadAnimation(this, R.anim.fab_open);

    fabCloseAnimation = AnimationUtils.loadAnimation(this, R.anim.fab_close);

}

private void expandFabMenu() {

    ViewCompat.animate(binding.baseFloatingActionButton).rotation(45.0F).withLayer().setDuration(300).setInterpolator(new OvershootInterpolator(10.0F)).start();
    binding.createLayout.startAnimation(fabOpenAnimation);
    binding.shareLayout.startAnimation(fabOpenAnimation);
    binding.createFab.setClickable(true);
    binding.shareFab.setClickable(true);
    isFabMenuOpen = true;


}

private void collapseFabMenu() {

    ViewCompat.animate(binding.baseFloatingActionButton).rotation(0.0F).withLayer().setDuration(300).setInterpolator(new OvershootInterpolator(10.0F)).start();
    binding.createLayout.startAnimation(fabCloseAnimation);
    binding.shareLayout.startAnimation(fabCloseAnimation);
    binding.createFab.setClickable(false);
    binding.shareFab.setClickable(false);
    isFabMenuOpen = false;

}


public class FabHandler {

    public void onBaseFabClick(View view) {

        if (isFabMenuOpen)
            collapseFabMenu();
        else
            expandFabMenu();


    }

    public void onCreateFabClick(View view) {

        Snackbar.make(binding.coordinatorLayout, "Create FAB tapped", Snackbar.LENGTH_SHORT).show();

    }

    public void onShareFabClick(View view) {

        Snackbar.make(binding.coordinatorLayout, "Share FAB tapped", Snackbar.LENGTH_SHORT).show();

    }


}

@Override
public void onBackPressed() {

    if (isFabMenuOpen)
        collapseFabMenu();
    else
        super.onBackPressed();
}
}

Here are the screenshots

Floating Action Menu with Label Textview in new Cursive Font Family of Android

Floating Action Menu with Label Textview in new Roboto Font Family of Android

Is it better to return null or empty collection?

I like to give explain here, with suitable example.

Consider a case here..

int totalValue = MySession.ListCustomerAccounts()
                          .FindAll(ac => ac.AccountHead.AccountHeadID 
                                         == accountHead.AccountHeadID)
                          .Sum(account => account.AccountValue);

Here Consider the functions I am using ..

1. ListCustomerAccounts() // User Defined
2. FindAll()              // Pre-defined Library Function

I can easily use ListCustomerAccount and FindAll instead of.,

int totalValue = 0; 
List<CustomerAccounts> custAccounts = ListCustomerAccounts();
if(custAccounts !=null ){
  List<CustomerAccounts> custAccountsFiltered = 
        custAccounts.FindAll(ac => ac.AccountHead.AccountHeadID 
                                   == accountHead.AccountHeadID );
   if(custAccountsFiltered != null)
      totalValue = custAccountsFiltered.Sum(account => 
                                            account.AccountValue).ToString();
}

NOTE : Since AccountValue is not null, the Sum() function will not return null., Hence I can use it directly.

How to check if another instance of my shell script is running

I create a temporary file during execution.

This is how I do it:

#!/bin/sh
# check if lock file exists
if [ -e /tmp/script.lock ]; then
  echo "script is already running"
else
# create a lock file
  touch /tmp/script.lock
  echo "run script..."
#remove lock file
 rm /tmp/script.lock
fi

How to perform a sum of an int[] array

When you declare a variable, you need to declare its type - in this case: int. Also you've put a random comma in the while loop. It probably worth looking up the syntax for Java and consider using a IDE that picks up on these kind of mistakes. You probably want something like this:

int [] numbers = { 1, 2, 3, 4, 5 ,6, 7, 8, 9 , 10 };
int sum = 0;
for(int i = 0; i < numbers.length; i++){
    sum += numbers[i];
}
System.out.println("The sum is: " + sum);

Unable to create migrations after upgrading to ASP.NET Core 2.0

Previously, you configured the seed data in the Configure method in Startup.cs. It is now recommended that you use the Configure method only to set up the request pipeline. Application startup code belongs in the Main method.

The refactored Main method. Add the following references to the Program.cs:

using Microsoft.Extensions.DependencyInjection;

using MyProject.MyDbContextFolder;

_x000D_
_x000D_
public static void Main(string[] args)_x000D_
{_x000D_
    var host = BuildWebHost(args);_x000D_
_x000D_
    using (var scope = host.Services.CreateScope())_x000D_
    {_x000D_
        var services = scope.ServiceProvider;_x000D_
        try_x000D_
        {_x000D_
            var context = services.GetRequiredService<MyDbConext>();_x000D_
            DbInitializer.Initialize(context);_x000D_
        }_x000D_
        catch (Exception ex)_x000D_
        {_x000D_
            var logger = services.GetRequiredService<ILogger<Program>>();_x000D_
            logger.LogError(ex, "An error occurred while seeding the database.");_x000D_
        }_x000D_
    }_x000D_
_x000D_
    host.Run();_x000D_
}
_x000D_
_x000D_
_x000D_

How can I replace non-printable Unicode characters in Java?

I have redesigned the code for phone numbers +9 (987) 124124 Extract digits from a string in Java

 public static String stripNonDigitsV2( CharSequence input ) {
    if (input == null)
        return null;
    if ( input.length() == 0 )
        return "";

    char[] result = new char[input.length()];
    int cursor = 0;
    CharBuffer buffer = CharBuffer.wrap( input );
    int i=0;
    while ( i< buffer.length()  ) { //buffer.hasRemaining()
        char chr = buffer.get(i);
        if (chr=='u'){
            i=i+5;
            chr=buffer.get(i);
        }

        if ( chr > 39 && chr < 58 )
            result[cursor++] = chr;
        i=i+1;
    }

    return new String( result, 0, cursor );
}

Is there a performance difference between CTE , Sub-Query, Temporary Table or Table Variable?

#temp is materalized and CTE is not.

CTE is just syntax so in theory it is just a subquery. It is executed. #temp is materialized. So an expensive CTE in a join that is execute many times may be better in a #temp. On the other side if it is an easy evaluation that is not executed but a few times then not worth the overhead of #temp.

The are some people on SO that don't like table variable but I like them as the are materialized and faster to create than #temp. There are times when the query optimizer does better with a #temp compared to a table variable.

The ability to create a PK on a #temp or table variable gives the query optimizer more information than a CTE (as you cannot declare a PK on a CTE).

Retrieving a property of a JSON object by index?

"""
This could be done in python as follows.
Form the command as a string and then execute
"""
context = {
    "whoami": "abc",
    "status": "0",
    "curStep": 2,
    "parentStepStatus": {
        "step1":[{"stepStatus": 0, "stepLog": "f1.log"}],
        "step2":[{"stepStatus": 0, "stepLog": "f2.log"}]
    }
}
def punc():
          i = 1
          while (i < 10):
              x = "print(" + "context" + "['parentStepStatus']" + "['%s']"%("step%s")%(i) + ")"
              exec(x)
              i+=1
punc()

OPTION (RECOMPILE) is Always Faster; Why?

To add to the excellent list (given by @CodeCowboyOrg) of situations where OPTION(RECOMPILE) can be very helpful,

  1. Table Variables. When you are using table variables, there will not be any pre-built statistics for the table variable, often leading to large differences between estimated and actual rows in the query plan. Using OPTION(RECOMPILE) on queries with table variables allows generation of a query plan that has a much better estimate of the row numbers involved. I had a particularly critical use of a table variable that was unusable, and which I was going to abandon, until I added OPTION(RECOMPILE). The run time went from hours to just a few minutes. That is probably unusual, but in any case, if you are using table variables and working on optimizing, it's well worth seeing whether OPTION(RECOMPILE) makes a difference.

Reading the selected value from asp:RadioButtonList using jQuery

this:

$('#rblDiv input').click(function(){
    alert($('#rblDiv input').index(this));
});

will get you the index of the radio button that was clicked (i think, untested) (note you've had to wrap your RBL in #rblDiv

you could then use that to display the corresponding div like this:

$('.divCollection div:eq(' + $('#rblDiv input').index(this) +')').show();

Is that what you meant?

Edit: Another approach would be to give the rbl a class name, then go:

$('.rblClass').val();

Android ImageView Animation

imgDics = (ImageView) v.findViewById(R.id.img_player_tab2_dics);
    imgDics.setOnClickListener(onPlayer2Click);
    anim = new RotateAnimation(0f, 360f,
            Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
                            0.5f);
    anim.setInterpolator(new LinearInterpolator());
    anim.setRepeatCount(Animation.INFINITE);
    anim.setDuration(4000);

    // Start animating the image
    imgDics.startAnimation(anim);

How to click an element in Selenium WebDriver using JavaScript

Executing a click via JavaScript has some behaviors of which you should be aware. If for example, the code bound to the onclick event of your element invokes window.alert(), you may find your Selenium code hanging, depending on the implementation of the browser driver. That said, you can use the JavascriptExecutor class to do this. My solution differs from others proposed, however, in that you can still use the WebDriver methods for locating the elements.

// Assume driver is a valid WebDriver instance that
// has been properly instantiated elsewhere.
WebElement element = driver.findElement(By.id("gbqfd"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", element);

You should also note that you might be better off using the click() method of the WebElement interface, but disabling native events before instantiating your driver. This would accomplish the same goal (with the same potential limitations), but not force you to write and maintain your own JavaScript.

How to get a list of column names

The result set of a query in PHP offers a couple of functions allowing just that:

    numCols() 
    columnName(int $column_number )

Example

    $db = new SQLIte3('mysqlite.db');
    $table = 'mytable';

    $tableCol = getColName($db, $table);

    for ($i=0; $i<count($tableCol); $i++){
        echo "Column $i = ".$tableCol[$i]."\n";
    }           

    function getColName($db, $table){
        $qry = "SELECT * FROM $table LIMIT 1";
        $result = $db->query($qry);
        $nCols = $result->numCols();
        for ($i = 0; $i < $ncols; $i++) {
            $colName[$i] = $result->columnName($i);
        }
        return $colName;
    }

FirebaseInstanceIdService is deprecated

Just Add This On build.gradle. implementation 'com.google.firebase:firebase-messaging:20.2.3'

Cannot overwrite model once compiled Mongoose

I know there is an accepted solution but I feel that the current solution results in a lot of boilerplate just so that you can test Models. My solution is essentially to take you model and place it inside of a function resulting in returning the new Model if the Model has not been registered but returning the existing Model if it has.

function getDemo () {
  // Create your Schema
  const DemoSchema = new mongoose.Schema({
    name: String,
    email: String
  }, {
    collection: 'demo'
  })
  // Check to see if the model has been registered with mongoose
  // if it exists return that model
  if (mongoose.models && mongoose.models.Demo) return mongoose.models.Demo
  // if no current model exists register and return new model
  return mongoose.model('Demo', DemoSchema)
}

export const Demo = getDemo()

Opening and closing connections all over the place is frustrating and does not compress well.

This way if I were to require the model two different places or more specifically in my tests I would not get errors and all the correct information is being returned.

Total Number of Row Resultset getRow Method

One better way would be to use SELECT COUNT statement of SQL.

Just when you need the count of number of rows returned, execute another query returning the exact number of result of that query.

 try
{
   Conn=ConnectionODBC.getConnection();
   Statement stmt = Conn.createStatement();        
    String sqlStmt = sql;        
    String sqlrow = SELECT COUNT(*) from (sql) rowquery;
    String total = stmt.executeQuery(sqlrow);
    int rowcount = total.getInt(1);
    }

Create XML in Javascript

xml-writer(npm package) I think this is the good way to create and write xml file easy. Also it can be used on server side with nodejs.

var XMLWriter = require('xml-writer');
xw = new XMLWriter;
xw.startDocument();
xw.startElement('root');
xw.writeAttribute('foo', 'value');
xw.text('Some content');
xw.endDocument();
console.log(xw.toString());

How do I close an Android alertdialog

Replying to an old post but hopefully somebody might find this useful. Do this instead

final AlertDialog builder = new AlertDialog.Builder(getActivity()).create();

You can then go ahead and do,

builder.dismiss();

Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference

In all these scenarios outerScopeVar is modified or assigned a value asynchronously or happening in a later time(waiting or listening for some event to occur),for which the current execution will not wait.So all these cases current execution flow results in outerScopeVar = undefined

Let's discuss each examples(I marked the portion which is called asynchronously or delayed for some events to occur):

1.

enter image description here

Here we register an eventlistner which will be executed upon that particular event.Here loading of image.Then the current execution continuous with next lines img.src = 'lolcat.png'; and alert(outerScopeVar); meanwhile the event may not occur. i.e, funtion img.onload wait for the referred image to load, asynchrously. This will happen all the folowing example- the event may differ.

2.

2

Here the timeout event plays the role, which will invoke the handler after the specified time. Here it is 0, but still it registers an asynchronous event it will be added to the last position of the Event Queue for execution, which makes the guaranteed delay.

3.

enter image description here This time ajax callback.

4.

enter image description here

Node can be consider as a king of asynchronous coding.Here the marked function is registered as a callback handler which will be executed after reading the specified file.

5.

enter image description here

Obvious promise (something will be done in future) is asynchronous. see What are the differences between Deferred, Promise and Future in JavaScript?

https://www.quora.com/Whats-the-difference-between-a-promise-and-a-callback-in-Javascript

How to make a drop down list in yii2?

Following can also be done. If you want to append prepend icon. This will be helpful.

<?php $form = ActiveForm::begin();    
   echo $form->field($model, 'field')->begin();
     echo Html::activeLabel($model, 'field', ["class"=>"control-label col-md-4"]); ?>
       <div class="col-md-5">
          <?php echo Html::activeDropDownList($model, 'field', $array_list, ['class'=>'form-control']); ?>
          <p><i><small>Please select field</small></i>.</p>
          <?php echo Html::error($model, 'field', ['class'=>'help-block']); ?>
       </div>
   <?php echo $form->field($model, 'field')->end(); 
ActiveForm::end();?>

C non-blocking keyboard input

You probably want kbhit();

//Example will loop until a key is pressed
#include <conio.h>
#include <iostream>

using namespace std;

int main()
{
    while(1)
    {
        if(kbhit())
        {
            break;
        }
    }
}

this may not work on all environments. A portable way would be to create a monitoring thread and set some flag on getch();

React - Display loading screen while DOM is rendering?

I'm also using React in my app. For requests I'm using axios interceptors, so great way to make loader screen (fullpage as you showed an example) is to add class or id to for example body inside interceptors (here code from official documentation with some custom code):

// Add a request interceptor
axios.interceptors.request.use(function (config) {
    // Do something before request is sent
     document.body.classList.add('custom-loader');
     return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });

// Add a response interceptor
axios.interceptors.response.use(function (response) {
    // Do something with response data
       document.body.classList.remove('custom-loader');
       return response;
  }, function (error) {
    // Do something with response error
    return Promise.reject(error);
  }); 

And then just implement in CSS your loader with pseudo-elements (or add class or id to different element, not body as you like) - you can set color of background to opaque or transparent, etc... Example:

custom-loader:before {
    background: #000000;
    content: "";
    position: fixed;
    ...
}

custom-loader:after {
    background: #000000;
    content: "Loading content...";
    position: fixed;
    color: white;
    ...
}

Writing data into CSV file in C#

Handling Commas

For handling commas inside of values when using string.Format(...), the following has worked for me:

var newLine = string.Format("\"{0}\",\"{1}\",\"{2}\"",
                              first,
                              second,
                              third                                    
                              );
csv.AppendLine(newLine);

So to combine it with Johan's answer, it'd look like this:

//before your loop
var csv = new StringBuilder();

//in your loop
  var first = reader[0].ToString();
  var second = image.ToString();
  //Suggestion made by KyleMit
  var newLine = string.Format("\"{0}\",\"{1}\"", first, second);
  csv.AppendLine(newLine);  

//after your loop
File.WriteAllText(filePath, csv.ToString());

Returning CSV File

If you simply wanted to return the file instead of writing it to a location, this is an example of how I accomplished it:

From a Stored Procedure

public FileContentResults DownloadCSV()
{
  // I have a stored procedure that queries the information I need
  SqlConnection thisConnection = new SqlConnection("Data Source=sv12sql;User ID=UI_Readonly;Password=SuperSecure;Initial Catalog=DB_Name;Integrated Security=false");
  SqlCommand queryCommand = new SqlCommand("spc_GetInfoINeed", thisConnection);
  queryCommand.CommandType = CommandType.StoredProcedure;

  StringBuilder sbRtn = new StringBuilder();

  // If you want headers for your file
  var header = string.Format("\"{0}\",\"{1}\",\"{2}\"",
                             "Name",
                             "Address",
                             "Phone Number"
                            );
  sbRtn.AppendLine(header);

  // Open Database Connection
  thisConnection.Open();
  using (SqlDataReader rdr = queryCommand.ExecuteReader())
  {
    while (rdr.Read())
    {
      // rdr["COLUMN NAME"].ToString();
      var queryResults = string.Format("\"{0}\",\"{1}\",\"{2}\"",
                                        rdr["Name"].ToString(),
                                        rdr["Address"}.ToString(),
                                        rdr["Phone Number"].ToString()
                                       );
      sbRtn.AppendLine(queryResults);
    }
  }
  thisConnection.Close();

  return File(new System.Text.UTF8Encoding().GetBytes(sbRtn.ToString()), "text/csv", "FileName.csv");
}

From a List

/* To help illustrate */
public static List<Person> list = new List<Person>();

/* To help illustrate */
public class Person
{
  public string name;
  public string address;
  public string phoneNumber;
}

/* The important part */
public FileContentResults DownloadCSV()
{
  StringBuilder sbRtn = new StringBuilder();

  // If you want headers for your file
  var header = string.Format("\"{0}\",\"{1}\",\"{2}\"",
                             "Name",
                             "Address",
                             "Phone Number"
                            );
  sbRtn.AppendLine(header);

  foreach (var item in list)
  {
      var listResults = string.Format("\"{0}\",\"{1}\",\"{2}\"",
                                        item.name,
                                        item.address,
                                        item.phoneNumber
                                       );
      sbRtn.AppendLine(listResults);
    }
  }

  return File(new System.Text.UTF8Encoding().GetBytes(sbRtn.ToString()), "text/csv", "FileName.csv");
}

Hopefully this is helpful.

Extracting a parameter from a URL in WordPress

When passing parameters through the URL you're able to retrieve the values as GET parameters.

Use this:

$variable = $_GET['param_name'];

//Or as you have it
$ppc = $_GET['ppc'];

It is safer to check for the variable first though:

if (isset($_GET['ppc'])) {
  $ppc = $_GET['ppc'];
} else {
  //Handle the case where there is no parameter
}

Here's a bit of reading on GET/POST params you should look at: http://php.net/manual/en/reserved.variables.get.php

EDIT: I see this answer still gets a lot of traffic years after making it. Please read comments attached to this answer, especially input from @emc who details a WordPress function which accomplishes this goal securely.

what's the default value of char?

I think it is '\u00000' or just '' rather than '\u0000' (The 1st one has 5 zeros while the last one has four zeroes.)

Cast from VARCHAR to INT - MySQL

As described in Cast Functions and Operators:

The type for the result can be one of the following values:

  • BINARY[(N)]
  • CHAR[(N)]
  • DATE
  • DATETIME
  • DECIMAL[(M[,D])]
  • SIGNED [INTEGER]
  • TIME
  • UNSIGNED [INTEGER]

Therefore, you should use:

SELECT CAST(PROD_CODE AS UNSIGNED) FROM PRODUCT

'innerText' works in IE, but not in Firefox

myElement.innerText = myElement.textContent = "foo";

Edit (thanks to Mark Amery for the comment below): Only do it this way if you know beyond a reasonable doubt that no code will be relying on checking the existence of these properties, like (for example) jQuery does. But if you are using jQuery, you would probably just use the "text" function and do $('#myElement').text('foo') as some other answers show.

Remove directory which is not empty

While recursive is an experimental option of fs.rmdir

function rm (path, cb) {
    fs.stat(path, function (err, stats) {
        if (err)
            return cb(err);

        if (stats.isFile())
            return fs.unlink(path, cb);

        fs.rmdir(path, function (err) {
            if (!err || err && err.code != 'ENOTEMPTY') 
                return cb(err);

            fs.readdir(path, function (err, files) {
                if (err)
                    return cb(err);

                let next = i => i == files.length ? 
                    rm(path, cb) : 
                    rm(path + '/' + files[i], err => err ? cb(err) : next(i + 1));

                next(0);
            });
        });
    });
}

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - process out of memory

I found that max_new_space_size is not an option in node 4.1.1 and max_old_space_size alone did not solve my problem. I am adding the following to my shebang and the combination of these seems to work:

#!/usr/bin/env node --max_old_space_size=4096 --optimize_for_size --max_executable_size=4096 --stack_size=4096

[EDIT]: 4096 === 4GB of memory, if your device is low on memory you may want to choose a smaller amount.

[UPDATE]: Also discovered this error while running grunt which previously was run like so:

./node_modules/.bin/grunt

After updating the command to the following it stopped having memory errors:

node --max_old_space_size=2048 ./node_modules/.bin/grunt 

ERROR 2013 (HY000): Lost connection to MySQL server at 'reading authorization packet', system error: 0

I have a mac but would assume all linux are the same for this part...

In my case I got this:

2018-12-03 11:13:27 - Start server: 
2018-12-03 11:13:27 - Server start done.
2018-12-03 11:13:27 - Checking server status...
2018-12-03 11:13:27 - Trying to connect to MySQL...
2018-12-03 11:13:27 - Lost connection to MySQL server at 'reading authorization packet', system error: 0 (2013)
2018-12-03 11:13:27 - Assuming server is not running

I ran this:

sudo killall mysqld

And then started the mysql again through mysqlworkbench although in your case it might be like this:

mysql.server start

*sidenote: I tried running mysql.server stop and got this Shutting down MySQL .... SUCCESS! but after running ps aux | grep mysql I saw that it hasn't really shut down...

How to print all session variables currently set?

echo '<pre>';
var_dump($_SESSION);
echo '</pre>';

Or you can use print_r if you don't care about types. If you use print_r, you can make the second argument TRUE so it will return instead of echo, useful for...

echo '<pre>' . print_r($_SESSION, TRUE) . '</pre>';

C#: what is the easiest way to subtract time?

try this

namespace dateandtime
{

    class DatesTime
    {

        public static DateTime Substract(DateTime now, int hours,int minutes,int seconds)
        {
            TimeSpan T1 = new TimeSpan(hours, minutes, seconds);
            return now.Subtract(T1);
        }


        static void Main(string[] args)
        {
            Console.WriteLine(Substract(DateTime.Now, 36, 0, 0).ToString());

        }
    }
}

How to get last key in an array?

$arr = array('key1'=>'value1','key2'=>'value2','key3'=>'value3');
list($last_key) = each(array_reverse($arr));
print $last_key;
// key3

How can I profile C++ code running on Linux?

These are the two methods I use for speeding up my code:

For CPU bound applications:

  1. Use a profiler in DEBUG mode to identify questionable parts of your code
  2. Then switch to RELEASE mode and comment out the questionable sections of your code (stub it with nothing) until you see changes in performance.

For I/O bound applications:

  1. Use a profiler in RELEASE mode to identify questionable parts of your code.

N.B.

If you don't have a profiler, use the poor man's profiler. Hit pause while debugging your application. Most developer suites will break into assembly with commented line numbers. You're statistically likely to land in a region that is eating most of your CPU cycles.

For CPU, the reason for profiling in DEBUG mode is because if your tried profiling in RELEASE mode, the compiler is going to reduce math, vectorize loops, and inline functions which tends to glob your code into an un-mappable mess when it's assembled. An un-mappable mess means your profiler will not be able to clearly identify what is taking so long because the assembly may not correspond to the source code under optimization. If you need the performance (e.g. timing sensitive) of RELEASE mode, disable debugger features as needed to keep a usable performance.

For I/O-bound, the profiler can still identify I/O operations in RELEASE mode because I/O operations are either externally linked to a shared library (most of the time) or in the worst case, will result in a sys-call interrupt vector (which is also easily identifiable by the profiler).

How to check if an element does NOT have a specific class?

use the .not() method and check for an attribute:

$('p').not('[class]');

Check it here: http://jsfiddle.net/AWb79/

Shared-memory objects in multiprocessing

This is the intended use case for Ray, which is a library for parallel and distributed Python. Under the hood, it serializes objects using the Apache Arrow data layout (which is a zero-copy format) and stores them in a shared-memory object store so they can be accessed by multiple processes without creating copies.

The code would look like the following.

import numpy as np
import ray

ray.init()

@ray.remote
def func(array, param):
    # Do stuff.
    return 1

array = np.ones(10**6)
# Store the array in the shared memory object store once
# so it is not copied multiple times.
array_id = ray.put(array)

result_ids = [func.remote(array_id, i) for i in range(4)]
output = ray.get(result_ids)

If you don't call ray.put then the array will still be stored in shared memory, but that will be done once per invocation of func, which is not what you want.

Note that this will work not only for arrays but also for objects that contain arrays, e.g., dictionaries mapping ints to arrays as below.

You can compare the performance of serialization in Ray versus pickle by running the following in IPython.

import numpy as np
import pickle
import ray

ray.init()

x = {i: np.ones(10**7) for i in range(20)}

# Time Ray.
%time x_id = ray.put(x)  # 2.4s
%time new_x = ray.get(x_id)  # 0.00073s

# Time pickle.
%time serialized = pickle.dumps(x)  # 2.6s
%time deserialized = pickle.loads(serialized)  # 1.9s

Serialization with Ray is only slightly faster than pickle, but deserialization is 1000x faster because of the use of shared memory (this number will of course depend on the object).

See the Ray documentation. You can read more about fast serialization using Ray and Arrow. Note I'm one of the Ray developers.

How to encrypt/decrypt data in php?

Answer Background and Explanation

To understand this question, you must first understand what SHA256 is. SHA256 is a Cryptographic Hash Function. A Cryptographic Hash Function is a one-way function, whose output is cryptographically secure. This means it is easy to compute a hash (equivalent to encrypting data), but hard to get the original input using the hash (equivalent to decrypting the data). Since using a Cryptographic hash function means decrypting is computationally infeasible, so therefore you cannot perform decryption with SHA256.

What you want to use is a two-way function, but more specifically, a Block Cipher. A function that allows for both encryption and decryption of data. The functions mcrypt_encrypt and mcrypt_decrypt by default use the Blowfish algorithm. PHP's use of mcrypt can be found in this manual. A list of cipher definitions to select the cipher mcrypt uses also exists. A wiki on Blowfish can be found at Wikipedia. A block cipher encrypts the input in blocks of known size and position with a known key, so that the data can later be decrypted using the key. This is what SHA256 cannot provide you.

Code

$key = 'ThisIsTheCipherKey';

$ciphertext = mcrypt_encrypt(MCRYPT_BLOWFISH, $key, 'This is plaintext.', MCRYPT_MODE_CFB);

$plaintext = mcrypt_decrypt(MCRYPT_BLOWFISH, $key, $encrypted, MCRYPT_MODE_CFB);

The easiest way to replace white spaces with (underscores) _ in bash

This is borderline programming, but look into using tr:

$ echo "this is just a test" | tr -s ' ' | tr ' ' '_'

Should do it. The first invocation squeezes the spaces down, the second replaces with underscore. You probably need to add TABs and other whitespace characters, this is for spaces only.

Import a custom class in Java

I see the picture, and all your classes are in the same package. So you don't have to import, you can create a new instance without the import sentence.

Check if element at position [x] exists in the list

if(list.ElementAtOrDefault(2) != null)
{
   // logic
}

ElementAtOrDefault() is part of the System.Linq namespace.

Although you have a List, so you can use list.Count > 2.

Connection failed: SQLState: '01000' SQL Server Error: 10061

  1. Windows firewall blocks the sql server. Even if you open the 1433 port from exceptions, in the client machine it sets the connection point to dynamic port. Add also the sql server to the exceptions.

"C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\Binn\Sqlservr.exe"

More info

  1. This page helped me to solve the problem. Especially

or if you feel brave, locate the alias in the registry and delete it there.

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSSQLServer\Client\ConnectTo\

How to use jQuery to get the current value of a file input field

I don't think there is any real legitimate way to access this via the DOM. It would be a security risk that browsers have of late locked down on to prevent drive-by uploads.

How to set cache: false in jQuery.get call

I think you have to use the AJAX method instead which allows you to turn caching off:

$.ajax({
  url: "test.html",
  data: 'foo',
  success: function(){
    alert('bar');
  },
  cache: false
});

Function return value in PowerShell

With PowerShell 5 we now have the ability to create classes. Change your function into a class, and return will only return the object immediately preceding it. Here is a real simple example.

class test_class {
    [int]return_what() {
        Write-Output "Hello, World!"
        return 808979
    }
}
$tc = New-Object -TypeName test_class
$tc.return_what()

If this was a function the expected output would be

Hello World
808979

but as a class the only thing returned is the integer 808979. A class is sort of like a guarantee that it will only return the type declared or void.

Error in if/while (condition) {: missing Value where TRUE/FALSE needed

this works with "NA" not for NA

comments = c("no","yes","NA")
  for (l in 1:length(comments)) {
    #if (!is.na(comments[l])) print(comments[l])
    if (comments[l] != "NA") print(comments[l])
  }

How can I force WebKit to redraw/repaint to propagate style changes?

I've found this method to be useful when working with transitions

$element[0].style.display = 'table'; 
$element[0].offsetWidth; // force reflow
$element.one($.support.transition.end, function () { 
    $element[0].style.display = 'block'; 
});

How do I test axios in Jest?

I've done this with nock, like so:

import nock from 'nock'
import axios from 'axios'
import httpAdapter from 'axios/lib/adapters/http'

axios.defaults.adapter = httpAdapter

describe('foo', () => {
    it('bar', () => {
        nock('https://example.com:443')
            .get('/example')
            .reply(200, 'some payload')

        // test...
    })
})

How can I easily add storage to a VirtualBox machine with XP installed?

I found this nugget at the link following. It worked perfect for me and only took 5 seconds.

As of VirtualBox 4 they added support for expansion.

VBoxManage modifyhd filename.vdi --resize 46080

That will resize a virtual disk image to 45GB.

https://superuser.com/questions/172651/increasing-disk-space-on-virtualbox

Can I install/update WordPress plugins without providing FTP access?

setting up a ftp or even an SFTP connection or chmod 777 are bad ways to go for anything other than a local environment. Opening even an SFTP method introduces more security risks that are not needed.

what is needed is a writeable permission to /wp-content/uploads & /wp-content/plugins/ by the owner of those directories. (linux ls -la will show you ownership).

Default apache user that runs is www-data.

chmod 777 allows any user on the machine to edit those file, not just the apache/php thread user.

SFTP if you are not already using it, will introduce another point of possible failure from an external source. Whereas you only need access by the local user running the apache/php process to complete the objective.

Didn't see anyone making these points, so I thought I would offer this info to help with our constant WP security issues online.

Angular: How to download a file from HttpClient?

Using Blob as a source for an img:

template:

<img [src]="url">

component:

 public url : SafeResourceUrl;

 constructor(private http: HttpClient, private sanitizer: DomSanitizer) {
   this.getImage('/api/image.jpg').subscribe(x => this.url = x)
 }

 public getImage(url: string): Observable<SafeResourceUrl> {
   return this.http
     .get(url, { responseType: 'blob' })
     .pipe(
       map(x => {
         const urlToBlob = window.URL.createObjectURL(x) // get a URL for the blob
         return this.sanitizer.bypassSecurityTrustResourceUrl(urlToBlob); // tell Anuglar to trust this value
       }),
     );
 }

Further reference about trusting save values

How do I get data from a table?

use Json & jQuery. It's way easier than oldschool javascript

function savedata1() { 

var obj = $('#myTable tbody tr').map(function() {
var $row = $(this);
var t1 = $row.find(':nth-child(1)').text();
var t2 = $row.find(':nth-child(2)').text();
var t3 = $row.find(':nth-child(3)').text();
return {
    td_1: $row.find(':nth-child(1)').text(),
    td_2: $row.find(':nth-child(2)').text(),
    td_3: $row.find(':nth-child(3)').text()
   };
}).get();

Facebook API error 191

For me, it was a missing app domain. Go into the app, and make sure that you have the root of your site set up as an app domain. See screenshot.

app domains is in the basic settings of your app

How can I convert NSDictionary to NSData and vice versa?

Use NSJSONSerialization:

NSDictionary *dict;
NSData *dataFromDict = [NSJSONSerialization dataWithJSONObject:dict
                                                       options:NSJSONWritingPrettyPrinted
                                                         error:&error];

NSDictionary *dictFromData = [NSJSONSerialization JSONObjectWithData:dataFromDict
                                                             options:NSJSONReadingAllowFragments
                                                               error:&error];

The latest returns id, so its a good idea to check the returned object type after you cast (here i casted to NSDictionary).

How to compute precision, recall, accuracy and f1-score for the multiclass case with scikit learn?

First of all it's a little bit harder using just counting analysis to tell if your data is unbalanced or not. For example: 1 in 1000 positive observation is just a noise, error or a breakthrough in science? You never know.
So it's always better to use all your available knowledge and choice its status with all wise.

Okay, what if it's really unbalanced?
Once again — look to your data. Sometimes you can find one or two observation multiplied by hundred times. Sometimes it's useful to create this fake one-class-observations.
If all the data is clean next step is to use class weights in prediction model.

So what about multiclass metrics?
In my experience none of your metrics is usually used. There are two main reasons.
First: it's always better to work with probabilities than with solid prediction (because how else could you separate models with 0.9 and 0.6 prediction if they both give you the same class?)
And second: it's much easier to compare your prediction models and build new ones depending on only one good metric.
From my experience I could recommend logloss or MSE (or just mean squared error).

How to fix sklearn warnings?
Just simply (as yangjie noticed) overwrite average parameter with one of these values: 'micro' (calculate metrics globally), 'macro' (calculate metrics for each label) or 'weighted' (same as macro but with auto weights).

f1_score(y_test, prediction, average='weighted')

All your Warnings came after calling metrics functions with default average value 'binary' which is inappropriate for multiclass prediction.
Good luck and have fun with machine learning!

Edit:
I found another answerer recommendation to switch to regression approaches (e.g. SVR) with which I cannot agree. As far as I remember there is no even such a thing as multiclass regression. Yes there is multilabel regression which is far different and yes it's possible in some cases switch between regression and classification (if classes somehow sorted) but it pretty rare.

What I would recommend (in scope of scikit-learn) is to try another very powerful classification tools: gradient boosting, random forest (my favorite), KNeighbors and many more.

After that you can calculate arithmetic or geometric mean between predictions and most of the time you'll get even better result.

final_prediction = (KNNprediction * RFprediction) ** 0.5

C++, copy set to vector

You need to use a back_inserter:

std::copy(input.begin(), input.end(), std::back_inserter(output));

std::copy doesn't add elements to the container into which you are inserting: it can't; it only has an iterator into the container. Because of this, if you pass an output iterator directly to std::copy, you must make sure it points to a range that is at least large enough to hold the input range.

std::back_inserter creates an output iterator that calls push_back on a container for each element, so each element is inserted into the container. Alternatively, you could have created a sufficient number of elements in the std::vector to hold the range being copied:

std::vector<double> output(input.size());
std::copy(input.begin(), input.end(), output.begin());

Or, you could use the std::vector range constructor:

std::vector<double> output(input.begin(), input.end()); 

What is mapDispatchToProps?

I feel like none of the answers have crystallized why mapDispatchToProps is useful.

This can really only be answered in the context of the container-component pattern, which I found best understood by first reading:Container Components then Usage with React.

In a nutshell, your components are supposed to be concerned only with displaying stuff. The only place they are supposed to get information from is their props.

Separated from "displaying stuff" (components) is:

  • how you get the stuff to display,
  • and how you handle events.

That is what containers are for.

Therefore, a "well designed" component in the pattern look like this:

class FancyAlerter extends Component {
    sendAlert = () => {
        this.props.sendTheAlert()
    }

    render() {
        <div>
          <h1>Today's Fancy Alert is {this.props.fancyInfo}</h1>
          <Button onClick={sendAlert}/>
        </div>
     }
}

See how this component gets the info it displays from props (which came from the redux store via mapStateToProps) and it also gets its action function from its props: sendTheAlert().

That's where mapDispatchToProps comes in: in the corresponding container

// FancyButtonContainer.js

function mapDispatchToProps(dispatch) {
    return({
        sendTheAlert: () => {dispatch(ALERT_ACTION)}
    })
}

function mapStateToProps(state) {
    return({fancyInfo: "Fancy this:" + state.currentFunnyString})
}

export const FancyButtonContainer = connect(
    mapStateToProps, mapDispatchToProps)(
    FancyAlerter
)

I wonder if you can see, now that it's the container 1 that knows about redux and dispatch and store and state and ... stuff.

The component in the pattern, FancyAlerter, which does the rendering doesn't need to know about any of that stuff: it gets its method to call at onClick of the button, via its props.

And ... mapDispatchToProps was the useful means that redux provides to let the container easily pass that function into the wrapped component on its props.

All this looks very like the todo example in docs, and another answer here, but I have tried to cast it in the light of the pattern to emphasize why.

(Note: you can't use mapStateToProps for the same purpose as mapDispatchToProps for the basic reason that you don't have access to dispatch inside mapStateToProp. So you couldn't use mapStateToProps to give the wrapped component a method that uses dispatch.

I don't know why they chose to break it into two mapping functions - it might have been tidier to have mapToProps(state, dispatch, props) IE one function to do both!


1 Note that I deliberately explicitly named the container FancyButtonContainer, to highlight that it is a "thing" - the identity (and hence existence!) of the container as "a thing" is sometimes lost in the shorthand

export default connect(...) ????????????

syntax that is shown in most examples

Align two divs horizontally side by side center to the page using bootstrap css

Use the bootstrap classes col-xx-# and col-xx-offset-#

So what is happening here is your screen is getting divided into 12 columns. In col-xx-#, # is the number of columns you cover and offset is the number of columns you leave.

For xx, in a general website, md is preferred and if you want your layout to look the same in a mobile device, xs is preferred.

With what I can make of your requirement,

<div class="row">
  <div class="col-md-4">First Div</div>
  <div class="col-md-8">Second DIV </div>
</div>

Should do the trick.

How do I use Ruby for shell scripting?

As the others have said already, your first line should be

#!/usr/bin/env ruby

And you also have to make it executable: (in the shell)

chmod +x test.rb

Then follows the ruby code. If you open a file

File.open("file", "r") do |io|
    # do something with io
end

the file is opened in the current directory you'd get with pwd in the shell.

The path to your script is also simple to get. With $0 you get the first argument of the shell, which is the relative path to your script. The absolute path can be determined like that:

#!/usr/bin/env ruby
require 'pathname'
p Pathname.new($0).realpath()

For file system operations I almost always use Pathname. This is a wrapper for many of the other file system related classes. Also useful: Dir, File...

What is a word boundary in regex, does \b match hyphen '-'?

A word boundary is a position that is either preceded by a word character and not followed by one, or followed by a word character and not preceded by one.

Stop all active ajax requests in jQuery

I found it too easy for multiple requests.

step1: define a variable at top of page:

  xhrPool = []; // no need to use **var**

step2: set beforeSend in all ajax requests:

  $.ajax({
   ...
   beforeSend: function (jqXHR, settings) {
        xhrPool.push(jqXHR);
    },
    ...

step3: use it whereever you required:

   $.each(xhrPool, function(idx, jqXHR) {
          jqXHR.abort();
    });

How to get cell value from DataGridView in VB.Net?

This helped me get close to what I needed and I will throw this out there for anyone else who needs it.

If you are looking for the value in the first cell in the selected column, you can try this. (I chose the first column, since you are asking for it to return "3", but you can change the number after Cells to get whichever column you need. Remember it is zero-based.)

This will copy the result to the clipboard: Clipboard.SetDataObject(Me.DataGridView1.CurrentRow.Cells(0).Value)

Count rows with not empty value

Given the range A:A, Id suggest:

=COUNTA(A:A)-(COUNTIF(A:A,"*")-COUNTIF(A:A,"?*"))

The problem is COUNTA over-counts by exactly the number of cells with zero length strings "".

The solution is to find a count of exactly these cells. This can be found by looking for all text cells and subtracting all text cells with at least one character

  • COUNTA(A:A): cells with value, including "" but excluding truly empty cells
  • COUNTIF(A:A,"*"): cells recognized as text, including "" but excluding truly blank cells
  • COUNTIF(A:A,"?*"): cells recognized as text with at least one character

This means that the value COUNTIF(A:A,"*")-COUNTIF(A:A,"?*") should be the number of text cells minus the number of text cells that have at least one character i.e. the count of cells containing exactly ""

Difference between "Complete binary tree", "strict binary tree","full binary Tree"?

Complete Binary Tree: All levels are completely filled except the lowest level and one main thing all the leaf elements must have left child. Strict Binary Tree: In this tree every non-leaf node has no child i.e. neither left nor right. Full Binary Tree: Every Node has either zero child or Two children (never having single child).

$(document).ready(function(){ Uncaught ReferenceError: $ is not defined

many other people answered your question above. This problen arises when your script don't find the jQuery script and if you are using other framework or cms then maybe there is a conflict between jQuery and other libraries. In my case i used as following- `

<script src="js_directory/jquery.1.7.min.js"></script>
    <script>
    jQuery.noConflict();
    jQuery(document).ready(
    function($){
    //your other code here
    });</script>

`

here might be some syntax error. Please forgive me because i'm writing from my cell phone. Thanks

Npm Error - No matching version found for

If none of this did not help, then try to swap ^ in "^version" to ~ "~version".

Static variable inside of a function in C

That is the same as having the following program:

static int x = 5;

void foo()
{
    x++;
    printf("%d", x);
}

int main()
{
     foo();
     foo();
     return 0;
}

All that the static keyword does in that program is it tells the compiler (essentially) 'hey, I have a variable here that I don't want anyone else accessing, don't tell anyone else it exists'.

Inside a method, the static keyword tells the compiler the same as above, but also, 'don't tell anyone that this exists outside of this function, it should only be accessible inside this function'.

I hope this helps

jQuery add image inside of div tag

var img;
for (var i = 0; i < jQuery('.MulImage').length; i++) {
                var imgsrc = jQuery('.MulImage')[i];
                var CurrentImgSrc = imgsrc.src;
                img = jQuery('<img class="dynamic" style="width:100%;">');
                img.attr('src', CurrentImgSrc);
                jQuery('.YourDivClass').append(img);

            }

Int division: Why is the result of 1/3 == 0?

Because it treats 1 and 3 as integers, therefore rounding the result down to 0, so that it is an integer.

To get the result you are looking for, explicitly tell java that the numbers are doubles like so:

double g = 1.0/3.0;

What do "branch", "tag" and "trunk" mean in Subversion repositories?

In general (tool agnostic view), a branch is the mechanism used for parallel development. An SCM can have from 0 to n branches. Subversion has 0.

  • Trunk is a main branch recommended by Subversion, but you are in no way forced to create it. You could call it 'main' or 'releases', or not have one at all!

  • Branch represents a development effort. It should never be named after a resource (like 'vonc_branch') but after:

    • a purpose 'myProject_dev' or 'myProject_Merge'
    • a release perimeter 'myProjetc1.0_dev'or myProject2.3_Merge' or 'myProject6..2_Patch1'...
  • Tag is a snapshot of files in order to easily get back to that state. The problem is that tag and branch is the same in Subversion. And I would definitely recommend the paranoid approach:

    you can use one of the access control scripts provided with Subversion to prevent anyone from doing anything but creating new copies in the tags area.

A tag is final. Its content should never change. NEVER. Ever. You forgot a line in the release note? Create a new tag. Obsolete or remove the old one.

Now, I read a lot about "merging back such and such in such and such branches, then finally in the trunk branch". That is called merge workflow and there is nothing mandatory here. It is not because you have a trunk branch that you have to merge back anything.

By convention, the trunk branch can represent the current state of your development, but that is for a simple sequential project, that is a project which has:

  • no 'in advance' development (for the preparing the next-next version implying such changes that they are not compatible with the current 'trunk' development)
  • no massive refactoring (for testing a new technical choice)
  • no long-term maintenance of a previous release

Because with one (or all) of those scenario, you get yourself four 'trunks', four 'current developments', and not all you do in those parallel development will necessarily have to be merged back in 'trunk'.

Spring MVC: Complex object as GET @RequestParam

While answers that refer to @ModelAttribute, @RequestParam, @PathParam and the likes are valid, there is a small gotcha I ran into. The resulting method parameter is a proxy that Spring wraps around your DTO. So, if you attempt to use it in a context that requires your own custom type, you may get some unexpected results.

The following will not work:

@GetMapping(produces = APPLICATION_JSON_VALUE)
public ResponseEntity<CustomDto> request(@ModelAttribute CustomDto dto) {
    return ResponseEntity.ok(dto);
}

In my case, attempting to use it in Jackson binding resulted in a com.fasterxml.jackson.databind.exc.InvalidDefinitionException.

You will need to create a new object from the dto.

HTML / CSS table with GRIDLINES

For internal gridlines, use the tag: td For external gridlines, use the tag: table

Working Soap client example

Calculator SOAP service test from SoapUI, Online SoapClient Calculator

Generate the SoapMessage object form the input SoapEnvelopeXML and SoapDataXml.

SoapEnvelopeXML

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
   <soapenv:Header/>
   <soapenv:Body>
      <tem:Add xmlns:tem="http://tempuri.org/">
         <tem:intA>3</tem:intA>
         <tem:intB>4</tem:intB>
      </tem:Add>
   </soapenv:Body>
</soapenv:Envelope>

use the following code to get SoapMessage Object.

MessageFactory messageFactory = MessageFactory.newInstance();
    MimeHeaders headers = new MimeHeaders();
    ByteArrayInputStream xmlByteStream = new ByteArrayInputStream(SoapEnvelopeXML.getBytes());
SOAPMessage soapMsg = messageFactory.createMessage(headers, xmlByteStream);

SoapDataXml

<tem:Add xmlns:tem="http://tempuri.org/">
    <tem:intA>3</tem:intA>
    <tem:intB>4</tem:intB>
</tem:Add>

use below code to get SoapMessage Object.

public static SOAPMessage getSOAPMessagefromDataXML(String saopBodyXML) throws Exception {
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    dbFactory.setNamespaceAware(true);
    dbFactory.setIgnoringComments(true);
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    InputSource ips = new org.xml.sax.InputSource(new StringReader(saopBodyXML));
    Document docBody = dBuilder.parse(ips);
    System.out.println("Data Document: "+docBody.getDocumentElement());
    
    MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL);
    SOAPMessage soapMsg = messageFactory.createMessage();
    
    SOAPBody soapBody = soapMsg.getSOAPPart().getEnvelope().getBody();
    soapBody.addDocument(docBody);
    
    return soapMsg;
}

By getting the SoapMessage Object. It is clear that the Soap XML is valid. Then prepare to hit the service to get response. It can be done in many ways.

  1. Using Client Code Generated form WSDL.
java.net.URL endpointURL = new java.net.URL(endPointUrl);
javax.xml.rpc.Service service = new org.apache.axis.client.Service();
((org.apache.axis.client.Service) service).setTypeMappingVersion("1.2");
CalculatorSoap12Stub obj_axis = new CalculatorSoap12Stub(endpointURL, service);
int add = obj_axis.add(10, 20);
System.out.println("Response: "+ add);
  1. Using javax.xml.soap.SOAPConnection.
public static void getSOAPConnection(SOAPMessage soapMsg) throws Exception {
    System.out.println("===== SOAPConnection =====");
    MimeHeaders headers = soapMsg.getMimeHeaders(); // new MimeHeaders();
    headers.addHeader("SoapBinding",   serverDetails.get("SoapBinding") );
    headers.addHeader("MethodName",    serverDetails.get("MethodName") );
    headers.addHeader("SOAPAction",    serverDetails.get("SOAPAction") );
    headers.addHeader("Content-Type",  serverDetails.get("Content-Type"));
    headers.addHeader("Accept-Encoding", serverDetails.get("Accept-Encoding"));
    if (soapMsg.saveRequired()) {
        soapMsg.saveChanges();
    }
    
    SOAPConnectionFactory newInstance = SOAPConnectionFactory.newInstance();
    javax.xml.soap.SOAPConnection connection = newInstance.createConnection();
    SOAPMessage soapMsgResponse = connection.call(soapMsg, getURL( serverDetails.get("SoapServerURI"), 5*1000 ));
    
    getSOAPXMLasString(soapMsgResponse);
}
  1. Form HTTP Connection Classes org.apache.commons.httpclient.
public static void getHttpConnection(SOAPMessage soapMsg) throws SOAPException, IOException {
    System.out.println("===== HttpClient =====");
    HttpClient httpClient = new HttpClient();
    HttpConnectionManagerParams params = httpClient.getHttpConnectionManager().getParams();
    params.setConnectionTimeout(3 * 1000); // Connection timed out
    params.setSoTimeout(3 * 1000);         // Request timed out
    params.setParameter("http.useragent", "Web Service Test Client");

    PostMethod methodPost = new PostMethod( serverDetails.get("SoapServerURI") );
    methodPost.setRequestBody( getSOAPXMLasString(soapMsg) );
    methodPost.setRequestHeader("Content-Type", serverDetails.get("Content-Type") );
    methodPost.setRequestHeader("SoapBinding",  serverDetails.get("SoapBinding") );
    methodPost.setRequestHeader("MethodName",   serverDetails.get("MethodName") );
    methodPost.setRequestHeader("SOAPAction",   serverDetails.get("SOAPAction") );

    methodPost.setRequestHeader("Accept-Encoding", serverDetails.get("Accept-Encoding"));

    try {
        int returnCode = httpClient.executeMethod(methodPost);
        if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {
            System.out.println("The Post method is not implemented by this URI");
            methodPost.getResponseBodyAsString();
        } else {
            BufferedReader br = new BufferedReader(new InputStreamReader(methodPost.getResponseBodyAsStream()));
            String readLine;
            while (((readLine = br.readLine()) != null)) {
                System.out.println(readLine);
            }
            br.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        methodPost.releaseConnection();
    }
}
public static void accessResource_AppachePOST(SOAPMessage soapMsg) throws Exception {
    System.out.println("===== HttpClientBuilder =====");
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    URIBuilder builder = new URIBuilder( serverDetails.get("SoapServerURI") );
    HttpPost methodPost = new HttpPost(builder.build());
    RequestConfig config = RequestConfig.custom()
            .setConnectTimeout(5 * 1000)
            .setConnectionRequestTimeout(5 * 1000)
            .setSocketTimeout(5 * 1000)
            .build();
    methodPost.setConfig(config);
        HttpEntity xmlEntity = new StringEntity(getSOAPXMLasString(soapMsg), "utf-8");
    methodPost.setEntity(xmlEntity);
        
    methodPost.setHeader("Content-Type", serverDetails.get("Content-Type"));
    methodPost.setHeader("SoapBinding", serverDetails.get("SoapBinding") );
    methodPost.setHeader("MethodName", serverDetails.get("MethodName") );
    methodPost.setHeader("SOAPAction", serverDetails.get("SOAPAction") );
    methodPost.setHeader("Accept-Encoding", serverDetails.get("Accept-Encoding"));
    
    // Create a custom response handler
    ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
        @Override
        public String handleResponse( final HttpResponse response) throws ClientProtocolException, IOException {
            int status = response.getStatusLine().getStatusCode();
            if (status >= 200 && status <= 500) {
                HttpEntity entity = response.getEntity();
                return entity != null ? EntityUtils.toString(entity) : null;
            }
            return "";
        }
    };
    String execute = httpClient.execute( methodPost, responseHandler );
    System.out.println("AppachePOST : "+execute);
}

Full Example:

public class SOAP_Calculator {
    static HashMap<String, String> serverDetails = new HashMap<>();
    static {
        // Calculator
        serverDetails.put("SoapServerURI", "http://www.dneonline.com/calculator.asmx");
        serverDetails.put("SoapWSDL", "http://www.dneonline.com/calculator.asmx?wsdl");
        serverDetails.put("SoapBinding", "CalculatorSoap");        // <wsdl:binding name="CalculatorSoap12" type="tns:CalculatorSoap">
        serverDetails.put("MethodName", "Add");                    // <wsdl:operation name="Add">
        serverDetails.put("SOAPAction", "http://tempuri.org/Add"); // <soap12:operation soapAction="http://tempuri.org/Add" style="document"/>
        serverDetails.put("SoapXML", "<tem:Add xmlns:tem=\"http://tempuri.org/\"><tem:intA>2</tem:intA><tem:intB>4</tem:intB></tem:Add>");
        
        serverDetails.put("Accept-Encoding", "gzip,deflate");
        serverDetails.put("Content-Type", "");
    }
    public static void callSoapService( ) throws Exception {
        String xmlData = serverDetails.get("SoapXML");
        
        SOAPMessage soapMsg = getSOAPMessagefromDataXML(xmlData);
        System.out.println("Requesting SOAP Message:\n"+ getSOAPXMLasString(soapMsg) +"\n");
        
        SOAPEnvelope envelope = soapMsg.getSOAPPart().getEnvelope();
        if (envelope.getElementQName().getNamespaceURI().equals("http://schemas.xmlsoap.org/soap/envelope/")) {
            System.out.println("SOAP 1.1 NamespaceURI: http://schemas.xmlsoap.org/soap/envelope/");
            serverDetails.put("Content-Type", "text/xml; charset=utf-8");
        } else {
            System.out.println("SOAP 1.2 NamespaceURI: http://www.w3.org/2003/05/soap-envelope");
            serverDetails.put("Content-Type", "application/soap+xml; charset=utf-8");
        }
        
        getHttpConnection(soapMsg);
        getSOAPConnection(soapMsg);
        accessResource_AppachePOST(soapMsg);
    }
    public static void main(String[] args) throws Exception {
        callSoapService();
    }

    private static URL getURL(String endPointUrl, final int timeOutinSeconds) throws MalformedURLException {
        URL endpoint = new URL(null, endPointUrl, new URLStreamHandler() {
            protected URLConnection openConnection(URL url) throws IOException {
                URL clone = new URL(url.toString());
                URLConnection connection = clone.openConnection();
                connection.setConnectTimeout(timeOutinSeconds);
                connection.setReadTimeout(timeOutinSeconds);
                //connection.addRequestProperty("Developer-Mood", "Happy"); // Custom header
                return connection;
            }
        });
        return endpoint;
    }
    public static String getSOAPXMLasString(SOAPMessage soapMsg) throws SOAPException, IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        soapMsg.writeTo(out);
        // soapMsg.writeTo(System.out);
        String strMsg = new String(out.toByteArray());
        System.out.println("Soap XML: "+ strMsg);
        return strMsg;
    }
}

@See list of some WebServices at http://sofa.uqam.ca/soda/webservices.php

Why doesn't CSS ellipsis work in table cell?

Apparently, adding:

td {
  display: block; /* or inline-block */
}

solves the problem as well.


Another possible solution is to set table-layout: fixed; for the table, and also set it's width. For example: http://jsfiddle.net/fd3Zx/5/

How can I increase a scrollbar's width using CSS?

This sets the scrollbar width:

::-webkit-scrollbar {
  width: 8px;   // for vertical scroll bar
  height: 8px;  // for horizontal scroll bar
}

// for Firefox add this class as well
.thin_scroll{
  scrollbar-width: thin; // auto | thin | none | <length>;
}

In Angular, I need to search objects in an array

Saw this thread but I wanted to search for IDs that did not match my search. Code to do that:

found = $filter('filter')($scope.fish, {id: '!fish_id'}, false);

Angular2 multiple router-outlet in the same template

<a [routerLink]="[{ outlets: { list:['streams'], details:['parties'] } }]">Link</a>

<div id="list">
    <router-outlet name="list"></router-outlet>
</div>
<div id="details">
    <router-outlet name="details"></router-outlet>
</div>

`

 {
    path: 'admin',
    component: AdminLayoutComponent,
    children:[
      {
        path: '',
        component: AdminStreamsComponent, 
        outlet:'list'
      },
      {
        path: 'stream/:id',
        component: AdminStreamComponent,
        outlet:'details'
      }
    ]
  }

How to test the `Mosquitto` server?

The OP has not defined the scope of testing, however, simple (gross) 'smoke testing' an install should be performed before any time is invested with functionality testing.

How to test if application is installed ('smoke-test')

Log into the mosquitto server's command line and type:

mosquitto

If mosquitto is installed the machine will return:

 mosquitto version 1.4.8 (build date Wed, date of installation) starting
 Using default config.
 Opening ipv4 listen socket on port 1883

EXC_BAD_ACCESS signal received

I've been debuging, and refactoring code to solve this error for the last four hours. A post above led me to see the problem:

Property before:

startPoint = [[DataPoint alloc] init] ;
startPoint= [DataPointList objectAtIndex: 0];
x = startPoint.x - 10; // EXC_BAD_ACCESS

Property after:

startPoint = [[DataPoint alloc] init] ;
startPoint = [[DataPointList objectAtIndex: 0] retain];

Goodbye EXC_BAD_ACCESS

Thank you so much for your answer. I've been struggling with this problem all day. You're awesome!

Gradient borders

For cross-browser support you can try as well imitate a gradient border with :before or :after pseudo elements, depends on what you want to do.

Way to insert text having ' (apostrophe) into a SQL table

INSERT INTO exampleTbl VALUES('he doesn''t work for me')

If you're adding a record through ASP.NET, you can use the SqlParameter object to pass in values so you don't have to worry about the apostrophe's that users enter in.

How do I convert a double into a string in C++?

Herb Sutter has an excellent article on string formatting. I recommend reading it. I've linked it before on SO.

How do I see the extensions loaded by PHP?

Running

php -m
will give you all the modules, and
php -i
will give you a lot more detailed information on what the current configuration.

Replace last occurrence of a string in a string

For the interested: I've written a function that utilises preg_match so that you're able to replace from right hand side using regex.

function preg_rreplace($search, $replace, $subject) {
    preg_match_all($search, $subject, $matches, PREG_SET_ORDER);
    $lastMatch = end($matches);

    if ($lastMatch && false !== $pos = strrpos($subject, $lastMatchedStr = $lastMatch[0])) {
        $subject = substr_replace($subject, $replace, $pos, strlen($lastMatchedStr));
    }

    return $subject;
}

Or as a shorthand combination/implementation of both options:

function str_rreplace($search, $replace, $subject) {
    return (false !== $pos = strrpos($subject, $search)) ?
        substr_replace($subject, $replace, $pos, strlen($search)) : $subject;
}
function preg_rreplace($search, $replace, $subject) {
    preg_match_all($search, $subject, $matches, PREG_SET_ORDER);
    return ($lastMatch = end($matches)) ? str_rreplace($lastMatch[0], $replace, $subject) : $subject;
}

based on https://stackoverflow.com/a/3835653/3017716 and https://stackoverflow.com/a/23343396/3017716

Rownum in postgresql

Postgresql have limit.

Oracle's code:

select *
from
  tbl
where rownum <= 1000;

same in Postgresql's code:

select *
from
  tbl
limit 1000

Difference between OData and REST web services

UPDATE Warning, this answer is extremely out of date now that OData V4 is available.


I wrote a post on the subject a while ago here.

As Franci said, OData is based on Atom Pub. However, they have layered some functionality on top and unfortunately have ignored some of the REST constraints in the process.

The querying capability of an OData service requires you to construct URIs based on information that is not available, or linked to in the response. It is what REST people call out-of-band information and introduces hidden coupling between the client and server.

The other coupling that is introduced is through the use of EDMX metadata to define the properties contained in the entry content. This metadata can be discovered at a fixed endpoint called $metadata. Again, the client needs to know this in advance, it cannot be discovered.

Unfortunately, Microsoft did not see fit to create media types to describe these key pieces of data, so any OData client has to make a bunch of assumptions about the service that it is talking to and the data it is receiving.

Not equal to != and !== in PHP

You can find the info here: http://www.php.net/manual/en/language.operators.comparison.php

It's scarce because it wasn't added until PHP4. What you have is fine though, if you know there may be a type difference then it's a much better comparison, since it's testing value and type in the comparison, not just value.

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

We have a large .SLN files with many project files. I started the policy of having a "ViewLocal" directory where all non-sourcecontrolled files are located. Inside that directory is an 'Inter' and an 'Out' directory. For the intermediate files, and the output files, respectively.

This obviously makes it easy to just go to your 'viewlocal' directory and do a simple delete, to get rid of everything.

Before you spent time figuring out a way to work around this with scripts, you might think about setting up something similar.

I won't lie though, maintaining such a setup in a large organization has proved....interesting. Especially when you use technologies such as QT that like to process files and create non-sourcecontrolled source files. But that is a whole OTHER story!

Return datetime object of previous month

Simplest Way that i have tried Just now

from datetime import datetime
from django.utils import timezone





current = timezone.now()
if current.month == 1:
     month = 12
else:
     month = current.month - 1
current = datetime(current.year, month, current.day)

How can I compile my Perl script so it can be executed on systems without perl installed?

pp can create an executable that includes perl and your script (and any module dependencies), but it will be specific to your architecture, so you couldn't run it on both Windows and linux for instance.

From its doc:

To make a stand-alone executable, suitable for running on a machine that doesn't have perl installed:

   % pp -o packed.exe source.pl        # makes packed.exe
   # Now, deploy 'packed.exe' to target machine...
   $ packed.exe                        # run it

(% and $ there are command prompts on different machines).

How to manually install an artifact in Maven 2?

If you ever get similar errors when using Windows PowerShell, you should try Windows' simple command-line. I didn't find out what caused this, but PowerShell seems to interpret some of Maven's parameters.

Replace \n with <br />

The Problem is When you denote '\n' in the replace() call , '\n' is treated as a String length=4 made out of ' \ n '
To get rid of this, use ascii notation. http://www.asciitable.com/

example:

newLine = chr(10)
thatLine=thatLine.replace(newLine , '<br />')

print(thatLine) #python3

print thatLine #python2 .

Getting list of lists into pandas DataFrame

With approach explained by EdChum above, the values in the list are shown as rows. To show the values of lists as columns in DataFrame instead, simply use transpose() as following:

table = [[1 , 2], [3, 4]]
df = pd.DataFrame(table)
df = df.transpose()
df.columns = ['Heading1', 'Heading2']

The output then is:

      Heading1  Heading2
0         1        3
1         2        4

Error 80040154 (Class not registered exception) when initializing VCProjectEngineObject (Microsoft.VisualStudio.VCProjectEngine.dll)

There are not many good reasons this would fail, especially the regsvr32 step. Run dumpbin /exports on that dll. If you don't see DllRegisterServer then you've got a corrupt install. It should have more side-effects, you wouldn't be able to build C/C++ projects anymore.

One standard failure mode is running this on a 64-bit operating system. This is 32-bit unmanaged code, you would indeed get the 'class not registered' exception. Project + Properties, Build tab, change Platform Target to x86.

How to limit the maximum files chosen when using multiple file input

You should also consider using libraries to do that: they allow limiting and much more:

They are also available at https://cdnjs.com/

Is there a Wikipedia API?

MediaWiki's API is running on Wikipedia (docs). You can also use the Special:Export feature to dump data and parse it yourself.

More information.

setting the id attribute of an input element dynamically in IE: alternative for setAttribute method

I had the same issue! I was unable to change/set the ID attribute of elements. It worked in all other browsers but not IE. It probably isn't relevant to your problem but here is what I ended up doing:

Background

I was building an MVC site with jquery tabs. I wanted to create tabs dynamically and do an AJAX postback to the server saving the tab in the database. I wanted to use a unique identifier, in the form of an int, for the tabs so I wouldn't get in to trouble if a user created two tabs with the same name. I then used the unique ID to identify the tabs like:

<ul>
<li><a href='#{href}'>#{label}</a> <span class='ui-icon ui-icon-close'>Remove List</span></li>
<ul>

When I then implemented the remove functions on the tabs the callback uses the index, witch is 0 based. Then I had no way to sending back the unique ID to the server to trash the DB entry. The callback for the tabremove event gives the jquery event and ui parameters. With one line of code I could get the ID of the span:

var dbIndex = event.currentTarget.id;

The problem was that the span tag didn't have any ID. So in the create callback I tried to set the ID buy extracting the ID from the a href like this:

ui.tab.parentNode.id = ui.tab.href.substring(ui.tab.href.indexOf('#list-') + 6);

That worked fine in FireFox but not in IE. So I tried a few other:

//ui.tab.parentNode.setAttribute('id', ui.tab.href.substring(ui.tab.href.indexOf('#list-') + 6));
//$(ui.tab.parentNode).attr({'id':ui.tab.href.substring(ui.tab.href.indexOf('#list-') + 6)});
//ui.tab.parentNode.id.value = ui.tab.href.substring(ui.tab.href.indexOf('#list-') + 6);

None of them worked! So after a few hours of test and Googeling I gave up and draw the conclusion that IE cant set the ID attribute of an element dynamically.

As I sad this is probably not relevant to your issue but I thought I would share.

Solution

And for all of you who found this by Googleing on the tabs issue I had here is what I ended up doing in the tabsremove callback to solve the issue:

var dbIndex = event.currentTarget.offsetParent.childNodes[0].href.substring(event.currentTarget.offsetParent.childNodes[0].href.indexOf('#list-') + 6);

Probably not the sexiest solution but hey it solved the issue. If anyone have any input please share...

Text file in VBA: Open/Find Replace/SaveAs/Close File

Guess I'm too late...

Came across the same problem today; here is my solution using FileSystemObject:

Dim objFSO
Const ForReading = 1
Const ForWriting = 2
Dim objTS 'define a TextStream object
Dim strContents As String
Dim fileSpec As String

fileSpec = "C:\Temp\test.txt"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTS = objFSO.OpenTextFile(fileSpec, ForReading)
strContents = objTS.ReadAll
strContents = Replace(strContents, "XXXXX", "YYYY")
objTS.Close

Set objTS = objFSO.OpenTextFile(fileSpec, ForWriting)
objTS.Write strContents
objTS.Close

Getting Data from Android Play Store

Disclaimer: I am from 42matters, who provides this data already on https://42matters.com/api , feel free to check it out or drop us a line.

As lenik mentioned there are open-source libraries that already help with obtaining some data from GPlay. If you want to build one yourself you can try to parse the Google Play App page, but you should pay attention to the following:

  • Make sure the URL you are trying to parse is not blocked in robots.txt - e.g. https://play.google.com/robots.txt
  • Make sure that you are not doing it too often, Google will throttle and potentially blacklist you if you are doing it too much.
  • Send a correct User-Agent header to actually show you are a bot
  • The page of an app is big - make sure you accept gzip and request the mobile version
  • GPlay website is not an API, it doesn't care that you parse it so it will change over time. Make sure you handle changes - e.g. by having test to make sure you get what you expected.

So that in mind getting one page metadata is a matter of fetching the page html and parsing it properly. With JSoup you can try:

      HttpClient httpClient = HttpClientBuilder.create().build();
      HttpGet request = new HttpGet(crawlUrl);
      HttpResponse rsp = httpClient.execute(request);

      int statusCode = rsp.getStatusLine().getStatusCode();

      if (statusCode == 200) {
           String content = EntityUtils.toString(rsp.getEntity());    
           Document doc = Jsoup.parse(content);
           //parse content, whatever you need
           Element price = doc.select("[itemprop=price]").first();
      }      

For that very simple use case that should get you started. However, the moment you want to do more interesting stuff, things get complicated:

  • Search is forbidden in robots.
  • Keeping app metadata up-to-date is hard to do. There are more than 2.2m apps, if you want to refresh their metadata daily there are 2.2 requests/day, which will 1) get blocked immediately, 2) costs a lot of money - pessimistic 220gb data transfer per day if one app is 100k
  • How do you discover new apps
  • How do you get pricing in each country, translations of each language

The list goes on. If you don't want to do all this by yourself, you can consider 42matters API, which supports lookup and search, top google charts, advanced queries and filters. And this for 35 languages and more than 50 countries.

[2]:

How to display the function, procedure, triggers source code in postgresql?

For function:

you can query the pg_proc view , just as the following

select proname,prosrc from pg_proc where proname= your_function_name; 

Another way is that just execute the commont \df and \ef which can list the functions.

skytf=> \df           
                                             List of functions
 Schema |         Name         | Result data type |              Argument data types               |  Type  
--------+----------------------+------------------+------------------------------------------------+--------
 public | pg_buffercache_pages | SETOF record     |                                                | normal


skytf=> \ef  pg_buffercache_pages

It will show the source code of the function.

For triggers:

I dont't know if there is a direct way to get the source code. Just know the following way, may be it will help you!

  • step 1 : Get the table oid of the trigger:
    skytf=> select tgrelid from pg_trigger  where tgname='insert_tbl_tmp_trigger';
      tgrelid
    ---------
       26599
    (1 row)
  • step 2: Get the table name of the above oid !
    skytf=> select oid,relname  from pg_class where oid=26599;
      oid  |           relname           
    -------+-----------------------------
     26599 | tbl_tmp
    (1 row)
  • step 3: list the table information
    skytf=> \d tbl_tmp

It will show you the details of the trigger of the table . Usually a trigger uses a function. So you can get the source code of the trigger function just as the above that I pointed out !

What is an OS kernel ? How does it differ from an operating system?

a kernel is part of the operating system, it is the first thing that the boot loader loads onto the cpu (for most operating systems), it is the part that interfaces with the hardware, and it also manages what programs can do what with the hardware, it is really the central part of the os, it is made up of drivers, a driver is a program that interfaces with a particular piece of hardware, for example: if I made a digital camera for computers, I would need to make a driver for it, the drivers are the only programs that can control the input and output of the computer

How to split strings into text and number?

import re

s = raw_input()
m = re.match(r"([a-zA-Z]+)([0-9]+)",s)
print m.group(0)
print m.group(1)
print m.group(2)

What is the difference between 'my' and 'our' in Perl?

The PerlMonks and PerlDoc links from cartman and Olafur are a great reference - below is my crack at a summary:

my variables are lexically scoped within a single block defined by {} or within the same file if not in {}s. They are not accessible from packages/subroutines defined outside of the same lexical scope / block.

our variables are scoped within a package/file and accessible from any code that use or require that package/file - name conflicts are resolved between packages by prepending the appropriate namespace.

Just to round it out, local variables are "dynamically" scoped, differing from my variables in that they are also accessible from subroutines called within the same block.

How can I check that two objects have the same set of property names?

Here is my attempt at validating JSON properties. I used @casey-foster 's approach, but added recursion for deeper validation. The third parameter in function is optional and only used for testing.

//compare json2 to json1
function isValidJson(json1, json2, showInConsole) {

    if (!showInConsole)
        showInConsole = false;

    var aKeys = Object.keys(json1).sort();
    var bKeys = Object.keys(json2).sort();

    for (var i = 0; i < aKeys.length; i++) {

        if (showInConsole)
            console.log("---------" + JSON.stringify(aKeys[i]) + "  " + JSON.stringify(bKeys[i]))

        if (JSON.stringify(aKeys[i]) === JSON.stringify(bKeys[i])) {

            if (typeof json1[aKeys[i]] === 'object'){ // contains another obj

                if (showInConsole)
                    console.log("Entering " + JSON.stringify(aKeys[i]))

                if (!isValidJson(json1[aKeys[i]], json2[bKeys[i]], showInConsole)) 
                    return false; // if recursive validation fails

                if (showInConsole)
                    console.log("Leaving " + JSON.stringify(aKeys[i]))

            }

        } else {

            console.warn("validation failed at " + aKeys[i]);
            return false; // if attribute names dont mactch

        }

    }

    return true;

}

Convert char* to string C++

There seems to be a few details left out of your explanation, but I will do my best...

If these are NUL-terminated strings or the memory is pre-zeroed, you can just iterate down the length of the memory segment until you hit a NUL (0) character or the maximum length (whichever comes first). Use the string constructor, passing the buffer and the size determined in the previous step.

string retrieveString( char* buf, int max ) {

    size_t len = 0;
    while( (len < max) && (buf[ len ] != '\0') ) {
        len++;
    }

    return string( buf, len );

}

If the above is not the case, I'm not sure how you determine where a string ends.

Styling the last td in a table with css

You can use the col element as specified in HTML 4.0 (link). It works in every browser. You can give it an ID or a class or an inline style. only caveat is that it affects the whole column across all rows. Example:

<table>
    <col />
    <col width="50" />
    <col id="anId" />
    <col class="whatever" />
    <col style="border:1px solid #000;" />
    <tbody>
        <tr>
            <td>One</td>
            <td>Two</td>
            <td>Three</td>
            <td>Four</td>
            <td>Five</td>
        </tr>
    </tbody>
</table>

Copy entire contents of a directory to another using php

// using exec

function rCopy($directory, $destination)
{

    $command = sprintf('cp -r %s/* %s', $directory, $destination);

    exec($command);

}

jQuery autoComplete view all on click?

You can trigger this event to show all of the options:

$("#example").autocomplete( "search", "" );

Or see the example in the link below. Looks like exactly what you want to do.

http://jqueryui.com/demos/autocomplete/#combobox

EDIT (from @cnanney)

Note: You must set minLength: 0 in your autocomplete for an empty search string to return all elements.

jQuery exclude elements with certain class in selector

use this..

$(".content_box a:not('.button')")

How do I create a chart with multiple series using different X values for each series?

You need to use the Scatter chart type instead of Line. That will allow you to define separate X values for each series.

MSBuild doesn't copy references (DLL files) if using project dependencies in solution

As Alex Burtsev mentioned in a comment anything that’s only used in a XAML resource dictionary, or in my case, anything that’s only used in XAML and not in code behind, isn't deemed to be 'in use' by MSBuild.

So simply new-ing up a dummy reference to a class/component in the assembly in some code behind was enough convince MSBuild that the assembly was actually in use.

How to restart a rails server on Heroku?

If you have several heroku apps, you must type heroku restart --app app_name or heroku restart -a app_name

Variable name as a string in Javascript

No, there is not.
Besides, if you can write variablesName(myFirstName), you already know the variable name ("myFirstName").

Convert Enumeration to a Set/List

You can use Collections.list() to convert an Enumeration to a List in one line:

List<T> list = Collections.list(enumeration);

There's no similar method to get a Set, however you can still do it one line:

Set<T> set = new HashSet<T>(Collections.list(enumeration));

What is the difference between "screen" and "only screen" in media queries?

To style for many smartphones with smaller screens, you could write:

@media screen and (max-width:480px) { … } 

To block older browsers from seeing an iPhone or Android phone style sheet, you could write:

@media only screen and (max-width: 480px;) { … } 

Read this article for more http://webdesign.about.com/od/css3/a/css3-media-queries.htm

How to convert a String to JsonObject using gson library

Note that as of Gson 2.8.6, instance method JsonParser.parse has been deprecated and replaced by static method JsonParser.parseString:

JsonObject jsonObject = JsonParser.parseString(json).getAsJsonObject();

Laravel Eloquent where field is X or null

You could merge two queries together:

$merged = $query_one->merge($query_two);

Using a dictionary to select function to execute

Often classes are used to enclose methods and following is the extension for answers above with default method in case the method is not found.

class P:

     def p1(self):
         print('Start')

     def p2(self):
         print('Help')

     def ps(self):
         print('Settings')

     def d(self):
         print('Default function')

     myDict = {
         "start": p1,
         "help": p2,
         "settings": ps
     }

     def call_it(self):
         name = 'start'
         f = lambda self, x : self.myDict.get(x, lambda x : self.d())(self)
         f(self, name)


 p = P()
 p.call_it()

Convert HTML5 into standalone Android App

Create an Android app using Eclipse.

Create a layout that has a <WebView> control.

Move your HTML code to /assets folder.

Load webview with your file:///android_asset/ file.

And you have an android app!

How to submit form on change of dropdown list?

Simple JavaScript will do -

<form action="myservlet.do" method="POST">
    <select name="myselect" id="myselect" onchange="this.form.submit()">
        <option value="1">One</option>
        <option value="2">Two</option>
        <option value="3">Three</option>
        <option value="4">Four</option>
    </select>
</form>

Here is a link for a good javascript tutorial.

Barcode scanner for mobile phone for Website in form

Check out https://github.com/serratus/quaggaJS

"QuaggaJS is a barcode-scanner entirely written in JavaScript supporting real- time localization and decoding of various types of barcodes such as EAN, CODE 128, CODE 39, EAN 8, UPC-A, UPC-C, I2of5, 2of5, CODE 93 and CODABAR. The library is also capable of using getUserMedia to get direct access to the user's camera stream. Although the code relies on heavy image-processing even recent smartphones are capable of locating and decoding barcodes in real-time."

Compiling LaTex bib source

You need to compile the bibtex file.

Suppose you have article.tex and article.bib. You need to run:

  • latex article.tex (this will generate a document with question marks in place of unknown references)
  • bibtex article (this will parse all the .bib files that were included in the article and generate metainformation regarding references)
  • latex article.tex (this will generate document with all the references in the correct places)
  • latex article.tex (just in case if adding references broke page numbering somewhere)

How to insert values in two dimensional array programmatically?

Try to code below,

String[][] shades = new String[4][3];
for(int i = 0; i < 4; i++)
{
  for(int y = 0; y < 3; y++)
  {
    shades[i][y] = value;
  }
}

Convert pem key to ssh-rsa format

I did with

ssh-keygen -i -f $sshkeysfile >> authorized_keys

Credit goes here

Calling multiple JavaScript functions on a button click

I think that since return validateView(); will return a value (to the click event?), your second call ShowDiv1(); will not get called.

You can always wrap multiple function calls in another function, i.e.

<asp:LinkButton OnClientClick="return display();">

function display() {
   if(validateView() && ShowDiv1()) return true;
}

You also might try:

<asp:LinkButton OnClientClick="return (validateView() && ShowDiv1());">

Though I have no idea if that would throw an exception.

Wait till a Function with animations is finished until running another Function

add the following to the end of the first function

return $.Deferred().resolve();

call both functions like so

functionOne().done(functionTwo);

C# Change A Button's Background Color

Code for set background color, for SolidColor:

button.Background = new SolidColorBrush(Color.FromArgb(Avalue, rValue, gValue, bValue));

Apache POI Excel - how to configure columns to be expanded?

If you know the count of your columns (f.e. it's equal to a collection list). You can simply use this one liner to adjust all columns of one sheet (if you use at least java 8):

IntStream.range(0, columnCount).forEach((columnIndex) -> sheet.autoSizeColumn(columnIndex));

How to split string and push in array using jquery

You don't need jQuery for that, you can do it with normal javascript:

http://www.w3schools.com/jsref/jsref_split.asp

var str = "a,b,c,d";
var res = str.split(","); // this returns an array

How to update and delete a cookie?

The cookie API is kind of lame. Let me clarify...

You don't update cookies; you overwrite them:

    document.cookie = "username=Arnold"; // Create 'username' cookie
    document.cookie = "username=Chuck"; // Update, i.e. overwrite, the 'username' cookie to "Chuck"

You also don't delete cookies; you expire them by setting the expires key to a time in the past (-1 works too).

Source: https://developer.mozilla.org/en-US/docs/Web/API/document.cookie

Routing HTTP Error 404.0 0x80070002

My solution, after trying EVERYTHING:

Bad deployment, an old PrecompiledApp.config was hanging around my deploy location, and making everything not work.

My final settings that worked:

  • IIS 7.5, Win2k8r2 x64,
  • Integrated mode application pool
  • Nothing changes in the web.config - this means no special handlers for routing. Here's my snapshot of the sections a lot of other posts reference. I'm using FluorineFX, so I do have that handler added, but I did not need any others:

    <system.web>
      <compilation debug="true" targetFramework="4.0" />
      <authentication mode="None"/>
    
      <pages validateRequest="false" controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/>
      <httpRuntime requestPathInvalidCharacters=""/>
    
      <httpModules>
        <add name="FluorineGateway" type="FluorineFx.FluorineGateway, FluorineFx"/>
      </httpModules>
    </system.web>
      <system.webServer>
        <!-- Modules for IIS 7.0 Integrated mode -->
        <modules>
          <add name="FluorineGateway" type="FluorineFx.FluorineGateway, FluorineFx" />
        </modules>
    
        <!-- Disable detection of IIS 6.0 / Classic mode ASP.NET configuration -->
        <validation validateIntegratedModeConfiguration="false" />
      </system.webServer>
    
  • Global.ashx: (only method of any note)

    void Application_Start(object sender, EventArgs e) {
        // Register routes...
        System.Web.Routing.Route echoRoute = new System.Web.Routing.Route(
              "{*message}",
            //the default value for the message
              new System.Web.Routing.RouteValueDictionary() { { "message", "" } },
            //any regular expression restrictions (i.e. @"[^\d].{4,}" means "does not start with number, at least 4 chars
              new System.Web.Routing.RouteValueDictionary() { { "message", @"[^\d].{4,}" } },
              new TestRoute.Handlers.PassthroughRouteHandler()
           );
    
        System.Web.Routing.RouteTable.Routes.Add(echoRoute);
    }
    
  • PassthroughRouteHandler.cs - this achieved an automatic conversion from http://andrew.arace.info/stackoverflow to http://andrew.arace.info/#stackoverflow which would then be handled by the default.aspx:

    public class PassthroughRouteHandler : IRouteHandler {
    
        public IHttpHandler GetHttpHandler(RequestContext requestContext) {
            HttpContext.Current.Items["IncomingMessage"] = requestContext.RouteData.Values["message"];
            requestContext.HttpContext.Response.Redirect("#" + HttpContext.Current.Items["IncomingMessage"], true);
            return null;
        }
    }
    

Angular.js: set element height on page load

angular.element(document).ready(function () {
    //your logic here
});

Multiple left joins on multiple tables in one query

The JOIN statements are also part of the FROM clause, more formally a join_type is used to combine two from_item's into one from_item, multiple one of which can then form a comma-separated list after the FROM. See http://www.postgresql.org/docs/9.1/static/sql-select.html .

So the direct solution to your problem is:

SELECT something
FROM
    master as parent LEFT JOIN second as parentdata
        ON parent.secondary_id = parentdata.id,
    master as child LEFT JOIN second as childdata
        ON child.secondary_id = childdata.id
WHERE parent.id = child.parent_id AND parent.parent_id = 'rootID'

A better option would be to only use JOIN's, as it has already been suggested.

Oracle date function for the previous month

I believe this would also work:

select count(distinct switch_id)   
  from [email protected]  
 where 
   dealer_name =  'XXXX'    
   and (creation_date BETWEEN add_months(trunc(sysdate,'mm'),-1) and  trunc(sysdate, 'mm'))

It has the advantage of using BETWEEN which is the way the OP used his date selection criteria.

100% width background image with an 'auto' height

You can use the CSS property background-size and set it to cover or contain, depending your preference. Cover will cover the window entirely, while contain will make one side fit the window thus not covering the entire page (unless the aspect ratio of the screen is equal to the image).

Please note that this is a CSS3 property. In older browsers, this property is ignored. Alternatively, you can use javascript to change the CSS settings depending on the window size, but this isn't preferred.

body {
    background-image: url(image.jpg); /* image */
    background-position: center;      /* center the image */
    background-size: cover;           /* cover the entire window */
}

Why does Python code use len() function instead of a length method?

met% python -c 'import this' | grep 'only one'
There should be one-- and preferably only one --obvious way to do it.

Self-reference for cell, column and row in worksheet functions

where F13 is the cell you need to reference:

=CELL("Row",F13)  yields 13; its row number

=CELL("Col",F13)  yields 6; its column number;  

=SUBSTITUTE(ADDRESS(1,COLUMN(F13)*1,4),"1","") yields F; its column letter

How to ignore parent css style

I had a similar situation while working on a joomla website.

Added a class name to the module to be affected. In your case:

<select name="funTimes" class="classname">

then made the following single line change in the css. Added the line

#elementId div.classname {style to be applied !important;}

worked well!

Redirecting to previous page after login? PHP

You can save a page using php, like this:

$_SESSION['current_page'] = $_SERVER['REQUEST_URI']

And return to the page with:

header("Location: ". $_SESSION['current_page'])

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

Create a .gemrc file (either in /etc/gemrc or ~/.gemrc or for example with chef gem in /opt/chef/embedded/etc/gemrc) containing:

http_proxy: http://proxy:3128

Then you can gem install as usual.

Get contentEditable caret index position

Try this:

Caret.js Get caret postion and offset from text field

https://github.com/ichord/Caret.js

demo: http://ichord.github.com/Caret.js

How to open a new tab in GNOME Terminal from command line?

I found the simplest way:

gnome-terminal --tab -e 'command 1' --tab -e 'command 2'

I use tmux instead of using terminal directly. So what I want is really a single and simple command/shell file to build the development env with several tmux windows. The shell code is as below:

#!/bin/bash
tabs="adb ana repo"
gen_params() {

    local params=""
    for tab in ${tabs}
    do  
        params="${params} --tab -e 'tmux -u attach-session -t ${tab}'"
    done
    echo "${params}"
}
cmd="gnome-terminal $(gen_params)"
eval $cmd

How to watch for a route change in AngularJS?

$rootScope.$on( "$routeChangeStart", function(event, next, current) {
  //if you want to interrupt going to another location.
  event.preventDefault();  });

Redirecting exec output to a buffer or file

You could also use the linux sh command and pass it a command that includes the redirection:

string cmd = "/bin/ls > " + filepath;

execl("/bin/sh", "sh", "-c", cmd.c_str(), 0);

Insert current date in datetime format mySQL

"datetime" expects the date to be formated like this: YYYY-MM-DD HH:MM:SS

so format your date like that when you are inserting.

How to force Docker for a clean build of an image

You can manage the builder cache with docker builder

To clean all the cache with no prompt: docker builder prune -af

Virtual/pure virtual explained

"Virtual" means that the method may be overridden in subclasses, but has an directly-callable implementation in the base class. "Pure virtual" means it is a virtual method with no directly-callable implementation. Such a method must be overridden at least once in the inheritance hierarchy -- if a class has any unimplemented virtual methods, objects of that class cannot be constructed and compilation will fail.

@quark points out that pure-virtual methods can have an implementation, but as pure-virtual methods must be overridden, the default implementation can't be directly called. Here is an example of a pure-virtual method with a default:

#include <cstdio>

class A {
public:
    virtual void Hello() = 0;
};

void A::Hello() {
    printf("A::Hello\n");
}

class B : public A {
public:
    void Hello() {
        printf("B::Hello\n");
        A::Hello();
    }
};

int main() {
    /* Prints:
           B::Hello
           A::Hello
    */
    B b;
    b.Hello();
    return 0;
}

According to comments, whether or not compilation will fail is compiler-specific. In GCC 4.3.3 at least, it won't compile:

class A {
public:
    virtual void Hello() = 0;
};

int main()
{
    A a;
    return 0;
}

Output:

$ g++ -c virt.cpp 
virt.cpp: In function ‘int main()’:
virt.cpp:8: error: cannot declare variable ‘a’ to be of abstract type ‘A’
virt.cpp:1: note:   because the following virtual functions are pure within ‘A’:
virt.cpp:3: note:   virtual void A::Hello()

How to find the Git commit that introduced a string in any branch?

Not sure why the accepted answer doesn't work in my environment, finally I run below command to get what I need

git log --pretty=format:"%h - %an, %ar : %s"|grep "STRING"

How do I set the time zone of MySQL?

When you can configure the time zone server for MySQL or PHP:

Remember:

  1. Change timezone system. Example for Ubuntu:

    $ sudo dpkg-reconfigure tzdata
    
  2. Restart the server or you can restart Apache 2 and MySQL:

    /etc/init.d/mysql restart
    

batch file Copy files with certain extensions from multiple directories into one directory

In a batch file solution

for /R c:\source %%f in (*.xml) do copy %%f x:\destination\

The code works as such;

for each file for in directory c:\source and subdirectories /R that match pattern (\*.xml) put the file name in variable %%f, then for each file do copy file copy %%f to destination x:\\destination\\

Just tested it here on my Windows XP computer and it worked like a treat for me. But I typed it into command prompt so I used the single %f variable name version, as described in the linked question above.

get the value of input type file , and alert if empty

<script type="text/javascript">
$(document).ready(function() {
    $('#upload').bind("click",function() 
    { 
        var imgVal = $('#uploadImage').val(); 
        if(imgVal=='') 
        { 
            alert("empty input file"); 

        } 
        return false; 

    }); 
});
</script> 

<input type="file" name="image" id="uploadImage" size="30" /> 
<input type="submit" name="upload" id="upload"  class="send_upload" value="upload" /> 

Connecting PostgreSQL 9.2.1 with Hibernate

If the project is maven placed it in src/main/resources, in the package phase it will copy it in ../WEB-INF/classes/hibernate.cfg.xml

How to measure height, width and distance of object using camera?

First of all i will say Nice Thaught to develop such app.

Now i am not sure about it, but if you can able to get the face-detection like thing for any object in android camera so with help of that you can achieve that things.

Well i am not sure about it but still have give some view so you can get idea of it.

All the Best. :))

Why Java Calendar set(int year, int month, int date) not returning correct date?

Months in Calendar object start from 0

0 = January = Calendar.JANUARY
1 = february = Calendar.FEBRUARY

Java HttpRequest JSON & Response Handling

The simplest way is using libraries like google-http-java-client but if you want parse the JSON response by yourself you can do that in a multiple ways, you can use org.json, json-simple, Gson, minimal-json, jackson-mapper-asl (from 1.x)... etc

A set of simple examples:

Using Gson:

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

public class Gson {

    public static void main(String[] args) {
    }

    public HttpResponse http(String url, String body) {

        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
            HttpPost request = new HttpPost(url);
            StringEntity params = new StringEntity(body);
            request.addHeader("content-type", "application/json");
            request.setEntity(params);
            HttpResponse result = httpClient.execute(request);
            String json = EntityUtils.toString(result.getEntity(), "UTF-8");

            com.google.gson.Gson gson = new com.google.gson.Gson();
            Response respuesta = gson.fromJson(json, Response.class);

            System.out.println(respuesta.getExample());
            System.out.println(respuesta.getFr());

        } catch (IOException ex) {
        }
        return null;
    }

    public class Response{

        private String example;
        private String fr;

        public String getExample() {
            return example;
        }
        public void setExample(String example) {
            this.example = example;
        }
        public String getFr() {
            return fr;
        }
        public void setFr(String fr) {
            this.fr = fr;
        }
    }
}

Using json-simple:

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class JsonSimple {

    public static void main(String[] args) {

    }

    public HttpResponse http(String url, String body) {

        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
            HttpPost request = new HttpPost(url);
            StringEntity params = new StringEntity(body);
            request.addHeader("content-type", "application/json");
            request.setEntity(params);
            HttpResponse result = httpClient.execute(request);

            String json = EntityUtils.toString(result.getEntity(), "UTF-8");
            try {
                JSONParser parser = new JSONParser();
                Object resultObject = parser.parse(json);

                if (resultObject instanceof JSONArray) {
                    JSONArray array=(JSONArray)resultObject;
                    for (Object object : array) {
                        JSONObject obj =(JSONObject)object;
                        System.out.println(obj.get("example"));
                        System.out.println(obj.get("fr"));
                    }

                }else if (resultObject instanceof JSONObject) {
                    JSONObject obj =(JSONObject)resultObject;
                    System.out.println(obj.get("example"));
                    System.out.println(obj.get("fr"));
                }

            } catch (Exception e) {
                // TODO: handle exception
            }

        } catch (IOException ex) {
        }
        return null;
    }
}

etc...

how to specify local modules as npm package dependencies

I couldn't find a neat way in the end so I went for create a directory called local_modules and then added this bashscript to the package.json in scripts->preinstall

#!/bin/sh
for i in $(find ./local_modules -type d -maxdepth 1) ; do
    packageJson="${i}/package.json"
    if [ -f "${packageJson}" ]; then
        echo "installing ${i}..."
        npm install "${i}"
    fi
done

Go to Matching Brace in Visual Studio?

For Visual Studio Code (as seen in their documentation), use Ctrl+Shift+\.

The setting can be found in:

File/Preferences/Keyboard Shortcut

I am using Visual Studio Code 1.8.0 . Note Visual Studio Code may behave differently for international keyboards (as seen in this answer re: German keyboard)

Hope this helps someone.

SQL Joins Vs SQL Subqueries (Performance)?

The two queries may not be semantically equivalent. If a employee works for more than one department (possible in the enterprise I work for; admittedly, this would imply your table is not fully normalized) then the first query would return duplicate rows whereas the second query would not. To make the queries equivalent in this case, the DISTINCT keyword would have to be added to the SELECT clause, which may have an impact on performance.

Note there is a design rule of thumb that states a table should model an entity/class or a relationship between entities/classes but not both. Therefore, I suggest you create a third table, say OrgChart, to model the relationship between employees and departments.