Programs & Examples On #Javabuilders

Create an application setup in visual studio 2013

Visual Studio 2013 now supports setup projects. Microsoft have shipped a Visual Studio extension to produce setup projects.

Visual Studio Installer Projects Extension

List submodules in a Git repository

To return just the names of the registered submodules, you can use this command:

grep path .gitmodules | sed 's/.*= //'

Think of it as git submodule --list which doesn't exist.

Change route params without reloading in Angular 2

For me it was actually a mix of both with Angular 4.4.5.

Using router.navigate kept destroying my url by not respecting the realtiveTo: activatedRoute part.

I've ended up with:

this._location.go(this._router.createUrlTree([this._router.url], { queryParams: { profile: value.id } }).toString())

Display the binary representation of a number in C?

#include<iostream>
#include<conio.h>
#include<stdlib.h>
using namespace std;
void displayBinary(int n)
{
       char bistr[1000];
       itoa(n,bistr,2);       //2 means binary u can convert n upto base 36
       printf("%s",bistr);

}

int main()
{
    int n;
    cin>>n;
    displayBinary(n);
    getch();
    return 0;
}

How to get number of entries in a Lua table?

There's one way, but it might be disappointing: use an additional variable (or one of the table's field) for storing the count, and increase it every time you make an insertion.

count = 0
tbl = {}

tbl["test"] = 47
count = count + 1

tbl[1] = 48
count = count + 1

print(count)   -- prints "2"

There's no other way, the # operator will only work on array-like tables with consecutive keys.

Multiple GitHub Accounts & SSH Config

I used,

Host github.com
   HostName github.com
   IdentityFile ~/.ssh/github_rsa
   User [email protected]

It wokred fine.

Use the above setting in your .ssh/config file for different rsa keys for different usernames.

exec failed because the name not a valid identifier?

Try this instead in the end:

exec (@query)

If you do not have the brackets, SQL Server assumes the value of the variable to be a stored procedure name.

OR

EXECUTE sp_executesql @query

And it should not be because of FULL JOIN.
But I hope you have already created the temp tables: #TrafficFinal, #TrafficFinal2, #TrafficFinal3 before this.


Please note that there are performance considerations between using EXEC and sp_executesql. Because sp_executesql uses forced statement caching like an sp.
More details here.


On another note, is there a reason why you are using dynamic sql for this case, when you can use the query as is, considering you are not doing any query manipulations and executing it the way it is?

Most efficient way to prepend a value to an array

I have some fresh tests of different methods of prepending. For small arrays (<1000 elems) the leader is for cycle coupled with a push method. For huge arrays, Unshift method becomes the leader.

But this situation is actual only for Chrome browser. In Firefox unshift has an awesome optimization and is faster in all cases.

ES6 spread is 100+ times slower in all browsers.

https://jsbench.me/cgjfc79bgx/1

IOException: Too many open files

As you are running on Linux I suspect you are running out of file descriptors. Check out ulimit. Here is an article that describes the problem: http://www.cyberciti.biz/faq/linux-increase-the-maximum-number-of-open-files/

Uncaught Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function but got: object

I was having the same issue and realized that I was providing an Undefined React component in the JSX markup. The thing is that the react component to render was dynamically calculated and it ended up being undefined!

The error stated:

Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in. Check the render method of C.,

The example producing this error:

_x000D_
_x000D_
var componentA = require('./components/A');_x000D_
var componentB = require('./components/B');_x000D_
_x000D_
const templates = {_x000D_
  a_type: componentA,_x000D_
  b_type: componentB_x000D_
}_x000D_
_x000D_
class C extends React.Component {_x000D_
  constructor(props) {_x000D_
    super(props);_x000D_
  }_x000D_
  _x000D_
  // ..._x000D_
  _x000D_
  render() {_x000D_
    //Let´s say that depending on the uiType coming in a data field you end up rendering a component A or B (as part of C)_x000D_
    const ComponentTemplate = templates[this.props.data.uiType];_x000D_
    return <ComponentTemplate></ComponentTemplate>_x000D_
  }_x000D_
  _x000D_
  // ..._x000D_
}
_x000D_
_x000D_
_x000D_

The problem was that an invalid "uiType" was provided and therefore this was producing undefined as result:

_x000D_
_x000D_
templates['InvalidString']
_x000D_
_x000D_
_x000D_

How do you concatenate Lists in C#?

targetList = list1.Concat(list2).ToList();

It's working fine I think so. As previously said, Concat returns a new sequence and while converting the result to List, it does the job perfectly.

How to add months to a date in JavaScript?

Split your date into year, month, and day components then use Date:

var d = new Date(year, month, day);
d.setMonth(d.getMonth() + 8);

Date will take care of fixing the year.

What possibilities can cause "Service Unavailable 503" error?

Your web pages are served by an application pool. If you disable/stop the application pool, and anyone tries to browse the application, you will get a Service Unavailable. It can happen due to multiple reasons...

  1. Your application may have crashed [check the event viewer and see if you can find event logs in your Application/System log]

  2. Your application may be crashing very frequently. If an app pool crashes for 5 times in 5 minutes [check your application pool settings for rapid fail], your application pool is disabled by IIS and you will end up getting this message.

In either case, the issue is that your worker process is failing and you should troubleshoot it from crash perspective.

What is a Crash (technically)... in ASP.NET and what to do if it happens?

How to change Android version and code version number?

I didn't get the other answers to work in Android Studio 1.4. But this worked: click on your app name to the left below the main ribbon. It will show a list of files. Open AndroidManifest.xml and change the version code and version number there.

SQL Transaction Error: The current transaction cannot be committed and cannot support operations that write to the log file

There are a few misunderstandings in the discussion above.

First, you can always ROLLBACK a transaction... no matter what the state of the transaction. So you only have to check the XACT_STATE before a COMMIT, not before a rollback.

As far as the error in the code, you will want to put the transaction inside the TRY. Then in your CATCH, the first thing you should do is the following:

 IF @@TRANCOUNT > 0
      ROLLBACK TRANSACTION @transaction

Then, after the statement above, then you can send an email or whatever is needed. (FYI: If you send the email BEFORE the rollback, then you will definitely get the "cannot... write to log file" error.)

This issue was from last year, so I hope you have resolved this by now :-) Remus pointed you in the right direction.

As a rule of thumb... the TRY will immediately jump to the CATCH when there is an error. Then, when you're in the CATCH, you can use the XACT_STATE to decide whether you can commit. But if you always want to ROLLBACK in the catch, then you don't need to check the state at all.

Python main call within class

That entire block is misplaced.

class Example(object):
    def main(self):     
        print "Hello World!"

if __name__ == '__main__':
    Example().main()

But you really shouldn't be using a class just to run your main code.

Is there a way I can capture my iPhone screen as a video?

Short of using a video camera, no.

Many youtube videos for demonstrating iPhone applications are made with a screen grabber application (such as iShowU, ScreenFlow, or Snapz Pro) and the simulator. Be aware that the speed of response in the simulator can be dramatically different than a device - so it's possible to get effects (and miss) with the simulator you'll never see on a device. In particular, default animations can flash by in the simulator, where they just look quick on a device.

How do I programmatically set the value of a select box element using JavaScript?

function setSelectValue (id, val) {
    document.getElementById(id).value = val;
}
setSelectValue('leaveCode', 14);

Rails.env vs RAILS_ENV

According to the docs, #Rails.env wraps RAILS_ENV:

    # File vendor/rails/railties/lib/initializer.rb, line 55
     def env
       @_env ||= ActiveSupport::StringInquirer.new(RAILS_ENV)
     end

But, look at specifically how it's wrapped, using ActiveSupport::StringInquirer:

Wrapping a string in this class gives you a prettier way to test for equality. The value returned by Rails.env is wrapped in a StringInquirer object so instead of calling this:

Rails.env == "production"

you can call this:

Rails.env.production?

So they aren't exactly equivalent, but they're fairly close. I haven't used Rails much yet, but I'd say #Rails.env is certainly the more visually attractive option due to using StringInquirer.

javascript : sending custom parameters with window.open() but its not working

To concatenate strings, use the + operator.

To insert data into a URI, encode it for URIs.

Bad:

var url = "http://localhost:8080/login?cid='username'&pwd='password'"

Good:

var url_safe_username = encodeURIComponent(username);
var url_safe_password = encodeURIComponent(password);
var url = "http://localhost:8080/login?cid=" + url_safe_username + "&pwd=" + url_safe_password;

The server will have to process the query string to make use of the data. You can't assign to arbitrary form fields.

… but don't trigger new windows or pass credentials in the URI (where they are exposed to over the shoulder attacks and may be logged).

Android draw a Horizontal line between views

It will draw Silver gray colored Line between TextView & ListView

<TextView
    android:id="@+id/textView1"
    style="@style/behindMenuItemLabel1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="1dp"
    android:text="FaceBook Feeds" />

<View
    android:layout_width="match_parent"
    android:layout_height="2dp"
    android:background="#c0c0c0"/>

<ListView
    android:id="@+id/list1"
    android:layout_width="350dp"
    android:layout_height="50dp" />

ASP.NET GridView RowIndex As CommandArgument

I typically bind this data using the RowDatabound event with the GridView:

protected void FormatGridView(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
   if (e.Row.RowType == DataControlRowType.DataRow) 
   {
      ((Button)e.Row.Cells(0).FindControl("btnSpecial")).CommandArgument = e.Row.RowIndex.ToString();
   }
}

How can I increment a char?

I came from PHP, where you can increment char (A to B, Z to AA, AA to AB etc.) using ++ operator. I made a simple function which does the same in Python. You can also change list of chars to whatever (lowercase, uppercase, etc.) is your need.

# Increment char (a -> b, az -> ba)
def inc_char(text, chlist = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'):
    # Unique and sort
    chlist = ''.join(sorted(set(str(chlist))))
    chlen = len(chlist)
    if not chlen:
        return ''
    text = str(text)
    # Replace all chars but chlist
    text = re.sub('[^' + chlist + ']', '', text)
    if not len(text):
        return chlist[0]
    # Increment
    inc = ''
    over = False
    for i in range(1, len(text)+1):
        lchar = text[-i]
        pos = chlist.find(lchar) + 1
        if pos < chlen:
            inc = chlist[pos] + inc
            over = False
            break
        else:
            inc = chlist[0] + inc
            over = True
    if over:
        inc += chlist[0]
    result = text[0:-len(inc)] + inc
    return result

How can I undo a mysql statement that I just executed?

You can only do so during a transaction.

BEGIN;
INSERT INTO xxx ...;
DELETE FROM ...;

Then you can either:

COMMIT; -- will confirm your changes

Or

ROLLBACK -- will undo your previous changes

How to specify table's height such that a vertical scroll bar appears?

to set the height of table, you need to first set css property "display: block" then you can add "width/height" properties. I find this Mozilla Article a very good resource to learn how to style tables : Link

How to import a module given its name as string?

You can use exec:

exec("import myapp.commands.%s" % command)

Why is __init__() always called after __new__()?

To quote the documentation:

Typical implementations create a new instance of the class by invoking the superclass's __new__() method using "super(currentclass, cls).__new__(cls[, ...])"with appropriate arguments and then modifying the newly-created instance as necessary before returning it.

...

If __new__() does not return an instance of cls, then the new instance's __init__() method will not be invoked.

__new__() is intended mainly to allow subclasses of immutable types (like int, str, or tuple) to customize instance creation.

Formatting a number with leading zeros in PHP

You can always abuse type juggling:

function zpad(int $value, int $pad): string {
    return substr(1, $value + 10 ** $pad);
}

This wont work as expected if either 10 ** pad > INT_MAX or value >= 10 * pad.

Why do we check up to the square root of a prime number to determine if it is prime?

Any composite number is a product of primes.

Let say n = p1 * p2, where p2 > p1 and they are primes.

If n % p1 === 0 then n is a composite number.

If n % p2 === 0 then guess what n % p1 === 0 as well!

So there is no way that if n % p2 === 0 but n % p1 !== 0 at the same time. In other words if a composite number n can be divided evenly by p2,p3...pi (its greater factor) it must be divided by its lowest factor p1 too. It turns out that the lowest factor p1 <= Math.square(n) is always true.

Renaming branches remotely in Git

You just have to create a new local branch with the desired name, push it to your remote, and then delete the old remote branch:

$ git branch new-branch-name origin/old-branch-name
$ git push origin --set-upstream new-branch-name
$ git push origin :old-branch-name

Then, to see the old branch name, each client of the repository would have to do:

$ git fetch origin
$ git remote prune origin

NOTE: If your old branch is your main branch, you should change your main branch settings. Otherwise, when you run $ git push origin :old-branch-name, you'll get the error "deletion of the current branch prohibited".

What do the makefile symbols $@ and $< mean?

The $@ and $< are called automatic variables. The variable $@ represents the name of the target and $< represents the first prerequisite required to create the output file.
For example:

hello.o: hello.c hello.h
         gcc -c $< -o $@

Here, hello.o is the output file. This is what $@ expands to. The first dependency is hello.c. That's what $< expands to.

The -c flag generates the .o file; see man gcc for a more detailed explanation. The -o specifies the output file to create.

For further details, you can read this article about Linux Makefiles.

Also, you can check the GNU make manuals. It will make it easier to make Makefiles and to debug them.

If you run this command, it will output the makefile database:

make -p 

jQuery How do you get an image to fade in on load?

window.onload is not that trustworthy.. I would use:

<script type="text/javascript">
    $(document).ready(function () {
        $('#logo').hide().fadeIn(3000);
    });
</script>

Rename package in Android Studio

If your package name is more than two dot separated, say com.hello.world and moreover, you did not put anything in com/ and com/hello/. All of your classes are putting into com/hello/world/, you might DO the following steps to refactoring your package name(s) in Android Studio or IntelliJ:

  • [FIRST] Add something under your directories(com/, com/hello/). You can achieve this by first add two files to package com.hello.world, say
   com.hello.world.PackageInfo1.java
   com.hello.world.PackageInfo2.java

then refactor them by moving them to com and com.hello respectively. You will see com and com.hello sitting there at the Project(Alt+1 or Command+1 for shortcut) and rename directories refactoring is waiting there as you expected.

  • Refactor to rename one or more of these directories to reach your aim. The only thing you should notice here is you must choose the directories rather than Packages when a dialog ask you.

  • If you've got lots of classes in your project, it will take you a while to wait for its auto-scan-and-rename.

  • Besides, you need to rename the package name inside the AndroidManifest.xml manually, I guess, such that other names in this file can benefit the prefix.

  • [ALSO], it might need you to replace all com.hello.world.R to the new XXX.XXX.XXX.R(Command+Shift+R for short)

  • Rebuild and run your project to see whether it work. And use "Find in Path" to find other non-touch names you'd like to rename.

  • Enjoy it.

stdcall and cdecl

Those things are Compiler- and Platform-specific. Neither the C nor the C++ standard say anything about calling conventions except for extern "C" in C++.

how does a caller know if it should free up the stack ?

The caller knows the calling convention of the function and handles the call accordingly.

At the call site, does the caller know if the function being called is a cdecl or a stdcall function ?

Yes.

How does it work ?

It is part of the function declaration.

How does the caller know if it should free up the stack or not ?

The caller knows the calling conventions and can act accordingly.

Or is it the linkers responsibility ?

No, the calling convention is part of a function's declaration so the compiler knows everything it needs to know.

If a function which is declared as stdcall calls a function(which has a calling convention as cdecl), or the other way round, would this be inappropriate ?

No. Why should it?

In general, can we say that which call will be faster - cdecl or stdcall ?

I don't know. Test it.

How do I Alter Table Column datatype on more than 1 column?

Use the following syntax:

  ALTER TABLE your_table
  MODIFY COLUMN column1 datatype,
  MODIFY COLUMN column2 datatype,
  ... ... ... ... ... 
  ... ... ... ... ...

Based on that, your ALTER command should be:

  ALTER TABLE webstore.Store
  MODIFY COLUMN ShortName VARCHAR(100),
  MODIFY COLUMN UrlShort VARCHAR(100)

Note that:

  1. There are no second brackets around the MODIFY statements.
  2. I used two separate MODIFY statements for two separate columns.

This is the standard format of the MODIFY statement for an ALTER command on multiple columns in a MySQL table.

Take a look at the following: http://dev.mysql.com/doc/refman/5.1/en/alter-table.html and Alter multiple columns in a single statement

How do I analyze a .hprof file?

Just get the Eclipse Memory Analyzer. There's nothing better out there and it's free.

JHAT is only usable for "toy applications"

AJAX POST and Plus Sign ( + ) -- How to Encode?

my problem was with the accents (á É ñ ) and the plus sign (+) when i to try to save javascript "code examples" to mysql:

my solution (not the better way, but it works):

javascript:

function replaceAll( text, busca, reemplaza ){
  while (text.toString().indexOf(busca) != -1)
  text = text.toString().replace(busca,reemplaza);return text;
}


function cleanCode(cod){
code = replaceAll(cod , "|", "{1}" ); // error | palos de explode en java
code = replaceAll(code, "+", "{0}" ); // error con los signos mas   
return code;
}

function to save:

function save(pid,code){
code = cleanCode(code); // fix sign + and |
code = escape(code); // fix accents
var url = 'editor.php';
var variables = 'op=save';
var myData = variables +'&code='+ code +'&pid='+ pid +'&newdate=' +(new Date()).getTime();    
var result = null;
$.ajax({
datatype : "html",
data: myData,  
url: url,
success : function(result) {
    alert(result); // result ok                     
},
}); 
} // end function

function in php:

<?php
function save($pid,$code){
    $code= preg_replace("[\{1\}]","|",$code);
    $code= preg_replace("[\{0\}]","+",$code);
    mysql_query("update table set code= '" . mysql_real_escape_string($code) . "' where pid='$pid'");
}
?>

How to find good looking font color if background color is known?

I have implemented something similar for a different reason - that was code to tell the end user whether the foreground and background colors that they selected would result in unreadable text. To do this, rather than examining the RGB values, I converted the color value to HSL/HSV and then determined by experimentation what my cutoff point was for readability when comparing the fg and bg values. This is something you may want/need to consider.

How to normalize a histogram in MATLAB?

The area of abcd`s PDF is not one, which is impossible like pointed out in many comments. Assumptions done in many answers here

  1. Assume constant distance between consecutive edges.
  2. Probability under pdf should be 1. The normalization should be done as Normalization with probability, not as Normalization with pdf, in histogram() and hist().

Fig. 1 Output of hist() approach, Fig. 2 Output of histogram() approach

enter image description here enter image description here

The max amplitude differs between two approaches which proposes that there are some mistake in hist()'s approach because histogram()'s approach uses the standard normalization. I assume the mistake with hist()'s approach here is about the normalization as partially pdf, not completely as probability.

Code with hist() [deprecated]

Some remarks

  1. First check: sum(f)/N gives 1 if Nbins manually set.
  2. pdf requires the width of the bin (dx) in the graph g

Code

%http://stackoverflow.com/a/5321546/54964
N=10000;
Nbins=50;
[f,x]=hist(randn(N,1),Nbins); % create histogram from ND

%METHOD 4: Count Densities, not Sums!
figure(3)
dx=diff(x(1:2)); % width of bin
g=1/sqrt(2*pi)*exp(-0.5*x.^2) .* dx; % pdf of ND with dx
% 1.0000
bar(x, f/sum(f));hold on
plot(x,g,'r');hold off

Output is in Fig. 1.

Code with histogram()

Some remarks

  1. First check: a) sum(f) is 1 if Nbins adjusted with histogram()'s Normalization as probability, b) sum(f)/N is 1 if Nbins is manually set without normalization.
  2. pdf requires the width of the bin (dx) in the graph g

Code

%%METHOD 5: with histogram()
% http://stackoverflow.com/a/38809232/54964
N=10000;

figure(4);
h = histogram(randn(N,1), 'Normalization', 'probability') % hist() deprecated!
Nbins=h.NumBins;
edges=h.BinEdges; 
x=zeros(1,Nbins);
f=h.Values;
for counter=1:Nbins
    midPointShift=abs(edges(counter)-edges(counter+1))/2; % same constant for all
    x(counter)=edges(counter)+midPointShift;
end
dx=diff(x(1:2)); % constast for all
g=1/sqrt(2*pi)*exp(-0.5*x.^2) .* dx; % pdf of ND
% Use if Nbins manually set
%new_area=sum(f)/N % diff of consecutive edges constant
% Use if histogarm() Normalization probability
new_area=sum(f)
% 1.0000
% No bar() needed here with histogram() Normalization probability
hold on;
plot(x,g,'r');hold off

Output in Fig. 2 and expected output is met: area 1.0000.

Matlab: 2016a
System: Linux Ubuntu 16.04 64 bit
Linux kernel 4.6

Hexadecimal To Decimal in Shell Script

In dash and other shells, you can use

printf "%d\n" (your hexadecimal number)

to convert a hexadecimal number to decimal. This is not bash, or ksh, specific.

Get first element from a dictionary

Dictionary<string, Dictionary<string, string>> like = new Dictionary<string, Dictionary<string, string>>();
Dictionary<string, string> first = like.Values.First();

How to use `subprocess` command with pipes

Or you can always use the communicate method on the subprocess objects.

cmd = "ps -A|grep 'process_name'"
ps = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
output = ps.communicate()[0]
print(output)

The communicate method returns a tuple of the standard output and the standard error.

How to add header row to a pandas DataFrame

You can use names directly in the read_csv

names : array-like, default None List of column names to use. If file contains no header row, then you should explicitly pass header=None

Cov = pd.read_csv("path/to/file.txt", 
                  sep='\t', 
                  names=["Sequence", "Start", "End", "Coverage"])

How can I read the contents of an URL with Python?

To answer your question:

import urllib

link = "http://www.somesite.com/details.pl?urn=2344"
f = urllib.urlopen(link)
myfile = f.read()
print(myfile)

You need to read(), not readline()

EDIT (2018-06-25): Since Python 3, the legacy urllib.urlopen() was replaced by urllib.request.urlopen() (see notes from https://docs.python.org/3/library/urllib.request.html#urllib.request.urlopen for details).

If you're using Python 3, see answers by Martin Thoma or i.n.n.m within this question: https://stackoverflow.com/a/28040508/158111 (Python 2/3 compat) https://stackoverflow.com/a/45886824/158111 (Python 3)

Or, just get this library here: http://docs.python-requests.org/en/latest/ and seriously use it :)

import requests

link = "http://www.somesite.com/details.pl?urn=2344"
f = requests.get(link)
print(f.text)

Where to place and how to read configuration resource files in servlet based application?

Word of warning: if you put config files in your WEB-INF/classes folder, and your IDE, say Eclipse, does a clean/rebuild, it will nuke your conf files unless they were in the Java source directory. BalusC's great answer alludes to that in option 1 but I wanted to add emphasis.

I learned the hard way that if you "copy" a web project in Eclipse, it does a clean/rebuild from any source folders. In my case I had added a "linked source dir" from our POJO java library, it would compile to the WEB-INF/classes folder. Doing a clean/rebuild in that project (not the web app project) caused the same problem.

I thought about putting my confs in the POJO src folder, but these confs are all for 3rd party libs (like Quartz or URLRewrite) that are in the WEB-INF/lib folder, so that didn't make sense. I plan to test putting it in the web projects "src" folder when i get around to it, but that folder is currently empty and having conf files in it seems inelegant.

So I vote for putting conf files in WEB-INF/commonConfFolder/filename.properties, next to the classes folder, which is Balus option 2.

C++: variable 'std::ifstream ifs' has initializer but incomplete type

This seems to be answered - #include <fstream>.

The message means :-

incomplete type - the class has not been defined with a full class. The compiler has seen statements such as class ifstream; which allow it to understand that a class exists, but does not know how much memory the class takes up.

The forward declaration allows the compiler to make more sense of :-

void BindInput( ifstream & inputChannel ); 

It understands the class exists, and can send pointers and references through code without being able to create the class, see any data within the class, or call any methods of the class.

The has initializer seems a bit extraneous, but is saying that the incomplete object is being created.

Oracle date to string conversion

The data in COL1 is in dd-mon-yy

No it's not. A DATE column does not have any format. It is only converted (implicitely) to that representation by your SQL client when you display it.

If COL1 is really a DATE column using to_date() on it is useless because to_date() converts a string to a DATE.

You only need to_char(), nothing else:

SELECT TO_CHAR(col1, 'mm/dd/yyyy') 
FROM TABLE1

What happens in your case is that calling to_date() converts the DATE into a character value (applying the default NLS format) and then converting that back to a DATE. Due to this double implicit conversion some information is lost on the way.


Edit

So you did make that big mistake to store a DATE in a character column. And that's why you get the problems now.

The best (and to be honest: only sensible) solution is to convert that column to a DATE. Then you can convert the values to any rerpresentation that you want without worrying about implicit data type conversion.

But most probably the answer is "I inherited this model, I have to cope with it" (it always is, apparently no one ever is responsible for choosing the wrong datatype), then you need to use RR instead of YY:

SELECT TO_CHAR(TO_DATE(COL1,'dd-mm-rr'), 'mm/dd/yyyy')
FROM TABLE1

should do the trick. Note that I also changed mon to mm as your example is 27-11-89 which has a number for the month, not an "word" (like NOV)

For more details see the manual: http://docs.oracle.com/cd/B28359_01/server.111/b28286/sql_elements004.htm#SQLRF00215

Calculate a Running Total in SQL Server

The APPLY operator in SQL 2005 and higher works for this:

select
    t.id ,
    t.somedate ,
    t.somevalue ,
    rt.runningTotal
from TestTable t
 cross apply (select sum(somevalue) as runningTotal
                from TestTable
                where somedate <= t.somedate
            ) as rt
order by t.somedate

How to send email from localhost WAMP Server to send email Gmail Hotmail or so forth?

For me Fake Sendmail works.

What to do:

1) Edit C:\wamp\sendmail\sendmail.ini:

smtp_server=smtp.gmail.com
smtp_port=465
[email protected]
auth_password=your_password

2) Edit php.ini and set sendmail_path

sendmail_path = "C:\wamp\sendmail\sendmail.exe -t"

That's it. Now you can test a mail.

Why doesn't TFS get latest get the latest?

Tool: TFS Power Tools

Source: http://dennymichael.net/2013/03/19/tfs-scorch/

Command: tfpt scorch /recursive /deletes C:\LocationOfWorkspaceOrFolder

This will bring up a dialog box that will ask you to Delete or Download a list of files. Select or Unselect the files accordingly and press ok. Appearance in Grid (CheckBox, FileName, FileAction, FilePath)

Cause: TFS will only compare against items in the workspace. If alterations were made outside of the workspace TFS will be unaware of them.

Hopefully someone finds this useful. I found this post after deleting a handful of folders in varying locations. Not remembering which folders I deleted excluded the usual Force Get/Replace option I would have used.

Composer: how can I install another dependency without updating old ones?

My use case is simpler, and fits simply your title but not your further detail.

That is, I want to install a new package which is not yet in my composer.json without updating all the other packages.

The solution here is composer require x/y

moving committed (but not pushed) changes to a new branch after pull

A simpler approach, which I have been using (assuming you want to move 4 commits):

git format-patch HEAD~4

(Look in the directory from which you executed the last command for the 4 .patch files)

git reset HEAD~4 --hard

git checkout -b tmp/my-new-branch

Then:

git apply /path/to/patch.patch

In whatever order you wanted.

Rounded corners for <input type='text' /> using border-radius.htc for IE

That won't work in IE<9 though, however, you can make IEs support that using:

CSS3Pie

PIE makes Internet Explorer 6-8 capable of rendering several of the most useful CSS3 decoration features.

Regex: ignore case sensitivity

Addition to the already-accepted answers:

Grep usage:

Note that for greping it is simply the addition of the -i modifier. Ex: grep -rni regular_expression to search for this 'regular_expression' 'r'ecursively, case 'i'nsensitive, showing line 'n'umbers in the result.

Also, here's a great tool for verifying regular expressions: https://regex101.com/

Ex: See the expression and Explanation in this image.

enter image description here

References:

Pandas - How to flatten a hierarchical index in columns

pd.DataFrame(df.to_records()) # multiindex become columns and new index is integers only

Input type for HTML form for integer

You should change your type to number If you accept decimals first and remove them on keyUp, you might solve this...

$("#state").on('keyup', function(){
    $(this).val($(this).val().replace(".", ''));
})

or

$("#state").on('keyup', function(){
    $(this).val(parseInt($(this).val()));
})

This will remove the period, but there is no 'Integer Type'.

What is REST call and how to send a REST call?

REST is somewhat of a revival of old-school HTTP, where the actual HTTP verbs (commands) have semantic meaning. Til recently, apps that wanted to update stuff on the server would supply a form containing an 'action' variable and a bunch of data. The HTTP command would almost always be GET or POST, and would be almost irrelevant. (Though there's almost always been a proscription against using GET for operations that have side effects, in reality a lot of apps don't care about the command used.)

With REST, you might instead PUT /profiles/cHao and send an XML or JSON representation of the profile info. (Or rather, I would -- you would have to update your own profile. :) That'd involve logging in, usually through HTTP's built-in authentication mechanisms.) In the latter case, what you want to do is specified by the URL, and the request body is just the guts of the resource involved.

http://en.wikipedia.org/wiki/Representational_State_Transfer has some details.

Xcode 10 Error: Multiple commands produce

In my case (I'm using Carthage) the problem with

error: Multiple commands produce 
1) Target *** has copy command from
2) That command depends on command in Target ***: script phase “Run Carthage Script” 

was caused due to importing frameworks both to Embeded frameworks and Run carthage script phases in Build Phases configuration

These 2 phases copy frameworks to derrived data, so Xcode see duplicated files and print these errors with warning:

ignoring duplicated output file: (in target ***)

After removing duplicated frameworks from Embeded frameworks phase everything is working correctly.

How do I run PHP code when a user clicks on a link?

either send the user to another page which does it

<a href="exec.php">Execute PHP</a>

or do it with ajax

<script type="text/javascript">
// <![CDATA[
    document.getElementById('link').onclick = function() {
        // call script via ajax...
        return false;
    }
// ]]>
</script>
...
<a href="#" id="link">Execute PHP</a>

SQLite: How do I save the result of a query as a CSV file?

Alternatively you can do it in one line (tested in win10)

sqlite3 -help
sqlite3 -header -csv db.sqlite 'select * from tbl1;' > test.csv

Bonus: Using powershell with cmdlet and pipe (|).

get-content query.sql | sqlite3 -header -csv db.sqlite > test.csv

where query.sql is a file containing your SQL query

How to correctly iterate through getElementsByClassName

I followed Alohci's recommendation of looping in reverse because it's a live nodeList. Here's what I did for those who are curious...

  var activeObjects = documents.getElementsByClassName('active'); // a live nodeList

  //Use a reverse-loop because the array is an active NodeList
  while(activeObjects.length > 0) {
    var lastElem = activePaths[activePaths.length-1]; //select the last element

    //Remove the 'active' class from the element.  
    //This will automatically update the nodeList's length too.
    var className = lastElem.getAttribute('class').replace('active','');
    lastElem.setAttribute('class', className);
  }

Using getopts to process long and short command line options

In ksh93, getopts does support long names...

while getopts "f(file):s(server):" flag
do
    echo "$flag" $OPTIND $OPTARG
done

Or so the tutorials I have found have said. Try it and see.

How to return rows from left table not found in right table?

If you are asking for T-SQL then lets look at fundamentals first. There are three types of joins here each with its own set of logical processing phases as:

  1. A cross join is simplest of all. It implements only one logical query processing phase, a Cartesian Product. This phase operates on the two tables provided as inputs to the join and produces a Cartesian product of the two. That is, each row from one input is matched with all rows from the other. So if you have m rows in one table and n rows in the other, you get m×n rows in the result.
  2. Then are Inner joins : They apply two logical query processing phases: A Cartesian product between the two input tables as in a cross join, and then it filters rows based on a predicate that you specify in ON clause (also known as Join condition).
  3. Next comes the third type of joins, Outer Joins:

    In an outer join, you mark a table as a preserved table by using the keywords LEFT OUTER JOIN, RIGHT OUTER JOIN, or FULL OUTER JOIN between the table names. The OUTER keyword is optional. The LEFT keyword means that the rows of the left table are preserved; the RIGHT keyword means that the rows in the right table are preserved; and the FULL keyword means that the rows in both the left and right tables are preserved.

    The third logical query processing phase of an outer join identifies the rows from the preserved table that did not find matches in the other table based on the ON predicate. This phase adds those rows to the result table produced by the first two phases of the join, and uses NULL marks as placeholders for the attributes from the nonpreserved side of the join in those outer rows.

Now if we look at the question: To return records from the left table which are not found in the right table use Left outer join and filter out the rows with NULL values for the attributes from the right side of the join.

How to solve "The directory is not empty" error when running rmdir command in a batch script?

What worked for me is the following. I appears like the RMDir command will issue “The directory is not empty” nearly all the time...

:Cleanup_Temporary_Files_and_Folders

Erase /F /S /Q C:\MyDir

RMDir /S /Q C:\MyDir
If  Exist  C:\MyDir  GoTo Cleanup_Temporary_Files_and_Folders

How to remove all null elements from a ArrayList or String Array?

This is easy way to remove default null values from arraylist

     tourists.removeAll(Arrays.asList(null));  

otherwise String value "null" remove from arraylist

       tourists.removeAll(Arrays.asList("null"));  

check if a key exists in a bucket in s3 using boto3

This could check both prefix and key, and fetches at most 1 key.

def prefix_exits(bucket, prefix):
    s3_client = boto3.client('s3')
    res = s3_client.list_objects_v2(Bucket=bucket, Prefix=prefix, MaxKeys=1)
    return 'Contents' in res

Using Gradle to build a jar with dependencies

To generate a fat JAR with a main executable class, avoiding problems with signed JARs, I suggest gradle-one-jar plugin. A simple plugin that uses the One-JAR project.

Easy to use:

apply plugin: 'gradle-one-jar'

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.github.rholder:gradle-one-jar:1.0.4'
    }
}

task myjar(type: OneJar) {
    mainClass = 'com.benmccann.gradle.test.WebServer'
}

Using command line arguments in VBscript

Set args = Wscript.Arguments

For Each arg In args
  Wscript.Echo arg
Next

From a command prompt, run the script like this:

CSCRIPT MyScript.vbs 1 2 A B "Arg with spaces"

Will give results like this:

1
2
A
B
Arg with spaces

Is it possible to sort a ES6 map object?

Perhaps a more realistic example about not sorting a Map object but preparing the sorting up front before doing the Map. The syntax gets actually pretty compact if you do it like this. You can apply the sorting before the map function like this, with a sort function before map (Example from a React app I am working on using JSX syntax)

Mark that I here define a sorting function inside using an arrow function that returns -1 if it is smaller and 0 otherwise sorted on a property of the Javascript objects in the array I get from an API.

report.ProcedureCodes.sort((a, b) => a.NumericalOrder < b.NumericalOrder ? -1 : 0).map((item, i) =>
                        <TableRow key={i}>

                            <TableCell>{item.Code}</TableCell>
                            <TableCell>{item.Text}</TableCell>
                            {/* <TableCell>{item.NumericalOrder}</TableCell> */}
                        </TableRow>
                    )

Determine if map contains a value for a key?

If you want to determine whether a key is there in map or not, you can use the find() or count() member function of map. The find function which is used here in example returns the iterator to element or map::end otherwise. In case of count the count returns 1 if found, else it returns zero(or otherwise).

if(phone.count(key))
{ //key found
}
else
{//key not found
}

for(int i=0;i<v.size();i++){
    phoneMap::iterator itr=phone.find(v[i]);//I have used a vector in this example to check through map you cal receive a value using at() e.g: map.at(key);
    if(itr!=phone.end())
        cout<<v[i]<<"="<<itr->second<<endl;
    else
        cout<<"Not found"<<endl;
}

Java JDBC - How to connect to Oracle using Service Name instead of SID

http://download.oracle.com/docs/cd/B28359_01/java.111/b31224/urls.htm#BEIDHCBA

Thin-style Service Name Syntax

Thin-style service names are supported only by the JDBC Thin driver. The syntax is:

@//host_name:port_number/service_name

For example:

jdbc:oracle:thin:scott/tiger@//myhost:1521/myservicename

So I would try:

jdbc:oracle:thin:@//oracle.hostserver2.mydomain.ca:1522/ABCD

Also, per Robert Greathouse's answer, you can also specify the TNS name in the JDBC URL as below:

jdbc:oracle:thin:@(DESCRIPTION =(ADDRESS_LIST =(ADDRESS =(PROTOCOL=TCP)(HOST=blah.example.com)(PORT=1521)))(CONNECT_DATA=(SID=BLAHSID)(GLOBAL_NAME=BLAHSID.WORLD)(SERVER=DEDICATED)))

Angular ng-repeat add bootstrap row every 3 or 4 cols

Building on Alpar's answer, here's a more generalised way to split a single list of items into multiple containers (rows, columns, buckets, whatever):

<div class="row" ng-repeat="row in [0,1,2]">
  <div class="col" ng-repeat="item in $ctrl.items" ng-if="$index % 3 == row">
    <span>{{item.name}}</span>
  </div>
</div> 

for a list of 10 items, generates:

<div class="row">
  <div class="col"><span>Item 1</span></div>
  <div class="col"><span>Item 4</span></div>
  <div class="col"><span>Item 7</span></div>
  <div class="col"><span>Item 10</span></div>
</div> 
<div class="row">
  <div class="col"><span>Item 2</span></div>
  <div class="col"><span>Item 5</span></div>
  <div class="col"><span>Item 8</span></div>
</div> 
<div class="row">
  <div class="col"><span>Item 3</span></div>
  <div class="col"><span>Item 6</span></div>
  <div class="col"><span>Item 9</span></div>
</div> 

The number of containers can be quickly coded into a controller function:

JS (ES6)

$scope.rowList = function(rows) {
  return Array(rows).fill().map((x,i)=>i);
}
$scope.rows = 2;

HTML

<div class="row" ng-repeat="row in rowList(rows)">
  <div ng-repeat="item in $ctrl.items" ng-if="$index % rows == row">
    ...

This approach avoids duplicating the item markup (<span>{{item.name}}</span> in this case) in the source template - not a huge win for a simple span, but for a more complex DOM structure (which I had) this helps keep the template DRY.

How to make RatingBar to show five stars

For me, I had an issue until I removed the padding. It looks like there is a bug on certain devices that doesn't alter the size of the view to accommodate the padding, and instead compresses the contents.

Remove padding, use layout_margin instead.

How to correctly use the ASP.NET FileUpload control

My solution in code behind was:

System.Web.UI.WebControls.FileUpload fileUpload;

I don't know why, but when you are using FileUpload without System.Web.UI.WebControls it is referencing to YourProject.FileUpload not System.Web.UI.WebControls.FileUpload.

How do I do a simple 'Find and Replace" in MsSQL?

This pointed me in the right direction, but I have a DB that originated in MSSQL 2000 and is still using the ntext data type for the column I was replacing on. When you try to run REPLACE on that type you get this error:

Argument data type ntext is invalid for argument 1 of replace function.

The simplest fix, if your column data fits within nvarchar, is to cast the column during replace. Borrowing the code from the accepted answer:

UPDATE YourTable
SET Column1 = REPLACE(cast(Column1 as nvarchar(max)),'a','b')
WHERE Column1 LIKE '%a%'

This worked perfectly for me. Thanks to this forum post I found for the fix. Hopefully this helps someone else!

Capturing Groups From a Grep RegEx

I realize that an answer was already accepted for this, but from a "strictly *nix purist angle" it seems like the right tool for the job is pcregrep, which doesn't seem to have been mentioned yet. Try changing the lines:

    echo $f | grep -oEi '[0-9]+_([a-z]+)_[0-9a-z]*'
    name=$?

to the following:

    name=$(echo $f | pcregrep -o1 -Ei '[0-9]+_([a-z]+)_[0-9a-z]*')

to get only the contents of the capturing group 1.

The pcregrep tool utilizes all of the same syntax you've already used with grep, but implements the functionality that you need.

The parameter -o works just like the grep version if it is bare, but it also accepts a numeric parameter in pcregrep, which indicates which capturing group you want to show.

With this solution there is a bare minimum of change required in the script. You simply replace one modular utility with another and tweak the parameters.

Interesting Note: You can use multiple -o arguments to return multiple capture groups in the order in which they appear on the line.

Undefined columns selected when subsetting data frame

You want rows where that condition is true so you need a comma:

data[data$Ozone > 14, ]

Adding author name in Eclipse automatically to existing files

Quick and in some cases error-prone solution:

Find Regexp: (?sm)(.*?)([^\n]*\b(class|interface|enum)\b.*)

Replace: $1/**\n * \n * @author <a href="mailto:[email protected]">John Smith</a>\n */\n$2

This will add the header to the first encountered class/interface/enum in the file. Class should have no existing header yet.

Controlling fps with requestAnimationFrame?

For throttling FPS to any value, pls see jdmayfields answer. However, for a very quick and easy solution to halve your frame rate, you can simply do your computations only every 2nd frame by:

requestAnimationFrame(render);
function render() {
  // ... computations ...
  requestAnimationFrame(skipFrame);
}
function skipFrame() { requestAnimationFrame(render); }

Similarly you could always call render but use a variable to control whether you do computations this time or not, allowing you to also cut FPS to a third or fourth (in my case, for a schematic webgl-animation 20fps is still enough while considerably lowering computational load on the clients)

String length in bytes in JavaScript

You can try this:

function getLengthInBytes(str) {
  var b = str.match(/[^\x00-\xff]/g);
  return (str.length + (!b ? 0: b.length)); 
}

It works for me.

Remove white space below image

I found this question and none of the solutions here worked for me. I found another solution that got rid of the gaps below images in Chrome. I had to add line-height:0; to the img selector in my CSS and the gaps below images went away.

Crazy that this problem persists in browsers in 2013.

How to mark-up phone numbers?

Although Apple recommends tel: in their docs for Mobile Safari, currently (iOS 4.3) it accepts callto: just the same. So I recommend using callto: on a generic web site as it works with both Skype and iPhone and I expect it will work on Android phones, too.

Update (June 2013)

This is still a matter of deciding what you want your web page to offer. On my websites I provide both tel: and callto: links (the latter labeled as being for Skype) since Desktop browsers on Mac don't do anything with tel: links while mobile Android doesn't do anything with callto: links. Even Google Chrome with the Google Talk plugin does not respond to tel: links. Still, I prefer offering both links on the desktop in case someone has gone to the trouble of getting tel: links to work on their computer.

If the site design dictated that I only provide one link, I'd use a tel: link that I would try to change to callto: on desktop browsers.

VB.NET - How to move to next item a For Each Loop?

I'd use the Continue statement instead:

For Each I As Item In Items

    If I = x Then
        Continue For
    End If

    ' Do something

Next

Note that this is slightly different to moving the iterator itself on - anything before the If will be executed again. Usually this is what you want, but if not you'll have to use GetEnumerator() and then MoveNext()/Current explicitly rather than using a For Each loop.

jQuery event to trigger action when a div is made visible

There is a jQuery plugin available for watching change in DOM attributes,

https://github.com/darcyclarke/jQuery-Watch-Plugin

The plugin wraps All you need do is bind MutationObserver

You can then use it to watch the div using:

$("#selector").watch('css', function() {
    console.log("Visibility: " + this.style.display == 'none'?'hidden':'shown'));
    //or any random events
});

How to get the current time as datetime

Swift 4

let dateFormatter : DateFormatter = DateFormatter()
//  dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.dateFormat = "yyyy-MMM-dd HH:mm:ss"
let date = Date()
let dateString = dateFormatter.string(from: date)
let interval = date.timeIntervalSince1970

OUTPUT

2018-May-01 10:41:31

How to make a launcher

They're examples provided by the Android team, if you've already loaded Samples, you can import Home screen replacement sample by following these steps.

File > New > Other >Android > Android Sample Project > Android x.x > Home > Finish

But if you do not have samples loaded, then download it using the below steps

Windows > Android SDK Manager > chooses "Sample for SDK" for SDK you need it > Install package > Accept License > Install

How to download a file over HTTP?

You can use PycURL on Python 2 and 3.

import pycurl

FILE_DEST = 'pycurl.html'
FILE_SRC = 'http://pycurl.io/'

with open(FILE_DEST, 'wb') as f:
    c = pycurl.Curl()
    c.setopt(c.URL, FILE_SRC)
    c.setopt(c.WRITEDATA, f)
    c.perform()
    c.close()

How to print variables without spaces between values

https://docs.python.org/2/library/functions.html#print

print(*objects, sep=' ', end='\n', file=sys.stdout)

Note: This function is not normally available as a built-in since the name print is recognized as the print statement. To disable the statement and use the print() function, use this future statement at the top of your module:

from future import print_function

What is the difference between JDK and JRE?

The difference between JDK and JRE is that JDK is the software development kit for java while JRE is the place where you run your programs.

Bootstrap 3 collapsed menu doesn't close on click

Simple Try to make a function in javascript for dropdown collapse class.

Example:

JS:

$scope.toogleMyClass  = function(){

    //dropdown-element

    $timeout(function(){
        $scope.preLoader = false;
        $(document).ready(function() {
            $("#dropdown-element").toggleClass('show');
        });
    },100);

};

Hook this function to onClick simple works for me.

Java: Converting String to and from ByteBuffer and associated problems

Check out the CharsetEncoder and CharsetDecoder API descriptions - You should follow a specific sequence of method calls to avoid this problem. For example, for CharsetEncoder:

  1. Reset the encoder via the reset method, unless it has not been used before;
  2. Invoke the encode method zero or more times, as long as additional input may be available, passing false for the endOfInput argument and filling the input buffer and flushing the output buffer between invocations;
  3. Invoke the encode method one final time, passing true for the endOfInput argument; and then
  4. Invoke the flush method so that the encoder can flush any internal state to the output buffer.

By the way, this is the same approach I am using for NIO although some of my colleagues are converting each char directly to a byte in the knowledge they are only using ASCII, which I can imagine is probably faster.

Angular 2 filter/search list

<md-input placeholder="Item name..." [(ngModel)]="name" (keyup)="filterResults()"></md-input>

<div *ngFor="let item of filteredValue">
{{item.name}}
</div>

  filterResults() {
    if (!this.name) {
      this.filteredValue = [...this.items];
    } else {
      this.filteredValue = [];
      this.filteredValue = this.items.filter((item) => {
        return item.name.toUpperCase().indexOf(this.name.toUpperCase()) > -1;
      });
    }
 }

Don't do any modification on 'items' array(list of items from which results are filtered). When searched item 'name' is empty return the complete list of 'items', if not compare the 'name' with every 'name' in the 'items ' array and filter out only the name that is present in 'items' array and store it in the 'filteredValue'.

HTML5 Video // Completely Hide Controls

A simple solution is – just to ignore user interactions :-)

video {
  pointer-events: none;
}

PHP Curl And Cookies

You can define different cookies for every user with CURLOPT_COOKIEFILE and CURLOPT_COOKIEJAR. Make different file for every user so each one would have it's own cookie-based session on remote server.

How do I wait for an asynchronously dispatched block to finish?

In addition to the semaphore technique covered exhaustively in other answers, we can now use XCTest in Xcode 6 to perform asynchronous tests via XCTestExpectation. This eliminates the need for semaphores when testing asynchronous code. For example:

- (void)testDataTask
{
    XCTestExpectation *expectation = [self expectationWithDescription:@"asynchronous request"];

    NSURL *url = [NSURL URLWithString:@"http://www.apple.com"];
    NSURLSessionTask *task = [self.session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        XCTAssertNil(error, @"dataTaskWithURL error %@", error);

        if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
            NSInteger statusCode = [(NSHTTPURLResponse *) response statusCode];
            XCTAssertEqual(statusCode, 200, @"status code was not 200; was %d", statusCode);
        }

        XCTAssert(data, @"data nil");

        // do additional tests on the contents of the `data` object here, if you want

        // when all done, Fulfill the expectation

        [expectation fulfill];
    }];
    [task resume];

    [self waitForExpectationsWithTimeout:10.0 handler:nil];
}

For the sake of future readers, while the dispatch semaphore technique is a wonderful technique when absolutely needed, I must confess that I see too many new developers, unfamiliar with good asynchronous programming patterns, gravitate too quickly to semaphores as a general mechanism for making asynchronous routines behave synchronously. Worse I've seen many of them use this semaphore technique from the main queue (and we should never block the main queue in production apps).

I know this isn't the case here (when this question was posted, there wasn't a nice tool like XCTestExpectation; also, in these testing suites, we must ensure the test does not finish until the asynchronous call is done). This is one of those rare situations where the semaphore technique for blocking the main thread might be necessary.

So with my apologies to the author of this original question, for whom the semaphore technique is sound, I write this warning to all of those new developers who see this semaphore technique and consider applying it in their code as a general approach for dealing with asynchronous methods: Be forewarned that nine times out of ten, the semaphore technique is not the best approach when encounting asynchronous operations. Instead, familiarize yourself with completion block/closure patterns, as well as delegate-protocol patterns and notifications. These are often much better ways of dealing with asynchronous tasks, rather than using semaphores to make them behave synchronously. Usually there are good reasons that asynchronous tasks were designed to behave asynchronously, so use the right asynchronous pattern rather than trying to make them behave synchronously.

How to get thread id of a pthread in linux c program?

pthread_getthreadid_np wasn't on my Mac os x. pthread_t is an opaque type. Don't beat your head over it. Just assign it to void* and call it good. If you need to printf use %p.

Fastest way to compute entropy in Python

def entropy(base, prob_a, prob_b ):
  import math
  base=2
  x=prob_a
  y=prob_b
  expression =-((x*math.log(x,base)+(y*math.log(y,base))))    
  return [expression]

How to find a whole word in a String in java

You can use regular expressions. Use Matcher and Pattern methods to get the desired output

How to extract the substring between two markers?

In python, extracting substring form string can be done using findall method in regular expression (re) module.

>>> import re
>>> s = 'gfgfdAAA1234ZZZuijjk'
>>> ss = re.findall('AAA(.+)ZZZ', s)
>>> print ss
['1234']

How to make blinking/flashing text with CSS 3

It works for me by using class=blink for the respective element(s)

Simple JS Code

// Blink
      setInterval(function()
        {

        setTimeout(function()
        {

        //$(".blink").css("color","rgba(0,0,0,0.1)"); // If you want simply black/white blink of text
        $(".blink").css("visibility","hidden"); // This is for Visibility of the element  


        },900);


        //$(".blink").css("color","rgba(0,0,0,1)");  // If you want simply black/white blink of text
        $(".blink").css("visibility","visible");  // This is for Visibility of the element

        },1000);

Could not open a connection to your authentication agent

The following command worked for me. I am using CentOS.

exec ssh-agent bash

How to force a line break on a Javascript concatenated string?

document.getElementById("address_box").value = 
(title + "\n" + address + "\n" + address2 + "\n" + address3 + "\n" + address4);

Intent from Fragment to Activity

public class OneWayFragment extends Fragment {

    ImageView img_search;


public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {


        View view = inflater.inflate(R.layout.one_way_fragment, container, false);
        img_search = (ImageView) view.findViewById(R.id.search);


        img_search.setOnClickListener(new View.OnClickListener() {
            @Override`enter code here`
            public void onClick(View v) {
                Intent displayFlights = new Intent(getActivity(), SelectFlight.class);
                startActivity(displayFlights);
            }
        });

python numpy ValueError: operands could not be broadcast together with shapes

It's possible that the error didn't occur in the dot product, but after. For example try this

a = np.random.randn(12,1)
b = np.random.randn(1,5)
c = np.random.randn(5,12)
d = np.dot(a,b) * c

np.dot(a,b) will be fine; however np.dot(a, b) * c is clearly wrong (12x1 X 1x5 = 12x5 which cannot element-wise multiply 5x12) but numpy will give you

ValueError: operands could not be broadcast together with shapes (12,1) (1,5)

The error is misleading; however there is an issue on that line.

Exists Angularjs code/naming conventions?

Check out this GitHub repository that describes best practices for AngularJS apps. It has naming conventions for different components. It is not complete, but it is community-driven so everyone can contribute.

Traits vs. interfaces

The main difference is that, with interfaces, you must define the actual implementation of each method within each class that implements said interface, so you can have many classes implement the same interface but with different behavior, while traits are just chunks of code injected in a class; another important difference is that trait methods can only be class-methods or static-methods, unlike interface methods which can also (and usually are) be instance methods.

How to get UTC time in Python?

import datetime
import pytz

# datetime object with timezone awareness:
datetime.datetime.now(tz=pytz.utc)

# seconds from epoch:
datetime.datetime.now(tz=pytz.utc).timestamp() 

# ms from epoch:
int(datetime.datetime.now(tz=pytz.utc).timestamp() * 1000) 

What is difference between 'git reset --hard HEAD~1' and 'git reset --soft HEAD~1'?

Git reset has 5 main modes: soft, mixed, merged, hard, keep. The difference between them is to change or not change head, stage (index), working directory.

Git reset --hard will change head, index and working directory.
Git reset --soft will change head only. No change to index, working directory.

So in other words if you want to undo your commit, --soft should be good enough. But after that you still have the changes from bad commit in your index and working directory. You can modify the files, fix them, add them to index and commit again.

With the --hard, you completely get a clean slate in your project. As if there hasn't been any change from the last commit. If you are sure this is what you want then move forward. But once you do this, you'll lose your last commit completely. (Note: there are still ways to recover the lost commit).

Design Documents (High Level and Low Level Design Documents)

High-Level Design (HLD) involves decomposing a system into modules, and representing the interfaces & invocation relationships among modules. An HLD is referred to as software architecture.

LLD, also known as a detailed design, is used to design internals of the individual modules identified during HLD i.e. data structures and algorithms of the modules are designed and documented.

Now, HLD and LLD are actually used in traditional Approach (Function-Oriented Software Design) whereas, in OOAD, the system is seen as a set of objects interacting with each other.

As per the above definitions, a high-level design document will usually include a high-level architecture diagram depicting the components, interfaces, and networks that need to be further specified or developed. The document may also depict or otherwise refer to work flows and/or data flows between component systems.

Class diagrams with all the methods and relations between classes come under LLD. Program specs are covered under LLD. LLD describes each and every module in an elaborate manner so that the programmer can directly code the program based on it. There will be at least 1 document for each module. The LLD will contain - a detailed functional logic of the module in pseudo code - database tables with all elements including their type and size - all interface details with complete API references(both requests and responses) - all dependency issues - error message listings - complete inputs and outputs for a module.

Android Studio - Auto complete and other features not working

It's Working

Disable Power Save Mode

Untick Power Save Mode Option :: File -> Power Save Mode

How to get to Model or Viewbag Variables in a Script Tag

When you're doing this

var model = @Html.Raw(Json.Encode(Model));

You're probably getting a JSON string, and not a JavaScript object.

You need to parse it in to an object:

var model = JSON.parse(model); //or $.parseJSON() since if jQuery is included
console.log(model.Sections);

How to reposition Chrome Developer Tools

Keyboard shortcut to toggle the docking position (side/bottom)

CTRL+SHIFT+D

And there are many shortcuts you can see them by going to

Settings » Shortcuts, as displayed here:
Settings screenshot

Alternatively, use CTRL + ? to go to the settings, from there one can reach the "Shortcuts" sub-item on the left or use the Official reference.

In DB2 Display a table's definition

Right-click the table in DB2 Control Center and chose Generate DDL... That will give you everything you need and more.

Moment.js: Date between dates

if (date.isBefore(endDate) 
 && date.isAfter(startDate) 
 || (date.isSame(startDate) || date.isSame(endDate))

is logically the same as

if (!(date.isBefore(startDate) || date.isAfter(endDate)))

which saves you a couple of lines of code and (in some cases) method calls.

Might be easier than pulling in a whole plugin if you only want to do this once or twice.

Importing modules from parent folder

For me the shortest and my favorite oneliner for accessing to the parent directory is:

sys.path.append(os.path.dirname(os.getcwd()))

or:

sys.path.insert(1, os.path.dirname(os.getcwd()))

os.getcwd() returns the name of the current working directory, os.path.dirname(directory_name) returns the directory name for the passed one.

Actually, in my opinion Python project architecture should be done the way where no one module from child directory will use any module from the parent directory. If something like this happens it is worth to rethink about the project tree.

Another way is to add parent directory to PYTHONPATH system environment variable.

Open files in 'rt' and 'wt' modes

t refers to the text mode. There is no difference between r and rt or w and wt since text mode is the default.

Documented here:

Character   Meaning
'r'     open for reading (default)
'w'     open for writing, truncating the file first
'x'     open for exclusive creation, failing if the file already exists
'a'     open for writing, appending to the end of the file if it exists
'b'     binary mode
't'     text mode (default)
'+'     open a disk file for updating (reading and writing)
'U'     universal newlines mode (deprecated)

The default mode is 'r' (open for reading text, synonym of 'rt').

React Modifying Textarea Values

As a newbie in React world, I came across a similar issues where I could not edit the textarea and struggled with binding. It's worth knowing about controlled and uncontrolled elements when it comes to react.

The value of the following uncontrolled textarea cannot be changed because of value

 <textarea type="text" value="some value"
    onChange={(event) => this.handleOnChange(event)}></textarea>

The value of the following uncontrolled textarea can be changed because of use of defaultValue or no value attribute

<textarea type="text" defaultValue="sample" 
    onChange={(event) => this.handleOnChange(event)}></textarea>

<textarea type="text" 
   onChange={(event) => this.handleOnChange(event)}></textarea>

The value of the following controlled textarea can be changed because of how value is mapped to a state as well as the onChange event listener

<textarea value={this.state.textareaValue} 
onChange={(event) => this.handleOnChange(event)}></textarea>

Here is my solution using different syntax. I prefer the auto-bind than manual binding however, if I were to not use {(event) => this.onXXXX(event)} then that would cause the content of textarea to be not editable OR the event.preventDefault() does not work as expected. Still a lot to learn I suppose.

class Editor extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      textareaValue: ''
    }
  }
  handleOnChange(event) {
    this.setState({
      textareaValue: event.target.value
    })
  }
  handleOnSubmit(event) {
    event.preventDefault();
    this.setState({
      textareaValue: this.state.textareaValue + ' [Saved on ' + (new Date()).toLocaleString() + ']'
    })
  }
  render() {
    return <div>
        <form onSubmit={(event) => this.handleOnSubmit(event)}>
          <textarea rows={10} cols={30} value={this.state.textareaValue} 
            onChange={(event) => this.handleOnChange(event)}></textarea>
          <br/>
          <input type="submit" value="Save"/>
        </form>
      </div>
  }
}
ReactDOM.render(<Editor />, document.getElementById("content"));

The versions of libraries are

"babel-cli": "6.24.1",
"babel-preset-react": "6.24.1"
"React & ReactDOM v15.5.4" 

How to find the socket connection state in C?

There is an easy way to check socket connection state via poll call. First, you need to poll socket, whether it has POLLIN event.

  1. If socket is not closed and there is data to read then read will return more than zero.
  2. If there is no new data on socket, then POLLIN will be set to 0 in revents
  3. If socket is closed then POLLIN flag will be set to one and read will return 0.

Here is small code snippet:

int client_socket_1, client_socket_2;
if ((client_socket_1 = accept(listen_socket, NULL, NULL)) < 0)
{
    perror("Unable to accept s1");
    abort();
}
if ((client_socket_2 = accept(listen_socket, NULL, NULL)) < 0)
{
    perror("Unable to accept s2");
    abort();
}
pollfd pfd[]={{client_socket_1,POLLIN,0},{client_socket_2,POLLIN,0}};
char sock_buf[1024]; 
while (true)
{
    poll(pfd,2,5);
    if (pfd[0].revents & POLLIN)
    {
        int sock_readden = read(client_socket_1, sock_buf, sizeof(sock_buf));
        if (sock_readden == 0)
            break;
        if (sock_readden > 0)
            write(client_socket_2, sock_buf, sock_readden);
    }
    if (pfd[1].revents & POLLIN)
    {
        int sock_readden = read(client_socket_2, sock_buf, sizeof(sock_buf));
        if (sock_readden == 0)
            break;
        if (sock_readden > 0)
            write(client_socket_1, sock_buf, sock_readden);
    }
}

Tuples( or arrays ) as Dictionary keys in C#

If your consuming code can make do with an IDictionary<> interface, instead of Dictionary, my instinct would have been to use a SortedDictionary<> with a custom array comparer, ie:

class ArrayComparer<T> : IComparer<IList<T>>
    where T : IComparable<T>
{
    public int Compare(IList<T> x, IList<T> y)
    {
        int compare = 0;
        for (int n = 0; n < x.Count && n < y.Count; ++n)
        {
            compare = x[n].CompareTo(y[n]);
        }
        return compare;
    }
}

And create thus (using int[] just for concrete example's sake):

var dictionary = new SortedDictionary<int[], string>(new ArrayComparer<int>());

Regex to check if valid URL that ends in .jpg, .png, or .gif

Here's the basic idea in Perl. Salt to taste.

#!/usr/bin/perl

use LWP::UserAgent;

my $ua = LWP::UserAgent->new;

@ARGV = qw(http://www.example.com/logo.png);

my $response = $ua->head( $ARGV[0] );

my( $class, $type ) = split m|/|, lc $response->content_type;

print "It's an image!\n" if $class eq 'image';

If you need to inspect the URL, use a solid library for it rather than trying to handle all the odd situations yourself:

use URI;

my $uri = URI->new( $ARGV[0] );

my $last = ( $uri->path_segments )[-1];

my( $extension ) = $last =~ m/\.([^.]+)$/g;

print "My extension is $extension\n";

Good luck, :)

VBA changing active workbook

Use ThisWorkbook which will refer to the original workbook which holds the code.

Alternatively at code start

Dim Wb As Workbook
Set Wb = ActiveWorkbook

sample code that activates all open books before returning to ThisWorkbook

Sub Test()
Dim Wb As Workbook
Dim Wb2 As Workbook
Set Wb = ThisWorkbook
For Each Wb2 In Application.Workbooks
    Wb2.Activate
Next
Wb.Activate
End Sub

How to send an HTTP request with a header parameter?

With your own Code and a Slight Change withou jQuery,

function testingAPI(){ 
    var key = "8a1c6a354c884c658ff29a8636fd7c18"; 
    var url = "https://api.fantasydata.net/nfl/v2/JSON/PlayerSeasonStats/2015";
    console.log(httpGet(url,key)); 
}


function httpGet(url,key){
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "GET", url, false );
    xmlHttp.setRequestHeader("Ocp-Apim-Subscription-Key",key);
    xmlHttp.send(null);
    return xmlHttp.responseText;
}

Thank You

How to set an environment variable from a Gradle build?

This one is working for me for settings environment variable for the test plugin

test {
    systemProperties = [
        'catalina.home': 'c:/test'
    ]
    println "Starting Tests"
    beforeTest { descriptor ->
       logger.lifecycle("Running test: " + descriptor)                
    }    
}

Command line to remove an environment variable from the OS level configuration

I agree with CupawnTae.

SET is not useful for changes to the master environment.

FYI: System variables are in HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment (a good deal longer than user vars).

The full command for a system var named FOOBAR therefore is:

REG delete "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /F /V FOOBAR

(Note the quotes required to handle the space.)

It is too bad the setx command doesn't support a delete syntax. :(

PS: Use responsibly - If you kill your path variable, don't blame me!

How to truncate milliseconds off of a .NET DateTime

I know the answer is quite late, but the best way to get rid of milliseconds is

var currentDateTime = DateTime.Now.ToString("s");

Try printing the value of the variable, it will show the date time, without milliseconds.

Fill remaining vertical space with CSS using display:flex

A more modern approach would be to use the grid property.

_x000D_
_x000D_
section {_x000D_
  display: grid;_x000D_
  align-items: stretch;_x000D_
  height: 300px;_x000D_
  grid-template-rows: min-content auto 60px;_x000D_
}_x000D_
header {_x000D_
  background: tomato;_x000D_
}_x000D_
div {_x000D_
  background: gold;_x000D_
  overflow: auto;_x000D_
}_x000D_
footer {_x000D_
  background: lightgreen;_x000D_
}
_x000D_
<section>_x000D_
  <header>_x000D_
    header: sized to content_x000D_
    <br>(but is it really?)_x000D_
  </header>_x000D_
  <div>_x000D_
    main content: fills remaining space<br>_x000D_
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
    _x000D_
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
    _x000D_
  </div>_x000D_
  <footer>_x000D_
    footer: fixed height in px_x000D_
  </footer>_x000D_
</section>
_x000D_
_x000D_
_x000D_

Mock a constructor with parameter

The code you posted works for me with the latest version of Mockito and Powermockito. Maybe you haven't prepared A? Try this:

A.java

public class A {
     private final String test;

    public A(String test) {
        this.test = test;
    }

    public String check() {
        return "checked " + this.test;
    }
}

MockA.java

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest(A.class)
public class MockA {
    @Test
    public void test_not_mocked() throws Throwable {
        assertThat(new A("random string").check(), equalTo("checked random string"));
    }
    @Test
    public void test_mocked() throws Throwable {
         A a = mock(A.class); 
         when(a.check()).thenReturn("test");
         PowerMockito.whenNew(A.class).withArguments(Mockito.anyString()).thenReturn(a);
         assertThat(new A("random string").check(), equalTo("test"));
    }
}

Both tests should pass with mockito 1.9.0, powermockito 1.4.12 and junit 4.8.2

Combine Multiple child rows into one row MYSQL

If you really need multiple columns in your result, and the amount of options is limited, you can even do this:

select
  ordered_item.id as `Id`,
  ordered_item.Item_Name as `ItemName`,
  if(ordered_options.id=1,Ordered_Options.Value,null) as `Option1`,
  if(ordered_options.id=2,Ordered_Options.Value,null) as `Option2`,
  if(ordered_options.id=43,Ordered_Options.Value,null) as `Option43`,
  if(ordered_options.id=44,Ordered_Options.Value,null) as `Option44`,
  GROUP_CONCAT(if(ordered_options.id not in (1,2,43,44),Ordered_Options.Value,null)) as `OtherOptions`
from
  ordered_item,
  ordered_options
where
  ordered_item.id=ordered_options.ordered_item_id
group by
  ordered_item.id

Angular ForEach in Angular4/Typescript?

arrayData.forEach((key : any, val: any) => {
                        key['index'] = val + 1;

                        arrayData2.forEach((keys : any, vals :any) => {
                            if (key.group_id == keys.id) {
                                key.group_name = keys.group_name;
                            }
                        })
                    })

How do you set the title color for the new Toolbar?

If you are supporting API 23 and above, you can now use the titleTextColor attribute to set the Toolbar's title color.

layout/toolbar.xml

<android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:titleTextColor="@color/colorPrimary"
        />

MyActivity.java

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar)
toolbar.setTitleTextColor(Color.WHITE);

How to include file in a bash shell script

Yes, use source or the short form which is just .:

. other_script.sh

Regular expression include and exclude special characters

[a-zA-Z0-9~@#\^\$&\*\(\)-_\+=\[\]\{\}\|\\,\.\?\s]*

This would do the matching, if you only want to allow that just wrap it in ^$ or any other delimiters that you see appropriate, if you do this no specific disallow logic is needed.

Bootstrap 3: How do you align column content to bottom of row

I don't know why but for me the solution proposed by Marius Stanescu is breaking the specificity of col (a col-md-3 followed by a col-md-4 will take all of the twelve row)

I found another working solution :

.bottom-column 
{
   display: inline-block;
   vertical-align: middle;
   float: none;
}

"NOT IN" clause in LINQ to Entities

Try:

from p in db.Products
where !theBadCategories.Contains(p.Category)
select p;

What's the SQL query you want to translate into a Linq query?

How to programmatically log out from Facebook SDK 3.0 without using Facebook login/logout button?

Since Facebook's Android SDK v4.0 you need to execute the following:

LoginManager.getInstance().logOut();

This is not sufficient. This will simply clear cached access token and profile so that AccessToken.getCurrentAccessToken() and Profile.getCurrentProfile() will now become null.

To completely logout you need to revoke permissions and then call LoginManager.getInstance().logOut();. To revoke permission execute following graph API -

    GraphRequest delPermRequest = new GraphRequest(AccessToken.getCurrentAccessToken(), "/{user-id}/permissions/", null, HttpMethod.DELETE, new GraphRequest.Callback() {
        @Override
        public void onCompleted(GraphResponse graphResponse) {
            if(graphResponse!=null){
                FacebookRequestError error =graphResponse.getError();
                if(error!=null){
                    Log.e(TAG, error.toString());
                }else {
                    finish();
                }
            }
        }
    });
    Log.d(TAG,"Executing revoke permissions with graph path" + delPermRequest.getGraphPath());
    delPermRequest.executeAsync();

What's the better (cleaner) way to ignore output in PowerShell?

I just did some tests of the four options that I know about.

Measure-Command {$(1..1000) | Out-Null}

TotalMilliseconds : 76.211

Measure-Command {[Void]$(1..1000)}

TotalMilliseconds : 0.217

Measure-Command {$(1..1000) > $null}

TotalMilliseconds : 0.2478

Measure-Command {$null = $(1..1000)}

TotalMilliseconds : 0.2122

## Control, times vary from 0.21 to 0.24
Measure-Command {$(1..1000)}

TotalMilliseconds : 0.2141

So I would suggest that you use anything but Out-Null due to overhead. The next important thing, to me, would be readability. I kind of like redirecting to $null and setting equal to $null myself. I use to prefer casting to [Void], but that may not be as understandable when glancing at code or for new users.

I guess I slightly prefer redirecting output to $null.

Do-Something > $null

Edit

After stej's comment again, I decided to do some more tests with pipelines to better isolate the overhead of trashing the output.

Here are some tests with a simple 1000 object pipeline.

## Control Pipeline
Measure-Command {$(1..1000) | ?{$_ -is [int]}}

TotalMilliseconds : 119.3823

## Out-Null
Measure-Command {$(1..1000) | ?{$_ -is [int]} | Out-Null}

TotalMilliseconds : 190.2193

## Redirect to $null
Measure-Command {$(1..1000) | ?{$_ -is [int]} > $null}

TotalMilliseconds : 119.7923

In this case, Out-Null has about a 60% overhead and > $null has about a 0.3% overhead.

Addendum 2017-10-16: I originally overlooked another option with Out-Null, the use of the -inputObject parameter. Using this the overhead seems to disappear, however the syntax is different:

Out-Null -inputObject ($(1..1000) | ?{$_ -is [int]})

And now for some tests with a simple 100 object pipeline.

## Control Pipeline
Measure-Command {$(1..100) | ?{$_ -is [int]}}

TotalMilliseconds : 12.3566

## Out-Null
Measure-Command {$(1..100) | ?{$_ -is [int]} | Out-Null}

TotalMilliseconds : 19.7357

## Redirect to $null
Measure-Command {$(1..1000) | ?{$_ -is [int]} > $null}

TotalMilliseconds : 12.8527

Here again Out-Null has about a 60% overhead. While > $null has an overhead of about 4%. The numbers here varied a bit from test to test (I ran each about 5 times and picked the middle ground). But I think it shows a clear reason to not use Out-Null.

Rails create or update magic?

Rails 6

Rails 6 added an upsert and upsert_all methods that deliver this functionality.

Model.upsert(column_name: value)

[upsert] It does not instantiate any models nor does it trigger Active Record callbacks or validations.

Rails 5, 4, and 3

Not if you are looking for an "upsert" (where the database executes an update or an insert statement in the same operation) type of statement. Out of the box, Rails and ActiveRecord have no such feature. You can use the upsert gem, however.

Otherwise, you can use: find_or_initialize_by or find_or_create_by, which offer similar functionality, albeit at the cost of an additional database hit, which, in most cases, is hardly an issue at all. So unless you have serious performance concerns, I would not use the gem.

For example, if no user is found with the name "Roger", a new user instance is instantiated with its name set to "Roger".

user = User.where(name: "Roger").first_or_initialize
user.email = "[email protected]"
user.save

Alternatively, you can use find_or_initialize_by.

user = User.find_or_initialize_by(name: "Roger")

In Rails 3.

user = User.find_or_initialize_by_name("Roger")
user.email = "[email protected]"
user.save

You can use a block, but the block only runs if the record is new.

User.where(name: "Roger").first_or_initialize do |user|
  # this won't run if a user with name "Roger" is found
  user.save 
end

User.find_or_initialize_by(name: "Roger") do |user|
  # this also won't run if a user with name "Roger" is found
  user.save
end

If you want to use a block regardless of the record's persistence, use tap on the result:

User.where(name: "Roger").first_or_initialize.tap do |user|
  user.email = "[email protected]"
  user.save
end

How do I print out the value of this boolean? (Java)

There are several problems.

One is of style; always capitalize class names. This is a universally observed Java convention. Failing to do so confuses other programmers.

Secondly, the line

System.out.println(boolean isLeapYear);

is a syntax error. Delete it.

Thirdly.

You never call the function from your main routine. That is why you never see any reply to the input.

How do I delete files programmatically on Android?

Why don't you test this with this code:

File fdelete = new File(uri.getPath());
if (fdelete.exists()) {
    if (fdelete.delete()) {
        System.out.println("file Deleted :" + uri.getPath());
    } else {
        System.out.println("file not Deleted :" + uri.getPath());
    }
}

I think part of the problem is you never try to delete the file, you just keep creating a variable that has a method call.

So in your case you could try:

File file = new File(uri.getPath());
file.delete();
if(file.exists()){
      file.getCanonicalFile().delete();
      if(file.exists()){
           getApplicationContext().deleteFile(file.getName());
      }
}

However I think that's a little overkill.

You added a comment that you are using an external directory rather than a uri. So instead you should add something like:

String root = Environment.getExternalStorageDirectory().toString();
File file = new File(root + "/images/media/2918"); 

Then try to delete the file.

Hadoop MapReduce: Strange Result when Storing Previous Value in Memory in a Reduce Class (Java)

It is very inefficient to store all values in memory, so the objects are reused and loaded one at a time. See this other SO question for a good explanation. Summary:

[...] when looping through the Iterable value list, each Object instance is re-used, so it only keeps one instance around at a given time.

Enable the display of line numbers in Visual Studio

It's not enabled by default but you can enable it by going to:

  1. Click Tools
  2. Options
  3. Text Editor (expand)
  4. All Languages
  5. Line Numbers (Checkbox)
  6. Click Ok

settings

Mysql service is missing

Go to

C:\Program Files\MySQL\MySQL Server 5.2\bin

then Open MySQLInstanceConfig file

then complete the wizard.

Click finish

Solve the problem

I think this is the best way to change the port number also.

It works for me

box-shadow on bootstrap 3 container

http://jsfiddle.net/Y93TX/2/

     @import url("http://netdna.bootstrapcdn.com/bootstrap/3.0.0-wip/css/bootstrap.min.css");

.row {
    height: 100px;
    background-color: green;
}
.container {
    margin-top: 50px;
    box-shadow: 0 0 30px black;
    padding:0 15px 0 15px;
}



    <div class="container">
        <div class="row">one</div>
        <div class="row">two</div>
        <div class="row">three</div>
    </div>
</body>

Git: Find the most recent common ancestor of two branches

As noted in a prior answer, although git merge-base works,

$ git merge-base myfeature develop
050dc022f3a65bdc78d97e2b1ac9b595a924c3f2

If myfeature is the current branch, as is common, you can use --fork-point:

$ git merge-base --fork-point develop
050dc022f3a65bdc78d97e2b1ac9b595a924c3f2

This argument works only in sufficiently recent versions of git. Unfortunately it doesn't always work, however, and it is not clear why. Please refer to the limitations noted toward the end of this answer.


For full commit info, consider:

$ git log -1 $(git merge-base --fork-point develop) 

How do I detect the Python version at runtime?

Just in case you want to see all of the gory details in human readable form, you can use:

import platform;

print(platform.sys.version);

Output for my system:

3.6.5 |Anaconda, Inc.| (default, Apr 29 2018, 16:14:56) 
[GCC 7.2.0]

Something very detailed but machine parsable would be to get the version_info object from platform.sys, instead, and then use its properties to take a predetermined course of action. For example:

import platform;

print(platform.sys.version_info)

Output on my system:

sys.version_info(major=3, minor=6, micro=5, releaselevel='final', serial=0)

What is the LD_PRELOAD trick?

If you set LD_PRELOAD to the path of a shared object, that file will be loaded before any other library (including the C runtime, libc.so). So to run ls with your special malloc() implementation, do this:

$ LD_PRELOAD=/path/to/my/malloc.so /bin/ls

Access to the path is denied

I had a lot of trouble with this, specifically related to my code running locally but when I needed to run it on IIS it was throwing this error. I found that adding a check to my code and letting the application create the folder on the first run fixed the issue without having to mess with the folders authorizations.

something like this before you call your method that uses the folder

bool exists = System.IO.Directory.Exists("mypath");

        if (!exists)
            System.IO.Directory.CreateDirectory("mypath");

How can I change eclipse's Internal Browser from IE to Firefox on Windows XP?

I like the Aptana Browser Preview windo for this.

You can get it from their update site: http://download.aptana.org/tools/studio/plugin/update/studio/

After you install the Aptana plugin, open an Aptana project and there should be an option under help to install aptana features. under other you will find a Firefox/XUL browser. There may be a more direct way to install the XUL plugin, but the above procedure works.

Displaying a Table in Django from Database

The easiest way is to use a for loop template tag.

Given the view:

def MyView(request):
    ...
    query_results = YourModel.objects.all()
    ...
    #return a response to your template and add query_results to the context

You can add a snippet like this your template...

<table>
    <tr>
        <th>Field 1</th>
        ...
        <th>Field N</th>
    </tr>
    {% for item in query_results %}
    <tr> 
        <td>{{ item.field1 }}</td>
        ...
        <td>{{ item.fieldN }}</td>
    </tr>
    {% endfor %}
</table>

This is all covered in Part 3 of the Django tutorial. And here's Part 1 if you need to start there.

How to remove old Docker containers

The official way is:

docker rm `docker ps -aq`

The Docker maintainers have indicated there will be no command for this - and you compose the commands like that:

We have discussed this before and prefer users to use the above line without having to add additional code to Docker.

How to a convert a date to a number and back again in MATLAB

Use DATESTR

>> datestr(40189)
ans =
12-Jan-0110

Unfortunately, Excel starts counting at 1-Jan-1900. Find out how to convert serial dates from Matlab to Excel by using DATENUM

>> datenum(2010,1,11)
ans =
      734149
>> datenum(2010,1,11)-40189
ans =
      693960
>> datestr(40189+693960)
ans =
11-Jan-2010

In other words, to convert any serial Excel date, call

datestr(excelSerialDate + 693960)

EDIT

To get the date in mm/dd/yyyy format, call datestr with the specified format

excelSerialDate = 40189;
datestr(excelSerialDate + 693960,'mm/dd/yyyy')
ans =
01/11/2010

Also, if you want to get rid of the leading zero for the month, you can use REGEXPREP to fix things

excelSerialDate = 40189;
regexprep(datestr(excelSerialDate + 693960,'mm/dd/yyyy'),'^0','')
ans =
1/11/2010

"column not allowed here" error in INSERT statement

Like Scaffman said - You are missing quotes. Always when you are passing a value to varchar2 use quotes

INSERT INTO LOCATION VALUES('PQ95VM','HAPPY_STREET','FRANCE');

So one (') starts the string and the second (') closes it.

But if you want to add a quote symbol into a string for example:

My father told me: 'you have to be brave, son'.

You have to use a triple quote symbol like:

'My father told me: ''you have to be brave, son''.'

*adding quote method can vary on different db engines

jQuery - trapping tab select event

Simply:

$("#tabs_div").tabs();
$("#tabs_div").on("click", "a.tab_a", function(){
    console.log("selected tab id: " + $(this).attr("href"));
    console.log("selected tab name: " + $(this).find("span").text());
});

But you have to add class name to your anchors named "tab_a":

<div id="tabs">
<UL>
    <LI><A class="tab_a" href="#fragment-1"><SPAN>Tab1</SPAN></A></LI>
    <LI><A class="tab_a" href="#fragment-2"><SPAN>Tab2</SPAN></A></LI>
    <LI><A class="tab_a" href="#fragment-3"><SPAN>Tab3</SPAN></A></LI>
    <LI><A class="tab_a" href="#fragment-4"><SPAN>Tab4</SPAN></A></LI>
</UL>

<DIV id=fragment-1>
<UL>
    <LI><A class="tab_a" href="#fragment-1a"><SPAN>Sub-Tab1</SPAN></A></LI>
    <LI><A class="tab_a" href="#fragment-1b"><SPAN>Sub-Tab2</SPAN></A></LI>
    <LI><A class="tab_a" href="#fragment-1c"><SPAN>Sub-Tab3</SPAN></A></LI>
</UL>
</DIV>
.
.
</DIV>

How to get a URL parameter in Express?

If you want to grab the query parameter value in the URL, follow below code pieces

//url.localhost:8888/p?tagid=1234
req.query.tagid
OR
req.param.tagid

If you want to grab the URL parameter using Express param function

Express param function to grab a specific parameter. This is considered middleware and will run before the route is called.

This can be used for validations or grabbing important information about item.

An example for this would be:

// parameter middleware that will run before the next routes
app.param('tagid', function(req, res, next, tagid) {

// check if the tagid exists
// do some validations
// add something to the tagid
var modified = tagid+ '123';

// save name to the request
req.tagid= modified;

next();
});

// http://localhost:8080/api/tags/98
app.get('/api/tags/:tagid', function(req, res) {
// the tagid was found and is available in req.tagid
res.send('New tag id ' + req.tagid+ '!');
});

No 'Access-Control-Allow-Origin' header is present on the requested resource error

Please use @CrossOrigin on the backendside in Spring boot controller (either class level or method level) as the solution for Chrome error 'No 'Access-Control-Allow-Origin' header is present on the requested resource.'

This solution is working for me 100% ...

Example : Class level

@CrossOrigin
@Controller
public class UploadController {

----- OR -------

Example : Method level

@CrossOrigin(origins = "http://localhost:3000", maxAge = 3600)
@RequestMapping(value = "/loadAllCars")
    @ResponseBody
    public List<Car> loadAllCars() {


Ref: https://spring.io/blog/2015/06/08/cors-support-in-spring-framework

How to use pip with python 3.4 on windows?

I had the same problem when I install python3.5.3. And finally I find the pip.exe in this folder: ~/python/scripts/pip.exe. Hope that help.

Get the value of a dropdown in jQuery

Another option:

$("#<%=dropDownId.ClientID%>").children("option:selected").val();

Alternative to itoa() for converting integer to string C++?

Archeology

itoa was a non-standard helper function designed to complement the atoi standard function, and probably hiding a sprintf (Most its features can be implemented in terms of sprintf): http://www.cplusplus.com/reference/clibrary/cstdlib/itoa.html

The C Way

Use sprintf. Or snprintf. Or whatever tool you find.

Despite the fact some functions are not in the standard, as rightly mentioned by "onebyone" in one of his comments, most compiler will offer you an alternative (e.g. Visual C++ has its own _snprintf you can typedef to snprintf if you need it).

The C++ way.

Use the C++ streams (in the current case std::stringstream (or even the deprecated std::strstream, as proposed by Herb Sutter in one of his books, because it's somewhat faster).

Conclusion

You're in C++, which means that you can choose the way you want it:

  • The faster way (i.e. the C way), but you should be sure the code is a bottleneck in your application (premature optimizations are evil, etc.) and that your code is safely encapsulated to avoid risking buffer overruns.

  • The safer way (i.e., the C++ way), if you know this part of the code is not critical, so better be sure this part of the code won't break at random moments because someone mistook a size or a pointer (which happens in real life, like... yesterday, on my computer, because someone thought it "cool" to use the faster way without really needing it).

Checking if float is an integer

if (fmod(f, 1) == 0.0) {
  ...
}

Don't forget math.h and libm.

JS how to cache a variable

I have written a generic caching func() which will cache any variable easily and very readable format. Caching function:

function calculateSomethingMaybe(args){
  return args;
}

function caching(fn){
  const cache = {};
  return function(){
    const string = arguments[0];
    if(!cache[string]){
      const result = fn.apply(this, arguments);
      cache[string] = result;
      return result;
    }
    return cache[string];
  }
}

const letsCache = caching(calculateSomethingMaybe);

console.log(letsCache('a book'), letsCache('a pen'), letsCache('a book'));

Eclipse - Installing a new JRE (Java SE 8 1.8.0)

You can have many java versions in your system.

I think you should add the java 8 in yours JREs installed or edit.

Take a look my screen:

enter image description here

If you click in edit (check your java 8 path):

enter image description here

How do you log all events fired by an element in jQuery?

There is a nice generic way using the .data('events') collection:

function getEventsList($obj) {
    var ev = new Array(),
        events = $obj.data('events'),
        i;
    for(i in events) { ev.push(i); }
    return ev.join(' ');
}

$obj.on(getEventsList($obj), function(e) {
    console.log(e);
});

This logs every event that has been already bound to the element by jQuery the moment this specific event gets fired. This code was pretty damn helpful for me many times.

Btw: If you want to see every possible event being fired on an object use firebug: just right click on the DOM element in html tab and check "Log Events". Every event then gets logged to the console (this is sometimes a bit annoying because it logs every mouse movement...).

Excel VBA - Sum up a column

Here is what you can do if you want to add a column of numbers in Excel. ( I am using Excel 2010 but should not make a difference.)

Example: Lets say you want to add the cells in Column B form B10 to B100 & want the answer to be in cell X or be Variable X ( X can be any cell or any variable you create such as Dim X as integer, etc). Here is the code:

Range("B5") = "=SUM(B10:B100)"

or

X = "=SUM(B10:B100)

There are no quotation marks inside the parentheses in "=Sum(B10:B100) but there are quotation marks inside the parentheses in Range("B5"). Also there is a space between the equals sign and the quotation to the right of it.

It will not matter if some cells are empty, it will simply see them as containing zeros!

This should do it for you!

How do I float a div to the center?

Simple solution:

<style>
.center {
    margin: auto;

}
</style>

<div class="center">
    <p> somthing goes here </p>
</div>

Try Online

How to turn off the Eclipse code formatter for certain sections of Java code?

If you put the plus sign on the beginning of the line, it formats differently:

String query = 
    "SELECT FOO, BAR, BAZ" 
    +    "  FROM ABC"           
    +    " WHERE BAR > 4";

get string from right hand side

SQL> select substr('123456',-1,6) from dual;

S
-
6

SQL> select substr('123456',-6,6) from dual;

SUBSTR
------
123456

SQL> select substr('123456',-7,6) from dual;

S
-

If you watch above statements, 3 query gives null value as -7 > length('123456').

So check the length of CONT_PHONE_NUMBERS and PHONE_NUMBERS

Hope this helps you

running a command as a super user from a python script

The safest way to do this is to prompt for the password beforehand and then pipe it into the command. Prompting for the password will avoid having the password saved anywhere in your code and it also won't show up in your bash history. Here's an example:

from getpass import getpass
from subprocess import Popen, PIPE

password = getpass("Please enter your password: ")
# sudo requires the flag '-S' in order to take input from stdin
proc = Popen("sudo -S apach2ctl restart".split(), stdin=PIPE, stdout=PIPE, stderr=PIPE)
# Popen only accepts byte-arrays so you must encode the string
proc.communicate(password.encode())

Jquery submit form

Use the following jquery to submit a selectbox with out a submit button. Use "change" instead of click as shown above.

$("selectbox").change(function() { 
   document.forms["form"].submit();
});

Cheers!

Rounding to two decimal places in Python 2.7?

A rather simple workaround is to convert the float into string first, the select the substring of the first four numbers, finally convert the substring back to float. For example:

>>> out1 = 1.2345
>>> out1 = float(str(out1)[0:4])
>>> out1

May not be super efficient but simple and works :)

Laravel 5 – Clear Cache in Shared Hosting Server

This package is for php ^7.0 and ^laravel5.5.

Use this package in cronjob that I have created for this purpose only. I was also facing same situation. https://packagist.org/packages/afrazahmad/clear-cached-data Install it and run:

php artisan clear:data

and it will run the following commands automcatically

php artisan cache:clear
php artisan view:clear
php artisan route:clear
php artisan clear-compiled
php artisan config:cache

Hope it helps.

If you want to run it automatically at specific time then you will have to setup crnjob first. e.g.

 in app/console/kernel.php

In schedule function:

$schedule->command('clear:data')->dailyAt('07:00');

Invalid application of sizeof to incomplete type with a struct

I think that the problem is that you put #ifdef instead of #ifndef at the top of your header.h file.

Accessing the web page's HTTP Headers in JavaScript

To get the headers as an object which is handier (improvement of Raja's answer):

var req = new XMLHttpRequest();
req.open('GET', document.location, false);
req.send(null);
var headers = req.getAllResponseHeaders().toLowerCase();
headers = headers.split(/\n|\r|\r\n/g).reduce(function(a, b) {
    if (b.length) {
        var [ key, value ] = b.split(': ');
        a[key] = value;
    }
    return a;
}, {});
console.log(headers);

Work on a remote project with Eclipse via SSH

This answer currently only applies to using two Linux computers [or maybe works on Mac too?--untested on Mac] (syncing from one to the other) because I wrote this synchronization script in bash. It is simply a wrapper around git, however, so feel free to take it and convert it into a cross-platform Python solution or something if you wish


This doesn't directly answer the OP's question, but it is so close I guarantee it will answer many other peoples' question who land on this page (mine included, actually, as I came here first before writing my own solution), so I'm posting it here anyway.

I want to:

  1. develop code using a powerful IDE like Eclipse on a light-weight Linux computer, then
  2. build that code via ssh on a different, more powerful Linux computer (from the command-line, NOT from inside Eclipse)

Let's call the first computer where I write the code "PC1" (Personal Computer 1), and the 2nd computer where I build the code "PC2". I need a tool to easily synchronize from PC1 to PC2. I tried rsync, but it was insanely slow for large repos and took tons of bandwidth and data.

So, how do I do it? What workflow should I use? If you have this question too, here's the workflow that I decided upon. I wrote a bash script to automate the process by using git to automatically push changes from PC1 to PC2 via a remote repository, such as github. So far it works very well and I'm very pleased with it. It is far far far faster than rsync, more trustworthy in my opinion because each PC maintains a functional git repo, and uses far less bandwidth to do the whole sync, so it's easily doable over a cell phone hot spot without using tons of your data.

Setup:

  1. Install the script on PC1 (this solution assumes ~/bin is in your $PATH):

    git clone https://github.com/ElectricRCAircraftGuy/eRCaGuy_dotfiles.git
    cd eRCaGuy_dotfiles/useful_scripts
    mkdir -p ~/bin
    ln -s "${PWD}/sync_git_repo_from_pc1_to_pc2.sh" ~/bin/sync_git_repo_from_pc1_to_pc2
    cd ..
    cp -i .sync_git_repo ~/.sync_git_repo
    
  2. Now edit the "~/.sync_git_repo" file you just copied above, and update its parameters to fit your case. Here are the parameters it contains:

    # The git repo root directory on PC2 where you are syncing your files TO; this dir must *already exist* 
    # and you must have *already `git clone`d* a copy of your git repo into it!
    # - Do NOT use variables such as `$HOME`. Be explicit instead. This is because the variable expansion will 
    #   happen on the local machine when what we need is the variable expansion from the remote machine. Being 
    #   explicit instead just avoids this problem.
    PC2_GIT_REPO_TARGET_DIR="/home/gabriel/dev/eRCaGuy_dotfiles" # explicitly type this out; don't use variables
    
    PC2_SSH_USERNAME="my_username" # explicitly type this out; don't use variables
    PC2_SSH_HOST="my_hostname"     # explicitly type this out; don't use variables
    
  3. Git clone your repo you want to sync on both PC1 and PC2.

  4. Ensure your ssh keys are all set up to be able to push and pull to the remote repo from both PC1 and PC2. Here's some helpful links:
    1. https://help.github.com/en/github/authenticating-to-github/connecting-to-github-with-ssh
    2. https://help.github.com/en/github/authenticating-to-github/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent
  5. Ensure your ssh keys are all set up to ssh from PC1 to PC2.
  6. Now cd into any directory within the git repo on PC1, and run:

    sync_git_repo_from_pc1_to_pc2
    
  7. That's it! About 30 seconds later everything will be magically synced from PC1 to PC2, and it will be printing output the whole time to tell you what it's doing and where it's doing it on your disk and on which computer. It's safe too, because it doesn't overwrite or delete anything that is uncommitted. It backs it up first instead! Read more below for how that works.

Here's the process this script uses (ie: what it's actually doing)

  1. From PC1: It checks to see if any uncommitted changes are on PC1. If so, it commits them to a temporary commit on the current branch. It then force pushes them to a remote SYNC branch. Then it uncommits its temporary commit it just did on the local branch, then it puts the local git repo back to exactly how it was by staging any files that were previously staged at the time you called the script. Next, it rsyncs a copy of the script over to PC2, and does an ssh call to tell PC2 to run the script with a special option to just do PC2 stuff.
  2. Here's what PC2 does: it cds into the repo, and checks to see if any local uncommitted changes exist. If so, it creates a new backup branch forked off of the current branch (sample name: my_branch_SYNC_BAK_20200220-0028hrs-15sec <-- notice that's YYYYMMDD-HHMMhrs--SSsec), and commits any uncommitted changes to that branch with a commit message such as DO BACKUP OF ALL UNCOMMITTED CHANGES ON PC2 (TARGET PC/BUILD MACHINE). Now, it checks out the SYNC branch, pulling it from the remote repository if it is not already on the local machine. Then, it fetches the latest changes on the remote repository, and does a hard reset to force the local SYNC repository to match the remote SYNC repository. You might call this a "hard pull". It is safe, however, because we already backed up any uncommitted changes we had locally on PC2, so nothing is lost!
  3. That's it! You now have produced a perfect copy from PC1 to PC2 without even having to ensure clean working directories, as the script handled all of the automatic committing and stuff for you! It is fast and works very well on huge repositories. Now you have an easy mechanism to use any IDE of your choice on one machine while building or testing on another machine, easily, over a wifi hot spot from your cell phone if needed, even if the repository is dozens of gigabytes and you are time and resource-constrained.

Resources:

  1. The whole project: https://github.com/ElectricRCAircraftGuy/eRCaGuy_dotfiles
    1. See tons more links and references in the source code itself within this project.
  2. How to do a "hard pull", as I call it: How do I force "git pull" to overwrite local files?

Related:

  1. git repository sync between computers, when moving around?

Where does one get the "sys/socket.h" header/source file?

Try to reinstall cygwin with selected package:gcc-g++ : gnu compiler collection c++ (from devel category), openssh server and client program (net), make: the gnu version (devel), ncurses terminal (utils), enhanced vim editors (editors), an ANSI common lisp implementation (math) and libncurses-devel (lib).

This library files should be under cygwin\usr\include

Regards.

How to check if a list is empty in Python?

Empty lists evaluate to False in boolean contexts (such as if some_list:).

MYSQL import data from csv using LOAD DATA INFILE

You can load data from a csv or text file. If you have a text file with records from a table, you can load those records within the table. For example if you have a text file, where each row is a record with the values for each column, you can load the records this way.

table.sql

id //field 1

name //field2

table.txt

1,peter

2,daniel

...

--example on windows

LOAD DATA LOCAL INFILE 'C:\\directory_example\\table.txt'
INTO TABLE Table
CHARACTER SET UTF8
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\r\n'; 

How to loop through a plain JavaScript object with the objects as members?

If you use recursion you can return object properties of any depth-

function lookdeep(object){
    var collection= [], index= 0, next, item;
    for(item in object){
        if(object.hasOwnProperty(item)){
            next= object[item];
            if(typeof next== 'object' && next!= null){
                collection[index++]= item +
                ':{ '+ lookdeep(next).join(', ')+'}';
            }
            else collection[index++]= [item+':'+String(next)];
        }
    }
    return collection;
}

//example

var O={
    a:1, b:2, c:{
        c1:3, c2:4, c3:{
            t:true, f:false
        }
    },
    d:11
};
var lookdeepSample= 'O={'+ lookdeep(O).join(',\n')+'}';


/*  returned value: (String)
O={
    a:1, 
    b:2, 
    c:{
        c1:3, c2:4, c3:{
            t:true, f:false
        }
    },
    d:11
}

*/

Stop Visual Studio from launching a new browser window when starting debug?

If you're using the Web Publish feature in IIS, then the solution I found was to edit the publish configuration and remove the Destination URL from the configuration (leave it blank).

If this is defined, then every time you publish the project it will open the URL specified in the Destination URL (which is a redirect URL).

Reference: https://support.winhost.com/kb/a1604/visual-studio-publish-web-deploy.aspx

What's the best way to loop through a set of elements in JavaScript?

Form of loop provided by Juan Mendez is very useful and practical, I changed it a little bit, so that now it works with - false, null, zero and empty strings too.

var items = [
    true,
    false,
    null,
    0,
    ""
];

for(var i = 0, item; (item = items[i]) !== undefined; i++)
{
    console.log("Index: " + i + "; Value: " + item);
}

dd: How to calculate optimal blocksize?

The optimal block size depends on various factors, including the operating system (and its version), and the various hardware buses and disks involved. Several Unix-like systems (including Linux and at least some flavors of BSD) define the st_blksize member in the struct stat that gives what the kernel thinks is the optimal block size:

#include <sys/stat.h>
#include <stdio.h>

int main(void)
{
    struct stat stats;

    if (!stat("/", &stats))
    {
        printf("%u\n", stats.st_blksize);
    }
}

The best way may be to experiment: copy a gigabyte with various block sizes and time that. (Remember to clear kernel buffer caches before each run: echo 3 > /proc/sys/vm/drop_caches).

However, as a rule of thumb, I've found that a large enough block size lets dd do a good job, and the differences between, say, 64 KiB and 1 MiB are minor, compared to 4 KiB versus 64 KiB. (Though, admittedly, it's been a while since I did that. I use a mebibyte by default now, or just let dd pick the size.)

combining results of two select statements

You can use a Union.

This will return the results of the queries in separate rows.

First you must make sure that both queries return identical columns.

Then you can do :

SELECT tableA.Id, tableA.Name, [tableB].Username AS Owner, [tableB].ImageUrl, [tableB].CompanyImageUrl, COUNT(tableD.UserId) AS Number
FROM tableD 
RIGHT OUTER JOIN [tableB] 
INNER JOIN tableA ON [tableB].Id = tableA.Owner ON tableD.tableAId = tableA.Id 
GROUP BY tableA.Name, [tableB].Username, [tableB].ImageUrl, [tableB].CompanyImageUrl

UNION

SELECT tableA.Id, tableA.Name,  '' AS Owner, '' AS ImageUrl, '' AS CompanyImageUrl, COUNT([tableC].Id) AS Number
FROM 
[tableC] 
RIGHT OUTER JOIN tableA ON [tableC].tableAId = tableA.Id GROUP BY tableA.Id, tableA.Name

As has been mentioned, both queries return quite different data. You would probably only want to do this if both queries return data that could be considered similar.

SO

You can use a Join

If there is some data that is shared between the two queries. This will put the results of both queries into a single row joined by the id, which is probably more what you want to be doing here...

You could do :

SELECT tableA.Id, tableA.Name, [tableB].Username AS Owner, [tableB].ImageUrl, [tableB].CompanyImageUrl, COUNT(tableD.UserId) AS NumberOfUsers, query2.NumberOfPlans
FROM tableD 
RIGHT OUTER JOIN [tableB] 
INNER JOIN tableA ON [tableB].Id = tableA.Owner ON tableD.tableAId = tableA.Id 


INNER JOIN 
  (SELECT tableA.Id, COUNT([tableC].Id) AS NumberOfPlans 
   FROM [tableC] 
   RIGHT OUTER JOIN tableA ON [tableC].tableAId = tableA.Id 
   GROUP BY tableA.Id, tableA.Name) AS query2 
ON query2.Id = tableA.Id

GROUP BY tableA.Name, [tableB].Username, [tableB].ImageUrl, [tableB].CompanyImageUrl

How to Set focus to first text input in a bootstrap modal after shown

The answer of David Taiaroa is correct, but doesn’t work because the time to "fade in" the modal doesn’t let you set focus on input. You need to create a delay:

$('#myModal').on('shown.bs.modal', function () {
    ...
    setTimeout(function (){
        $('#textareaID').focus();
    }, 1000);

})

Changing SqlConnection timeout

If you want to provide a timeout for a particular query, then CommandTimeout is the way forward.

Its usage is:

command.CommandTimeout = 60; //The time in seconds to wait for the command to execute. The default is 30 seconds.

docker mounting volumes on host

This is from the Docker documentation itself, might be of help, simple and plain:

"The host directory is, by its nature, host-dependent. For this reason, you can’t mount a host directory from Dockerfile, the VOLUME instruction does not support passing a host-dir, because built images should be portable. A host directory wouldn’t be available on all potential hosts.".

Sorting 1 million 8-decimal-digit numbers with 1 MB of RAM

If the numbers are evenly distributed we can use Counting sort. We should keep the number of times that each number is repeated in an array. Available space is: 1 MB - 3 KB = 1045504 B or 8364032 bits Number of bits per number= 8364032/1000000 = 8 Therefore, we can store the number of times each number is repeated to the maximum of 2^8-1=255. Using this approach we have an extra 364032 bits unused that can be used to handle cases where a number is repeated more than 255 times. For example we can say a number 255 indicates a repetition greater than or equal to 255. In this case we should store a sequence of numbers+repetitions. We can handle 7745 special cases as shown bellow:

364032/ (bits need to represent each number + bits needed to represent 1 million)= 364032 / (27+20)=7745

How do I include inline JavaScript in Haml?

I'm using fileupload-jquery in haml. The original js is below:

_x000D_
_x000D_
<!-- The template to display files available for download -->_x000D_
<script id="template-download" type="text/x-tmpl">_x000D_
  {% for (var i=0, file; file=o.files[i]; i++) { %}_x000D_
    <tr class="template-download fade">_x000D_
      {% if (file.error) { %}_x000D_
        <td></td>_x000D_
        <td class="name"><span>{%=file.name%}</span></td>_x000D_
        <td class="size"><span>{%=o.formatFileSize(file.size)%}</span></td>_x000D_
        <td class="error" colspan="2"><span class="label label-important">{%=locale.fileupload.error%}</span> {%=locale.fileupload.errors[file.error] || file.error%}</td>_x000D_
        {% } else { %}_x000D_
        <td class="preview">{% if (file.thumbnail_url) { %}_x000D_
          <a href="{%=file.url%}" title="{%=file.name%}" rel="gallery" download="{%=file.name%}"><img src="{%=file.thumbnail_url%}"></a>_x000D_
          {% } %}</td>_x000D_
        <td class="name">_x000D_
          <a href="{%=file.url%}" title="{%=file.name%}" rel="{%=file.thumbnail_url&&'gallery'%}" download="{%=file.name%}">{%=file.name%}</a>_x000D_
        </td>_x000D_
        <td class="size"><span>{%=o.formatFileSize(file.size)%}</span></td>_x000D_
        <td colspan="2"></td>_x000D_
        {% } %}_x000D_
      <td class="delete">_x000D_
        <button class="btn btn-danger" data-type="{%=file.delete_type%}" data-url="{%=file.delete_url%}">_x000D_
          <i class="icon-trash icon-white"></i>_x000D_
          <span>{%=locale.fileupload.destroy%}</span>_x000D_
        </button>_x000D_
        <input type="checkbox" name="delete" value="1">_x000D_
      </td>_x000D_
    </tr>_x000D_
    {% } %}_x000D_
</script>
_x000D_
_x000D_
_x000D_

At first I used the :cdata to convert (from html2haml), it doesn't work properly (Delete button can't remove relevant component in callback).

_x000D_
_x000D_
<script id='template-download' type='text/x-tmpl'>_x000D_
      <![CDATA[_x000D_
          {% for (var i=0, file; file=o.files[i]; i++) { %}_x000D_
          <tr class="template-download fade">_x000D_
          {% if (file.error) { %}_x000D_
          <td></td>_x000D_
          <td class="name"><span>{%=file.name%}</span></td>_x000D_
          <td class="size"><span>{%=o.formatFileSize(file.size)%}</span></td>_x000D_
          <td class="error" colspan="2"><span class="label label-important">{%=locale.fileupload.error%}</span> {%=locale.fileupload.errors[file.error] || file.error%}</td>_x000D_
          {% } else { %}_x000D_
          <td class="preview">{% if (file.thumbnail_url) { %}_x000D_
          <a href="{%=file.url%}" title="{%=file.name%}" rel="gallery" download="{%=file.name%}"><img src="{%=file.thumbnail_url%}"></a>_x000D_
          {% } %}</td>_x000D_
          <td class="name">_x000D_
          <a href="{%=file.url%}" title="{%=file.name%}" rel="{%=file.thumbnail_url&&'gallery'%}" download="{%=file.name%}">{%=file.name%}</a>_x000D_
          </td>_x000D_
          <td class="size"><span>{%=o.formatFileSize(file.size)%}</span></td>_x000D_
          <td colspan="2"></td>_x000D_
          {% } %}_x000D_
          <td class="delete">_x000D_
          <button class="btn btn-danger" data-type="{%=file.delete_type%}" data-url="{%=file.delete_url%}">_x000D_
          <i class="icon-trash icon-white"></i>_x000D_
          <span>{%=locale.fileupload.destroy%}</span>_x000D_
          </button>_x000D_
          <input type="checkbox" name="delete" value="1">_x000D_
          </td>_x000D_
          </tr>_x000D_
          {% } %}_x000D_
      ]]>_x000D_
    </script>
_x000D_
_x000D_
_x000D_

So I use :plain filter:

_x000D_
_x000D_
%script#template-download{:type => "text/x-tmpl"}_x000D_
  :plain_x000D_
    {% for (var i=0, file; file=o.files[i]; i++) { %}_x000D_
    <tr class="template-download fade">_x000D_
    {% if (file.error) { %}_x000D_
    <td></td>_x000D_
    <td class="name"><span>{%=file.name%}</span></td>_x000D_
    <td class="size"><span>{%=o.formatFileSize(file.size)%}</span></td>_x000D_
    <td class="error" colspan="2"><span class="label label-important">{%=locale.fileupload.error%}</span> {%=locale.fileupload.errors[file.error] || file.error%}</td>_x000D_
    {% } else { %}_x000D_
    <td class="preview">{% if (file.thumbnail_url) { %}_x000D_
    <a href="{%=file.url%}" title="{%=file.name%}" rel="gallery" download="{%=file.name%}"><img src="{%=file.thumbnail_url%}"></a>_x000D_
    {% } %}</td>_x000D_
    <td class="name">_x000D_
    <a href="{%=file.url%}" title="{%=file.name%}" rel="{%=file.thumbnail_url&&'gallery'%}" download="{%=file.name%}">{%=file.name%}</a>_x000D_
    </td>_x000D_
    <td class="size"><span>{%=o.formatFileSize(file.size)%}</span></td>_x000D_
    <td colspan="2"></td>_x000D_
    {% } %}_x000D_
    <td class="delete">_x000D_
    <button class="btn btn-danger" data-type="{%=file.delete_type%}" data-url="{%=file.delete_url%}">_x000D_
    <i class="icon-trash icon-white"></i>_x000D_
    <span>{%=locale.fileupload.destroy%}</span>_x000D_
    </button>_x000D_
    <input type="checkbox" name="delete" value="1">_x000D_
    </td>_x000D_
    </tr>_x000D_
    {% } %}
_x000D_
_x000D_
_x000D_

The converted result is exactly the same as the original.

So :plain filter in this senario fits my need.

:plain Does not parse the filtered text. This is useful for large blocks of text without HTML tags, when you don’t want lines starting with . or - to be parsed.

For more detail, please refer to haml.info

using setTimeout on promise chain

In node.js you can also do the following:

const { promisify } = require('util')
const delay = promisify(setTimeout)

delay(1000).then(() => console.log('hello'))

How does Facebook Sharer select Images and other metadata when sharing my URL?

This is what worked for me: I placed the desired thumbnail image on the page right after the tag and making it too small to see..

<img src="imagename.jpg" width="1" height="1" />

I have not tested it with height 0 and width 0 but it probably will still work.. This does not guarantee the user will select this image..

ALSO it seems like Facebook caches the thumbnails on your page and doesnt always check it for new ones.. try adding this to another page on your site and you'll see that it works.

Declaring variables inside or outside of a loop

As many people have pointed out,

String str;
while(condition){
    str = calculateStr();
    .....
}

is NOT better than this:

while(condition){
    String str = calculateStr();
    .....
}

So don't declare variables outside their scopes if you are not reusing it...

SQL: How do I SELECT only the rows with a unique value on certain column?

Sorry you're not using PostgreSQL...

SELECT DISTINCT ON contract, activity * FROM thetable ORDER BY contract, activity

http://www.postgresql.org/docs/8.3/static/sql-select.html#SQL-DISTINCT

Oh wait. You only want values with exactly one...

SELECT contract, activity, count() FROM thetable GROUP BY contract, activity HAVING count() = 1

How do I turn off Unicode in a VC++ project?

Burgos has the right answer. Just to clarify, the Character Set should be changed to "Not Set".

How do you specify a different port number in SQL Management Studio?

127.0.0.1,6283

Add a comma between the ip and port

SQL Server stored procedure Nullable parameter

You can/should set your parameter to value to DBNull.Value;

if (variable == "")
{
     cmd.Parameters.Add("@Param", SqlDbType.VarChar, 500).Value = DBNull.Value;
}
else
{
     cmd.Parameters.Add("@Param", SqlDbType.VarChar, 500).Value = variable;
}

Or you can leave your server side set to null and not pass the param at all.

Cannot implicitly convert type 'System.DateTime?' to 'System.DateTime'. An explicit conversion exists

The problem is that you are passing a nullable type to a non-nullable type.

You can do any of the following solution:

A. Declare your dt as nullable

DateTime? dt = dateTime;

B. Use Value property of the the DateTime? datetime

DateTime dt = datetime.Value;

C. Cast it

DateTime dt = (DateTime) datetime;

Typescript Type 'string' is not assignable to type

I was facing the same issue, I made below changes and the issue got resolved.

Open watchQueryOptions.d.ts file

\apollo-client\core\watchQueryOptions.d.ts

Change the query type any instead of DocumentNode, Same for mutation

Before:

export interface QueryBaseOptions<TVariables = OperationVariables> {
    query: **DocumentNode**;

After:

export interface QueryBaseOptions<TVariables = OperationVariables> {
    query: **any**;

FtpWebRequest Download File

Easiest way

The most trivial way to download a binary file from an FTP server using .NET framework is using WebClient.DownloadFile:

WebClient client = new WebClient();
client.Credentials = new NetworkCredential("username", "password");
client.DownloadFile(
    "ftp://ftp.example.com/remote/path/file.zip", @"C:\local\path\file.zip");

Advanced options

Use FtpWebRequest, only if you need a greater control, that WebClient does not offer (like TLS/SSL encryption, progress monitoring, ascii/text transfer mode, resuming transfers, etc). Easy way is to just copy an FTP response stream to FileStream using Stream.CopyTo:

FtpWebRequest request =
    (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip");
request.Credentials = new NetworkCredential("username", "password");
request.Method = WebRequestMethods.Ftp.DownloadFile;

using (Stream ftpStream = request.GetResponse().GetResponseStream())
using (Stream fileStream = File.Create(@"C:\local\path\file.zip"))
{
    ftpStream.CopyTo(fileStream);
}

Progress monitoring

If you need to monitor a download progress, you have to copy the contents by chunks yourself:

FtpWebRequest request =
    (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip");
request.Credentials = new NetworkCredential("username", "password");
request.Method = WebRequestMethods.Ftp.DownloadFile;

using (Stream ftpStream = request.GetResponse().GetResponseStream())
using (Stream fileStream = File.Create(@"C:\local\path\file.zip"))
{
    byte[] buffer = new byte[10240];
    int read;
    while ((read = ftpStream.Read(buffer, 0, buffer.Length)) > 0)
    {
        fileStream.Write(buffer, 0, read);
        Console.WriteLine("Downloaded {0} bytes", fileStream.Position);
    }
}

For GUI progress (WinForms ProgressBar), see:
FtpWebRequest FTP download with ProgressBar


Downloading folder

If you want to download all files from a remote folder, see
C# Download all files and subdirectories through FTP.

How to recursively find and list the latest modified files in a directory with subdirectories and times

Quick Bash function:

# findLatestModifiedFiles(directory, [max=10, [format="%Td %Tb %TY, %TT"]])
function findLatestModifiedFiles() {
    local d="${1:-.}"
    local m="${2:-10}"
    local f="${3:-%Td %Tb %TY, %TT}"

    find "$d" -type f -printf "%T@ :$f %p\n" | sort -nr | cut -d: -f2- | head -n"$m"
}

Find the latest modified file in a directory:

findLatestModifiedFiles "/home/jason/" 1

You can also specify your own date/time format as the third argument.