Programs & Examples On #Ora 12560

ORA-12560: TNS:protocol adaptor error

Another possible solution that just worked for me...considering I was using my local login as the dba permissions.

Follow the steps to get to Services. Right click on the instance and go to 'Log On'? (might not be the name but it's one of the tabs containing permissions). Change the settings to use LOCAL.

ASP.NET MVC Bundle not rendering script files on staging server. It works on development server

I used Identity2 then Scripts didn't load for anonymous user then I add this code in webconfig and Sloved.

<location path="bundles">
<system.web>
  <authorization>
    <allow users="*" />
  </authorization>  
</system.web>
 </location>

Synchronizing a local Git repository with a remote one

You need to understand that a Git repository is not just a tree of directories and files, but also stores a history of those trees - which might contain branches and merges.

When fetching from a repository, you will copy all or some of the branches there to your repository. These are then in your repository as "remote tracking branches", e.g. branches named like remotes/origin/master or such.

Fetching new commits from the remote repository will not change anything about your local working copy.

Your working copy has normally a commit checked out, called HEAD. This commit is usually the tip of one of your local branches.

I think you want to update your local branch (or maybe all the local branches?) to the corresponding remote branch, and then check out the latest branch.

To avoid any conflicts with your working copy (which might have local changes), you first clean everything which is not versioned (using git clean). Then you check out the local branch corresponding to the remote branch you want to update to, and use git reset to switch it to the fetched remote branch. (git pull will incorporate all updates of the remote branch in your local one, which might do the same, or create a merge commit if you have local commits.)

(But then you will really lose any local changes - both in working copy and local commits. Make sure that you really want this - otherwise better use a new branch, this saves your local commits. And use git stash to save changes which are not yet committed.)


Edit: If you have only one local branch and are tracking one remote branch, all you need to do is

git pull

from inside the working directory.

This will fetch the current version of all tracked remote branches and update the current branch (and the working directory) to the current version of the remote branch it is tracking.

What is `git push origin master`? Help with git's refs, heads and remotes

Git has two types of branches: local and remote. To use git pull and git push as you'd like, you have to tell your local branch (my_test) which remote branch it's tracking. In typical Git fashion this can be done in both the config file and with commands.

Commands

Make sure you're on your master branch with

1)git checkout master

then create the new branch with

2)git branch --track my_test origin/my_test

and check it out with

3)git checkout my_test.

You can then push and pull without specifying which local and remote.

However if you've already created the branch then you can use the -u switch to tell git's push and pull you'd like to use the specified local and remote branches from now on, like so:

git pull -u my_test origin/my_test
git push -u my_test origin/my_test

Config

The commands to setup remote branch tracking are fairly straight forward but I'm listing the config way as well as I find it easier if I'm setting up a bunch of tracking branches. Using your favourite editor open up your project's .git/config and add the following to the bottom.

[remote "origin"]
    url = [email protected]:username/repo.git
    fetch = +refs/heads/*:refs/remotes/origin/*
[branch "my_test"]
    remote = origin
    merge = refs/heads/my_test

This specifies a remote called origin, in this case a GitHub style one, and then tells the branch my_test to use it as it's remote.

You can find something very similar to this in the config after running the commands above.

Some useful resources:

How to find a string inside a entire database?

I think you have to options:

  1. Build a dynamic SQL using sys.tables and sys.columns to perform the search (example here).

  2. Use any program that have this function. An example of this is SQL Workbench (free).

Get driving directions using Google Maps API v2

This is what I am using,

Intent intent = new Intent(android.content.Intent.ACTION_VIEW, 
Uri.parse("http://maps.google.com/maps?saddr="+latitude_cur+","+longitude_cur+"&daddr="+latitude+","+longitude));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addCategory(Intent.CATEGORY_LAUNCHER );     
intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
startActivity(intent);

#1045 - Access denied for user 'root'@'localhost' (using password: YES)

After I updated my MySql, I was getting the same error message. It turned out that after installing a different version on MySql, inside the my.ini, the port was different. Previous MySql version had port 3306 but the new one have port 3308. Check your MySql my.ini, if it is different use the port from .ini in your connection.

Insecure content in iframe on secure page

Based on generality of this question, I think, that you'll need to setup your own HTTPS proxy on some server online. Do the following steps:

  • Prepare your proxy server - install IIS, Apache
  • Get valid SSL certificate to avoid security errors (free from startssl.com for example)
  • Write a wrapper, which will download insecure content (how to below)
  • From your site/app get https://yourproxy.com/?page=http://insecurepage.com

If you simply download remote site content via file_get_contents or similiar, you can still have insecure links to content. You'll have to find them with regex and also replace. Images are hard to solve, but Ï found workaround here: http://foundationphp.com/tutorials/image_proxy.php


Note: While this solution may have worked in some browsers when it was written in 2014, it no longer works. Navigating or redirecting to an HTTP URL in an iframe embedded in an HTTPS page is not permitted by modern browsers, even if the frame started out with an HTTPS URL.

The best solution I created is to simply use google as the ssl proxy...

https://www.google.com/search?q=%http://yourhttpsite.com&btnI=Im+Feeling+Lucky

Tested and works in firefox.

Other Methods:

  • Use a Third party such as embed.ly (but it it really only good for well known http APIs).

  • Create your own redirect script on an https page you control (a simple javascript redirect on a relative linked page should do the trick. Something like: (you can use any langauge/method)

    https://example.com That has a iframe linking to...

    https://example.com/utilities/redirect.html Which has a simple js redirect script like...

    document.location.href ="http://thenonsslsite.com";

  • Alternatively, you could add an RSS feed or write some reader/parser to read the http site and display it within your https site.

  • You could/should also recommend to the http site owner that they create an ssl connection. If for no other reason than it increases seo.

Unless you can get the http site owner to create an ssl certificate, the most secure and permanent solution would be to create an RSS feed grabing the content you need (presumably you are not actually 'doing' anything on the http site -that is to say not logging in to any system).

The real issue is that having http elements inside a https site represents a security issue. There are no completely kosher ways around this security risk so the above are just current work arounds.

Note, that you can disable this security measure in most browsers (yourself, not for others). Also note that these 'hacks' may become obsolete over time.

OnChange event handler for radio button (INPUT type="radio") doesn't work as one value

As you can see from this example: http://jsfiddle.net/UTwGS/

HTML:

<label><input type="radio" value="1" name="my-radio">Radio One</label>
<label><input type="radio" value="2" name="my-radio">Radio One</label>

jQuery:

$('input[type="radio"]').on('click change', function(e) {
    console.log(e.type);
});

both the click and change events are fired when selecting a radio button option (at least in some browsers).

I should also point out that in my example the click event is still fired when you use tab and the keyboard to select an option.

So, my point is that even though the change event is fired is some browsers, the click event should supply the coverage you need.

How to install an APK file on an Android phone?

If you have access to a Gmail account on the phone then an easy way (in terms of minimal set up effort) is to mail the .apk file to that Gmail account.

If you then access that account from the native Gmail app on the phone it recognises that the attachment is an app and offers an "Install" button.

As per other responses this approach also requires that you have selected USB debugging on the device.

Try this - it is remarkably easy ;-)

Find Java classes implementing an interface

Package Level Annotations

I know this question has already been answered a long time ago but another solution to this problem is to use Package Level Annotations.

While its pretty hard to go find all the classes in the JVM its actually pretty easy to browse the package hierarchy.

Package[] ps = Package.getPackages();
for (Package p : ps) {
  MyAno a = p.getAnnotation(MyAno.class)
  // Recursively descend
}

Then just make your annotation have an argument of an array of Class. Then in your package-info.java for a particular package put the MyAno.

I'll add more details (code) if people are interested but most probably get the idea.

MetaInf Service Loader

To add to @erickson answer you can also use the service loader approach. Kohsuke has an awesome way of generating the the required META-INF stuff you need for the service loader approach:

http://weblogs.java.net/blog/kohsuke/archive/2009/03/my_project_of_t.html

How do I get to IIS Manager?

You need to make sure the IIS Management Console is installed.

Regular expression matching a multiline block of text

find:

^>([^\n\r]+)[\n\r]([A-Z\n\r]+)

\1 = some_varying_text

\2 = lines of all CAPS

Edit (proof that this works):

text = """> some_Varying_TEXT

DSJFKDAFJKDAFJDSAKFJADSFLKDLAFKDSAF
GATACAACATAGGATACA
GGGGGAAAAAAAATTTTTTTTT
CCCCAAAA

> some_Varying_TEXT2

DJASDFHKJFHKSDHF
HHASGDFTERYTERE
GAGAGAGAGAG
PPPPPAAAAAAAAAAAAAAAP
"""

import re

regex = re.compile(r'^>([^\n\r]+)[\n\r]([A-Z\n\r]+)', re.MULTILINE)
matches = [m.groups() for m in regex.finditer(text)]

for m in matches:
    print 'Name: %s\nSequence:%s' % (m[0], m[1])

Constants in Kotlin -- what's a recommended way to create them?

class Myclass {

 companion object {
        const val MYCONSTANT = 479
}

you have two choices you can use const keyword or use the @JvmField which makes it a java's static final constant.

class Myclass {

     companion object {
           @JvmField val MYCONSTANT = 479
    }

If you use the @JvmField annotation then after it compiles the constant gets put in for you the way you would call it in java.
Just like you would call it in java the compiler will replace that for you when you call the companion constant in code.

However, if you use the const keyword then the value of the constant gets inlined. By inline i mean the actual value is used after it compiles.

so to summarize here is what the compiler will do for you :

//so for @JvmField:

Foo var1 = Constants.FOO;

//and for const:

Foo var1 = 479

How to add hours to current date in SQL Server?

DATEADD (datepart , number , date )

declare @num_hours int; 
    set @num_hours = 5; 

select dateadd(HOUR, @num_hours, getdate()) as time_added, 
       getdate() as curr_date  

Adding external library into Qt Creator project

And to add multiple library files you can write as below:

INCLUDEPATH *= E:/DebugLibrary/VTK E:/DebugLibrary/VTK/Common E:/DebugLibrary/VTK/Filtering E:/DebugLibrary/VTK/GenericFiltering E:/DebugLibrary/VTK/Graphics E:/DebugLibrary/VTK/GUISupport/Qt E:/DebugLibrary/VTK/Hybrid E:/DebugLibrary/VTK/Imaging E:/DebugLibrary/VTK/IO E:/DebugLibrary/VTK/Parallel E:/DebugLibrary/VTK/Rendering E:/DebugLibrary/VTK/Utilities E:/DebugLibrary/VTK/VolumeRendering E:/DebugLibrary/VTK/Widgets E:/DebugLibrary/VTK/Wrapping

LIBS *= -LE:/DebugLibrary/VTKBin/bin/release -lvtkCommon -lvtksys -lQVTK -lvtkWidgets -lvtkRendering -lvtkGraphics -lvtkImaging -lvtkIO -lvtkFiltering -lvtkDICOMParser -lvtkpng -lvtktiff -lvtkzlib -lvtkjpeg -lvtkexpat -lvtkNetCDF -lvtkexoIIc -lvtkftgl -lvtkfreetype -lvtkHybrid -lvtkVolumeRendering -lQVTKWidgetPlugin -lvtkGenericFiltering

Pip freeze vs. pip list

To answer the second part of this question, the two packages shown in pip list but not pip freeze are setuptools (which is easy_install) and pip itself.

It looks like pip freeze just doesn't list packages that pip itself depends on. You may use the --all flag to show also those packages.

From the documentation:

--all

Do not skip these packages in the output: pip, setuptools, distribute, wheel

Laravel 5.2 Missing required parameters for [Route: user.profile] [URI: user/{nickname}/profile]

You have to pass the route parameters to the route method, for example:

<li><a href="{{ route('user.profile', $nickname) }}">Profile</a></li>
<li><a href="{{ route('user.settings', $nickname) }}">Settings</a></li>

It's because, both routes have a {nickname} in the route declaration. I've used $nickname for example but make sure you change the $nickname to appropriate value/variable, for example, it could be something like the following:

<li><a href="{{ route('user.settings', auth()->user()->nickname) }}">Settings</a></li>

How to force NSLocalizedString to use a specific language

Do not use on iOS 9. This returns nil for all strings passed through it.

I have found another solution that allows you to update the language strings, w/o restarting the app and compatible with genstrings:

Put this macro in the Prefix.pch:

#define currentLanguageBundle [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:[[NSLocale preferredLanguages] objectAtIndex:0] ofType:@"lproj"]]

and where ever you need a localized string use:

NSLocalizedStringFromTableInBundle(@"GalleryTitleKey", nil, currentLanguageBundle, @"")

To set the language use:

[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObject:@"de"] forKey:@"AppleLanguages"];

Works even with consecutive language hopping like:

NSLog(@"test %@", NSLocalizedStringFromTableInBundle(@"NewKey", nil, currentLanguageBundle, @""));
[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObject:@"fr"] forKey:@"AppleLanguages"];
NSLog(@"test %@", NSLocalizedStringFromTableInBundle(@"NewKey", nil, currentLanguageBundle, @""));
[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObject:@"it"] forKey:@"AppleLanguages"];
NSLog(@"test %@", NSLocalizedStringFromTableInBundle(@"NewKey", nil, currentLanguageBundle, @""));
[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObject:@"de"] forKey:@"AppleLanguages"];
NSLog(@"test %@", NSLocalizedStringFromTableInBundle(@"NewKey", nil, currentLanguageBundle, @""));

How do I concatenate text in a query in sql server?

You have to explicitly cast the string types to the same in order to concatenate them, In your case you may solve the issue by simply addig an 'N' in front of 'SomeText' (N'SomeText'). If that doesn't work, try Cast('SomeText' as nvarchar(8)).

R: Break for loop

Well, your code is not reproducible so we will never know for sure, but this is what help('break')says:

break breaks out of a for, while or repeat loop; control is transferred to the first statement outside the inner-most loop.

So yes, break only breaks the current loop. You can also see it in action with e.g.:

for (i in 1:10)
{
    for (j in 1:10)
    {
        for (k in 1:10)
        {
            cat(i," ",j," ",k,"\n")
            if (k ==5) break
        }   
    }
}

Efficient thresholding filter of an array with numpy

b = a[a>threshold] this should do

I tested as follows:

import numpy as np, datetime
# array of zeros and ones interleaved
lrg = np.arange(2).reshape((2,-1)).repeat(1000000,-1).flatten()

t0 = datetime.datetime.now()
flt = lrg[lrg==0]
print datetime.datetime.now() - t0

t0 = datetime.datetime.now()
flt = np.array(filter(lambda x:x==0, lrg))
print datetime.datetime.now() - t0

I got

$ python test.py
0:00:00.028000
0:00:02.461000

http://docs.scipy.org/doc/numpy/user/basics.indexing.html#boolean-or-mask-index-arrays

Will using 'var' affect performance?

The C# compiler infers the true type of the var variable at compile time. There's no difference in the generated IL.

Convert date to UTC using moment.js

I use this method and it works. ValueOf does not work for me.

moment.utc(yourDate).format()

Clear listview content?

Call clear() method from your custom adapter .

jquery onclick change css background image

Use your jquery like this

$('.home').css({'background-image':'url(images/tabs3.png)'});

check if file exists on remote host with ssh

This also works :

if ssh user@ip "[ -s /path/file_name ]" ;then 
  status=RECEIVED ; 
 else 
  status=MISSING ; 
 fi

is it possible to add colors to python output?

If your console (like your standard ubuntu console) understands ANSI color codes, you can use those.

Here an example:

print ('This is \x1b[31mred\x1b[0m.') 

WPF chart controls

Sparrow Chart Toolkit a best opensource chart control for multiple platforms
-WPF
-Silverlight
-WinRT
-Windows phone
-Windows Forms
-Mono

https://sparrowtoolkit.codeplex.com/

CSS: auto height on containing div, 100% height on background div inside containing div

I ended up making 2 display:table;

#container-tv { /* Tiled background */
    display:table;
    width:100%;
    background-image: url(images/back.jpg);
    background-repeat: repeat;  
}
#container-body-background { /* center column but not 100% width */ 
    display:table;
    margin:0 auto;
    background-image:url(images/middle-back.png);
    background-repeat: repeat-y;

}

This made it have a tiled background image with a background image in the middle as a column. It stretches to 100% height of page not just 100% of browser window size

Fail during installation of Pillow (Python module) in Linux

The quickest fix is upgrate the pip. Did worked for me:

pip install --upgrade pip

When is a language considered a scripting language?

First point, a programming language isn't a "scripting language" or a something else. It can be a "scripting language" and something else.

Second point, the implementer of the language will tell you if it's a scripting language.

Your question should read "In what implementations would a programming language be considered a scripting language?", not "What is the difference between a scripting language and a programming language?". There is no between.

Yet, I will consider a language a scripting language if it is used to provide some type of middle ware. For example, I would consider most implementations of JavaScript a scripting language. If JavaScript were run in the OS, not the browser, then it would not be a scripting language. If PHP runs inside of Apache, it's a scripting language. If it's run from the command line, it's not.

Most efficient conversion of ResultSet to JSON?

The JIT Compiler is probably going to make this pretty fast since it's just branches and basic tests. You could probably make it more elegant with a HashMap lookup to a callback but I doubt it would be any faster. As to memory, this is pretty slim as is.

Somehow I doubt this code is actually a critical bottle neck for memory or performance. Do you have any real reason to try to optimize it?

Why should we include ttf, eot, woff, svg,... in a font-face

Woff is a compressed (zipped) form of the TrueType - OpenType font. It is small and can be delivered over the network like a graphic file. Most importantly, this way the font is preserved completely including rendering rule tables that very few people care about because they use only Latin script.

Take a look at [dead URL removed]. The font you see is an experimental web delivered smartfont (woff) that has thousands of combined characters making complex shapes. The underlying text is simple Latin code of romanized Singhala. (Copy and paste to Notepad and see).

Only woff can do this because nobody has this font and yet it is seen anywhere (Mac, Win, Linux and even on smartphones by all browsers except by IE. IE does not have full support for Open Types).

How to kill all processes matching a name?

pkill -x matches the process name exactly.

pkill -x amarok

pkill -f is similar but allows a regular expression pattern.

Note that pkill with no other parameters (e.g. -x, -f) will allow partial matches on process names. So "pkill amarok" would kill amarok, amarokBanana, bananaamarok, etc.

I wish -x was the default behavior!

How to write "Html.BeginForm" in Razor

The following code works fine:

@using (Html.BeginForm("Upload", "Upload", FormMethod.Post, 
                                      new { enctype = "multipart/form-data" }))
{
    @Html.ValidationSummary(true)
    <fieldset>
        Select a file <input type="file" name="file" />
        <input type="submit" value="Upload" />
    </fieldset>
}

and generates as expected:

<form action="/Upload/Upload" enctype="multipart/form-data" method="post">    
    <fieldset>
        Select a file <input type="file" name="file" />
        <input type="submit" value="Upload" />
    </fieldset>
</form>

On the other hand if you are writing this code inside the context of other server side construct such as an if or foreach you should remove the @ before the using. For example:

@if (SomeCondition)
{
    using (Html.BeginForm("Upload", "Upload", FormMethod.Post, 
                                      new { enctype = "multipart/form-data" }))
    {
        @Html.ValidationSummary(true)
        <fieldset>
            Select a file <input type="file" name="file" />
            <input type="submit" value="Upload" />
        </fieldset>
    }
}

As far as your server side code is concerned, here's how to proceed:

[HttpPost]
public ActionResult Upload(HttpPostedFileBase file) 
{
    if (file != null && file.ContentLength > 0) 
    {
        var fileName = Path.GetFileName(file.FileName);
        var path = Path.Combine(Server.MapPath("~/content/pics"), fileName);
        file.SaveAs(path);
    }
    return RedirectToAction("Upload");
}

How to use Visual Studio Code as Default Editor for Git

Just want to add these back slashes to previous answers, I am on Windows 10 CMD, and it doesn't work without back slashes before the spaces.

git config --global core.editor "C:\\Users\\your_user_name\\AppData\\Local\\Programs\\Microsoft\ VS\ Code\\Code.exe"

How to force browser to download file?

This is from a php script which solves the problem perfectly with every browser I've tested (FF since 3.5, IE8+, Chrome)

header("Content-Disposition: attachment; filename=\"".$fname_local."\"");
header("Content-Type: application/force-download");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($fname));

So as far as I can see, you're doing everything correctly. Have you checked your browser settings?

How can I find out what version of git I'm running?

In a command prompt:

$ git --version

server error:405 - HTTP verb used to access this page is not allowed

I fixed mine by adding these lines on my IIS webconfig.

<httpErrors>
    <remove statusCode="405" subStatusCode="-1" />
    <error statusCode="405" prefixLanguageFilePath="" path="/my-page.htm" responseMode="ExecuteURL" />
</httpErrors>

TypeError: expected a character buffer object - while trying to save integer to textfile

from __future__ import with_statement
with open('file.txt','r+') as f:
    counter = str(int(f.read().strip())+1)
    f.seek(0)
    f.write(counter)

ng-repeat :filter by single field

If you want filter for one field:

label>Any: <input ng-model="search.color"></label> <br>
<tr ng-repeat="friendObj in friends | filter:search:strict">

If you want filter for all field:

 label>Any: <input ng-model="search.$"></label> <br>
 <tr ng-repeat="friendObj in friends | filter:search:strict">

and https://docs.angularjs.org/api/ng/filter/filter good for you

how to find my angular version in my project?

For Angular 2+ you can run this in the console:

document.querySelector('[ng-version]').getAttribute('ng-version')

For AngularJS 1.x:

angular.version.full

How does Django's Meta class work?

In Django, it acts as a configuration class and keeps the configuration data in one place!!

Dynamically converting java object of Object class to a given class when class name is known

If you didnt know that mojb is of type MyClass, then how can you create that variable?

If MyClass is an interface type, or a super type, then there is no need to do a cast.

How to install Android SDK Build Tools on the command line?

Build tools could not be downloaded automatically by default as Nate said in https://stackoverflow.com/a/19416222/1104031 post.

But I wrote small tool that make everything for you

I used "expect" tool as danb in https://stackoverflow.com/a/17863931/1104031 post. You only need android-sdk and python27, expect.

This script will install all build tools, all sdks and everything you need for automated build:

import subprocess,re,sys

w = subprocess.check_output(["android", "list", "sdk", "--all"])
lines = w.split("\n")
tools = filter(lambda x: "Build-tools" in x, lines)
filters = []
for tool in tools:
  m = re.search("^\s+([0-9]+)-", tool)
  tool_no = m.group(1)
  filters.append(tool_no)

if len(filters) == 0:
  raise Exception("Not found build tools")


filters.extend(['extra', 'platform', 'platform-tool', 'tool'])

filter = ",".join(filters)

expect= '''set timeout -1;
spawn android update sdk --no-ui --all --filter %s;
expect {
  "Do you accept the license" { exp_send "y\\r" ; exp_continue }
  eof
}''' % (filter)

print expect

ret = subprocess.call(["expect", "-c", expect])
sys.exit(ret)

Count number of occurrences of a pattern in a file (even on same line)

To count all occurrences, use -o. Try this:

echo afoobarfoobar | grep -o foo | wc -l

And man grep of course (:

Update

Some suggest to use just grep -co foo instead of grep -o foo | wc -l.

Don't.

This shortcut won't work in all cases. Man page says:

-c print a count of matching lines

Difference in these approaches is illustrated below:

1.

$ echo afoobarfoobar | grep -oc foo
1

As soon as the match is found in the line (a{foo}barfoobar) the searching stops. Only one line was checked and it matched, so the output is 1. Actually -o is ignored here and you could just use grep -c instead.

2.

$ echo afoobarfoobar | grep -o foo
foo
foo

$ echo afoobarfoobar | grep -o foo | wc -l
2

Two matches are found in the line (a{foo}bar{foo}bar) because we explicitly asked to find every occurrence (-o). Every occurence is printed on a separate line, and wc -l just counts the number of lines in the output.

How do I get Bin Path?

You could do this

    Assembly asm = Assembly.GetExecutingAssembly();
    string path = System.IO.Path.GetDirectoryName(asm.Location);

What is the difference between Step Into and Step Over in a debugger

step into will dig into method calls
step over will just execute the line and go to the next one

Bootstrap 3: Offset isn't working?

If I get you right, you want something that seems to be the opposite of what is desired normally: you want a horizontal layout for small screens and vertically stacked elements on large screens. You may achieve this in a way like this:

<div class="container">
    <div class="row">
        <div class="hidden-md hidden-lg col-xs-3 col-xs-offset-6">a</div>
        <div class="hidden-md hidden-lg col-xs-3">b</div>
    </div>
    <div class="row">
        <div class="hidden-xs hidden-sm">c</div>

    </div>
</div>

On small screens, i.e. xs and sm, this generates one row with two columns with an offset of 6. On larger screens, i.e. md and lg, it generates two vertically stacked elements in full width (12 columns).

Switch to another Git tag

Clone the repository as normal:

git clone git://github.com/rspec/rspec-tmbundle.git RSpec.tmbundle

Then checkout the tag you want like so:

git checkout tags/1.1.4

This will checkout out the tag in a 'detached HEAD' state. In this state, "you can look around, make experimental changes and commit them, and [discard those commits] without impacting any branches by performing another checkout".

To retain any changes made, move them to a new branch:

git checkout -b 1.1.4-jspooner

You can get back to the master branch by using:

git checkout master

Note, as was mentioned in the first revision of this answer, there is another way to checkout a tag:

git checkout 1.1.4

But as was mentioned in a comment, if you have a branch by that same name, this will result in git warning you that the refname is ambiguous and checking out the branch by default:

warning: refname 'test' is ambiguous.
Switched to branch '1.1.4'

The shorthand can be safely used if the repository does not share names between branches and tags.

How do I expand the output display to see more columns of a pandas DataFrame?

You can set the output display to match your current terminal width:

pd.set_option('display.width', pd.util.terminal.get_terminal_size()[0])

How to use OKHTTP to make a post request?

You can make it like this:

    MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    RequestBody body = RequestBody.create(JSON, "{"jsonExample":"value"}");

    OkHttpClient client = new OkHttpClient();

    Request request = new Request.Builder()
            .url(url)
            .post(body)
            .addHeader("Authorization", "header value") //Notice this request has header if you don't need to send a header just erase this part
            .build();

    Call call = client.newCall(request);

    call.enqueue(new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {

            Log.e("HttpService", "onFailure() Request was: " + request);

            e.printStackTrace();
        }

        @Override
        public void onResponse(Response r) throws IOException {

            response = r.body().string();

            Log.e("response ", "onResponse(): " + response );

        }
    });

Compiling Java 7 code via Maven

right click on ur project in eclipse and open "Run Configurations"..check the jre version there. some times this will not change by default in eclipse,after even changing the version in the buildpath.

python dataframe pandas drop column using int

You can use the following line to drop the first two columns (or any column you don't need):

df.drop([df.columns[0], df.columns[1]], axis=1)

Reference

Seeing the underlying SQL in the Spring JdbcTemplate?

Parameter values seem to be printed on TRACE level. This worked for me:

log4j.logger.org.springframework.jdbc.core.JdbcTem plate=DEBUG, file
log4j.logger.org.springframework.jdbc.core.StatementCreatorUtils=TRACE, file

Console output:

02:40:56,519 TRACE http-bio-8080-exec-13 core.StatementCreatorUtils:206 - Setting SQL statement parameter value: column index 1, parameter value [Tue May 31 14:00:00 CEST 2005], value class [java.util.Date], SQL type unknown
02:40:56,528 TRACE http-bio-8080-exec-13 core.StatementCreatorUtils:206 - Setting SQL statement parameter value: column index 2, parameter value [61], value class [java.lang.Integer], SQL type unknown
02:40:56,528 TRACE http-bio-8080-exec-13 core.StatementCreatorUtils:206 - Setting SQL statement parameter value: column index 3, parameter value [80], value class [java.lang.Integer], SQL type unknown

Sort a list of numerical strings in ascending order

The recommended approach in this case is to sort the data in the database, adding an ORDER BY at the end of the query that fetches the results, something like this:

SELECT temperature FROM temperatures ORDER BY temperature ASC;  -- ascending order
SELECT temperature FROM temperatures ORDER BY temperature DESC; -- descending order

If for some reason that is not an option, you can change the sorting order like this in Python:

templist = [25, 50, 100, 150, 200, 250, 300, 33]
sorted(templist, key=int)               # ascending order
> [25, 33, 50, 100, 150, 200, 250, 300]
sorted(templist, key=int, reverse=True) # descending order
> [300, 250, 200, 150, 100, 50, 33, 25]

As has been pointed in the comments, the int key (or float if values with decimals are being stored) is required for correctly sorting the data if the data received is of type string, but it'd be very strange to store temperature values as strings, if that is the case, go back and fix the problem at the root, and make sure that the temperatures being stored are numbers.

Set variable with multiple values and use IN

Ideally you shouldn't be splitting strings in T-SQL at all.

Barring that change, on older versions before SQL Server 2016, create a split function:

CREATE FUNCTION dbo.SplitStrings
(
    @List      nvarchar(max), 
    @Delimiter nvarchar(2)
)
RETURNS TABLE
WITH SCHEMABINDING
AS
  RETURN ( WITH x(x) AS
    (
      SELECT CONVERT(xml, N'<root><i>' 
        + REPLACE(@List, @Delimiter, N'</i><i>') 
        + N'</i></root>')
    )
    SELECT Item = LTRIM(RTRIM(i.i.value(N'.',N'nvarchar(max)')))
      FROM x CROSS APPLY x.nodes(N'//root/i') AS i(i)
  );
GO

Now you can say:

DECLARE @Values varchar(1000);

SET @Values = 'A, B, C';

SELECT blah
  FROM dbo.foo
  INNER JOIN dbo.SplitStrings(@Values, ',') AS s
    ON s.Item = foo.myField;

On SQL Server 2016 or above (or Azure SQL Database), it is much simpler and more efficient, however you do have to manually apply LTRIM() to take away any leading spaces:

DECLARE @Values varchar(1000) = 'A, B, C';

SELECT blah
  FROM dbo.foo
  INNER JOIN STRING_SPLIT(@Values, ',') AS s
    ON LTRIM(s.value) = foo.myField;

How to restrict SSH users to a predefined set of commands after login?

You should acquire `rssh', the restricted shell

You can follow the restriction guides mentioned above, they're all rather self-explanatory, and simple to follow. Understand the terms `chroot jail', and how to effectively implement sshd/terminal configurations, and so on.

Being as most of your users access your terminals via sshd, you should also probably look into sshd_conifg, the SSH daemon configuration file, to apply certain restrictions via SSH. Be careful, however. Understand properly what you try to implement, for the ramifications of incorrect configurations are probably rather dire.

DB2 SQL error: SQLCODE: -206, SQLSTATE: 42703

That only means that an undefined column or parameter name was detected. The errror that DB2 gives should point what that may be:

DB2 SQL Error: SQLCODE=-206, SQLSTATE=42703, SQLERRMC=[THE_UNDEFINED_COLUMN_OR_PARAMETER_NAME], DRIVER=4.8.87

Double check your table definition. Maybe you just missed adding something.

I also tried google-ing this problem and saw this:

http://www.coderanch.com/t/515475/JDBC/databases/sql-insert-statement-giving-sqlcode

Equivalent of SQL ISNULL in LINQ?

Since aa is the set/object that might be null, can you check aa == null ?

(aa / xx might be interchangeable (a typo in the question); the original question talks about xx but only defines aa)

i.e.

select new {
    AssetID = x.AssetID,
    Status = aa == null ? (bool?)null : aa.Online; // a Nullable<bool>
}

or if you want the default to be false (not null):

select new {
    AssetID = x.AssetID,
    Status = aa == null ? false : aa.Online;
}

Update; in response to the downvote, I've investigated more... the fact is, this is the right approach! Here's an example on Northwind:

        using(var ctx = new DataClasses1DataContext())
        {
            ctx.Log = Console.Out;
            var qry = from boss in ctx.Employees
                      join grunt in ctx.Employees
                          on boss.EmployeeID equals grunt.ReportsTo into tree
                      from tmp in tree.DefaultIfEmpty()
                      select new
                             {
                                 ID = boss.EmployeeID,
                                 Name = tmp == null ? "" : tmp.FirstName
                        };
            foreach(var row in qry)
            {
                Console.WriteLine("{0}: {1}", row.ID, row.Name);
            }
        }

And here's the TSQL - pretty much what we want (it isn't ISNULL, but it is close enough):

SELECT [t0].[EmployeeID] AS [ID],
    (CASE
        WHEN [t2].[test] IS NULL THEN CONVERT(NVarChar(10),@p0)
        ELSE [t2].[FirstName]
     END) AS [Name]
FROM [dbo].[Employees] AS [t0]
LEFT OUTER JOIN (
    SELECT 1 AS [test], [t1].[FirstName], [t1].[ReportsTo]
    FROM [dbo].[Employees] AS [t1]
    ) AS [t2] ON ([t0].[EmployeeID]) = [t2].[ReportsTo]
-- @p0: Input NVarChar (Size = 0; Prec = 0; Scale = 0) []
-- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 3.5.30729.1

QED?

Floating elements within a div, floats outside of div. Why?

Here's more modern approach:

.parent {display: flow-root;} 

No more clearfixes.

p.s. Using overflow: hidden; hides the box-shadow so...

How to detect internet speed in JavaScript?

Well, this is 2017 so you now have Network Information API (albeit with a limited support across browsers as of now) to get some sort of estimate downlink speed information:

navigator.connection.downlink

This is effective bandwidth estimate in Mbits per sec. The browser makes this estimate from recently observed application layer throughput across recently active connections. Needless to say, the biggest advantage of this approach is that you need not download any content just for bandwidth/ speed calculation.

You can look at this and a couple of other related attributes here

Due to it's limited support and different implementations across browsers (as of Nov 2017), would strongly recommend read this in detail

Creating folders inside a GitHub repository without using Git

After searching a lot I find out that it is possible to create a new folder from the web interface, but it would require you to have at least one file within the folder when creating it.

When using the normal way of creating new files through the web interface, you can type in the folder into the file name to create the file within that new directory.

For example, if I would like to create the file filename.md in a series of sub-folders, I can do this (taken from the GitHub blog):

Enter image description here

Using new line(\n) in string and rendering the same in HTML

Set your css in the table cell to

white-space:pre-wrap;

_x000D_
_x000D_
document.body.innerHTML = 'First line\nSecond line\nThird line';
_x000D_
body{ white-space:pre-wrap; }
_x000D_
_x000D_
_x000D_

How to select label for="XYZ" in CSS?

If the label immediately follows a specified input element:

input#example + label { ... }
input:checked + label { ... }

How to add/subtract dates with JavaScript?

//In order to get yesterday's date in mm/dd/yyyy.


function gimmeYesterday(toAdd) {
            if (!toAdd || toAdd == '' || isNaN(toAdd)) return;
            var d = new Date();
            d.setDate(d.getDate() - parseInt(toAdd));
var yesterDAY = (d.getMonth() +1) + "/" + d.getDate() + "/" + d.getFullYear();
$("#endDate").html(yesterDAY);
        }
$(document).ready(function() {
gimmeYesterday(1);
});

you can try here: http://jsfiddle.net/ZQAHE/

Select DataFrame rows between two dates

Keeping the solution simple and pythonic, I would suggest you to try this.

In case if you are going to do this frequently the best solution would be to first set the date column as index which will convert the column in DateTimeIndex and use the following condition to slice any range of dates.

import pandas as pd

data_frame = data_frame.set_index('date')

df = data_frame[(data_frame.index > '2017-08-10') & (data_frame.index <= '2017-08-15')]

Why can't radio buttons be "readonly"?

JavaScript way - this worked for me.

<script>
$(document).ready(function() {
   $('#YourTableId').find('*').each(function () { $(this).attr("disabled", true); });
});
</script>

Reason:

  1. $('#YourTableId').find('*') -> this returns all the tags.

  2. $('#YourTableId').find('*').each(function () { $(this).attr("disabled", true); }); iterates over all objects captured in this and disable input tags.

Analysis (Debugging):

  1. form:radiobutton is internally considered as an "input" tag.

  2. Like in the above function(), if you try printing document.write(this.tagName);

  3. Wherever, in tags it finds radio buttons, it returns an input tag.

So, above code line can be more optimized for radio button tags, by replacing * with input: $('#YourTableId').find('input').each(function () { $(this).attr("disabled", true); });

What is the difference between %g and %f in C?

They are both examples of floating point input/output.

%g and %G are simplifiers of the scientific notation floats %e and %E.

%g will take a number that could be represented as %f (a simple float or double) or %e (scientific notation) and return it as the shorter of the two.

The output of your print statement will depend on the value of sum.

Disable validation of HTML5 form elements

Instead of trying to do an end run around the browser's validation, you could put the http:// in as placeholder text. This is from the very page you linked:

Placeholder Text

The first improvement HTML5 brings to web forms is the ability to set placeholder text in an input field. Placeholder text is displayed inside the input field as long as the field is empty and not focused. As soon as you click on (or tab to) the input field, the placeholder text disappears.

You’ve probably seen placeholder text before. For example, Mozilla Firefox 3.5 now includes placeholder text in the location bar that reads “Search Bookmarks and History”:

enter image description here

When you click on (or tab to) the location bar, the placeholder text disappears:

enter image description here

Ironically, Firefox 3.5 does not support adding placeholder text to your own web forms. C’est la vie.

Placeholder Support

IE  FIREFOX SAFARI  CHROME  OPERA   IPHONE  ANDROID
·   3.7+    4.0+    4.0+    ·       ·       ·

Here’s how you can include placeholder text in your own web forms:

<form>
  <input name="q" placeholder="Search Bookmarks and History">
  <input type="submit" value="Search">
</form>

Browsers that don’t support the placeholder attribute will simply ignore it. No harm, no foul. See whether your browser supports placeholder text.

It wouldn't be exactly the same since it wouldn't provide that "starting point" for the user, but it's halfway there at least.

Map HTML to JSON

Thank you @Gorge Reith. Working off the solution provided by @George Reith, here is a function that furthers (1) separates out the individual 'hrefs' links (because they might be useful), (2) uses attributes as keys (since attributes are more descriptive), and (3) it's usable within Node.js without needing Chrome by using the 'jsdom' package:

const jsdom = require('jsdom') // npm install jsdom provides in-built Window.js without needing Chrome


// Function to map HTML DOM attributes to inner text and hrefs
function mapDOM(html_string, json) {
    treeObject = {}

    // IMPT: use jsdom because of in-built Window.js
    // DOMParser() does not provide client-side window for element access if coding in Nodejs
    dom = new jsdom.JSDOM(html_string)
    document = dom.window.document
    element = document.firstChild

    // Recursively loop through DOM elements and assign attributes to inner text object
    // Why attributes instead of elements? 1. attributes more descriptive, 2. usually important and lesser
    function treeHTML(element, object) {
        var nodeList = element.childNodes;
        if (nodeList != null) {
           if (nodeList.length) {
               object[element.nodeName] = []  // IMPT: empty [] array for non-text recursivable elements (see below)
               for (var i = 0; i < nodeList.length; i++) {
                   // if final text
                   if (nodeList[i].nodeType == 3) {
                       if (element.attributes != null) {
                           for (var j = 0; j < element.attributes.length; j++) {
                                if (element.attributes[j].nodeValue !== '' && 
                                    nodeList[i].nodeValue !== '') {
                                    if (element.attributes[j].name === 'href') { // separate href
                                        object[element.attributes[j].name] = element.attributes[j].nodeValue;
                                    } else {
                                        object[element.attributes[j].nodeValue] = nodeList[i].nodeValue;
                                    }

                                }
                           }
                       }
                   // else if non-text then recurse on recursivable elements
                   } else {
                       object[element.nodeName].push({}); // if non-text push {} into empty [] array
                       treeHTML(nodeList[i], object[element.nodeName][object[element.nodeName].length -1]);
                   }
               }
           }
        }
    }
    treeHTML(element, treeObject);

    return (json) ? JSON.stringify(treeObject) : treeObject;
}

Why do we use arrays instead of other data structures?

Not all programs do the same thing or run on the same hardware.

This is usually the answer why various language features exist. Arrays are a core computer science concept. Replacing arrays with lists/matrices/vectors/whatever advanced data structure would severely impact performance, and be downright impracticable in a number of systems. There are any number of cases where using one of these "advanced" data collection objects should be used because of the program in question.

In business programming (which most of us do), we can target hardware that is relatively powerful. Using a List in C# or Vector in Java is the right choice to make in these situations because these structures allow the developer to accomplish the goals faster, which in turn allows this type of software to be more featured.

When writing embedded software or an operating system an array may often be the better choice. While an array offers less functionality, it takes up less RAM, and the compiler can optimize code more efficiently for look-ups into arrays.

I am sure I am leaving out a number of the benefits for these cases, but I hope you get the point.

How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson

Answer seems to be a little old, What I did was to use this mapper to convert a MAP

      ObjectMapper mapper = new ObjectMapper().configure(SerializationConfig.Feature.WRITE_NULL_MAP_VALUES, false);

a simple Map:

          Map<String, Object> user = new HashMap<String,Object>();
            user.put( "id",  teklif.getAccount().getId() );
            user.put( "fname", teklif.getAccount().getFname());
            user.put( "lname", teklif.getAccount().getLname());
            user.put( "email", teklif.getAccount().getEmail());
            user.put( "test", null);

Use it like this for example:

      String json = mapper.writeValueAsString(user);

Java - How do I make a String array with values?

You could do something like this

String[] myStrings = { "One", "Two", "Three" };

or in expression

functionCall(new String[] { "One", "Two", "Three" });

or

String myStrings[];
myStrings = new String[] { "One", "Two", "Three" };

Delete duplicate elements from an array

It's easier using Array.filter:

var unique = arr.filter(function(elem, index, self) {
    return index === self.indexOf(elem);
})

In NetBeans how do I change the Default JDK?

If I remember correctly, you'll need to set the netbeans_jdkhome property in your netbeans config file. Should be in your etc/netbeans.conf file.

How can I select rows with most recent timestamp for each key value?

You can join the table with itself (on sensor id), and add left.timestamp < right.timestamp as join condition. Then you pick the rows, where right.id is null. Voila, you got the latest entry per sensor.

http://sqlfiddle.com/#!9/45147/37

SELECT L.* FROM sensorTable L
LEFT JOIN sensorTable R ON
L.sensorID = R.sensorID AND
L.timestamp < R.timestamp
WHERE isnull (R.sensorID)

But please note, that this will be very resource intensive if you have a little amount of ids and many values! So, I wouldn't recommend this for some sort of Measuring-Stuff, where each Sensor collects a value every minute. However in a Use-Case, where you need to track "Revisions" of something that changes just "sometimes", it's easy going.

Angular expression if array contains

Somewhere in your initialisation put this code.

Array.prototype.contains = function contains(obj) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] === obj) {
            return true;
        }
    }
    return false;
};

Then, you can use it this way:

<li ng-class="{approved: selectedForApproval.contains(jobSet)}"></li>

Send a file via HTTP POST with C#

To send the raw file only:

using(WebClient client = new WebClient()) {
    client.UploadFile(address, filePath);
}

If you want to emulate a browser form with an <input type="file"/>, then that is harder. See this answer for a multipart/form-data answer.

Iterate over elements of List and Map using JSTL <c:forEach> tag

try this

<c:forEach items="${list}" var="map">
    <tr>
        <c:forEach items="${map}" var="entry">

            <td>${entry.value}</td>

        </c:forEach>
    </tr>
</c:forEach>

How to use ng-repeat for dictionaries in AngularJs?

In Angular 7, the following simple example would work (assuming dictionary is in a variable called d):

my.component.ts:

keys: string[] = [];  // declaration of class member 'keys'
// component code ...

this.keys = Object.keys(d);

my.component.html: (will display list of key:value pairs)

<ul *ngFor="let key of keys">
    {{key}}: {{d[key]}}
</ul>

How to compile c# in Microsoft's new Visual Studio Code?

Install the extension "Code Runner". Check if you can compile your program with csc (ex.: csc hello.cs). The command csc is shipped with Mono. Then add this to your VS Code user settings:

"code-runner.executorMap": {
        "csharp": "echo '# calling mono\n' && cd $dir && csc /nologo $fileName && mono $dir$fileNameWithoutExt.exe",
        // "csharp": "echo '# calling dotnet run\n' && dotnet run"
    }

Open your C# file and use the execution key of Code Runner.

Edit: also added dotnet run, so you can choose how you want to execute your program: with Mono, or with dotnet. If you choose dotnet, then first create the project (dotnet new console, dotnet restore).

How to generate JAXB classes from XSD?

I hope this helps!

force client disconnect from server with socket.io and nodejs

Add new socket connections to an array and then when you want to close all - loop through them and disconnect. (server side)

var socketlist = [];

   io.sockets.on('connection', function (socket) {
        socketlist.push(socket);  
        //...other code for connection here..
   });


    //close remote sockets
    socketlist.forEach(function(socket) {        
        socket.disconnect();                      
    });    

Is it possible to iterate through JSONArray?

You can use the opt(int) method and use a classical for loop.

Raw SQL Query without DbSet - Entity Framework Core

Not directly targeting the OP's scenario, but since I have been struggling with this, I'd like to drop these ex. methods that make it easier to execute raw SQL with the DbContext:

public static class DbContextCommandExtensions
{
  public static async Task<int> ExecuteNonQueryAsync(this DbContext context, string rawSql,
    params object[] parameters)
  {
    var conn = context.Database.GetDbConnection();
    using (var command = conn.CreateCommand())
    {
      command.CommandText = rawSql;
      if (parameters != null)
        foreach (var p in parameters)
          command.Parameters.Add(p);
      await conn.OpenAsync();
      return await command.ExecuteNonQueryAsync();
    }
  }

  public static async Task<T> ExecuteScalarAsync<T>(this DbContext context, string rawSql,
    params object[] parameters)
  {
    var conn = context.Database.GetDbConnection();
    using (var command = conn.CreateCommand())
    {
      command.CommandText = rawSql;
      if (parameters != null)
        foreach (var p in parameters)
          command.Parameters.Add(p);
      await conn.OpenAsync();
      return (T)await command.ExecuteScalarAsync();
    }
  }
}

jQuery / Javascript code check, if not undefined

I generally like the shorthand version:

if (!!wlocation) { window.location = wlocation; }

What is the proper way to display the full InnerException?

To pretty print just the Messages part of deep exceptions, you could do something like this:

public static string ToFormattedString(this Exception exception)
{
    IEnumerable<string> messages = exception
        .GetAllExceptions()
        .Where(e => !String.IsNullOrWhiteSpace(e.Message))
        .Select(e => e.Message.Trim());
    string flattened = String.Join(Environment.NewLine, messages); // <-- the separator here
    return flattened;
}

public static IEnumerable<Exception> GetAllExceptions(this Exception exception)
{
    yield return exception;

    if (exception is AggregateException aggrEx)
    {
        foreach (Exception innerEx in aggrEx.InnerExceptions.SelectMany(e => e.GetAllExceptions()))
        {
            yield return innerEx;
        }
    }
    else if (exception.InnerException != null)
    {
        foreach (Exception innerEx in exception.InnerException.GetAllExceptions())
        {
            yield return innerEx;
        }
    }
}

This recursively goes through all inner exceptions (including the case of AggregateExceptions) to print all Message property contained in them, delimited by line break.

E.g.

var outerAggrEx = new AggregateException(
    "Outer aggr ex occurred.",
    new AggregateException("Inner aggr ex.", new FormatException("Number isn't in correct format.")),
    new IOException("Unauthorized file access.", new SecurityException("Not administrator.")));
Console.WriteLine(outerAggrEx.ToFormattedString());

Outer aggr ex occurred.
Inner aggr ex.
Number isn't in correct format.
Unauthorized file access.
Not administrator.


You will need to listen to other Exception properties for more details. For e.g. Data will have some information. You could do:

foreach (DictionaryEntry kvp in exception.Data)

To get all derived properties (not on base Exception class), you could do:

exception
    .GetType()
    .GetProperties()
    .Where(p => p.CanRead)
    .Where(p => p.GetMethod.GetBaseDefinition().DeclaringType != typeof(Exception));

Removing duplicate objects with Underscore for Javascript

Try iterator function

For example you can return first element

x = [['a',1],['b',2],['a',1]]

_.uniq(x,false,function(i){  

   return i[0]   //'a','b'

})

=> [['a',1],['b',2]]

clk'event vs rising_edge()

The linked comment is incorrect : 'L' to '1' will produce a rising edge.

In addition, if your clock signal transitions from 'H' to '1', rising_edge(clk) will (correctly) not trigger while (clk'event and clk = '1') (incorrectly) will.

Granted, that may look like a contrived example, but I have seen clock waveforms do that in real hardware, due to failures elsewhere.

Select first empty cell in column F starting from row 1. (without using offset )

Code of Sam is good but I think it need some correction,

Public Sub SelectFirstBlankCell()
    Dim sourceCol As Integer, rowCount As Integer, currentRow As Integer
    Dim currentRowValue As String

    sourceCol = 6   'column F has a value of 6
    rowCount = Cells(Rows.Count, sourceCol).End(xlUp).Row

    'for every row, find the first blank cell and select it
    For currentRow = 1 To rowCount
        currentRowValue = Cells(currentRow, sourceCol).Value
        If IsEmpty(currentRowValue) Or currentRowValue = "" Then
            Cells(currentRow, sourceCol).Select
            Exit For 'This is missing...
        End If
    Next
End Sub

Thanks

Git: How to return from 'detached HEAD' state

You may have made some new commits in the detached HEAD state. I believe if you do as other answers advise:

git checkout master
# or
git checkout -

then you may lose your commits!! Instead, you may want to do this:

# you are currently in detached HEAD state
git checkout -b commits-from-detached-head

and then merge commits-from-detached-head into whatever branch you want, so you don't lose the commits.

How can I ignore a property when serializing using the DataContractSerializer?

What you are saying is in conflict with what it says in the MSDN library at this location:

http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractserializer.aspx

I don't see any mention of the SP1 feature you mention.

How to return multiple values in one column (T-SQL)?

group_concat() sounds like what you're looking for.

http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat

since you're on mssql, i just googled "group_concat mssql" and found a bunch of hits to recreate group_concat functionality. here's one of the hits i found:

http://www.stevenmapes.com/index.php?/archives/23-Recreating-MySQL-GROUP_CONCAT-In-MSSQL-Cross-Tab-Query.html

Is there a C++ decompiler?

Yes, but none of them will manage to produce readable enough code to worth the effort. You will spend more time trying to read the decompiled source with assembler blocks inside, than rewriting your old app from scratch.

Where can I find "make" program for Mac OS X Lion?

Xcode 5.1 no longer provides command line tools in the Preferences section. You now go to https://developer.apple.com/downloads/index.action, and select the command line tools version for your OS X release. The installer puts them in /usr/bin.

get everything between <tag> and </tag> with php

You can use the following:

$regex = '#<\s*?code\b[^>]*>(.*?)</code\b[^>]*>#s';
  • \b ensures that a typo (like <codeS>) is not captured.
  • The first pattern [^>]* captures the content of a tag with attributes (eg a class).
  • Finally, the flag s capture content with newlines.

See the result here : http://lumadis.be/regex/test_regex.php?id=1081

How do I change the hover over color for a hover over table in Bootstrap?

.table-hover tbody tr:hover td {
    background: aqua;
}

this is the best solution i can gice so far.it works out perfectly in such scena

Create an instance of a class from a string

Its pretty simple. Assume that your classname is Car and the namespace is Vehicles, then pass the parameter as Vehicles.Car which returns object of type Car. Like this you can create any instance of any class dynamically.

public object GetInstance(string strFullyQualifiedName)
{         
     Type t = Type.GetType(strFullyQualifiedName); 
     return  Activator.CreateInstance(t);         
}

If your Fully Qualified Name(ie, Vehicles.Car in this case) is in another assembly, the Type.GetType will be null. In such cases, you have loop through all assemblies and find the Type. For that you can use the below code

public object GetInstance(string strFullyQualifiedName)
{
     Type type = Type.GetType(strFullyQualifiedName);
     if (type != null)
         return Activator.CreateInstance(type);
     foreach (var asm in AppDomain.CurrentDomain.GetAssemblies())
     {
         type = asm.GetType(strFullyQualifiedName);
         if (type != null)
             return Activator.CreateInstance(type);
     }
     return null;
 }

Now if you want to call a parameterized constructor do the following

Activator.CreateInstance(t,17); // Incase you are calling a constructor of int type

instead of

Activator.CreateInstance(t);

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

You can use requests and beautifulsoup libraries to read data on a website. Just install these two libraries and type the following code.

import requests
import bs4
help(requests)
help(bs4)

You will get all the information you need about the library.

Proper way of checking if row exists in table in PL/SQL block

Select 'YOU WILL SEE ME' as ANSWER from dual
where exists (select 1 from dual where 1 = 1);

Select 'YOU CAN NOT SEE ME' as ANSWER from dual
where exists (select 1 from dual where 1 = 0);

Select 'YOU WILL SEE ME, TOO' as ANSWER from dual
where not exists (select 1 from dual where 1 = 0);

How to convert seconds to time format?

This might be simpler

gmdate("H:i:s", $seconds)

PHP gmdate

To switch from vertical split to horizontal split fast in Vim

In VIM, take a look at the following to see different alternatives for what you might have done:

:help opening-window

For instance:

Ctrl-W s
Ctrl-W o
Ctrl-W v
Ctrl-W o
Ctrl-W s
...

click or change event on radio using jquery

Works for me too, here is a better solution::

fiddle demo

<form id="myForm">
  <input type="radio" name="radioName" value="1" />one<br />
  <input type="radio" name="radioName" value="2" />two 
</form>

<script>
$('#myForm input[type=radio]').change(function() {       
    alert(this.value);
});
</script>

You must make sure that you initialized jquery above all other imports and javascript functions. Because $ is a jquery function. Even

$(function(){
 <code>
}); 

will not check jquery initialised or not. It will ensure that <code> will run only after all the javascripts are initialized.

Install Chrome extension form outside the Chrome Web Store

For regular Windows users who are not skilled with computers, it is practically not possible to install and use extensions from outside the Chrome Web Store.

Users of other operating systems (Linux, Mac, Chrome OS) can easily install unpacked extensions (in developer mode).
Windows users can also load an unpacked extension, but they will always see an information bubble with "Disable developer mode extensions" when they start Chrome or open a new incognito window, which is really annoying. The only way for Windows users to use unpacked extensions without such dialogs is to switch to Chrome on the developer channel, by installing https://www.google.com/chrome/browser/index.html?extra=devchannel#eula.

Extensions can be loaded in unpacked mode by following the following steps:

  1. Visit chrome://extensions (via omnibox or menu -> Tools -> Extensions).
  2. Enable Developer mode by ticking the checkbox in the upper-right corner.
  3. Click on the "Load unpacked extension..." button.
  4. Select the directory containing your unpacked extension.

If you have a crx file, then it needs to be extracted first. CRX files are zip files with a different header. Any capable zip program should be able to open it. If you don't have such a program, I recommend 7-zip.

These steps will work for almost every extension, except extensions that rely on their extension ID. If you use the previous method, you will get an extension with a random extension ID. If it is important to preserve the extension ID, then you need to know the public key of your CRX file and insert this in your manifest.json. I have previously given a detailed explanation on how to get and use this key at https://stackoverflow.com/a/21500707.

Launch a shell command with in a python script, wait for the termination and return to the script

You can use subprocess.Popen. There's a few ways to do it:

import subprocess
cmd = ['/run/myscript', '--arg', 'value']
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
for line in p.stdout:
    print line
p.wait()
print p.returncode

Or, if you don't care what the external program actually does:

cmd = ['/run/myscript', '--arg', 'value']
subprocess.Popen(cmd).wait()

Validate that a string is a positive integer

If you are using HTML5 forms, you can use attribute min="0" for form element <input type="number" />. This is supported by all major browsers. It does not involve Javascript for such simple tasks, but is integrated in new html standard. It is documented on https://www.w3schools.com/tags/att_input_min.asp

pandas dataframe create new columns and fill with calculated values from same df

In [56]: df = pd.DataFrame(np.abs(randn(3, 4)), index=[1,2,3], columns=['A','B','C','D'])

In [57]: df.divide(df.sum(axis=1), axis=0)
Out[57]: 
          A         B         C         D
1  0.319124  0.296653  0.138206  0.246017
2  0.376994  0.326481  0.230464  0.066062
3  0.036134  0.192954  0.430341  0.340571

initializing a boolean array in java

I just need to initialize all the array elements to Boolean false.

Either use boolean[] instead so that all values defaults to false:

boolean[] array = new boolean[size];

Or use Arrays#fill() to fill the entire array with Boolean.FALSE:

Boolean[] array = new Boolean[size];
Arrays.fill(array, Boolean.FALSE);

Also note that the array index is zero based. The freq[Global.iParameter[2]] = false; line as you've there would cause ArrayIndexOutOfBoundsException. To learn more about arrays in Java, consult this basic Oracle tutorial.

iReport not starting using JRE 8

don't uninstall anything. a system with multiple versions of java works just fine. and you don't need to update your environment varables (e.g. java_home, path, etc..).

yes, ireports 3.6.1 needs java 7 (doesn't work with java 8).

all you have to do is edit C:\Program Files\Jaspersoft\iReport-nb-3.6.1\etc\ireport.conf:

# default location of JDK/JRE, can be overridden by using --jdkhome <dir> switch
jdkhome="C:/Program Files/Java/jdk1.7.0_45"

on linux (no spaces and standard file paths) its that much easier. keep your java 8 for other interesting projects...

How to add an element to the beginning of an OrderedDict?

There's no built-in method for doing this in Python 2. If you need this, you need to write a prepend() method/function that operates on the OrderedDict internals with O(1) complexity.

For Python 3.2 and later, you should use the move_to_end method. The method accepts a last argument which indicates whether the element will be moved to the bottom (last=True) or the top (last=False) of the OrderedDict.

Finally, if you want a quick, dirty and slow solution, you can just create a new OrderedDict from scratch.

Details for the four different solutions:


Extend OrderedDict and add a new instance method

from collections import OrderedDict

class MyOrderedDict(OrderedDict):

    def prepend(self, key, value, dict_setitem=dict.__setitem__):

        root = self._OrderedDict__root
        first = root[1]

        if key in self:
            link = self._OrderedDict__map[key]
            link_prev, link_next, _ = link
            link_prev[1] = link_next
            link_next[0] = link_prev
            link[0] = root
            link[1] = first
            root[1] = first[0] = link
        else:
            root[1] = first[0] = self._OrderedDict__map[key] = [root, first, key]
            dict_setitem(self, key, value)

Demo:

>>> d = MyOrderedDict([('a', '1'), ('b', '2')])
>>> d
MyOrderedDict([('a', '1'), ('b', '2')])
>>> d.prepend('c', 100)
>>> d
MyOrderedDict([('c', 100), ('a', '1'), ('b', '2')])
>>> d.prepend('a', d['a'])
>>> d
MyOrderedDict([('a', '1'), ('c', 100), ('b', '2')])
>>> d.prepend('d', 200)
>>> d
MyOrderedDict([('d', 200), ('a', '1'), ('c', 100), ('b', '2')])

Standalone function that manipulates OrderedDict objects

This function does the same thing by accepting the dict object, key and value. I personally prefer the class:

from collections import OrderedDict

def ordered_dict_prepend(dct, key, value, dict_setitem=dict.__setitem__):
    root = dct._OrderedDict__root
    first = root[1]

    if key in dct:
        link = dct._OrderedDict__map[key]
        link_prev, link_next, _ = link
        link_prev[1] = link_next
        link_next[0] = link_prev
        link[0] = root
        link[1] = first
        root[1] = first[0] = link
    else:
        root[1] = first[0] = dct._OrderedDict__map[key] = [root, first, key]
        dict_setitem(dct, key, value)

Demo:

>>> d = OrderedDict([('a', '1'), ('b', '2')])
>>> ordered_dict_prepend(d, 'c', 100)
>>> d
OrderedDict([('c', 100), ('a', '1'), ('b', '2')])
>>> ordered_dict_prepend(d, 'a', d['a'])
>>> d
OrderedDict([('a', '1'), ('c', 100), ('b', '2')])
>>> ordered_dict_prepend(d, 'd', 500)
>>> d
OrderedDict([('d', 500), ('a', '1'), ('c', 100), ('b', '2')])

Use OrderedDict.move_to_end() (Python >= 3.2)

Python 3.2 introduced the OrderedDict.move_to_end() method. Using it, we can move an existing key to either end of the dictionary in O(1) time.

>>> d1 = OrderedDict([('a', '1'), ('b', '2')])
>>> d1.update({'c':'3'})
>>> d1.move_to_end('c', last=False)
>>> d1
OrderedDict([('c', '3'), ('a', '1'), ('b', '2')])

If we need to insert an element and move it to the top, all in one step, we can directly use it to create a prepend() wrapper (not presented here).


Create a new OrderedDict - slow!!!

If you don't want to do that and performance is not an issue then easiest way is to create a new dict:

from itertools import chain, ifilterfalse
from collections import OrderedDict


def unique_everseen(iterable, key=None):
    "List unique elements, preserving order. Remember all elements ever seen."
    # unique_everseen('AAAABBBCCDAABBB') --> A B C D
    # unique_everseen('ABBCcAD', str.lower) --> A B C D
    seen = set()
    seen_add = seen.add
    if key is None:
        for element in ifilterfalse(seen.__contains__, iterable):
            seen_add(element)
            yield element
    else:
        for element in iterable:
            k = key(element)
            if k not in seen:
                seen_add(k)
                yield element

d1 = OrderedDict([('a', '1'), ('b', '2'),('c', 4)])
d2 = OrderedDict([('c', 3), ('e', 5)])   #dict containing items to be added at the front
new_dic = OrderedDict((k, d2.get(k, d1.get(k))) for k in \
                                           unique_everseen(chain(d2, d1)))
print new_dic

output:

OrderedDict([('c', 3), ('e', 5), ('a', '1'), ('b', '2')])

Backporting Python 3 open(encoding="utf-8") to Python 2

I think

from io import open

should do.

Applying CSS styles to all elements inside a DIV

Write all class/id CSS as below. #applyCSS ID will be parent of all CSS code.

For example you add class .ui-bar-a in CSS for applying to your div:

#applyCSS .ui-bar-a  { font-size:11px; } /* This will be your CSS part */

Below is your HTML part:

<div id="applyCSS">
   <div class="ui-bar-a">testing</div>
</div>

echo that outputs to stderr

Another option that I recently stumbled on is this:

    {
        echo "First error line"
        echo "Second error line"
        echo "Third error line"
    } >&2

This uses only Bash built-ins while making multi-line error output less error prone (since you don't have to remember to add &>2 to every line).

How to get the selected radio button’s value?

This works with any explorer.

document.querySelector('input[name="genderS"]:checked').value;

This is a simple way to get the value of any input type. You also do not need to include jQuery path.

Half circle with CSS (border, outline only)

Below is a minimal code to achieve the effect.

This also works responsively since the border-radius is in percentage.

_x000D_
_x000D_
.semi-circle{_x000D_
width: 200px;_x000D_
height: 100px;_x000D_
border-radius: 50% 50% 0 0 / 100% 100% 0 0;_x000D_
border: 10px solid #000;_x000D_
border-bottom: 0;_x000D_
}
_x000D_
<div class="semi-circle"></div>
_x000D_
_x000D_
_x000D_

Regular expression to match balanced parentheses

Adding to bobble bubble's answer, there are other regex flavors where recursive constructs are supported.

Lua

Use %b() (%b{} / %b[] for curly braces / square brackets):

  • for s in string.gmatch("Extract (a(b)c) and ((d)f(g))", "%b()") do print(s) end (see demo)

Raku (former Perl6):

Non-overlapping multiple balanced parentheses matches:

my regex paren_any { '(' ~ ')' [ <-[()]>+ || <&paren_any> ]* }
say "Extract (a(b)c) and ((d)f(g))" ~~ m:g/<&paren_any>/;
# => (?(a(b)c)? ?((d)f(g))?)

Overlapping multiple balanced parentheses matches:

say "Extract (a(b)c) and ((d)f(g))" ~~ m:ov:g/<&paren_any>/;
# => (?(a(b)c)? ?(b)? ?((d)f(g))? ?(d)? ?(g)?)

See demo.

Python re non-regex solution

See poke's answer for How to get an expression between balanced parentheses.

Java customizable non-regex solution

Here is a customizable solution allowing single character literal delimiters in Java:

public static List<String> getBalancedSubstrings(String s, Character markStart, 
                                 Character markEnd, Boolean includeMarkers) 

{
        List<String> subTreeList = new ArrayList<String>();
        int level = 0;
        int lastOpenDelimiter = -1;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == markStart) {
                level++;
                if (level == 1) {
                    lastOpenDelimiter = (includeMarkers ? i : i + 1);
                }
            }
            else if (c == markEnd) {
                if (level == 1) {
                    subTreeList.add(s.substring(lastOpenDelimiter, (includeMarkers ? i + 1 : i)));
                }
                if (level > 0) level--;
            }
        }
        return subTreeList;
    }
}

Sample usage:

String s = "some text(text here(possible text)text(possible text(more text)))end text";
List<String> balanced = getBalancedSubstrings(s, '(', ')', true);
System.out.println("Balanced substrings:\n" + balanced);
// => [(text here(possible text)text(possible text(more text)))]

2D character array initialization in C

I think what you originally meant to do was to make an array only of characters, not of pointers:

char options[2][100];

options[0][0]='t';
options[0][1]='e';
options[0][2]='s';
options[0][3]='t';
options[0][4]='1';
options[0][5]='\0';  /* NUL termination of C string */

/* A standard C library function which copies strings. */
strcpy(options[1], "test2");

The code above shows two distinct methods of setting the character values in memory you have set aside to contain characters.

Usage of @see in JavaDoc?

The @see tag is a bit different than the @link tag,
limited in some ways and more flexible in others:

different JavaDoc link types Different JavaDoc link types

  1. Displays the member name for better learning, and is refactorable; the name will update when renaming by refactor
  2. Refactorable and customizable; your text is displayed instead of the member name
  3. Displays name, refactorable
  4. Refactorable, customizable
  5. A rather mediocre combination that is:
  • Refactorable, customizable, and stays in the See Also section
  • Displays nicely in the Eclipse hover
  • Displays the link tag and its formatting when generated
  • When using multiple @see items, commas in the description make the output confusing
  1. Completely illegal; causes unexpected content and illegal character errors in the generator

See the results below:

JavaDoc generation results with different link types JavaDoc generation results with different link types

Best regards.

Is String.Contains() faster than String.IndexOf()?

Use a benchmark library, like this recent foray from Jon Skeet to measure it.

Caveat Emptor

As all (micro-)performance questions, this depends on the versions of software you are using, the details of the data inspected and the code surrounding the call.

As all (micro-)performance questions, the first step has to be to get a running version which is easily maintainable. Then benchmarking, profiling and tuning can be applied to the measured bottlenecks instead of guessing.

In a Dockerfile, How to update PATH environment variable?

This is discouraged (if you want to create/distribute a clean Docker image), since the PATH variable is set by /etc/profile script, the value can be overridden.

head /etc/profile:

if [ "`id -u`" -eq 0 ]; then
  PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
else
  PATH="/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games"
fi
export PATH

At the end of the Dockerfile, you could add:

RUN echo "export PATH=$PATH" > /etc/environment

So PATH is set for all users.

Resolve promises one after another (i.e. in sequence)?

To do this simply in ES6:

function(files) {
  // Create a new empty promise (don't do that with real people ;)
  var sequence = Promise.resolve();

  // Loop over each file, and add on a promise to the
  // end of the 'sequence' promise.
  files.forEach(file => {

    // Chain one computation onto the sequence
    sequence = 
      sequence
        .then(() => performComputation(file))
        .then(result => doSomething(result)); 
        // Resolves for each file, one at a time.

  })

  // This will resolve after the entire chain is resolved
  return sequence;
}

Match at every second occurrence

There's no "direct" way of doing so but you can specify the pattern twice as in: a[^a]*a that match up to the second "a".

The alternative is to use your programming language (perl? C#? ...) to match the first occurence and then the second one.

EDIT: I've seen other responded using the "non-greedy" operators which might be a good way to go, assuming you have them in your regex library!

How can I add an image file into json object?

You will need to read the bytes from that File into a byte[] and put that object into your JSONObject.

You should also have a look at the following posts :

Hope this helps.

How do you implement a circular buffer in C?

A simple implementation could consist of:

  • A buffer, implemented as an array of size n, of whatever type you need
  • A read pointer or index (whichever is more efficient for your processor)
  • A write pointer or index
  • A counter indicating how much data is in the buffer (derivable from the read and write pointers, but faster to track it separately)

Every time you write data, you advance the write pointer and increment the counter. When you read data, you increase the read pointer and decrement the counter. If either pointer reaches n, set it to zero.

You can't write if counter = n. You can't read if counter = 0.

What is the simplest SQL Query to find the second largest value?

It is the most esiest way:

SELECT
      Column name
FROM
      Table name 
ORDER BY 
      Column name DESC
LIMIT 1,1

Biggest differences of Thrift vs Protocol Buffers?

I think most of these points have missed the basic fact that Thrift is an RPC framework, which happens to have the ability to serialize data using a variety of methods (binary, XML, etc).

Protocol Buffers are designed purely for serialization, it's not a framework like Thrift.

Invoking a static method using reflection

// String.class here is the parameter type, that might not be the case with you
Method method = clazz.getMethod("methodName", String.class);
Object o = method.invoke(null, "whatever");

In case the method is private use getDeclaredMethod() instead of getMethod(). And call setAccessible(true) on the method object.

How do you find the sum of all the numbers in an array in Java?

I use this:

public static long sum(int[] i_arr)
{
    long sum;
    int i;
    for(sum= 0, i= i_arr.length - 1; 0 <= i; sum+= i_arr[i--]);
    return sum;
}

Get property value from string using reflection

public class YourClass
{
    //Add below line in your class
    public object this[string propertyName] => GetType().GetProperty(propertyName)?.GetValue(this, null);
    public string SampleProperty { get; set; }
}

//And you can get value of any property like this.
var value = YourClass["SampleProperty"];

How to prevent a jQuery Ajax request from caching in Internet Explorer?

This is an old post, but if IE is giving you trouble. Change your GET requests to POST and IE will no longer cache them.

I spent way too much time figuring this out the hard way. Hope it helps.

Could not load file or assembly '***.dll' or one of its dependencies

or one of its dependencies

That's the usual problem, you cannot see a missing unmanaged DLL with Fuslogvw.exe. Best thing to do is to run SysInternals' ProcMon utility. You'll see it searching for the DLL and not find it. Profile mode in Dependency Walker can show it too.

Get folder up one level

The parent directory of an included file would be

dirname(getcwd())

e.g. the file is /var/www/html/folder/inc/file.inc.php which is included in /var/www/html/folder/index.php

then by calling /file/index.php

getcwd() is /var/www/html/folder  
__DIR__ is /var/www/html/folder/inc  
so dirname(__DIR__) is /var/www/html/folder

but what we want is /var/www/html which is dirname(getcwd())

SQL split values to multiple rows

CREATE PROCEDURE `getVal`()
BEGIN
        declare r_len integer;
        declare r_id integer;
        declare r_val varchar(20);
        declare i integer;
        DECLARE found_row int(10);
        DECLARE row CURSOR FOR select length(replace(val,"|","")),id,val from split;
        create table x(id int,name varchar(20));
      open row;
            select FOUND_ROWS() into found_row ;
            read_loop: LOOP
                IF found_row = 0 THEN
                         LEAVE read_loop;
                END IF;
            set i = 1;  
            FETCH row INTO r_len,r_id,r_val;
            label1: LOOP        
                IF i <= r_len THEN
                  insert into x values( r_id,SUBSTRING(replace(r_val,"|",""),i,1));
                  SET i = i + 1;
                  ITERATE label1;
                END IF;
                LEAVE label1;
            END LOOP label1;
            set found_row = found_row - 1;
            END LOOP;
        close row;
        select * from x;
        drop table x;
END

Vertically align an image inside a div with responsive height

You can center an image, both horizontally and vertically, using margin: auto and absolute positioning. Also:

  1. It is possible to ditch extra markup by using pseudo elements.
  2. It is possible to display the middle portion of LARGE images by using negative left, top, right and bottom values.

_x000D_
_x000D_
.responsive-container {_x000D_
  margin: 1em auto;_x000D_
  min-width: 200px;       /* cap container min width */_x000D_
  max-width: 500px;       /* cap container max width */_x000D_
  position: relative;     _x000D_
  overflow: hidden;       /* crop if image is larger than container */_x000D_
  background-color: #CCC; _x000D_
}_x000D_
.responsive-container:before {_x000D_
  content: "";            /* using pseudo element for 1:1 ratio */_x000D_
  display: block;_x000D_
  padding-top: 100%;_x000D_
}_x000D_
.responsive-container img {_x000D_
  position: absolute;_x000D_
  top: -999px;            /* use sufficiently large number */_x000D_
  bottom: -999px;_x000D_
  left: -999px;_x000D_
  right: -999px;_x000D_
  margin: auto;           /* center horizontally and vertically */_x000D_
}
_x000D_
<p>Note: images are center-cropped on &lt;400px screen width._x000D_
  <br>Open full page demo and resize browser.</p>_x000D_
<div class="responsive-container">_x000D_
  <img src="http://lorempixel.com/400/400/sports/9/">_x000D_
</div>_x000D_
<div class="responsive-container">_x000D_
  <img src="http://lorempixel.com/400/200/sports/8/">_x000D_
</div>_x000D_
<div class="responsive-container">_x000D_
  <img src="http://lorempixel.com/200/400/sports/7/">_x000D_
</div>_x000D_
<div class="responsive-container">_x000D_
  <img src="http://lorempixel.com/200/200/sports/6/">_x000D_
</div>
_x000D_
_x000D_
_x000D_

Write HTML to string

You could use System.Xml.Linq objects. They were totally redesigned from the old System.Xml days which made constructing XML from scratch really annoying.

Other than the doctype I guess, you could easily do something like:

var html = new XElement("html",
    new XElement("head",
        new XElement("title", "My Page")
    ),
    new XElement("body",
        "this is some text"
    )
);

How do I make a dotted/dashed line in Android?

I liked the solution from Ruidge, but I needed more control from XML. So I changed it to Kotlin and added attributes.

1) Copy the Kotlin class:

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View

class DashedDividerView : View {
constructor(context: Context) : this(context, null, 0)
constructor(context: Context, attributeSet: AttributeSet) : this(context, attributeSet, 0)

companion object {
    const val DIRECTION_VERTICAL = 0
    const val DIRECTION_HORIZONTAL = 1
}

private var dGap = 5.25f
private var dWidth = 5.25f
private var dColor = Color.parseColor("#EE0606")
private var direction = DIRECTION_HORIZONTAL
private val paint = Paint()
private val path = Path()

constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
    context,
    attrs,
    defStyleAttr
) {
    val typedArray = context.obtainStyledAttributes(
        attrs,
        R.styleable.DashedDividerView,
        defStyleAttr,
        R.style.DashedDividerDefault
    )

    dGap = typedArray.getDimension(R.styleable.DashedDividerView_dividerDashGap, dGap)
    dWidth = typedArray.getDimension(R.styleable.DashedDividerView_dividerDashWidth, dWidth)
    dColor = typedArray.getColor(R.styleable.DashedDividerView_dividerDashColor, dColor)
    direction =
        typedArray.getInt(R.styleable.DashedDividerView_dividerDirection, DIRECTION_HORIZONTAL)

    paint.color = dColor
    paint.style = Paint.Style.STROKE
    paint.pathEffect = DashPathEffect(floatArrayOf(dWidth, dGap), 0f)
    paint.strokeWidth = dWidth

    typedArray.recycle()
}

override fun onDraw(canvas: Canvas) {
    super.onDraw(canvas)
    path.moveTo(0f, 0f)

    if (direction == DIRECTION_HORIZONTAL) {
        path.lineTo(measuredWidth.toFloat(), 0f)
    } else {
        path.lineTo(0f, measuredHeight.toFloat())
    }
    canvas.drawPath(path, paint)
}

}

2) Create an attr file in the /res directory and add this

 <declare-styleable name="DashedDividerView">
    <attr name="dividerDashGap" format="dimension" />
    <attr name="dividerDashWidth" format="dimension" />
    <attr name="dividerDashColor" format="reference|color" />
    <attr name="dividerDirection" format="enum">
        <enum name="vertical" value="0" />
        <enum name="horizontal" value="1" />
    </attr>
</declare-styleable>

3) Add a style to the styles file

 <style name="DashedDividerDefault">
    <item name="dividerDashGap">2dp</item>
    <item name="dividerDashWidth">2dp</item>
    <!-- or any color -->
    <item name="dividerDashColor">#EE0606</item>
    <item name="dividerDirection">horizontal</item>
</style>

4) Now you can use the default style

<!-- here will be your path to the class -->
<com.your.package.app.DashedDividerView
    android:layout_width="match_parent"
    android:layout_height="2dp"
    />

or set attributes in XML

<com.your.package.app.DashedDividerView
    android:layout_width="match_parent"
    android:layout_height="2dp"
    app:dividerDirection="horizontal"
    app:dividerDashGap="2dp"
    app:dividerDashWidth="2dp"
    app:dividerDashColor="@color/light_gray"/>

How to start new activity on button click

Start another activity from this activity and u can pass parameters via Bundle Object also.

Intent intent = new Intent(getBaseContext(), YourActivity.class);
intent.putExtra("USER_NAME", "[email protected]");
startActivity(intent);

Retrive data in another activity (YourActivity)

String s = getIntent().getStringExtra("USER_NAME");

What version of JBoss I am running?

This URL (JMX-Console) should provide you the informations

http://localhost:8080/jmx-console/HtmlAdaptor?action=inspectMBean&name=jboss.system%3Atype%3DServer

The tomcat version is implied by the jboss server version.

EDIT:

A complete list of versions you find here VersionOfTomcatInJBossAS

Where you reach your JBoss depends on the interface it is bound, using -b hostname If you start using JBoss with -b 0.0.0.0 option. That way, you can access the system using localhost, machineName and even the IP address. By default it's localhost, if you use th -b option you need to replace localhost by yourhostname.

Java - How to find the redirected url of a url?

Have a look at the HttpURLConnection class API documentation, especially setInstanceFollowRedirects().

LINQ Orderby Descending Query

Just to show it in a different format that I prefer to use for some reason: The first way returns your itemList as an System.Linq.IOrderedQueryable

using(var context = new ItemEntities())
{
    var itemList = context.Items.Where(x => !x.Items && x.DeliverySelection)
                                .OrderByDescending(x => x.Delivery.SubmissionDate);
}

That approach is fine, but if you wanted it straight into a List Object:

var itemList = context.Items.Where(x => !x.Items && x.DeliverySelection)
                                .OrderByDescending(x => x.Delivery.SubmissionDate).ToList();

All you have to do is append a .ToList() call to the end of the Query.

Something to note, off the top of my head I can't recall if the !(not) expression is acceptable in the Where() call.

Find duplicate records in a table using SQL Server

Just add all fields to the query and remember to add them to Group By as well.

Select shoppername, a, b, amountpayed, item, count(*) as cnt
from dbo.sales
group by shoppername, a, b, amountpayed, item
having count(*) > 1

How to insert element as a first child?

Use: $("<p>Test</p>").prependTo(".inner"); Check out the .prepend documentation on jquery.com

Difference between javacore, thread dump and heap dump in Websphere

A Thread dump is a dump of all threads's stack traces, i.e. as if each Thread suddenly threw an Exception and printStackTrace'ed that. This is so that you can see what each thread is doing at some specific point, and is for example very good to catch deadlocks.

A heap dump is a "binary dump" of the full memory the JVM is using, and is for example useful if you need to know why you are running out of memory - in the heap dump you could for example see that you have one billion User objects, even though you should only have a thousand, which points to a memory retention problem.

How can I increase the JVM memory?

When calling java use the -Xmx Flag for example -Xmx512m for 512 megs for the heap size. You may also want to consider the -xms flag to start the heap larger if you are going to have it grow right from the start. The default size is 128megs.

Pass variables between two PHP pages without using a form or the URL of page

Use Sessions.

Page1:

session_start();
$_SESSION['message'] = "Some message"

Page2:

session_start();
var_dump($_SESSION['message']);

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

Space characters may only be encoded as "+" in one context: application/x-www-form-urlencoded key-value pairs.

The RFC-1866 (HTML 2.0 specification), paragraph 8.2.1. subparagraph 1. says: "The form field names and values are escaped: space characters are replaced by `+', and then reserved characters are escaped").

Here is an example of such a string in URL where RFC-1866 allows encoding spaces as pluses: "http://example.com/over/there?name=foo+bar". So, only after "?", spaces can be replaced by pluses (in other cases, spaces should be encoded to %20). This way of encoding form data is also given in later HTML specifications, for example, look for relevant paragraphs about application/x-www-form-urlencoded in HTML 4.01 Specification, and so on.

But, because it's hard to always correctly determine the context, it's the best practice to never encode spaces as "+". It's better to percent-encode all character except "unreserved" defined in RFC-3986, p.2.3. Here is a code example that illustrates what should be encoded. It is given in Delphi (pascal) programming language, but it is very easy to understand how it works for any programmer regardless of the language possessed:

(* percent-encode all unreserved characters as defined in RFC-3986, p.2.3 *)
function UrlEncodeRfcA(const S: AnsiString): AnsiString;
const    
  HexCharArrA: array [0..15] of AnsiChar = '0123456789ABCDEF';
var
  I: Integer;
  c: AnsiChar;
begin
 // percent-encoding, see RFC-3986, p. 2.1
  Result := S;
  for I := Length(S) downto 1 do
  begin
    c := S[I];
    case c of
      'A' .. 'Z', 'a' .. 'z', // alpha
      '0' .. '9',             // digit
      '-', '.', '_', '~':;    // rest of unreserved characters as defined in the RFC-3986, p.2.3
      else
        begin
          Result[I] := '%';
          Insert('00', Result, I + 1);
          Result[I + 1] := HexCharArrA[(Byte(C) shr 4) and $F)];
          Result[I + 2] := HexCharArrA[Byte(C) and $F];
        end;
    end;
  end;
end;

function UrlEncodeRfcW(const S: UnicodeString): AnsiString;
begin
  Result := UrlEncodeRfcA(Utf8Encode(S));
end;

C#: easiest way to populate a ListBox from a List

Is this what you are looking for:

myListBox.DataSource = MyList;

Disabling submit button until all fields have values

Check out this jsfiddle.

HTML

// note the change... I set the disabled property right away
<input type="submit" id="register" value="Register" disabled="disabled" />

JavaScript

(function() {
    $('form > input').keyup(function() {

        var empty = false;
        $('form > input').each(function() {
            if ($(this).val() == '') {
                empty = true;
            }
        });

        if (empty) {
            $('#register').attr('disabled', 'disabled'); // updated according to http://stackoverflow.com/questions/7637790/how-to-remove-disabled-attribute-with-jquery-ie
        } else {
            $('#register').removeAttr('disabled'); // updated according to http://stackoverflow.com/questions/7637790/how-to-remove-disabled-attribute-with-jquery-ie
        }
    });
})()

The nice thing about this is that it doesn't matter how many input fields you have in your form, it will always keep the button disabled if there is at least 1 that is empty. It also checks emptiness on the .keyup() which I think makes it more convenient for usability.

Is it possible to change the content HTML5 alert messages?

You can use customValidity

$(function(){     var elements = document.getElementsByTagName("input");     for (var i = 0; i < elements.length; i++) {         elements[i].oninvalid = function(e) {             e.target.setCustomValidity("This can't be left blank!");         };     } }); 

I think that will work on at least Chrome and FF, I'm not sure about other browsers

JQuery datepicker not working

You did not include the datepicker library

so add

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.11/jquery-ui.min.js"></script>

to your <head> tag

live demo

How do I use Spring Boot to serve static content located in Dropbox folder?

Based on @Dave Syer, @kaliatech and @asmaier answers the springboot v2+ way would be:

@Configuration
@AutoConfigureAfter(DispatcherServletAutoConfiguration.class)
public class StaticResourceConfiguration implements WebMvcConfigurer  {

  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
    String myExternalFilePath = "file:///C:/temp/whatever/m/";

     registry.addResourceHandler("/m/**").addResourceLocations(myExternalFilePath);

  }

}

Why does CSV file contain a blank line in between each data line when outputting with Dictwriter in Python

Changing the 'w' (write) in this line:

output = csv.DictWriter(open('file3.csv','w'), delimiter=',', fieldnames=headers)

To 'wb' (write binary) fixed this problem for me:

output = csv.DictWriter(open('file3.csv','wb'), delimiter=',', fieldnames=headers)

Python v2.75: Open()

Credit to @dandrejvv for the solution in the comment on the original post above.

What data is stored in Ephemeral Storage of Amazon EC2 instance?

Basically, root volume (your entire virtual system disk) is ephemeral, but only if you choose to create AMI backed by Amazon EC2 instance store.

If you choose to create AMI backed by EBS then your root volume is backed by EBS and everything you have on your root volume will be saved between reboots.

If you are not sure what type of volume you have, look under EC2->Elastic Block Store->Volumes in your AWS console and if your AMI root volume is listed there then you are safe. Also, if you go to EC2->Instances and then look under column "Root device type" of your instance and if it says "ebs", then you don't have to worry about data on your root device.

More details here: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/RootDeviceStorage.html

How to add time to DateTime in SQL

For me, this code looks more explicit:

CAST(@SomeDate AS datetime) + CAST(@SomeTime AS datetime)

jQuery Uncaught TypeError: Property '$' of object [object Window] is not a function

This is a syntax issue, the jQuery library included with WordPress loads in "no conflict" mode. This is to prevent compatibility problems with other javascript libraries that WordPress can load. In "no-confict" mode, the $ shortcut is not available and the longer jQuery is used, i.e.

jQuery(document).ready(function ($) {

By including the $ in parenthesis after the function call you can then use this shortcut within the code block.

For full details see WordPress Codex

load scripts asynchronously

Here is a great contemporary solution to the asynchronous script loading though it only address the js script with async false.

There is a great article written in www.html5rocks.com - Deep dive into the murky waters of script loading .

After considering many possible solutions, the author concluded that adding js scripts to the end of body element is the best possible way to avoid blocking page rendering by js scripts.

In the mean time, the author added another good alternate solution for those people who are desperate to load and execute scripts asynchronously.

Considering you've four scripts named script1.js, script2.js, script3.js, script4.js then you can do it with applying async = false:

[
  'script1.js',
  'script2.js',
  'script3.js',
  'script4.js'
].forEach(function(src) {
  var script = document.createElement('script');
  script.src = src;
  script.async = false;
  document.head.appendChild(script);
});

Now, Spec says: Download together, execute in order as soon as all download.

Firefox < 3.6, Opera says: I have no idea what this “async” thing is, but it just so happens I execute scripts added via JS in the order they’re added.

Safari 5.0 says: I understand “async”, but don’t understand setting it to “false” with JS. I’ll execute your scripts as soon as they land, in whatever order.

IE < 10 says: No idea about “async”, but there is a workaround using “onreadystatechange”.

Everything else says: I’m your friend, we’re going to do this by the book.

Now, the full code with IE < 10 workaround:

var scripts = [
  'script1.js',
  'script2.js',
  'script3.js',
  'script4.js'
];
var src;
var script;
var pendingScripts = [];
var firstScript = document.scripts[0];

// Watch scripts load in IE
function stateChange() {
  // Execute as many scripts in order as we can
  var pendingScript;
  while (pendingScripts[0] && ( pendingScripts[0].readyState == 'loaded' || pendingScripts[0].readyState == 'complete' ) ) {
    pendingScript = pendingScripts.shift();
    // avoid future loading events from this script (eg, if src changes)
    pendingScript.onreadystatechange = null;
    // can't just appendChild, old IE bug if element isn't closed
    firstScript.parentNode.insertBefore(pendingScript, firstScript);
  }
}

// loop through our script urls
while (src = scripts.shift()) {
  if ('async' in firstScript) { // modern browsers
    script = document.createElement('script');
    script.async = false;
    script.src = src;
    document.head.appendChild(script);
  }
  else if (firstScript.readyState) { // IE<10
    // create a script and add it to our todo pile
    script = document.createElement('script');
    pendingScripts.push(script);
    // listen for state changes
    script.onreadystatechange = stateChange;
    // must set src AFTER adding onreadystatechange listener
    // else we’ll miss the loaded event for cached scripts
    script.src = src;
  }
  else { // fall back to defer
    document.write('<script src="' + src + '" defer></'+'script>');
  }
}

Can't include C++ headers like vector in Android NDK

It is possible. Here is some step by step:

In $PROJECT_DIR/jni/Application.mk:

APP_STL                 := stlport_static

I tried using stlport_shared, but no luck. Same with libstdc++.

In $PROJECT_DIR/jni/Android.mk:

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE    := hello-jni
LOCAL_SRC_FILES := hello-jni.cpp
LOCAL_LDLIBS    := -llog

include $(BUILD_SHARED_LIBRARY)

Nothing special here, but make sure your files are .cpp.

In $PROJECT_DIR/jni/hello-jni.cpp:

#include <string.h>
#include <jni.h>
#include <android/log.h>

#include <iostream>
#include <vector>


#define  LOG_TAG    "hellojni"
#define  LOGI(...)  __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__)
#define  LOGE(...)  __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__)


#ifdef __cplusplus
extern "C" {
#endif

// Comments omitted.    
void
Java_com_example_hellojni_HelloJni_stringFromJNI( JNIEnv* env,
                                                  jobject thiz )
{
    std::vector<std::string> vec;

    // Go ahead and do some stuff with this vector of strings now.
}

#ifdef __cplusplus
}
#endif

The only thing that bite me here was #ifdef __cplusplus.

Watch the directories.

To compile, use ndk-build clean && ndk-build.

Read a HTML file into a string variable in memory

This is mostly covered already, but one addition as I ran into an issue with the previous code samples.

Dim strHTML as String = System.IO.File.ReadAllText(HttpContext.Current.Server.MapPath("~/folder/filename.html"))

ElasticSearch, Sphinx, Lucene, Solr, Xapian. Which fits for which usage?

Try indextank.

As the case of elastic search, it was conceived to be much easier to use than lucene/solr. It also includes very flexible scoring system that can be tweaked without reindexing.

How many concurrent AJAX (XmlHttpRequest) requests are allowed in popular browsers?

I just checked with www.browserscope.org and with IE9 and Chrome 24 you can have 6 concurrent connections to a single domain, and up to 17 to multiple ones.

Multiple github accounts on the same computer?

If you have created or cloned another repository and you were not able to pull from origin or upstream adding the ssh key at that directory using the following command worked.

This is the error I was getting here:

Warning: Permanently added the RSA host key for IP address '61:fd9b::8c52:7203' to the list of known hosts.
Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

I used the following command, this works:

ssh-add ~/.ssh/id_rsa_YOUR_COMPANY_NAME

How to delete rows from a pandas DataFrame based on a conditional expression

If you want to drop rows of data frame on the basis of some complicated condition on the column value then writing that in the way shown above can be complicated. I have the following simpler solution which always works. Let us assume that you want to drop the column with 'header' so get that column in a list first.

text_data = df['name'].tolist()

now apply some function on the every element of the list and put that in a panda series:

text_length = pd.Series([func(t) for t in text_data])

in my case I was just trying to get the number of tokens:

text_length = pd.Series([len(t.split()) for t in text_data])

now add one extra column with the above series in the data frame:

df = df.assign(text_length = text_length .values)

now we can apply condition on the new column such as:

df = df[df.text_length  >  10]
def pass_filter(df, label, length, pass_type):

    text_data = df[label].tolist()

    text_length = pd.Series([len(t.split()) for t in text_data])

    df = df.assign(text_length = text_length .values)

    if pass_type == 'high':
        df = df[df.text_length  >  length]

    if pass_type == 'low':
        df = df[df.text_length  <  length]

    df = df.drop(columns=['text_length'])

    return df

"Are you missing an assembly reference?" compile error - Visual Studio

In my case it was a project defined using Target Framework: ".NET Framework 4.0 Client Profile " that tried to reference dll projects defined using Target Framework: ".NET Framework 4.0".

Once I changed the project settings to use Target Framework: ".NET Framework 4.0" everything was built nicely.

Right Click the project->Properties->Application->Target Framework

PHP: How to get referrer URL?

If $_SERVER['HTTP_REFERER'] variable doesn't seems to work, then you can either use Google Analytics or AddThis Analytics.

Can MySQL convert a stored UTC time to local timezone?

I propose to use

SET time_zone = 'proper timezone';

being done once right after connect to database. and after this all timestamps will be converted automatically when selecting them.

Correct use for angular-translate in controllers

To make a translation in the controller you could use $translate service:

$translate(['COMMON.SI', 'COMMON.NO']).then(function (translations) {
    vm.si = translations['COMMON.SI'];
    vm.no = translations['COMMON.NO'];
});

That statement only does the translation on controller activation but it doesn't detect the runtime change in language. In order to achieve that behavior, you could listen the $rootScope event: $translateChangeSuccess and do the same translation there:

    $rootScope.$on('$translateChangeSuccess', function () {
        $translate(['COMMON.SI', 'COMMON.NO']).then(function (translations) {
            vm.si = translations['COMMON.SI'];
            vm.no = translations['COMMON.NO'];
        });
    });

Of course, you could encapsulate the $translateservice in a method and call it in the controller and in the $translateChangeSucesslistener.

How to assign an exec result to a sql variable?

I always use the return value to pass back error status. If you need to pass back one value I'd use an output parameter.

sample stored procedure, with an OUTPUT parameter:

CREATE PROCEDURE YourStoredProcedure 
(
    @Param1    int
   ,@Param2    varchar(5)
   ,@Param3    datetime OUTPUT
)
AS
IF ISNULL(@Param1,0)>5
BEGIN
    SET @Param3=GETDATE()
END
ELSE
BEGIN
    SET @Param3='1/1/2010'
END
RETURN 0
GO

call to the stored procedure, with an OUTPUT parameter:

DECLARE @OutputParameter  datetime
       ,@ReturnValue      int

EXEC @ReturnValue=YourStoredProcedure 1,null, @OutputParameter OUTPUT
PRINT @ReturnValue
PRINT CONVERT(char(23),@OutputParameter ,121)

OUTPUT:

0
2010-01-01 00:00:00.000

Null check in an enhanced for loop

Use, CollectionUtils.isEmpty(Collection coll) method which is Null-safe check if the specified collection is empty.

for this import org.apache.commons.collections.CollectionUtils.

Maven dependency

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-collections4</artifactId>
    <version>4.0</version>
</dependency>

I forgot the password I entered during postgres installation

If you are running postgresql on mac os, try these:

  1. Edit the pg_hba.conf file

  2. sudo vi /Library/PostgreSQL/9.2/data/pg_hba.conf

  3. Change the "md5" method for all users to "trust" near the bottom of the file

  4. Find the name of the service

  5. ls /Library/LaunchDaemons

  6. Look for postgresql

  7. Stop the postgresql service

  8. sudo launchctl stop com.edb.launchd.postgresql-9.2

  9. Start the postgresql service

  10. sudo launchctl start com.edb.launchd.postgresql-9.2

  11. Start psql session as postgres

  12. psql -U postgres

  13. (shouldn't ask for password because of 'trust' setting)

  14. Reset password in psql session by typing

  15. ALTER USER postgres with password 'secure-new-password';

  16. \q
  17. enter

  18. Edit the pg_hba.conf file

  19. Switch it back to 'md5'

  20. Restart services again

How to get File Created Date and Modified Date

You can do that using FileInfo class:

FileInfo fi = new FileInfo("path");
var created = fi.CreationTime;
var lastmodified = fi.LastWriteTime;

Reading and writing binary file

It can be done with simple commands in the following snippet.

Copies the whole file of any size. No size constraint!

Just use this. Tested And Working!!

#include<iostream>
#include<fstream>
using namespace std;
int main()
{
  ifstream infile;
  infile.open("source.pdf",ios::binary|ios::in);

  ofstream outfile;
  outfile.open("temppdf.pdf",ios::binary|ios::out);

  int buffer[2];
  while(infile.read((char *)&buffer,sizeof(buffer)))
  {
      outfile.write((char *)&buffer,sizeof(buffer));
  }

  infile.close();
  outfile.close();
  return 0;
}

Having a smaller buffer size would be helpful in copying tiny files. Even "char buffer[2]" would do the job.

Why is this rsync connection unexpectedly closed on Windows?

This error message probably means that you either mistyped the server name or forgot to start an ssh server at server. Make absolutely certain that an ssh server is running on the server at port 22, and that it's not firewalled. You can test that with ssh user@server.

How to convert BigInteger to String in java

When constructing a BigInteger with a string, the string must be formatted as a decimal number. You cannot use letters, unless you specify a radix in the second argument, you can specify up to 36 in the radix. 36 will give you alphanumeric characters only [0-9,a-z], so if you use this, you will have no formatting. You can create: new BigInteger("ihavenospaces", 36) Then to convert back, use a .toString(36)

BUT TO KEEP FORMATTING: Use the byte[] method that a couple people mentioned. That will pack the data with formatting into the smallest size, and allow you to keep track of number of bytes easily

That should be perfect for an RSA public key crypto system example program, assuming you keep the number of bytes in the message smaller than the number of bytes of PQ

(I realize this thread is old)

How to hide "Showing 1 of N Entries" with the dataTables.js library

If you also need to disable the drop-down (not to hide the text) then set the lengthChange option to false

$('#datatable').dataTable( {
  "lengthChange": false
} );

Works for DataTables 1.10+

Read more in the official documentation

Java FileWriter how to write to next Line

.newLine() is the best if your system property line.separator is proper . and sometime you don't want to change the property runtime . So alternative solution is appending \n

Read from database and fill DataTable

Connection object is for illustration only. The DataAdapter is the key bit:

Dim strSql As String = "SELECT EmpCode,EmpID,EmpName FROM dbo.Employee"
Dim dtb As New DataTable
Using cnn As New SqlConnection(connectionString)
  cnn.Open()
  Using dad As New SqlDataAdapter(strSql, cnn)
    dad.Fill(dtb)
  End Using
  cnn.Close()
End Using

POST JSON fails with 415 Unsupported media type, Spring 3 mvc

I resolved this issue by adding jackson-json data binding to my pom.

<dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.6.3</version>
</dependency>

Android button background color

If you want to keep the general styling (rounded corners etc.) and just change the background color then I use the backgroundTint property

android:backgroundTint="@android:color/holo_green_light"

Android - styling seek bar

Android seekbar custom material style, for other seekbar customizations http://www.zoftino.com/android-seekbar-and-custom-seekbar-examples

<style name="MySeekBar" parent="Widget.AppCompat.SeekBar">
    <item name="android:progressBackgroundTint">#f4511e</item>
    <item name="android:progressTint">#388e3c</item>
    <item name="android:colorControlActivated">#c51162</item>
</style>

seekbar custom material style

Use of Custom Data Types in VBA

It looks like you want to define Truck as a Class with properties NumberOfAxles, AxleWeights & AxleSpacings.

This can be defined in a CLASS MODULE (here named clsTrucks)

Option Explicit

Private tID As String
Private tNumberOfAxles As Double
Private tAxleSpacings As Double


Public Property Get truckID() As String
    truckID = tID
End Property

Public Property Let truckID(value As String)
    tID = value
End Property

Public Property Get truckNumberOfAxles() As Double
    truckNumberOfAxles = tNumberOfAxles
End Property

Public Property Let truckNumberOfAxles(value As Double)
    tNumberOfAxles = value
End Property

Public Property Get truckAxleSpacings() As Double
    truckAxleSpacings = tAxleSpacings
End Property

Public Property Let truckAxleSpacings(value As Double)
    tAxleSpacings = value
End Property

then in a MODULE the following defines a new truck and it's properties and adds it to a collection of trucks and then retrieves the collection.

Option Explicit

Public TruckCollection As New Collection

Sub DefineNewTruck()
Dim tempTruck As clsTrucks
Dim i As Long

    'Add 5 trucks
    For i = 1 To 5
        Set tempTruck = New clsTrucks
        'Random data
        tempTruck.truckID = "Truck" & i
        tempTruck.truckAxleSpacings = 13.5 + i
        tempTruck.truckNumberOfAxles = 20.5 + i

        'tempTruck.truckID is the collection key
        TruckCollection.Add tempTruck, tempTruck.truckID
    Next i

    'retrieve 5 trucks
    For i = 1 To 5
        'retrieve by collection index
        Debug.Print TruckCollection(i).truckAxleSpacings
        'retrieve by key
        Debug.Print TruckCollection("Truck" & i).truckAxleSpacings

    Next i

End Sub

There are several ways of doing this so it really depends on how you intend to use the data as to whether an a class/collection is the best setup or arrays/dictionaries etc.

How to pass password to scp?

Use sshpass:

sshpass -p "password" scp -r [email protected]:/some/remote/path /some/local/path

or so the password does not show in the bash history

sshpass -f "/path/to/passwordfile" scp -r [email protected]:/some/remote/path /some/local/path

The above copies contents of path from the remote host to your local.

Install :

  • ubuntu/debian
    • apt install sshpass
  • centos/fedora
    • yum install sshpass
  • mac w/ macports
    • port install sshpass
  • mac w/ brew
    • brew install https://raw.githubusercontent.com/kadwanev/bigboybrew/master/Library/Formula/sshpass.rb

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

You must write onActivityResult() in your FirstActivity.Java as follows

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
   super.onActivityResult(requestCode, resultCode, data);
}

So this will call your fragment's onActivityResult()

Edit: the solution is to replace getActivity().startActivityForResult(i, 1); with startActivityForResult(i, 1);

validate a dropdownlist in asp.net mvc

For ListBox / DropDown in MVC5 - i've found this to work for me sofar:

in Model:

[Required(ErrorMessage = "- Select item -")]
 public List<string> SelectedItem { get; set; }
 public List<SelectListItem> AvailableItemsList { get; set; }

in View:

@Html.ListBoxFor(model => model.SelectedItem, Model.AvailableItemsList)
@Html.ValidationMessageFor(model => model.SelectedItem, "", new { @class = "text-danger" })

Storing image in database directly or as base64 data?

I contend that images (files) are NOT usually stored in a database base64 encoded. Instead, they are stored in their raw binary form in a binary (blob) column (or file).

Base64 is only used as a transport mechanism, not for storage. For example, you can embed a base64 encoded image into an XML document or an email message.

Base64 is also stream friendly. You can encode and decode on the fly (without knowing the total size of the data).

While base64 is fine for transport, do not store your images base64 encoded.

Base64 provides no checksum or anything of any value for storage.

Base64 encoding increases the storage requirement by 33% over a raw binary format. It also increases the amount of data that must be read from persistent storage, which is still generally the largest bottleneck in computing. It's generally faster to read less bytes and encode them on the fly. Only if your system is CPU bound instead of IO bound, and you're regularly outputting the image in base64, then consider storing in base64.

Inline images (base64 encoded images embedded in HTML) are a bottleneck themselves--you're sending 33% more data over the wire, and doing it serially (the web browser has to wait on the inline images before it can finish downloading the page HTML).

If you still wish to store images base64 encoded, please, whatever you do, make sure you don't store base64 encoded data in a UTF8 column then index it.

codes for ADD,EDIT,DELETE,SEARCH in vb2010

A good resource start off point would be MSDN as your looking into a microsoft product

Javascript window.open pass values using POST

Even though this question was long time ago, thanks all for the inputs that helping me out a similar problem. I also made a bit modification based on the others' answers here and making multiple inputs/valuables into a Single Object (json); and hope this helps someone.

js:

//example: params={id:'123',name:'foo'};

mapInput.name = "data";
mapInput.value = JSON.stringify(params); 

php:

$data=json_decode($_POST['data']); 

echo $data->id;
echo $data->name;

CSS transition between left -> right and top -> bottom positions

This worked for me on Chromium. The % for translate is in reference to the size of the bounding box of the element it is applied to so it perfectly gets the element to the lower right edge while not having to switch which property is used to specify it's location.

topleft {
  top: 0%;
  left: 0%;
}
bottomright {
  top: 100%;
  left: 100%;
  -webkit-transform: translate(-100%,-100%);
}

jquery select element by xpath

If you are debugging or similar - In chrome developer tools, you can simply use

$x('/html/.//div[@id="text"]')

The communication object, System.ServiceModel.Channels.ServiceChannel, cannot be used for communication

To prevent the Server from fall in Fault state, you have to ensure that no unhandled exception is raised. If WCF sees an unexpected Exception, no more calls are accepted - safety first.
Two possibilties to avoid this behaviour:

  1. Use a FaultException (this one is not unexpected for WCF, so the WCF knows that the server has still a valid state)
    instead of

    throw new Exception("Error xy in my function")  
    

    use always

    throw new FaultException("Error xy in my function")  
    

    perhaps you can try..catch the whole block and throw a FaultException in all cases of an Exception

    try   
    {  
        ... some code here   
    }
    catch (Exception ex)
    {  
        throw new FaultException(ex.Message)   
    }
    
  2. Tell WCF to handle all Exceptions using an Errorhandler. This can be done in several ways, I chose a simple one using an Attribute:
    All we have to do more, is to use the attribute [SvcErrorHandlerBehaviour] on the wanted Service Implementation

    using System;
    using System.Collections.ObjectModel;
    using System.ServiceModel;
    using System.ServiceModel.Channels;
    using System.ServiceModel.Description;
    using System.ServiceModel.Dispatcher;
    
    namespace MainService.Services
    {
        /// <summary>
        /// Provides FaultExceptions for all Methods Calls of a Service that fails with an Exception
        /// </summary>
        public class SvcErrorHandlerBehaviourAttribute : Attribute, IServiceBehavior
        {
            public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
            { } //implementation not needed
    
            public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints,
                                             BindingParameterCollection bindingParameters)
            { } //implementation not needed
    
            public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
            {
                foreach (ChannelDispatcherBase chanDispBase in serviceHostBase.ChannelDispatchers)
                {
                    ChannelDispatcher channelDispatcher = chanDispBase as ChannelDispatcher;
                    if (channelDispatcher == null)
                        continue;
                    channelDispatcher.ErrorHandlers.Add(new SvcErrorHandler());
                }
            }
        }
    
        public class SvcErrorHandler: IErrorHandler
        {
            public bool HandleError(Exception error)
            {
                //You can log th message if you want.
                return true;
            }
    
            public void ProvideFault(Exception error, MessageVersion version, ref Message msg)
            {
                if (error is FaultException)
                    return;
    
                FaultException faultException = new FaultException(error.Message);
                MessageFault messageFault = faultException.CreateMessageFault();
                msg = Message.CreateMessage(version, messageFault, faultException.Action);
            }
        }
    }
    

This is an easy example, you can dive deeper into IErrorhandler by not using the naked FaultException, but a FaultException<> with a type that provides additional info see IErrorHandler for an detailed example.

How to set default Checked in checkbox ReactJS?

Here's a code I did some time ago, it might be useful. you have to play with this line => this.state = { checked: false, checked2: true};

class Componente extends React.Component {
  constructor(props) {
    super(props);

    this.state = { checked: false, checked2: true};
    this.handleChange = this.handleChange.bind(this);
    this.handleChange2 = this.handleChange2.bind(this);

  }  

  handleChange() {
    this.setState({
        checked: !this.state.checked      
    })
  }

  handleChange2() {
    this.setState({
        checked2: !this.state.checked2      
    })
  }

  render() {
    const togglecheck1 = this.state.checked ? 'hidden-check1' : '';
    const togglecheck2 = this.state.checked2 ? 'hidden-check2' : '';

    return <div>
        <div>
        <label>Check 1</label>
        <input type="checkbox" id="chk1"className="chk11" checked={ this.state.checked } onChange={ this.handleChange } />
        <label>Check 2</label>
        <input type="checkbox" id="chk2" className="chk22" checked={ this.state.checked2 } onChange={ this.handleChange2 } />
      </div>

      <div className={ togglecheck1 }>show hide div with check 1</div>
      <div className={ togglecheck2 }>show hide div with check 2</div>

    </div>;
  }
}

ReactDOM.render(
  <Componente />,
  document.getElementById('container')
);

CSS

.hidden-check1 {
  display: none;  
  }

.hidden-check2 {
  visibility: hidden;
}

HTML

  <div id="container">
      <!-- This element's contents will be replaced with your component. -->
  </div>

here's the codepen => http://codepen.io/parlop/pen/EKmaWM

using jQuery .animate to animate a div from right to left?

I think the reason it doesn't work has something to do with the fact that you have the right position set, but not the left.

If you manually set the left to the current position, it seems to go:

Live example: http://jsfiddle.net/XqqtN/

var left = $('#coolDiv').offset().left;  // Get the calculated left position

$("#coolDiv").css({left:left})  // Set the left to its calculated position
             .animate({"left":"0px"}, "slow");

EDIT:

Appears as though Firefox behaves as expected because its calculated left position is available as the correct value in pixels, whereas Webkit based browsers, and apparently IE, return a value of auto for the left position.

Because auto is not a starting position for an animation, the animation effectively runs from 0 to 0. Not very interesting to watch. :o)

Setting the left position manually before the animate as above fixes the issue.


If you don't like cluttering the landscape with variables, here's a nice version of the same thing that obviates the need for a variable:

$("#coolDiv").css('left', function(){ return $(this).offset().left; })
             .animate({"left":"0px"}, "slow");    ?

Java null check why use == instead of .equals()

In Java 0 or null are simple types and not objects.

The method equals() is not built for simple types. Simple types can be matched with ==.

Customizing the template within a Directive

Tried to use the solution proposed by Misko, but in my situation, some attributes, which needed to be merged into my template html, were themselves directives.

Unfortunately, not all of the directives referenced by the resulting template did work correctly. I did not have enough time to dive into angular code and find out the root cause, but found a workaround, which could potentially be helpful.

The solution was to move the code, which creates the template html, from compile to a template function. Example based on code from above:

    angular.module('formComponents', [])
  .directive('formInput', function() {
    return {
        restrict: 'E',
        template: function(element, attrs) {
           var type = attrs.type || 'text';
            var required = attrs.hasOwnProperty('required') ? "required='required'" : "";
            var htmlText = '<div class="control-group">' +
                '<label class="control-label" for="' + attrs.formId + '">' + attrs.label + '</label>' +
                    '<div class="controls">' +
                    '<input type="' + type + '" class="input-xlarge" id="' + attrs.formId + '" name="' + attrs.formId + '" ' + required + '>' +
                    '</div>' +
                '</div>';
             return htmlText;
        }
        compile: function(element, attrs)
        {
           //do whatever else is necessary
        }
    }
})

Using Oracle to_date function for date string with milliseconds

You have to change date class to timestamp.

String s=df.format(c.getTime());
java.util.Date parsedUtilDate = df.parse(s);  
java.sql.Timestamp timestamp = new java.sql.Timestamp(parsedUtilDate.getTime());