Programs & Examples On #Tortoisesvn

TortoiseSVN is a Subversion client for Windows, implemented as a shell extension.

Remove file from SVN repository without deleting local copy

Rename your file, commit the changes including the "deleted" file, and don't include the new (renamed) file.

Rename your file back.

Update Item to Revision vs Revert to Revision

The text from the Tortoise reference:

Update item to revision Update your working copy to the selected revision. Useful if you want to have your working copy reflect a time in the past, or if there have been further commits to the repository and you want to update your working copy one step at a time. It is best to update a whole directory in your working copy, not just one file, otherwise your working copy could be inconsistent.

If you want to undo an earlier change permanently, use Revert to this revision instead.

Revert to this revision Revert to an earlier revision. If you have made several changes, and then decide that you really want to go back to how things were in revision N, this is the command you need. The changes are undone in your working copy so this operation does not affect the repository until you commit the changes. Note that this will undo all changes made after the selected revision, replacing the file/folder with the earlier version.

If your working copy is in an unmodified state, after you perform this action your working copy will show as modified. If you already have local changes, this command will merge the undo changes into your working copy.

What is happening internally is that Subversion performs a reverse merge of all the changes made after the selected revision, undoing the effect of those previous commits.

If after performing this action you decide that you want to undo the undo and get your working copy back to its previous unmodified state, you should use TortoiseSVN ? Revert from within Windows Explorer, which will discard the local modifications made by this reverse merge action.

If you simply want to see what a file or folder looked like at an earlier revision, use Update to revision or Save revision as... instead.

Folder is locked and I can't unlock it

In addition to David M's answer, while doing cleanup -> check 'break locks' option. This will ensure release of locks. Then do svn update. This worked for me.

Working copy locked error in tortoise svn while committing

If this (https://stackoverflow.com/a/11764922/3045875) does not help: Check if another SVN tool is interfering and close the tool. We just struggled a couple of hours at merging using TortoiseSVN and had dozens of such lock errors. Eventually we figured that Matlabs SVN integration is interfering and after closing it all worked out.

What ports need to be open for TortoiseSVN to authenticate (clear text) and commit?

What's the first part of your Subversion repository URL?

  • If your URL looks like: http://subversion/repos/, then you're probably going over Port 80.
  • If your URL looks like: https://subversion/repos/, then you're probably going over Port 443.
  • If your URL looks like: svn://subversion/, then you're probably going over Port 3690.
  • If your URL looks like: svn+ssh://subversion/repos/, then you're probably going over Port 22.
  • If your URL contains a port number like: http://subversion/repos:8080, then you're using that port.

I can't guarantee the first four since it's possible to reconfigure everything to use different ports, of if you go through a proxy of some sort.

If you're using a VPN, you may have to configure your VPN client to reroute these to their correct ports. A lot of places don't configure their correctly VPNs to do this type of proxying. It's either because they have some sort of anal-retentive IT person who's being overly security conscious, or because they simply don't know any better. Even worse, they'll give you a client where this stuff can't be reconfigured.

The only way around that is to log into a local machine over the VPN, and then do everything from that system.

SVN commit command

Command-line SVN

You need to add your files to your working copy, before you commit your changes to the repository:

svn add <file|folder>

Afterwards:

svn commit

See here for detailed information about svn add.

TortoiseSVN

It works with TortoiseSVN, because it adds the file to your working copy automatically (commit dialog):

If you want to include an unversioned file, just check that file to add it to the commit.

See: TortoiseSVN: Committing Your Changes To The Repository

Working copy XXX locked and cleanup failed in SVN

I had this under TortoiseSVN and the error was related to a new directory I'd created under a new project. I had just created this project, so there was no way this directory had existed before. I looked in the repository browser and the new folder was indeed already in the repository, but TortoiseSVN didn't show it as committed.

In order to get around it, since I'd just created the folder anyway, I deleted it in the repository, and then did a commit. It worked fine.

Since I did this outside of Visual Studio, I then had to restart Visual Studio for it to figure everything out again.

How do I create a new branch?

In the Repository Browser of TortoiseSVN, find the branch that you want to create the new branch from. Right-click, Copy To.... and enter the new branch path. Now you can "switch" your local WC to that branch.

Resolving tree conflict

What you can do to resolve your conflict is

svn resolve --accept working -R <path>

where <path> is where you have your conflict (can be the root of your repo).

Explanations:

  • resolve asks svn to resolve the conflict
  • accept working specifies to keep your working files
  • -R stands for recursive

Hope this helps.

EDIT:

To sum up what was said in the comments below:

  • <path> should be the directory in conflict (C:\DevBranch\ in the case of the OP)
  • it's likely that the origin of the conflict is
    • either the use of the svn switch command
    • or having checked the Switch working copy to new branch/tag option at branch creation
  • more information about conflicts can be found in the dedicated section of Tortoise's documentation.
  • to be able to run the command, you should have the CLI tools installed together with Tortoise:

Command line client tools

SVN Error: Commit blocked by pre-commit hook (exit code 1) with output: Error: n/a (6)

If you are getting following exception:

Error: Commit failed (details follow):
Error: Commit blocked by pre-commit hook (exit code 1) with output:
Error: svnlook: Path 'trunk/Development/ProjectName' is not a file

Then first check-in all the the directories and then all the files. It will work.

Reverting to a previous revision using TortoiseSVN

In the TortoiseSVN context menu, select 'Update to Revision', enter the desired revision number, and voilà :)

TortoiseSVN Error: "OPTIONS of 'https://...' could not connect to server (...)"

I realize this is an old question, but the same issue happened to me, but for a completely different reason.

It could be that cvs-dude changed certificates, so it no longer matches the certificate you have cached.

You can go to TortoiseSVN->Settings->Saved Data and click the 'Clear' button next to 'Authentication data' and then try again.

svn cleanup: sqlite: database disk image is malformed

cd to folder containing .svn

rm -rf .svn
svn co http://mon.svn/mondepot/ . --force

Where is svn.exe in my machine?

Depending on what you need to do, automating TortoiseSVN may be a good solution. For example, the following will update a repository and close the TortoiseSVN window if there were no errors or conflicts:

TortoiseProc.exe /command:update /path:"c:\path\to\repo\" /closeonend:2

How to change users in TortoiseSVN

Replace the line in htpasswd file:

Go to: http://www.htaccesstools.com/htpasswd-generator-windows/

(If the link is expired, search another generator from google.com.)

Enter your username and password. The site will generate an encrypted line. Copy that line and replace it with the previous line in the file "repo/htpasswd".

You might also need to Clear the 'Authentication data' from TortoiseSVN ? Settings ? Saved Data.

Working Copy Locked

You can fix it with only one step.

Step 1 : Open terminal and go to your project then fire command "svn cleanup" then "svn update"

SVN "Already Locked Error"

I am not using AnkhSVN but got a similar problem after cancelling a Tortoise SVN update. It left two directories "already locked". Similar to Roman C's solution. Use Get lock to to lock one file in each directory that is "already locked" and then release those locks, then do a cleanup on the highest directory. That seemed to fix the problem.

What equivalents are there to TortoiseSVN, on Mac OSX?

My previous version of this answer had links, that kept becoming dead.
So, I've pointed it to the internet archive to preserve the original answer.

Subversion client releases for Windows and Macintosh

Wiki - Subversion clients comparison table

SVN Commit failed, access forbidden

If the problem lies client side, this could be one of the causes of the error.

On clients TortoiseSVN saves client credentials under

Tortoise settings / saved data / authentication data.

I got the same error trying to commit my files, but my credentials were changed. Clearing this cache here will give you a popup on next commit attempt for re-entering your correct credentials.

SVN icon overlays not showing properly

They showed up after installing Ankh SVN

Using TortoiseSVN how do I merge changes from the trunk to a branch and vice versa?

Take a look at svnmerge.py. It's command-line, can't be invoked by TortoiseSVN, but it's more powerful. From the FAQ:

Traditional subversion will let you merge changes, but it doesn't "remember" what you've already merged. It also doesn't provide a convenient way to exclude a change set from being merged. svnmerge.py automates some of the work, and simplifies it. Svnmerge also creates a commit message with the log messages from all of the things it merged.

Error "can't use subversion command line client : svn" when opening android project checked out from svn

Saw your problems.

Solutions:

First Download Subversion 1.8.13 ( 1.8 ) client Download link (https://subversion.apache.org/packages.html) at the time of this post the android studio version is less than 1.4 in my case 1.3.2 so you must avoid the issues here subversion command line client version is too old so just download the 1.8 preferably.

enter image description here

Then unzipped in a folder. There will have one folder "bin".

Then

Go to settings - > Version control -> Subversion

Copy the url of your downloaded svn.exe that is in bin folder that you have downloaded.

follow the picture:

enter image description here

Don't forget to give the end name like svn.exe last as per image.

Apply -> Ok

Restart your android studio now.

Happy Coding!

svn list of files that are modified in local copy

svn status | grep ^M will list files which are modified. M - stands for modified :)

What is the correct way to restore a deleted file from SVN?

If you're using Tortoise SVN, you should be able to revert changes from just that revision into your working copy (effectively performing a reverse-merge), then do another commit to re-add the file. Steps to follow are:

  1. Browse to folder in working copy where you deleted the file.
  2. Go to repo-browser.
  3. Browse to revision where you deleted the file.
  4. In the change list, find the file you deleted.
  5. Right click on the file and go to "Revert changes from this revision".
  6. This will restore the file to your working copy, keeping history.
  7. Commit the file to add it back into your repository.

How to checkout a specific Subversion revision from the command line?

You should never use TortoiseProc.exe as a command-line Subversion client! TortoiseProc should be utilized only for automating TortoiseSVN's GUI. See the note in TortoiseSVN's Manual:

Remember that TortoiseSVN is a GUI client, and this automation guide shows you how to make the TortoiseSVN dialogs appear to collect user input. If you want to write a script which requires no input, you should use the official Subversion command line client instead.

Use the Subversion command-line svn.exe client. With the command-line client, you can

You may notice that with svn checkout and svn export you can enter REV number as --revision REV argument and as trailing @REV after URL. The first one is called operative revision, and the second one is called peg revision. Read SVNBook for more information about peg and operative revisions concept.

TortoiseSVN icons not showing up under Windows 7

They display fine here. Are you using the 64-bit version of Windows 7 along with the 32-bit version of TortoiseSVN? If so, then they will only show up in the 32-bit Explorer (or in the CFDs of 32-bit applications). You can install both 32-bit and 64-bit versions side-by-side, though.

How do you move a file?

If I'm not wrong starting from version 1.5 SVN can track moved files\folders. In TortoiseSVN use can move file via drag&drop.

Using TortoiseSVN via the command line

My solution was to use DOSKEY to set up some aliases to for the commands I use the most:

DOSKEY svc=TortoiseProc.exe /command:commit /path:.
DOSKEY svu=TortoiseProc.exe /command:update /path:.
DOSKEY svl=TortoiseProc.exe /command:log /path:.
DOSKEY svd=TortoiseProc.exe /command:diff /path:$*

Google "doskey persist" for tips on how to set up a .cmd file that runs every time you open the command prompt like a .*rc file in Unix.

How to change password using TortoiseSVN?

I changed windows password today then Tortoise declined to connect me to SVN server. I got around it by opening a Dos box and doing an "svn co ...". It prompted for the new credential then happily did its work. After that, Tortoise works also.

How do I download code using SVN/Tortoise from Google Code?

If you have Tortoise SVN, like I do, take the google link, and ONLY copy the URL.

Regular- (svn checkout http://wittytwitter.googlecode.com/svn/trunk/ wittytwitter-read-only)

Modified to URL- (http://wittytwitter.googlecode.com/svn/trunk/ wittytwitter)

Create a folder, right click the empty space. You can Browse Repo or just download it all via checkout.

I don't know whether you have to be a Google member or not, but I signed up just in case. Have fun with the code.

Misanthropy

SVN Repository on Google Drive or DropBox

For free private SVN hosting try the following:

Or use BitBucket for free private git/mercurial repositories

Cannot connect to repo with TortoiseSVN

You need to determine whether this is a problem with TortoiseSVN, your Subversion repository, or your network connection.

  • First of all, check your URL. I never used User-Friendly SVN, so I don't know what it does to the Apache httpd configuration. However, the standard Apache configuration for multiple repositories is usually http://<server>/svn/<module> and not http://<server>/svn/usvn/<module>. Is that /usvn/ directory suppose to be there?
    • By the way, how was Apache configured? Does User-Friendly SVN do that too, or does it merely allow you to configure the repositories? Are you using Visual-SVN, or did someone manually configure Apache httpd?
  • If the URL is correct, try pinging your Subversion server. Can you ping it from your Windows box? If not, you have a network issue. For some reason that IP address isn't even reachable from your client box.
  • Try opening a browser, and putting the URL of the Subversion repository into the window. This should work. If it does, the issue is probably with TortoiseSVN. Download a command line Subversion client, and see if you can checkout with that.
  • Try using the same URL on another box. Can you checkout from there? If so, it points to a problem with the network.

Subversion stuck due to "previous operation has not finished"?

I had the same issue, what worked for me:

  1. Copy your folders and files to another place, say to a folder (I changed my files recently and the commitment failed and led to the addressed problem)
  2. check out a new working copy
  3. copy your changed files from folder to your working copy and override existing files. Commiting / Updating should work now

TortoiseSVN icons overlay not showing after updating to Windows 10

Check your monitor scaling.

My problem turned out to be this:

It turned out to be different DPI-scaling on the primary and secondary monitor. When the secondary monitor was set to 125% (same as the primary monitor) the icons appeared again.

Answer actually provided by User3163 posting on SuperUser.com

ASP.NET Display "Loading..." message while update panel is updating

You can use code as below when

using Image as Loading

<asp:UpdateProgress id="updateProgress" runat="server">
    <ProgressTemplate>
        <div style="position: fixed; text-align: center; height: 100%; width: 100%; top: 0; right: 0; left: 0; z-index: 9999999; background-color: #000000; opacity: 0.7;">
            <asp:Image ID="imgUpdateProgress" runat="server" ImageUrl="~/images/ajax-loader.gif" AlternateText="Loading ..." ToolTip="Loading ..." style="padding: 10px;position:fixed;top:45%;left:50%;" />
        </div>
    </ProgressTemplate>
</asp:UpdateProgress>

using Text as Loading

<asp:UpdateProgress id="updateProgress" runat="server">
    <ProgressTemplate>
        <div style="position: fixed; text-align: center; height: 100%; width: 100%; top: 0; right: 0; left: 0; z-index: 9999999; background-color: #000000; opacity: 0.7;">
            <span style="border-width: 0px; position: fixed; padding: 50px; background-color: #FFFFFF; font-size: 36px; left: 40%; top: 40%;">Loading ...</span>
        </div>
    </ProgressTemplate>
</asp:UpdateProgress>

Represent space and tab in XML tag

I think you could use an actual space or tab directly in XML document, but if you are looking for special characters to represent them so that text processors can't mess them up, then it's:

space = &#032;
tab   = &#009;

Get month and year from a datetime in SQL Server 2005

How about this?

Select DateName( Month, getDate() ) + ' ' + DateName( Year, getDate() )

How do I import a .dmp file into Oracle?

.dmp files are dumps of oracle databases created with the "exp" command. You can import them using the "imp" command.

If you have an oracle client intalled on your machine, you can executed the command

imp help=y

to find out how it works. What will definitely help is knowing from wich schema the data was exported and what the oracle version was.

Why are #ifndef and #define used in C++ header files?

This prevent from the multiple inclusion of same header file multiple time.

#ifndef __COMMON_H__
#define __COMMON_H__
//header file content
#endif

Suppose you have included this header file in multiple files. So first time __COMMON_H__ is not defined, it will get defined and header file included.

Next time __COMMON_H__ is defined, so it will not include again.

Mean of a column in a data frame, given the column's name

Use summarise in the dplyr package:

library(dplyr)
summarise(df, Average = mean(col_name, na.rm = T))

note: dplyr supports both summarise and summarize.

PDO get the last ID inserted

You can get the id of the last transaction by running lastInsertId() method on the connection object($conn).

Like this $lid = $conn->lastInsertId();

Please check out the docs https://www.php.net/manual/en/language.oop5.basic.php

ERROR 2003 (HY000): Can't connect to MySQL server on localhost (10061)

I will advise to use first check if my.ini exist in mysql folder in c drive or in windows folder mysqld -install (Service successfully installed) mysqld --initialize (no prompt) Also another advise is not to use mysql 8, since it is not compatible with wordpress or any other opensource yet, there are lot of changes between version 5 and version 8, so if you are using mysql please use version 5.x.

Why is Dictionary preferred over Hashtable in C#?

People are saying that a Dictionary is the same as a hash table.

This is not necessarily true. A hash table is one way to implement a dictionary. A typical one at that, and it may be the default one in .NET in the Dictionary class, but it's not by definition the only one.

You could equally well implement a dictionary using a linked list or a search tree, it just wouldn't be as efficient (for some metric of efficient).

How do I output the difference between two specific revisions in Subversion?

To compare entire revisions, it's simply:

svn diff -r 8979:11390


If you want to compare the last committed state against your currently saved working files, you can use convenience keywords:

svn diff -r PREV:HEAD

(Note, without anything specified afterwards, all files in the specified revisions are compared.)


You can compare a specific file if you add the file path afterwards:

svn diff -r 8979:HEAD /path/to/my/file.php

Laravel 5 route not defined, while it is?

On a side note:

I had the similar issues where many times I get the error Action method not found, but clearly it is define in controller.

The issue is not in controller, but rather how routes.php file is setup

Lets say you have Controller class set as a resource in route.php file

Route::resource('example', 'ExampleController');

then '/example' will have all RESTful Resource listed here: http://laravel.com/docs/5.0/controllers#restful-resource-controllers

but now you want to have some definition in form e.g: 'action'=>'ExampleController@postStore' then you have to change this route (in route.php file) to:

Route::controller('example', 'ExampleController');

How can I center an image in Bootstrap?

Since the img is an inline element, Just use text-center on it's container. Using mx-auto will center the container (column) too.

<div class="row">
    <div class="col-4 mx-auto text-center">
        <img src="..">
    </div>
</div>

By default, images are display:inline. If you only want the center the image (and not the other column content), make the image display:block using the d-block class, and then mx-auto will work.

<div class="row">
  <div class="col-4">
    <img class="mx-auto d-block" src="..">
  </div>
</div>

Demo: http://codeply.com/go/iakGGLdB8s

How to trap on UIViewAlertForUnsatisfiableConstraints?

Whenever I attempt to remove the constraints that the system had to break, my constraints are no longer enough to satisfy the IB (ie "missing constraints" shows in the IB, which means they're incomplete and won't be used). I actually got around this by setting the constraint it wants to break to low priority, which (and this is an assumption) allows the system to break the constraint gracefully. It's probably not the best solution, but it solved my problem and the resulting constraints worked perfectly.

Determine when a ViewPager changes pages

Kotlin Users,

viewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {

            override fun onPageScrollStateChanged(state: Int) {
            }

            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {

            }

            override fun onPageSelected(position: Int) {
            }
        })

Update 2020 for ViewPager2

        viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
        override fun onPageScrollStateChanged(state: Int) {
            println(state)
        }

        override fun onPageScrolled(
            position: Int,
            positionOffset: Float,
            positionOffsetPixels: Int
        ) {
            super.onPageScrolled(position, positionOffset, positionOffsetPixels)
            println(position)
        }


        override fun onPageSelected(position: Int) {
            super.onPageSelected(position)
            println(position)
        }
    })

Multiple simultaneous downloads using Wget?

They always say it depends but when it comes to mirroring a website The best exists httrack. It is super fast and easy to work. The only downside is it's so called support forum but you can find your way using official documentation. It has both GUI and CLI interface and it Supports cookies just read the docs This is the best.(Be cureful with this tool you can download the whole web on your harddrive)

httrack -c8 [url]

By default maximum number of simultaneous connections limited to 8 to avoid server overload

When to use a linked list over an array/array list?

The advantage of lists appears if you need to insert items in the middle and don't want to start resizing the array and shifting things around.

You're correct in that this is typically not the case. I've had a few very specific cases like that, but not too many.

Strip last two characters of a column in MySQL

To select all characters except the last n from a string (or put another way, remove last n characters from a string); use the SUBSTRING and CHAR_LENGTH functions together:

SELECT col
     , /* ANSI Syntax  */ SUBSTRING(col FROM 1 FOR CHAR_LENGTH(col) - 2) AS col_trimmed
     , /* MySQL Syntax */ SUBSTRING(col,     1,    CHAR_LENGTH(col) - 2) AS col_trimmed
FROM tbl

To remove a specific substring from the end of string, use the TRIM function:

SELECT col
     , TRIM(TRAILING '.php' FROM col)
-- index.php becomes index
-- index.txt remains index.txt

Laravel requires the Mcrypt PHP extension

For non MAMP or XAMPP users on OSX (with homebrew installed):

brew install homebrew/php/php56-mcrypt

Cheers!

Setting network adapter metric priority in Windows 7

I had the same problem on Windows 7 64-bit Pro. I adjusted network adapters binding using Control panel but nothing changed. Also metrics where showing that Win should use Ethernet adapter as primary, but it didn't.

Then a tried to uninstall Ethernet adapter driver and then install it again (without restart) and then I checked metrics for sure.

After this, Windows started prioritize Ethernet adapter.

What is the difference between a web API and a web service?

The basic difference between Web Services and Web APIs

Web Service:

1) It is a SOAP-based service and returns data as XML.

2) It only supports the HTTP protocol.

3) It is not open source but can be used by any client that understands XML.

5) It requires a SOAP protocol to receive and send data over the network, so it is not a light-weight architecture.

Web API:

1) A Web API is an HTTP based service and returns JSON or XML data by default.

2) It supports the HTTP protocol.

3) It can be hosted within an application or IIS.

4) It is open source and it can be used by any client that understands JSON or XML.

5) It has light-weight architecture and good for devices which have limited bandwidth, like mobile devices.

Find integer index of rows with NaN in pandas dataframe

And just in case, if you want to find the coordinates of 'nan' for all the columns instead (supposing they are all numericals), here you go:

df = pd.DataFrame([[0,1,3,4,np.nan,2],[3,5,6,np.nan,3,3]])

df
   0  1  2    3    4  5
0  0  1  3  4.0  NaN  2
1  3  5  6  NaN  3.0  3

np.where(np.asanyarray(np.isnan(df)))
(array([0, 1]), array([4, 3]))

How to store Query Result in variable using mysql

Additionally, if you want to set multiple variables at once by one query, you can use the other syntax for setting variables which goes like this: SELECT @varname:=value.

A practical example:

SELECT @total_count:=COUNT(*), @total_price:=SUM(quantity*price) FROM items ...

How do I do a HTTP GET in Java?

The simplest way that doesn't require third party libraries it to create a URL object and then call either openConnection or openStream on it. Note that this is a pretty basic API, so you won't have a lot of control over the headers.

What is the difference between onBlur and onChange attribute in HTML?

In Firefox the onchange fires only when you tab or else click outside the input field. The same is true of Onblur. The difference is that onblur will fire whether you changed anything in the field or not. It is possible that ENTER will fire one or both of these, but you wouldn't know that if you disable the ENTER in your forms to prevent unexpected submits.

How do I run a bat file in the background from another bat file?

Since START is the only way to execute something in the background from a CMD script, I would recommend you keep using it. Instead of the /B modifier, try /MIN so the newly created window won't bother you. Also, you can set the priority to something lower with /LOW or /BELOWNORMAL, which should improve your system responsiveness.

Using DISTINCT and COUNT together in a MySQL Query

What the hell of all this work anthers

it's too simple

if you want a list of how much productId in each keyword here it's the code

SELECT count(productId),  keyword  FROM `Table_name` GROUP BY keyword; 

PHP Pass variable to next page

try this code

using hidden field we can pass php varibale to another page

page1.php

<?php $myVariable = "Some text";?>
<form method="post" action="page2.php">
 <input type="hidden" name="text" value="<?php echo $myVariable; ?>">
 <button type="submit">Submit</button>
</form>

pass php variable to hidden field value so you can access this variable into another page

page2.php

<?php
 $text=$_POST['text'];
 echo $text;
?>

PostgreSQL database default location on Linux

On Centos 6.5/PostgreSQL 9.3:

Change the value of "PGDATA=/var/lib/pgsql/data" to whatever location you want in the initial script file /etc/init.d/postgresql.

Remember to chmod 700 and chown postgres:postgres to the new location and you're the boss.

html div onclick event

Change your jQuery code with this. It will alert the id of the a.

$('.expandable-panel-heading:not(#ancherComplaint)').click(function () {
markActiveLink();    
     alert('123');
 });

function markActiveLink(el) {   
var el = $('a').attr("id")
    alert(el);
} 

Demo

What is the difference between venv, pyvenv, pyenv, virtualenv, virtualenvwrapper, pipenv, etc?

UPDATE 20200825:

Added below "Conclusion" paragraph

I've went down the pipenv rabbit hole (it's a deep and dark hole indeed...) and since the last answer is over 2 years ago, felt it was useful to update the discussion with the latest developments on the Python virtual envelopes topic I've found.

DISCLAIMER:

This answer is NOT about continuing the raging debate about the merits of pipenv versus venv as envelope solutions- I make no endorsement of either. It's about PyPA endorsing conflicting standards and how future development of virtualenv promises to negate making an either/or choice between them at all. I focused on these two tools precisely because they are the anointed ones by PyPA.

venv

As the OP notes, venv is a tool for virtualizing environments. NOT a third party solution, but native tool. PyPA endorses venv for creating VIRTUAL ENVELOPES: "Changed in version 3.5: The use of venv is now recommended for creating virtual environments".

pipenv

pipenv- like venv - can be used to create virtual envelopes but additionally rolls-in package management and vulnerability checking functionality. Instead of using requirements.txt, pipenv delivers package management via Pipfile. As PyPA endorses pipenv for PACKAGE MANAGEMENT, that would seem to imply pipfile is to supplant requirements.txt.

HOWEVER: pipenv uses virtualenv as its tool for creating virtual envelopes, NOT venv which is endorsed by PyPA as the go-to tool for creating virtual envelopes.

Conflicting Standards:

So if settling on a virtual envelope solution wasn't difficult enough, we now have PyPA endorsing two different tools which use different virtual envelope solutions. The raging Github debate on venv vs virtualenv which highlights this conflict can be found here.

Conflict Resolution:

The Github debate referenced in above link has steered virtualenv development in the direction of accommodating venv in future releases:

prefer built-in venv: if the target python has venv we'll create the environment using that (and then perform subsequent operations on that to facilitate other guarantees we offer)

Conclusion:

So it looks like there will be some future convergence between the two rival virtual envelope solutions, but as of now pipenv- which uses virtualenv - varies materially from venv.

Given the problems pipenv solves and the fact that PyPA has given its blessing, it appears to have a bright future. And if virtualenv delivers on its proposed development objectives, choosing a virtual envelope solution should no longer be a case of either pipenv OR venv.

Update 20200825:

An oft repeated criticism of Pipenv I saw when producing this analysis was that it was not actively maintained. Indeed, what's the point of using a solution whose future could be seen questionable due to lack of continuous development? After a dry spell of about 18 months, Pipenv is once again being actively developed. Indeed, large and material updates have since been released.

Uncaught ReferenceError: $ is not defined error in jQuery

Change the order you're including your scripts (jQuery first):

<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript" src="./javascript.js"></script>
<script
    src="http://maps.googleapis.com/maps/api/js?key=YOUR_APIKEY&sensor=false">
</script>

Which loop is faster, while or for?

I used a for and while loop on a solid test machine (no non-standard 3rd party background processes running). I ran a for loop vs while loop as it relates to changing the style property of 10,000 <button> nodes.

The test is was run consecutively 10 times, with 1 run timed out for 1500 milliseconds before execution:

Here is the very simple javascript I made for this purpose

function runPerfTest() {
    "use strict";

    function perfTest(fn, ns) {
        console.time(ns);
        fn();
        console.timeEnd(ns);
    }

    var target = document.getElementsByTagName('button');

    function whileDisplayNone() {
        var x = 0;
        while (target.length > x) {
            target[x].style.display = 'none';
            x++;
        }
    }

    function forLoopDisplayNone() {
        for (var i = 0; i < target.length; i++) {
            target[i].style.display = 'none';
        }
    }

    function reset() {
        for (var i = 0; i < target.length; i++) {
            target[i].style.display = 'inline-block';
        }
    }

    perfTest(function() {
        whileDisplayNone();
    }, 'whileDisplayNone');

    reset();

    perfTest(function() {
        forLoopDisplayNone();
    }, 'forLoopDisplayNone');

    reset();
};

$(function(){
    runPerfTest();
    runPerfTest();
    runPerfTest();
    runPerfTest();
    runPerfTest();
    runPerfTest();
    runPerfTest();
    runPerfTest();
    runPerfTest();
    setTimeout(function(){
        console.log('cool run');
        runPerfTest();
    }, 1500);
});

Here are the results I got

pen.js:8 whileDisplayNone: 36.987ms
pen.js:8 forLoopDisplayNone: 20.825ms

pen.js:8 whileDisplayNone: 19.072ms
pen.js:8 forLoopDisplayNone: 25.701ms

pen.js:8 whileDisplayNone: 21.534ms
pen.js:8 forLoopDisplayNone: 22.570ms

pen.js:8 whileDisplayNone: 16.339ms
pen.js:8 forLoopDisplayNone: 21.083ms

pen.js:8 whileDisplayNone: 16.971ms
pen.js:8 forLoopDisplayNone: 16.394ms

pen.js:8 whileDisplayNone: 15.734ms
pen.js:8 forLoopDisplayNone: 21.363ms

pen.js:8 whileDisplayNone: 18.682ms
pen.js:8 forLoopDisplayNone: 18.206ms

pen.js:8 whileDisplayNone: 19.371ms
pen.js:8 forLoopDisplayNone: 17.401ms

pen.js:8 whileDisplayNone: 26.123ms
pen.js:8 forLoopDisplayNone: 19.004ms

pen.js:61 cool run
pen.js:8 whileDisplayNone: 20.315ms
pen.js:8 forLoopDisplayNone: 17.462ms

Here is the demo link

Update

A separate test I have conducted is located below, which implements 2 differently written factorial algorithms, 1 using a for loop, the other using a while loop.

Here is the code:

function runPerfTest() {
    "use strict";

    function perfTest(fn, ns) {
        console.time(ns);
        fn();
        console.timeEnd(ns);
    }

    function whileFactorial(num) {
        if (num < 0) {
            return -1;
        }
        else if (num === 0) {
            return 1;
        }
        var factl = num;
        while (num-- > 2) {
            factl *= num;
        }
        return factl;
    }

    function forFactorial(num) {
        var factl = 1;
        for (var cur = 1; cur <= num; cur++) {
            factl *= cur;
        }
        return factl;
    }

    perfTest(function(){
        console.log('Result (100000):'+forFactorial(80));
    }, 'forFactorial100');

    perfTest(function(){
        console.log('Result (100000):'+whileFactorial(80));
    }, 'whileFactorial100');
};

(function(){
    runPerfTest();
    runPerfTest();
    runPerfTest();
    runPerfTest();
    runPerfTest();
    runPerfTest();
    runPerfTest();
    runPerfTest();
    runPerfTest();
    console.log('cold run @1500ms timeout:');
    setTimeout(runPerfTest, 1500);
})();

And the results for the factorial benchmark:

pen.js:41 Result (100000):7.15694570462638e+118
pen.js:8 whileFactorial100: 0.280ms
pen.js:38 Result (100000):7.156945704626378e+118
pen.js:8 forFactorial100: 0.241ms
pen.js:41 Result (100000):7.15694570462638e+118
pen.js:8 whileFactorial100: 0.254ms
pen.js:38 Result (100000):7.156945704626378e+118
pen.js:8 forFactorial100: 0.254ms
pen.js:41 Result (100000):7.15694570462638e+118
pen.js:8 whileFactorial100: 0.285ms
pen.js:38 Result (100000):7.156945704626378e+118
pen.js:8 forFactorial100: 0.294ms
pen.js:41 Result (100000):7.15694570462638e+118
pen.js:8 whileFactorial100: 0.181ms
pen.js:38 Result (100000):7.156945704626378e+118
pen.js:8 forFactorial100: 0.172ms
pen.js:41 Result (100000):7.15694570462638e+118
pen.js:8 whileFactorial100: 0.195ms
pen.js:38 Result (100000):7.156945704626378e+118
pen.js:8 forFactorial100: 0.279ms
pen.js:41 Result (100000):7.15694570462638e+118
pen.js:8 whileFactorial100: 0.185ms
pen.js:55 cold run @1500ms timeout:
pen.js:38 Result (100000):7.156945704626378e+118
pen.js:8 forFactorial100: 0.404ms
pen.js:41 Result (100000):7.15694570462638e+118
pen.js:8 whileFactorial100: 0.314ms

Conclusion: No matter the sample size or specific task type tested, there is no clear winner in terms of performance between a while and for loop. Testing done on a MacAir with OS X Mavericks on Chrome evergreen.

Getting GET "?" variable in laravel

Query params are used like this:

use Illuminate\Http\Request;

class MyController extends BaseController{

    public function index(Request $request){
         $param = $request->query('param');
    }

View tabular file such as CSV from command line

Tabview is really good. Worked with 200+MB files that displayed nicely which were buggy with LibreOffice as well as csv plugin in gvim.

The Anaconda version is available here: https://anaconda.org/bioconda/tabview

How to add LocalDB to Visual Studio 2015 Community's SQL Server Object Explorer?

To check if LocalDb is installed or not:

  • run cmd and type in sqllocaldb i this should give you the installed sqllocaldb instances if found.
  • Run SSMS (SQL Server Management Studio).
  • Try to connect to this instance (localdb)\V11.0 using windows authentication.

If an error is raised Cannot connect to (localdb)\V11.0. change the instance name to (localdb)\MSSQLLocalDB and try again to connect, if you still get the same error.

Follow these steps to install LocalDb:

  • Close SSMS.
  • Close VS (Visual Studio) if it's running.
  • Go to Start Menu and type in search sqlLocalDb.
  • From the results that appears choose sqlLocalDb.msi and click it.
  • SQL setup will start to install LocalDB

after finishing the installation re-run SSMS and try connecting to either of the instances (localdb)\V11.0 or (localdb)\MSSQLLocalDB, one of it should work depending on what Visual Studio version you have.

You can also verify that localdb is installed using Visual Studio by simply creating new sql file and go to the connect icon on the top header of the file which by default lists all the servers you can connect to including localdb if installed.

In addition to the above mentioned ways of finding if localdb is installed, you can also use the MS windows power shell or windows command processor CMD or even NuGet package manager console on your server machine and run these commands sqllocaldb i and sqllocaldb v that will show you the localdb name if it is installed and the MSSQL server version installed and running on your machine.

split string in two on given index and return both parts

Try this

_x000D_
_x000D_
function split_at_index(value, index)
{
 return value.substring(0, index) + "," + value.substring(index);
}

console.log(split_at_index('3123124', 2));
_x000D_
_x000D_
_x000D_

Windows Scipy Install: No Lapack/Blas Resources Found

The solution to the absence of BLAS/LAPACK libraries for SciPy installations on Windows 7 64-bit is described here:

http://www.scipy.org/scipylib/building/windows.html

Installing Anaconda is much easier, but you still don't get Intel MKL or GPU support without paying for it (they are in the MKL Optimizations and Accelerate add-ons for Anaconda - I'm not sure if they use PLASMA and MAGMA either). With MKL optimization, numpy has outperformed IDL on large matrix computations by 10-fold. MATLAB uses the Intel MKL library internally and supports GPU computing, so one might as well use that for the price if they're a student ($50 for MATLAB + $10 for the Parallel Computing Toolbox). If you get the free trial of Intel Parallel Studio, it comes with the MKL library, as well as C++ and FORTRAN compilers that will come in handy if you want to install BLAS and LAPACK from MKL or ATLAS on Windows:

http://icl.cs.utk.edu/lapack-for-windows/lapack/

Parallel Studio also comes with the Intel MPI library, useful for cluster computing applications and their latest Xeon processsors. While the process of building BLAS and LAPACK with MKL optimization is not trivial, the benefits of doing so for Python and R are quite large, as described in this Intel webinar:

https://software.intel.com/en-us/articles/powered-by-mkl-accelerating-numpy-and-scipy-performance-with-intel-mkl-python

Anaconda and Enthought have built businesses out of making this functionality and a few other things easier to deploy. However, it is freely available to those willing to do a little work (and a little learning).

For those who use R, you can now get MKL optimized BLAS and LAPACK for free with R Open from Revolution Analytics.

EDIT: Anaconda Python now ships with MKL optimization, as well as support for a number of other Intel library optimizations through the Intel Python distribution. However, GPU support for Anaconda in the Accelerate library (formerly known as NumbaPro) is still over $10k USD! The best alternatives for that are probably PyCUDA and scikit-cuda, as copperhead (essentially a free version of Anaconda Accelerate) unfortunately ceased development five years ago. It can be found here if anybody wants to pick up where they left off.

LINQ: Distinct values

In addition to Jon Skeet's answer, you can also use the group by expressions to get the unique groups along w/ a count for each groups iterations:

var query = from e in doc.Elements("whatever")
            group e by new { id = e.Key, val = e.Value } into g
            select new { id = g.Key.id, val = g.Key.val, count = g.Count() };

How do I find which application is using up my port?

How about netstat?

http://support.microsoft.com/kb/907980

The command is netstat -anob.

(Make sure you run command as admin)

I get:

C:\Windows\system32>netstat -anob

Active Connections

     Proto  Local Address          Foreign Address        State           PID
  TCP           0.0.0.0:80                0.0.0.0:0                LISTENING         4
 Can not obtain ownership information

  TCP    0.0.0.0:135            0.0.0.0:0              LISTENING       692
  RpcSs
 [svchost.exe]

  TCP    0.0.0.0:443            0.0.0.0:0              LISTENING       7540
 [Skype.exe]

  TCP    0.0.0.0:445            0.0.0.0:0              LISTENING       4
 Can not obtain ownership information
  TCP    0.0.0.0:623            0.0.0.0:0              LISTENING       564
 [LMS.exe]

  TCP    0.0.0.0:912            0.0.0.0:0              LISTENING       4480
 [vmware-authd.exe]

And If you want to check for the particular port, command to use is: netstat -aon | findstr 8080 from the same path

INSERT with SELECT

Of course you can.

One thing should be noted however: The INSERT INTO SELECT statement copies data from one table and inserts it into another table AND requires that data types in source and target tables match. If data types from given table columns does not match (i.e. trying to insert VARCHAR into INT, or TINYINT intoINT) the MySQL server will throw an SQL Error (1366).

So be careful.

Here is the syntax of the command:

INSERT INTO table2 (column1, column2, column3)
SELECT column1, column2, column3 FROM table1
WHERE condition;

Side note: There is a way to circumvent different column types insertion problem by using casting in your SELECT, for example:

SELECT CAST('qwerty' AS CHAR CHARACTER SET utf8) COLLATE utf8_bin;

This conversion (CAST() is synonym of CONVERT() ) is very useful if your tables have different character sets on the same table column (which can potentially lead to data loss if not handled properly).

Segmentation fault on large array sizes

You're probably just getting a stack overflow here. The array is too big to fit in your program's stack address space.

If you allocate the array on the heap you should be fine, assuming your machine has enough memory.

int* array = new int[1000000];

But remember that this will require you to delete[] the array. A better solution would be to use std::vector<int> and resize it to 1000000 elements.

How to get difference between two dates in Year/Month/Week/Day?

This is actually quite tricky. A different total number of days can result in the same result. For example:

  • 19th June 2008 to 19th June 2010 = 2 years, but also 365 * 2 days

  • 19th June 2006 to 19th June 2008 = 2 years, but also 365 + 366 days due to leap years

You may well want to subtract years until you get to the point where you've got two dates which are less than a year apart. Then subtract months until you get to the point where you've got two dates which are less than a month apart.

Further confusion: subtracting (or adding) months is tricky when you might start with a date of "30th March" - what's a month earlier than that?

Even further confusion (may not be relevant): even a day isn't always 24 hours. Daylight saving anyone?

Even further confusion (almost certainly not relevant): even a minute isn't always 60 seconds. Leap seconds are highly confusing...

I don't have the time to work out the exact right way of doing this right now - this answer is mostly to raise the fact that it's not nearly as simple as it might sound.

EDIT: Unfortunately I'm not going to have enough time to answer this fully. I would suggest you start off by defining a struct representing a Period:

public struct Period
{
    private readonly int days;
    public int Days { get { return days; } }
    private readonly int months;
    public int Months { get { return months; } }
    private readonly int years;
    public int Years { get { return years; } }

    public Period(int years, int months, int days)
    {
        this.years = years;
        this.months = months;
        this.days = days;
    }

    public Period WithDays(int newDays)
    {
        return new Period(years, months, newDays);
    }

    public Period WithMonths(int newMonths)
    {
        return new Period(years, newMonths, days);
    }

    public Period WithYears(int newYears)
    {
        return new Period(newYears, months, days);
    }

    public static DateTime operator +(DateTime date, Period period)
    {
        // TODO: Implement this!
    }

    public static Period Difference(DateTime first, DateTime second)
    {
        // TODO: Implement this!
    }
}

I suggest you implement the + operator first, which should inform the Difference method - you should make sure that first + (Period.Difference(first, second)) == second for all first/second values.

Start with writing a whole slew of unit tests - initially "easy" cases, then move on to tricky ones involving leap years. I know the normal approach is to write one test at a time, but I'd personally brainstorm a bunch of them before you start any implementation work.

Allow yourself a day to implement this properly. It's tricky stuff.

Note that I've omitted weeks here - that value at least is easy, because it's always 7 days. So given a (positive) period, you'd have:

int years = period.Years;
int months = period.Months;
int weeks = period.Days / 7;
int daysWithinWeek = period.Days % 7;

(I suggest you avoid even thinking about negative periods - make sure everything is positive, all the time.)

Set timeout for ajax (jQuery)

You could use the timeout setting in the ajax options like this:

$.ajax({
    url: "test.html",
    timeout: 3000,
    error: function(){
        //do something
    },
    success: function(){
        //do something
    }
});

Read all about the ajax options here: http://api.jquery.com/jQuery.ajax/

Remember that when a timeout occurs, the error handler is triggered and not the success handler :)

Is it possible to hide/encode/encrypt php source code and let others have the system?

There are some online services for obfuscate php to hide the code from others. This is one Right Coder's Free Obfuscator Online

@Glavic is right. "Nothing is bulletproof". You can encode your source code and hide from bigger programmers, not from experts.

How do I find out what version of Sybase is running

1)From OS level(UNIX):-

dataserver -v

2)From Syabse isql:-

select @@version
go

sp_version
go

How to upsert (update or insert) in SQL Server 2005

Here is a useful article by Michael J. Swart on the matter, which covers different patterns and antipatterns for implementing UPSERT in SQL Server:
https://michaeljswart.com/2017/07/sql-server-upsert-patterns-and-antipatterns/

It addresses associated concurrency issues (primary key violations, deadlocks) - all of the answers provided here yet are considered antipatterns in the article (except for the @Bridge solution using triggers, which is not covered there).

Here is an extract from the article with the solution preferred by the author:

Inside a serializable transaction with lock hints:

CREATE PROCEDURE s_AccountDetails_Upsert ( @Email nvarchar(4000), @Etc nvarchar(max) )
AS 
  SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
  BEGIN TRAN

    IF EXISTS ( SELECT * FROM dbo.AccountDetails WITH (UPDLOCK) WHERE Email = @Email )

      UPDATE dbo.AccountDetails
         SET Etc = @Etc
       WHERE Email = @Email;

    ELSE 

      INSERT dbo.AccountDetails ( Email, Etc )
      VALUES ( @Email, @Etc );

  COMMIT

There is also related question with answers here on stackoverflow: Insert Update stored proc on SQL Server

Rounding float in Ruby

You can also provide a negative number as an argument to the round method to round to the nearest multiple of 10, 100 and so on.

# Round to the nearest multiple of 10. 
12.3453.round(-1)       # Output: 10

# Round to the nearest multiple of 100. 
124.3453.round(-2)      # Output: 100

Reading a key from the Web.Config using ConfigurationManager

with assuming below setting in .config file:

<configuration>
   <appSettings>
     <add key="PFUserName" value="myusername"/>
     <add key="PFPassWord" value="mypassword"/>
   </appSettings> 
</configuration>

try this:

public class myController : Controller
{
    NameValueCollection myKeys = ConfigurationManager.AppSettings;

    public void MyMethod()
    {
        var myUsername = myKeys["PFUserName"];
        var myPassword = myKeys["PFPassWord"];
    }
}

How to detect a route change in Angular?

Capture route change events in the following manner...

import { Component, OnInit, Output, ViewChild } from "@angular/core";
import { Router, NavigationStart, NavigationEnd, Event as NavigationEvent } from '@angular/router';

@Component({
    selector: "my-app",
    templateUrl: "app/app.component.html",
    styleUrls: ["app/app.component.css"]
})
export class AppComponent {

    constructor(private cacheComponentObj: CacheComponent,
        private router: Router) {

        /*  Route event types
            NavigationEnd
            NavigationCancel
            NavigationError
            RoutesRecognized
        */
        router.events.forEach((event: NavigationEvent) => {

            //Before Navigation
            if (event instanceof NavigationStart) {
                switch (event.url) {
                case "/app/home":
                {
                    //Do Work
                    break;
                }
                case "/app/About":
                {
                    //Do Work
                    break;
                }
                }
            }

            //After Navigation
            if (event instanceof NavigationEnd) {
                switch (event.url) {
                case "/app/home":
                {
                    //Do Work
                    break;
                }
                case "/app/About":
                {
                    //Do Work
                    break;
                }
                }
            }
        });
    }
}

When using SASS how can I import a file from a different directory?

The best way is to user sass-loader. It is available as npm package. It resolves all path related issues and make it super easy.

CSS no text wrap

Additionally to overflow:hidden, use

white-space:nowrap;

Use string contains function in oracle SQL query

The answer of ADTC works fine, but I've find another solution, so I post it here if someone wants something different.

I think ADTC's solution is better, but mine's also works.

Here is the other solution I found

select p.name
from   person p
where  instr(p.name,chr(8211)) > 0; --contains the character chr(8211) 
                                    --at least 1 time

Thank you.

telnet to port 8089 correct command

I believe telnet 74.255.12.25 8089 . Why don't u try both

Docker and securing passwords

An alternative to using environment variables, which can get messy if you have a lot of them, is to use volumes to make a directory on the host accessible in the container.

If you put all your credentials as files in that folder, then the container can read the files and use them as it pleases.

For example:

$ echo "secret" > /root/configs/password.txt
$ docker run -v /root/configs:/cfg ...

In the Docker container:

# echo Password is `cat /cfg/password.txt`
Password is secret

Many programs can read their credentials from a separate file, so this way you can just point the program to one of the files.

MAVEN_HOME, MVN_HOME or M2_HOME

We have M2_HOME,MAVEN_HOME,M3_HOME all are available in market
Previously M2_HOME is the only environment variable used by all as a standard.
But,due latest releases the MAVEN_Home came as standard but some old tools are still trying to find only M2_HOME
so we should have both M2_HOME,MAVEN_HOME to sustain with old and new tools.
M2_HOME can be used for both as well

How do I access ViewBag from JS

<script type="text/javascript">
      $(document).ready(function() {
                showWarning('@ViewBag.Message');
      });

</script>

You can use ViewBag.PropertyName in javascript like this.

How do I multiply each element in a list by a number?

Best way is to use list comprehension:

def map_to_list(my_list, n):
# multiply every value in my_list by n
# Use list comprehension!
    my_new_list = [i * n for i in my_list]
    return my_new_list
# To test:
print(map_to_list([1,2,3], -1))

Returns: [-1, -2, -3]

Why does sudo change the PATH?

Secure_path is your friend, but if you want to exempt yourself from secure_path just do

sudo visudo

And append

Defaults exempt_group=your_goup

If you want to exempt a bunch of users create a group, add all the users to it, and use that as your exempt_group. man 5 sudoers for more.

Applying styles to tables with Twitter Bootstrap

Twitter bootstrap tables can be styled and well designed. You can style your table just adding some classes on your table and it’ll look nice. You might use it on your data reports, showing information, etc.

enter image description here You can use :

basic table
Striped rows
Bordered table
Hover rows
Condensed table
Contextual classes
Responsive tables

Striped rows Table :

    <table class="table table-striped" width="647">
    <thead>
    <tr>
    <th>#</th>
    <th>Name</th>
    <th>Address</th>
    <th>mail</th>
    </tr>
    </thead>
    <tbody>
    <tr>
    <td>1</td>
    <td>Thomas bell</td>
    <td>Brick lane, London</td>
    <td>[email protected]</td>
    </tr>
    <tr>
    <td height="29">2</td>
    <td>Yan Chapel</td>
    <td>Toronto Australia</td>
    <td>[email protected]</td>
    </tr>
    <tr>
    <td>3</td>
    <td>Pit Sampras</td>
    <td>Berlin, Germany</td>
    <td>Pit @yahoo.com</td>
    </tr>
    </tbody>
    </table>

Condensed table :

Compacting a table you need to add class class=”table table-condensed” .

    <table class="table table-condensed" width="647">
    <thead>
    <tr>
    <th>#</th>
    <th>Sample Name</th>
    <th>Address</th>
    <th>Mail</th>
    </tr>
    </thead>
    <tbody>
    <tr>
    <td>1</td>
    <td>Thomas bell</td>
    <td>Brick lane, London</td>
    <td>[email protected]</td>
    </tr>
    <tr>
    <td height="29">2</td>
    <td>Yan Chapel</td>
    <td>Toronto Australia</td>
    <td>[email protected]</td>
    </tr>
    <tr>
    <td>3</td>
    <td>Pit Sampras</td>
    <td>Berlin, Germany</td>
    <td>Pit @yahoo.com</td>
    </tr>
    <tr>
    <td></td>
    <td colspan="3" align="center"></td>
    </tr>
    </tbody>
    </table>

Ref : http://twitterbootstrap.org/twitter-bootstrap-table-example-tutorial

What is the meaning of prepended double colon "::"?

:: is a operator of defining the namespace.

For example, if you want to use cout without mentioning using namespace std; in your code you write this:

std::cout << "test";

When no namespace is mentioned, that it is said that class belongs to global namespace.

How do I write a bash script to restart a process if it dies?

I use this for my npm Process

#!/bin/bash
for (( ; ; ))
do
date +"%T"
echo Start Process
cd /toFolder
sudo process
date +"%T"
echo Crash
sleep 1
done

How can I stop .gitignore from appearing in the list of untracked files?

In my case, I want to exclude an existing file. Only modifying .gitignore not work. I followed these steps:

git rm --cached dirToFile/file.php
vim .gitignore
git commit -a

In this way, I cleaned from cache the file that I wanted to exclude and after I added it to .gitignore.

How to check if a string starts with a specified string?

Use strpos():

if (strpos($string2, 'http') === 0) {
   // It starts with 'http'
}

Remember the three equals signs (===). It will not work properly if you only use two. This is because strpos() will return false if the needle cannot be found in the haystack.

How can I delay a method call for 1 second?

Best way to do is :

[self performSelector:@selector(YourFunctionName) 
           withObject:(can be Self or Object from other Classes) 
           afterDelay:(Time Of Delay)];

you can also pass nil as withObject parameter.

example :

[self performSelector:@selector(subscribe) withObject:self afterDelay:3.0 ];

Example on ToggleButton

You should follow the Google guide;

ToggleButton toggle = (ToggleButton) findViewById(R.id.togglebutton);
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            // The toggle is enabled
        } else {
            // The toggle is disabled
        }
    }
});

You can check the documentation here

Fatal error: Maximum execution time of 30 seconds exceeded in C:\xampp\htdocs\wordpress\wp-includes\class-http.php on line 1610

@Raphael your solution does work. I encountered the same problem and solved it by increasing the maximum execution time to 180. There is an easier way to do it though:

  1. Open the Xampp control panel

  2. Click on 'config' behind 'Apache'

  3. Select 'PHP (php.ini)' from the dropdown -> A file should now open in your text editor

  4. Press ctrl+f and search for 'max_execution_time', you should fine a line which only says

    max_execution_time=30

  5. Change 30 to a bigger number (180 worked for me), like this:

    max_execution_time=180

  6. Save the file

  7. 'Stop' Apache server

  8. Close Xampp

  9. Restart Xampp

  10. 'Start' Apache server

  11. Update Wordpress from the Admin dashboard

  12. Enjoy ;)

how to count length of the JSON array element

First if the object you're dealing with is a string then you need to parse it then figure out the length of the keys :

obj = JSON.parse(jsonString);
shareInfoLen = Object.keys(obj.shareInfo[0]).length;

how to realize countifs function (excel) in R

Easy peasy. Your data frame will look like this:

df <- data.frame(sex=c('M','F','M'),
                 occupation=c('Student','Analyst','Analyst'))

You can then do the equivalent of a COUNTIF by first specifying the IF part, like so:

df$sex == 'M'

This will give you a boolean vector, i.e. a vector of TRUE and FALSE. What you want is to count the observations for which the condition is TRUE. Since in R TRUE and FALSE double as 1 and 0 you can simply sum() over the boolean vector. The equivalent of COUNTIF(sex='M') is therefore

sum(df$sex == 'M')

Should there be rows in which the sex is not specified the above will give back NA. In that case, if you just want to ignore the missing observations use

sum(df$sex == 'M', na.rm=TRUE)

What's the u prefix in a Python string?

The u in u'Some String' means that your string is a Unicode string.

Q: I'm in a terrible, awful hurry and I landed here from Google Search. I'm trying to write this data to a file, I'm getting an error, and I need the dead simplest, probably flawed, solution this second.

A: You should really read Joel's Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) essay on character sets.

Q: sry no time code pls

A: Fine. try str('Some String') or 'Some String'.encode('ascii', 'ignore'). But you should really read some of the answers and discussion on Converting a Unicode string and this excellent, excellent, primer on character encoding.

Iterator Loop vs index loop

Iterators make your code more generic.
Every standard library container provides an iterator hence if you change your container class in future the loop wont be affected.

How to check for empty value in Javascript?

In my opinion, using "if(value)" to judge a value whether is an empty value is not strict, because the result of "v?true:false" is false when the value of v is 0(0 is not an empty value). You can use this function:

const isEmptyValue = (value) => {
    if (value === '' || value === null || value === undefined) {
        return true
    } else {
        return false
    }
}

Matplotlib connect scatterplot points with line - Python

For red lines an points

plt.plot(dates, values, '.r-') 

or for x markers and blue lines

plt.plot(dates, values, 'xb-')

C++/CLI Converting from System::String^ to std::string

I spent hours trying to convert a windows form listbox ToString value to a standard string so that I could use it with fstream to output to a txt file. My Visual Studio didn't come with marshal header files which several answers I found said to use. After so much trial and error I finally found a solution to the problem that just uses System::Runtime::InteropServices:

void MarshalString ( String ^ s, string& os ) {
   using namespace Runtime::InteropServices;
   const char* chars = 
      (const char*)(Marshal::StringToHGlobalAnsi(s)).ToPointer();
   os = chars;
   Marshal::FreeHGlobal(IntPtr((void*)chars));
}

//this is the code to use the function:
scheduleBox->SetSelected(0,true);
string a = "test";
String ^ c = gcnew String(scheduleBox->SelectedItem->ToString());
MarshalString(c, a);
filestream << a;

And here is the MSDN page with the example: http://msdn.microsoft.com/en-us/library/1b4az623(v=vs.80).aspx

I know it's a pretty simple solution but this took me HOURS of troubleshooting and visiting several forums to finally find something that worked.

Waiting till the async task finish its work

I think the easiest way is to create an interface to get the data from onpostexecute and run the Ui from interface :

Create an Interface :

public interface AsyncResponse {
    void processFinish(String output);
}

Then in asynctask

@Override
protected void onPostExecute(String data) {
    delegate.processFinish(data);
}

Then in yout main activity

@Override
public void processFinish(String data) {
     // do things

}

JavaScript pattern for multiple constructors

Sometimes, default values for parameters is enough for multiple constructors. And when that doesn't suffice, I try to wrap most of the constructor functionality into an init(other-params) function that is called afterwards. Also consider using the factory concept to make an object that can effectively create the other objects you want.

http://en.wikipedia.org/w/index.php?title=Factory_method_pattern&oldid=363482142#Javascript

appcompat-v7:21.0.0': No resource found that matches the given name: attr 'android:actionModeShareDrawable'

This is likely because you haven't set your compileSdkVersion to 21 in your build.gradle file. You also probably want to change your targetSdkVersion to 21.

android {
    //...
    compileSdkVersion 21

    defaultConfig {
        targetSdkVersion 21
    }
    //...
}

This requires you to have downloaded the latest SDK updates to begin with.

Android Studio SDK Manager

Once you've downloaded all the updates (don't forget to also update the Android Support Library/Repository, too!) and updated your compileSdkVersion, re-sync your Gradle project.

Edit: For Eclipse or general IntelliJ users

See reVerse's answer. He has a very thorough walk through!

How can I get a JavaScript stack trace when I throw an exception?

This polyfill code working in modern (2017) browsers (IE11, Opera, Chrome, FireFox, Yandex):

printStackTrace: function () {
    var err = new Error();
    var stack = err.stack || /*old opera*/ err.stacktrace || ( /*IE11*/ console.trace ? console.trace() : "no stack info");
    return stack;
}

Other answers:

function stackTrace() {
  var err = new Error();
  return err.stack;
}

not working in IE 11 !

Using arguments.callee.caller - not working in strict mode in any browser!

Convert an NSURL to an NSString

Try this in Swift :

var urlString = myUrl.absoluteString

Objective-C:

NSString *urlString = [myURL absoluteString];

Viewing local storage contents on IE

Edge (as opposed to IE11) has a better UI for Local storage / Session storage and cookies:

  • Open Dev tools (F12)
  • Go to Debugger tab
  • Click the folder icon to show a list of resources - opens in a separate tab

Dev tools screenshot

Javascript switch vs. if...else if...else

Other than syntax, a switch can be implemented using a tree which makes it O(log n), while a if/else has to be implemented with an O(n) procedural approach. More often they are both processed procedurally and the only difference is syntax, and moreover does it really matter -- unless you're statically typing 10k cases of if/else anyway?

How to reload .bashrc settings without logging out and back in again?

With this, you won't even have to type "source ~/.bashrc":

Include your bashrc file:

alias rc="vim ~/.bashrc && source ~/.bashrc"

Every time you want to edit your bashrc, just run the alias "rc"

Proper way to initialize a C# dictionary with values?

With ?# 6.0

var myDict = new Dictionary<string, string>
{
    ["Key1"] = "Value1",
    ["Key2"] = "Value2"
};

Why is using onClick() in HTML a bad practice?

Revision

Unobtrusive JavaScript approach was good in the PAST - especially events handler bind in HTML was considered as bad practice (mainly because onclick events run in the global scope and may cause unexpected error what was mention by YiddishNinja)

However...

Currently it seems that this approach is a little outdated and needs some update. If someone want to be professional frontend developper and write large and complicated apps then he need to use frameworks like Angular, Vue.js, etc... However that frameworks usually use (or allow to use) HTML-templates where event handlers are bind in html-template code directly and this is very handy, clear and effective - e.g. in angular template usually people write:

<button (click)="someAction()">Click Me</button> 

In raw js/html the equivalent of this will be

<button onclick="someAction()">Click Me</button>

The difference is that in raw js onclick event is run in the global scope - but the frameworks provide encapsulation.

So where is the problem?

The problem is when novice programmer who always heard that html-onclick is bad and who always use btn.addEventListener("onclick", ... ) wants to use some framework with templates (addEventListener also have drawbacks - if we update DOM in dynamic way using innerHTML= (which is pretty fast) - then we loose events handlers bind in that way). Then he will face something like bad-habits or wrong-approach to framework usage - and he will use framework in very bad way - because he will focus mainly on js-part and no on template-part (and produce unclear and hard to maintain code). To change this habits he will loose a lot of time (and probably he will need some luck and teacher).

So in my opinion, based on experience with my students, better would be for them if they use html-handlers-bind at the beginning. As I say it is true that handlers are call in global scope but a this stage students usually create small applications which are easy to control. To write bigger applications they choose some frameworks.

So what to do?

We can UPDATE the Unobtrusive JavaScript approach and allow bind event handlers (eventually with simple parameters) in html (but only bind handler - not put logic into onclick like in OP quesiton). So in my opinion in raw js/html this should be allowed

<button onclick="someAction(3)">Click Me</button>

or

_x000D_
_x000D_
function popup(num,str,event) {_x000D_
   let re=new RegExp(str);  _x000D_
   // ... _x000D_
   event.preventDefault();_x000D_
   console.log("link was clicked");_x000D_
}
_x000D_
<a href="https://example.com" onclick="popup(300,'map',event)">link</a>
_x000D_
_x000D_
_x000D_

But below examples should NOT be allowed

<button onclick="console.log('xx'); someAction(); return true">Click Me</button>

<a href="#" onclick="popup('/map/', 300, 300, 'map'); return false;">link</a>

The reality changes, our point of view should too

Is it possible to break a long line to multiple lines in Python?

It works in Python too:

>>> 1+\
      2+\
3
6
>>> (1+
          2+
 3)
6

Shadow Effect for a Text in Android?

put these in values/colors.xml

<resources>
    <color name="light_font">#FBFBFB</color>
    <color name="grey_font">#ff9e9e9e</color>
    <color name="text_shadow">#7F000000</color>
    <color name="text_shadow_white">#FFFFFF</color>
</resources>

Then in your layout xml here are some example TextView's

Example of Floating text on Light with Dark shadow

<TextView android:id="@+id/txt_example1"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:textSize="14sp"
                  android:textStyle="bold"
                  android:textColor="@color/light_font"
                  android:shadowColor="@color/text_shadow"
                  android:shadowDx="1"
                  android:shadowDy="1"
                  android:shadowRadius="2" />

enter image description here

Example of Etched text on Light with Dark shadow

<TextView android:id="@+id/txt_example2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="14sp"
                android:textStyle="bold"
                android:textColor="@color/light_font"
                android:shadowColor="@color/text_shadow"
                android:shadowDx="-1"
                android:shadowDy="-1"
                android:shadowRadius="1" />

enter image description here

Example of Crisp text on Light with Dark shadow

<TextView android:id="@+id/txt_example3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="14sp"
                android:textStyle="bold"
                android:textColor="@color/grey_font"
                android:shadowColor="@color/text_shadow_white"
                android:shadowDx="-2"
                android:shadowDy="-2"
                android:shadowRadius="1" />

enter image description here

Notice the positive and negative values... I suggest to play around with the colors/values yourself but ultimately you can adjust these settings to get the effect your looking for.

WPF User Control Parent

Try using the following:

Window parentWindow = Window.GetWindow(userControlReference);

The GetWindow method will walk the VisualTree for you and locate the window that is hosting your control.

You should run this code after the control has loaded (and not in the Window constructor) to prevent the GetWindow method from returning null. E.g. wire up an event:

this.Loaded += new RoutedEventHandler(UserControl_Loaded); 

Best way to initialize (empty) array in PHP

Initializing a simple array :

<?php $array1=array(10,20,30,40,50); ?>

Initializing array within array :

<?php  $array2=array(6,"santosh","rahul",array("x","y","z")); ?>

Source : Sorce for the code

Re-run Spring Boot Configuration Annotation Processor to update generated metadata

None of the answers worked for me. If you just want to disable the message, go to Intellij Preferences -> Editor -> General -> Appearance, uncheck "Show Spring Boot metadata panel".

However, you can also live with that message, if it does not bother you too much, so to make sure you don't miss any other Spring Boot metadata messages you may be interested in.

Android - Center TextView Horizontally in LinearLayout

What's happening is that since the the TextView is filling the whole width of the inner LinearLayout it is already in the horizontal center of the layout. When you use android:layout_gravity it places the widget, as a whole, in the gravity specified. Instead of placing the whole widget center what you're really trying to do is place the content in the center which can be accomplished with android:gravity="center_horizontal" and the android:layout_gravity attribute can be removed.

How to export iTerm2 Profiles

I didn't touch the "save to a folder" option. I just copied the two files/directories you mentioned in your question to the new machine, then ran defaults read com.googlecode.iterm2.

See https://apple.stackexchange.com/a/111559

How to temporarily exit Vim and go back

If you don't mind using your mouse a little bit:

  • Start your terminal,
  • select a file,
  • select Open Tab.

This creates a new tab on the terminal which you can run Vim on. Now use your mouse to shift to/from the terminal. I prefer this instead of always having to type (:shell and exit).

JAXB: How to ignore namespace during unmarshalling XML document?

I believe you must add the namespace to your xml document, with, for example, the use of a SAX filter.

That means:

  • Define a ContentHandler interface with a new class which will intercept SAX events before JAXB can get them.
  • Define a XMLReader which will set the content handler

then link the two together:

public static Object unmarshallWithFilter(Unmarshaller unmarshaller,
java.io.File source) throws FileNotFoundException, JAXBException 
{
    FileReader fr = null;
    try {
        fr = new FileReader(source);
        XMLReader reader = new NamespaceFilterXMLReader();
        InputSource is = new InputSource(fr);
        SAXSource ss = new SAXSource(reader, is);
        return unmarshaller.unmarshal(ss);
    } catch (SAXException e) {
        //not technically a jaxb exception, but close enough
        throw new JAXBException(e);
    } catch (ParserConfigurationException e) {
        //not technically a jaxb exception, but close enough
        throw new JAXBException(e);
    } finally {
        FileUtil.close(fr); //replace with this some safe close method you have
    }
}

gradient descent using python and numpy

I think your code is a bit too complicated and it needs more structure, because otherwise you'll be lost in all equations and operations. In the end this regression boils down to four operations:

  1. Calculate the hypothesis h = X * theta
  2. Calculate the loss = h - y and maybe the squared cost (loss^2)/2m
  3. Calculate the gradient = X' * loss / m
  4. Update the parameters theta = theta - alpha * gradient

In your case, I guess you have confused m with n. Here m denotes the number of examples in your training set, not the number of features.

Let's have a look at my variation of your code:

import numpy as np
import random

# m denotes the number of examples here, not the number of features
def gradientDescent(x, y, theta, alpha, m, numIterations):
    xTrans = x.transpose()
    for i in range(0, numIterations):
        hypothesis = np.dot(x, theta)
        loss = hypothesis - y
        # avg cost per example (the 2 in 2*m doesn't really matter here.
        # But to be consistent with the gradient, I include it)
        cost = np.sum(loss ** 2) / (2 * m)
        print("Iteration %d | Cost: %f" % (i, cost))
        # avg gradient per example
        gradient = np.dot(xTrans, loss) / m
        # update
        theta = theta - alpha * gradient
    return theta


def genData(numPoints, bias, variance):
    x = np.zeros(shape=(numPoints, 2))
    y = np.zeros(shape=numPoints)
    # basically a straight line
    for i in range(0, numPoints):
        # bias feature
        x[i][0] = 1
        x[i][1] = i
        # our target variable
        y[i] = (i + bias) + random.uniform(0, 1) * variance
    return x, y

# gen 100 points with a bias of 25 and 10 variance as a bit of noise
x, y = genData(100, 25, 10)
m, n = np.shape(x)
numIterations= 100000
alpha = 0.0005
theta = np.ones(n)
theta = gradientDescent(x, y, theta, alpha, m, numIterations)
print(theta)

At first I create a small random dataset which should look like this:

Linear Regression

As you can see I also added the generated regression line and formula that was calculated by excel.

You need to take care about the intuition of the regression using gradient descent. As you do a complete batch pass over your data X, you need to reduce the m-losses of every example to a single weight update. In this case, this is the average of the sum over the gradients, thus the division by m.

The next thing you need to take care about is to track the convergence and adjust the learning rate. For that matter you should always track your cost every iteration, maybe even plot it.

If you run my example, the theta returned will look like this:

Iteration 99997 | Cost: 47883.706462
Iteration 99998 | Cost: 47883.706462
Iteration 99999 | Cost: 47883.706462
[ 29.25567368   1.01108458]

Which is actually quite close to the equation that was calculated by excel (y = x + 30). Note that as we passed the bias into the first column, the first theta value denotes the bias weight.

Use of Java's Collections.singletonList()?

The javadoc says this:

"Returns an immutable list containing only the specified object. The returned list is serializable."

You ask:

Why would I want to have a separate method to do that?

Primarily as a convenience ... to save you having to write a sequence of statements to:

  • create an empty list object
  • add an element to it, and
  • wrap it with an immutable wrapper.

It may also be a bit faster and/or save a bit of memory, but it is unlikely that these small savings will be significant. (An application that creates vast numbers of singleton lists is unusual to say the least.)

How does immutability play a role here?

It is part of the specification of the method; see above.

Are there any special useful use-cases for this method, rather than just being a convenience method?

Clearly, there are use-cases where it is convenient to use the singletonList method. But I don't know how you would (objectively) distinguish between an ordinary use-case and a "specially useful" one ...

Representational state transfer (REST) and Simple Object Access Protocol (SOAP)

SOAP - Simple Object Access Protocol is a protocol!

REST - REpresentational State Transfer is an architectural style!

SOAP is an XML protocol used to transfer messages, typically over HTTP

REST and SOAP are arguably not mutually exclusive. A RESTful architecture might use HTTP or SOAP or some other communication protocol. REST is optimized for the web and thus HTTP is a perfect choice. HTTP is also the only protocol discussed in Roy Fielding's paper.

Although REST and SOAP are clearly very different, the question does illuminate the fact that REST and HTTP are often used in tandem. This is primarily due to the simplicity of HTTP and its very natural mapping to RESTful principles.

Fundamental REST Principles

Client-Server Communication

Client-server architectures have a very distinct separation of concerns. All applications built in the RESTful style must also be client-server in princple.

Stateless

Each each client request to the server requires that its state be fully represented. The server must be able to completely understand the client request without using any server context or server session state. It follows that all state must be kept on the client. We will discuss stateless representation in more detail later.

Cacheable

Cache constraints may be used, thus enabling response data to to be marked as cacheable or not-cachable. Any data marked as cacheable may be reused as the response to the same subsequent request.

Uniform Interface

All components must interact through a single uniform interface. Because all component interaction occurs via this interface, interaction with different services is very simple. The interface is the same! This also means that implementation changes can be made in isolation. Such changes, will not affect fundamental component interaction because the uniform interface is always unchanged. One disadvantage is that you are stuck with the interface. If an optimization could be provided to a specific service by changing the interface, you are out of luck as REST prohibits this. On the bright side, however, REST is optimized for the web, hence incredible popularity of REST over HTTP!

The above concepts represent defining characteristics of REST and differentiate the REST architecture from other architectures like web services. It is useful to note that a REST service is a web service, but a web service is not necessarily a REST service.

See this blog post on REST Design Principals for more details on REST and the above stated bullets.

What's the difference between getPath(), getAbsolutePath(), and getCanonicalPath() in Java?

The best way I have found to get a feel for things like this is to try them out:

import java.io.File;
public class PathTesting {
    public static void main(String [] args) {
        File f = new File("test/.././file.txt");
        System.out.println(f.getPath());
        System.out.println(f.getAbsolutePath());
        try {
            System.out.println(f.getCanonicalPath());
        }
        catch(Exception e) {}
    }
}

Your output will be something like:

test\..\.\file.txt
C:\projects\sandbox\trunk\test\..\.\file.txt
C:\projects\sandbox\trunk\file.txt

So, getPath() gives you the path based on the File object, which may or may not be relative; getAbsolutePath() gives you an absolute path to the file; and getCanonicalPath() gives you the unique absolute path to the file. Notice that there are a huge number of absolute paths that point to the same file, but only one canonical path.

When to use each? Depends on what you're trying to accomplish, but if you were trying to see if two Files are pointing at the same file on disk, you could compare their canonical paths. Just one example.

CMD: Export all the screen content to a text file

Just see this page

in cmd type:

Command | clip

Then open a *.Txt file and Paste. That's it. Done.

Split array into two parts without for loop in java

Use this code it works perfectly for odd or even list sizes. Hope it help somebody .

 int listSize = listOfArtist.size();
 int mid = 0;
 if (listSize % 2 == 0) {
    mid = listSize / 2;
    Log.e("Parting", "You entered an even number. mid " + mid
                    + " size is " + listSize);
 } else {
    mid = (listSize + 1) / 2;
    Log.e("Parting", "You entered an odd number. mid " + mid
                    + " size is " + listSize);
 }
 //sublist returns List convert it into arraylist * very important
 leftArray = new ArrayList<ArtistModel>(listOfArtist.subList(0, mid));
 rightArray = new ArrayList<ArtistModel>(listOfArtist.subList(mid,
                listSize));

How to draw border around a UILabel?

Solution for Swift 4:

yourLabel.layer.borderColor = UIColor.green.cgColor

Python math module

import math #imports math module

import math as m
print(m.sqrt(25))

from math import sqrt #imports a method from math module
print(sqrt(25))

from math import sqrt as s
print(s(25))

from math import *
print(sqrt(25))

What can I use for good quality code coverage for C#/.NET?

See the C# Test Coverage tool from my company, Semantic Designs:

It has very low overhead, handles huge systems of files, intuitive GUI, howing coverage on specific files, and generated report with coverage breakdown at method, class and package levels.

What is a magic number, and why is it bad?

Another advantage of extracting a magic number as a constant gives the possibility to clearly document the business information.

public class Foo {
    /** 
     * Max age in year to get child rate for airline tickets
     * 
     * The value of the constant is {@value}
     */
    public static final int MAX_AGE_FOR_CHILD_RATE = 2;

    public void computeRate() {
         if (person.getAge() < MAX_AGE_FOR_CHILD_RATE) {
               applyChildRate();
         }
    }
}

Check whether a string matches a regex in JS

Here's an example that looks for certain HTML tags so it's clear that /someregex/.test() returns a boolean:

if(/(span|h[0-6]|li|a)/i.test("h3")) alert('true');

compareTo() vs. equals()

String s1 = "a";
String s2 = "c";

System.out.println(s1.compareTo(s2));
System.out.println(s1.equals(s2));

This prints -2 and false

String s1 = "c";
String s2 = "a";
System.out.println(s1.compareTo(s2));
System.out.println(s1.equals(s2));

This prints 2 and false

String s1 = "c";
String s2 = "c";
System.out.println(s1.compareTo(s2));
System.out.println(s1.equals(s2));

This prints 0 and true

equals returns boolean if and only if both strings match.

compareTo is meant to not just tell if they match but also to tell which String is lesser than the other, and also by how much, lexicographically. This is mostly used while sorting in collection.

How to bind list to dataGridView?

Use a BindingList and set the DataPropertyName-Property of the column.

Try the following:

...
private void BindGrid()
{
    gvFilesOnServer.AutoGenerateColumns = false;

    //create the column programatically
    DataGridViewCell cell = new DataGridViewTextBoxCell();
    DataGridViewTextBoxColumn colFileName = new DataGridViewTextBoxColumn()
    {
        CellTemplate = cell, 
        Name = "Value",
        HeaderText = "File Name",
        DataPropertyName = "Value" // Tell the column which property of FileName it should use
     };

    gvFilesOnServer.Columns.Add(colFileName);

    var filelist = GetFileListOnWebServer().ToList();
    var filenamesList = new BindingList<FileName>(filelist); // <-- BindingList

    //Bind BindingList directly to the DataGrid, no need of BindingSource
    gvFilesOnServer.DataSource = filenamesList 
}

Delete data with foreign key in SQL Server table

SET foreign_key_checks = 0; DELETE FROM yourtable; SET foreign_key_checks = 1;

How to recover deleted rows from SQL server table?

What is gone is gone. The only protection I know of is regular backup.

File name without extension name VBA

strTestString = Left(ThisWorkbook.Name, (InStrRev(ThisWorkbook.Name, ".", -1, vbTextCompare) - 1))

full credit: http://mariaevert.dk/vba/?p=162

Text vertical alignment in WPF TextBlock

I think it's wise to use a textbox with no border and background as an easy and fast way to reach center aligned textblock

<TextBox
TextWrapping="Wrap"
HorizontalContentAlignment="Center"
VerticalContentAlignment="Center"
Background="{x:Null}"
BorderBrush="{x:Null}"
/>

JAX-WS and BASIC authentication, when user names and passwords are in a database

In your client SOAP handler you need to set javax.xml.ws.security.auth.username and javax.xml.ws.security.auth.password property as follow:

public class ClientHandler implements SOAPHandler<SOAPMessageContext>{

    public boolean handleMessage(final SOAPMessageContext soapMessageContext)
    {
        final Boolean outInd = (Boolean)soapMessageContext.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
        if (outInd.booleanValue())
        {
          try 
          {
               soapMessageContext.put("javax.xml.ws.security.auth.username", <ClientUserName>);
               soapMessageContext.put("javax.xml.ws.security.auth.password", <ClientPassword>);
          } 
          catch (Exception e)
          {
               e.printStackTrace();
               return false;
          }
         }
      return true;
     }
}

On duplicate key ignore?

Would suggest NOT using INSERT IGNORE as it ignores ALL errors (ie its a sloppy global ignore). Instead, since in your example tag is the unique key, use:

INSERT INTO table_tags (tag) VALUES ('tag_a'),('tab_b'),('tag_c') ON DUPLICATE KEY UPDATE tag=tag;

on duplicate key produces:

Query OK, 0 rows affected (0.07 sec)

TypeError: 'str' does not support the buffer interface

For Python 3.x you can convert your text to raw bytes through:

bytes("my data", "encoding")

For example:

bytes("attack at dawn", "utf-8")

The object returned will work with outfile.write.

Git: Could not resolve host github.com error while cloning remote repository in git

If all the above answers failed to solve your problem, try rebooting the router.

Worked for me.

How can I convert a DateTime to the number of seconds since 1970?

You can create a startTime and endTime of DateTime, then do endTime.Subtract(startTime). Then output your span.Seconds.

I think that should work.

How to know if .keyup() is a character key (jQuery)

I'm not totally satisfied with the other answers given. They've all got some kind of flaw to them.

Using keyPress with event.which is unreliable because you can't catch a backspace or a delete (as mentioned by Tarl). Using keyDown (as in Niva's and Tarl's answers) is a bit better, but the solution is flawed because it attempts to use event.keyCode with String.fromCharCode() (keyCode and charCode are not the same!).

However, what we DO have with the keydown or keyup event is the actual key that was pressed (event.key). As far as I can tell, any key with a length of 1 is a character (number or letter) regardless of which language keyboard you're using. Please correct me if that's not true!

Then there's that very long answer from asdf. That might work perfectly, but it seems like overkill.


So here's a simple solution that will catch all characters, backspace, and delete. (Note: either keyup or keydown will work here, but keypress will not)

$("input").keydown(function(event) {

    var isWordCharacter = event.key.length === 1;
    var isBackspaceOrDelete = event.keyCode === 8 || event.keyCode === 46;

    if (isWordCharacter || isBackspaceOrDelete) {
        // do something
    }
});

Show hide divs on click in HTML and CSS without jQuery

Using label and checkbox input

Keeps the selected item opened and togglable.

_x000D_
_x000D_
.collapse{_x000D_
  cursor: pointer;_x000D_
  display: block;_x000D_
  background: #cdf;_x000D_
}_x000D_
.collapse + input{_x000D_
  display: none; /* hide the checkboxes */_x000D_
}_x000D_
.collapse + input + div{_x000D_
  display:none;_x000D_
}_x000D_
.collapse + input:checked + div{_x000D_
  display:block;_x000D_
}
_x000D_
<label class="collapse" for="_1">Collapse 1</label>_x000D_
<input id="_1" type="checkbox"> _x000D_
<div>Content 1</div>_x000D_
_x000D_
<label class="collapse" for="_2">Collapse 2</label>_x000D_
<input id="_2" type="checkbox">_x000D_
<div>Content 2</div>
_x000D_
_x000D_
_x000D_

Using label and named radio input

Similar to checkboxes, it just closes the already opened one.
Use name="c1" type="radio" on both inputs.

_x000D_
_x000D_
.collapse{_x000D_
  cursor: pointer;_x000D_
  display: block;_x000D_
  background: #cdf;_x000D_
}_x000D_
.collapse + input{_x000D_
  display: none; /* hide the checkboxes */_x000D_
}_x000D_
.collapse + input + div{_x000D_
  display:none;_x000D_
}_x000D_
.collapse + input:checked + div{_x000D_
  display:block;_x000D_
}
_x000D_
<label class="collapse" for="_1">Collapse 1</label>_x000D_
<input id="_1" type="radio" name="c1"> _x000D_
<div>Content 1</div>_x000D_
_x000D_
<label class="collapse" for="_2">Collapse 2</label>_x000D_
<input id="_2" type="radio" name="c1">_x000D_
<div>Content 2</div>
_x000D_
_x000D_
_x000D_

Using tabindex and :focus

Similar to radio inputs, additionally you can trigger the states using the Tab key.
Clicking outside of the accordion will close all opened items.

_x000D_
_x000D_
.collapse > a{_x000D_
  background: #cdf;_x000D_
  cursor: pointer;_x000D_
  display: block;_x000D_
}_x000D_
.collapse:focus{_x000D_
  outline: none;_x000D_
}_x000D_
.collapse > div{_x000D_
  display: none;_x000D_
}_x000D_
.collapse:focus div{_x000D_
  display: block; _x000D_
}
_x000D_
<div class="collapse" tabindex="1">_x000D_
  <a>Collapse 1</a>_x000D_
  <div>Content 1....</div>_x000D_
</div>_x000D_
_x000D_
<div class="collapse" tabindex="1">_x000D_
  <a>Collapse 2</a>_x000D_
  <div>Content 2....</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Using :target

Similar to using radio input, you can additionally use Tab and keys to operate

_x000D_
_x000D_
.collapse a{_x000D_
  display: block;_x000D_
  background: #cdf;_x000D_
}_x000D_
.collapse > div{_x000D_
  display:none;_x000D_
}_x000D_
.collapse > div:target{_x000D_
  display:block; _x000D_
}
_x000D_
<div class="collapse">_x000D_
  <a href="#targ_1">Collapse 1</a>_x000D_
  <div id="targ_1">Content 1....</div>_x000D_
</div>_x000D_
_x000D_
<div class="collapse">_x000D_
  <a href="#targ_2">Collapse 2</a>_x000D_
  <div id="targ_2">Content 2....</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Using <detail> and <summary> tags (pure HTML)

You can use HTML5's detail and summary tags to solve this problem without any CSS styling or Javascript. Please note that these tags are not supported by Internet Explorer.

_x000D_
_x000D_
<details>_x000D_
  <summary>Collapse 1</summary>_x000D_
  <p>Content 1...</p>_x000D_
</details>_x000D_
<details>_x000D_
  <summary>Collapse 2</summary>_x000D_
  <p>Content 2...</p>_x000D_
</details>
_x000D_
_x000D_
_x000D_

Why can't I reference my class library?

If you're referencing assemblies for projects that are in the same solution, add a Project reference (using the "Projects" tab) rather than browsing for the dll in the \bin\Debug (or \bin\Release) folder (using the "Browse" tab). See screen shot below. Only browse for the assembly/dll file if it's considered an external assembly.

enter image description here

Why doesn't JUnit provide assertNotEquals methods?

I wonder same. The API of Assert is not very symmetric; for testing whether objects are the same, it provides assertSame and assertNotSame.

Of course, it is not too long to write:

assertFalse(foo.equals(bar));

With such an assertion, the only informative part of the output is unfortunately the name of the test method, so descriptive message should be formed separately:

String msg = "Expected <" + foo + "> to be unequal to <" + bar +">";
assertFalse(msg, foo.equals(bar));

That is of course so tedious, that it is better to roll your own assertNotEqual. Luckily in future it will maybe be part of the JUnit: JUnit issue 22

How to center a label text in WPF?

Sample:

Label label = new Label();
label.HorizontalContentAlignment = HorizontalAlignment.Center;

Calling a user defined function in jQuery

jQuery.fn.make_me_red = function() {
    alert($(this).attr('id'));
    $(this).siblings("#hello").toggle();
}
$("#user_button").click(function(){
    //$(this).siblings(".hello").make_me_red(); 
    $(this).make_me_red(); 
    $(this).addClass("active");
});
?

Function declaration and callback in jQuery.

java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.testing.models.Account

I had a similar exception (but different problem) - java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to org.bson.Document , and fortunately it's solved easier:

Instead of

List<Document> docs = obj.get("documents");
Document doc = docs.get(0)

which gives error on second line, One can use

List<Document> docs = obj.get("documents");
Document doc = new Document(docs.get(0));

Why doesn't logcat show anything in my Android?

OK. This is how I got it to work. I first followed MoMo's advice, that is...

If the LogCat panel is empty in Eclipse the emulator doesn't have the focus. Go to the DDMS perspective and try clicking on the 'emulator' entry in the Devices panel (top-left screen).

But to no avail.

I then attempted to reset adb (Android Debug Bridge) as suggested by furikuretsu. How? Window -> Devices -> upside down triangle menu button -> Reset adb.

It also didn't work, but I did get the following message:

Android hierarchyviewer: Unable to get the focused window from device

This meant that MoMo was right in that my Android device or emulator didn't have focus. However, the solution I did in my case is different.

What worked for me:

1) Replugged my Android device, which was connected to my computer via USB.

2) Restarted Eclipse, as mentioned by Abu Hamzah (although since I didn't know I can do File -> Restart, I manually closed down Eclipse, and then restarted the application again.)

I can now see logs in my logcat.

Hope this helps you too.

.NET 4.0 has a new GAC, why?

It doesn't make a lot of sense, the original GAC was already quite capable of storing different versions of assemblies. And there's little reason to assume a program will ever accidentally reference the wrong assembly, all the .NET 4 assemblies got the [AssemblyVersion] bumped up to 4.0.0.0. The new in-process side-by-side feature should not change this.

My guess: there were already too many .NET projects out there that broke the "never reference anything in the GAC directly" rule. I've seen it done on this site several times.

Only one way to avoid breaking those projects: move the GAC. Back-compat is sacred at Microsoft.

How to redirect user's browser URL to a different page in Nodejs?

For those who (unlike OP) are using the express lib:

http.get('*',function(req,res){  
    res.redirect('http://exmple.com'+req.url)
})

TSQL Pivot without aggregate function

Here is a great way to build dynamic fields for a pivot query:

--summarize values to a tmp table

declare @STR varchar(1000)
SELECT  @STr =  COALESCE(@STr +', ', '') 
+ QUOTENAME(DateRange) 
from (select distinct DateRange, ID from ##pivot)d order by ID

---see the fields generated

print @STr

exec('  .... pivot code ...
pivot (avg(SalesAmt) for DateRange IN (' + @Str +')) AS P
order by Decile')

How to change my Git username in terminal?

Firstly you need to change credentials from your local machine

  1. remove generic credentials if there is any

Generic credentials

  1. configure new user and email (you can make it globally if you want)
git config [--global] user.name "Your Name"
git config [--global] user.email "[email protected]"
  1. now upload or update your repo it will ask your username and password to get access to github

javax.faces.application.ViewExpiredException: View could not be restored

You coud use your own custom AjaxExceptionHandler or primefaces-extensions

Update your faces-config.xml

...
<factory>
  <exception-handler-factory>org.primefaces.extensions.component.ajaxerrorhandler.AjaxExceptionHandlerFactory</exception-handler-factory>
</factory>
...

Add following code in your jsf page

...
<pe:ajaxErrorHandler />
...

res.sendFile absolute path

Just try this instead:

res.sendFile('public/index1.html' , { root : __dirname});

This worked for me. the root:__dirname will take the address where server.js is in the above example and then to get to the index1.html ( in this case) the returned path is to get to the directory where public folder is.

How to use glOrtho() in OpenGL?

Have a look at this picture: Graphical Projections enter image description here

The glOrtho command produces an "Oblique" projection that you see in the bottom row. No matter how far away vertexes are in the z direction, they will not recede into the distance.

I use glOrtho every time I need to do 2D graphics in OpenGL (such as health bars, menus etc) using the following code every time the window is resized:

glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0f, windowWidth, windowHeight, 0.0f, 0.0f, 1.0f);

This will remap the OpenGL coordinates into the equivalent pixel values (X going from 0 to windowWidth and Y going from 0 to windowHeight). Note that I've flipped the Y values because OpenGL coordinates start from the bottom left corner of the window. So by flipping, I get a more conventional (0,0) starting at the top left corner of the window rather.

Note that the Z values are clipped from 0 to 1. So be careful when you specify a Z value for your vertex's position, it will be clipped if it falls outside that range. Otherwise if it's inside that range, it will appear to have no effect on the position except for Z tests.

Bitbucket fails to authenticate on git pull

This answer is for SO users who browse here after searching for the error.

  • Terminal will not accept your Bitbucket or Atlassian web app password if
    your account is associated with an Atlassian (Jira) account. If this is your case, you have a giant string generated for you that you can find in your MacOSX keychain app. This is the password Terminal accepts.
  • It is not clear how to re-generate this password or re-set it to match what Bitbucket will accept.
  • Changing password in SourceTree's settings did not work for me.
  • Changing password in Atlassian account profile did not work for me.
  • Bitbucket does not have a link or interface to change password for this case in the Bitbucket account profile - user has to go to Atlassian account profile.

In my case, nothing worked because I changed my username in Bitbucket.

Atlassian and Bitbucket are not completely integrated. Bitbucket uses the Atlassian user email and web app password, but allows you to have a different username.

There seems to be a bug in this process, especially since it's not clear which application or process is generating the authentication and where it's stored or editable. Changing the username breaks authentication.

There may be a way to update the username used by the credentials and Bitbucket, but I was already several hours behind when I discovered that changing my username back to what it was before restored authentication.

How to provide a file download from a JSF backing bean?

Introduction

You can get everything through ExternalContext. In JSF 1.x, you can get the raw HttpServletResponse object by ExternalContext#getResponse(). In JSF 2.x, you can use the bunch of new delegate methods like ExternalContext#getResponseOutputStream() without the need to grab the HttpServletResponse from under the JSF hoods.

On the response, you should set the Content-Type header so that the client knows which application to associate with the provided file. And, you should set the Content-Length header so that the client can calculate the download progress, otherwise it will be unknown. And, you should set the Content-Disposition header to attachment if you want a Save As dialog, otherwise the client will attempt to display it inline. Finally just write the file content to the response output stream.

Most important part is to call FacesContext#responseComplete() to inform JSF that it should not perform navigation and rendering after you've written the file to the response, otherwise the end of the response will be polluted with the HTML content of the page, or in older JSF versions, you will get an IllegalStateException with a message like getoutputstream() has already been called for this response when the JSF implementation calls getWriter() to render HTML.

Turn off ajax / don't use remote command!

You only need to make sure that the action method is not called by an ajax request, but that it is called by a normal request as you fire with <h:commandLink> and <h:commandButton>. Ajax requests and remote commands are handled by JavaScript which in turn has, due to security reasons, no facilities to force a Save As dialogue with the content of the ajax response.

In case you're using e.g. PrimeFaces <p:commandXxx>, then you need to make sure that you explicitly turn off ajax via ajax="false" attribute. In case you're using ICEfaces, then you need to nest a <f:ajax disabled="true" /> in the command component.

Generic JSF 2.x example

public void download() throws IOException {
    FacesContext fc = FacesContext.getCurrentInstance();
    ExternalContext ec = fc.getExternalContext();

    ec.responseReset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
    ec.setResponseContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ExternalContext#getMimeType() for auto-detection based on filename.
    ec.setResponseContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
    ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.

    OutputStream output = ec.getResponseOutputStream();
    // Now you can write the InputStream of the file to the above OutputStream the usual way.
    // ...

    fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}

Generic JSF 1.x example

public void download() throws IOException {
    FacesContext fc = FacesContext.getCurrentInstance();
    HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();

    response.reset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
    response.setContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ServletContext#getMimeType() for auto-detection based on filename.
    response.setContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.

    OutputStream output = response.getOutputStream();
    // Now you can write the InputStream of the file to the above OutputStream the usual way.
    // ...

    fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}

Common static file example

In case you need to stream a static file from the local disk file system, substitute the code as below:

File file = new File("/path/to/file.ext");
String fileName = file.getName();
String contentType = ec.getMimeType(fileName); // JSF 1.x: ((ServletContext) ec.getContext()).getMimeType(fileName);
int contentLength = (int) file.length();

// ...

Files.copy(file.toPath(), output);

Common dynamic file example

In case you need to stream a dynamically generated file, such as PDF or XLS, then simply provide output there where the API being used expects an OutputStream.

E.g. iText PDF:

String fileName = "dynamic.pdf";
String contentType = "application/pdf";

// ...

Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, output);
document.open();
// Build PDF content here.
document.close();

E.g. Apache POI HSSF:

String fileName = "dynamic.xls";
String contentType = "application/vnd.ms-excel";

// ...

HSSFWorkbook workbook = new HSSFWorkbook();
// Build XLS content here.
workbook.write(output);
workbook.close();

Note that you cannot set the content length here. So you need to remove the line to set response content length. This is technically no problem, the only disadvantage is that the enduser will be presented an unknown download progress. In case this is important, then you really need to write to a local (temporary) file first and then provide it as shown in previous chapter.

Utility method

If you're using JSF utility library OmniFaces, then you can use one of the three convenient Faces#sendFile() methods taking either a File, or an InputStream, or a byte[], and specifying whether the file should be downloaded as an attachment (true) or inline (false).

public void download() throws IOException {
    Faces.sendFile(file, true);
}

Yes, this code is complete as-is. You don't need to invoke responseComplete() and so on yourself. This method also properly deals with IE-specific headers and UTF-8 filenames. You can find source code here.

How to update array value javascript?

"But i want to know a better way to do this, if there is one ?"

Yes, since you seem to already have the original object, there's no reason to fetch it again from the Array.

  function Update(keyValue, newKey, newValue)
  {
    keyValue.Key = newKey;
    keyValue.Value = newValue; 
  }

converting drawable resource image into bitmap

Here is another way to convert Drawable resource into Bitmap in android:

Drawable drawable = getResources().getDrawable(R.drawable.input);
Bitmap bitmap = ((BitmapDrawable)drawable).getBitmap();

How to add a .dll reference to a project in Visual Studio

For Visual Studio 2019 you may not find Project -> Add Reference option. Use Project -> Add Project Reference. Then in dialog window navigate to Browse tab and use Browse to find and attach your dll.

Vue - Deep watching an array of objects and calculating the change?

It is well defined behaviour. You cannot get the old value for a mutated object. That's because both the newVal and oldVal refer to the same object. Vue will not keep an old copy of an object that you mutated.

Had you replaced the object with another one, Vue would have provided you with correct references.

Read the Note section in the docs. (vm.$watch)

More on this here and here.

C# constructors overloading

public Point2D(Point2D point) : this(point.X, point.Y) { }

How to set default text for a Tkinter Entry widget

Use Entry.insert. For example:

try:
    from tkinter import *  # Python 3.x
except Import Error:
    from Tkinter import *  # Python 2.x

root = Tk()
e = Entry(root)
e.insert(END, 'default text')
e.pack()
root.mainloop()

Or use textvariable option:

try:
    from tkinter import *  # Python 3.x
except Import Error:
    from Tkinter import *  # Python 2.x

root = Tk()
v = StringVar(root, value='default text')
e = Entry(root, textvariable=v)
e.pack()
root.mainloop()

Python regex findall

Use this pattern,

pattern = '\[P\].+?\[\/P\]'

Check here

java.util.regex - importance of Pattern.compile()?

It is matter of performance and memory usage, compile and keep the complied pattern if you need to use it a lot. A typical usage of regex is to validated user input (format), and also format output data for users, in these classes, saving the complied pattern, seems quite logical as they usually called a lot.

Below is a sample validator, which is really called a lot :)

public class AmountValidator {
    //Accept 123 - 123,456 - 123,345.34
    private static final String AMOUNT_REGEX="\\d{1,3}(,\\d{3})*(\\.\\d{1,4})?|\\.\\d{1,4}";
    //Compile and save the pattern  
    private static final Pattern AMOUNT_PATTERN = Pattern.compile(AMOUNT_REGEX);


    public boolean validate(String amount){

         if (!AMOUNT_PATTERN.matcher(amount).matches()) {
            return false;
         }    
        return true;
    }    
}

As mentioned by @Alan Moore, if you have reusable regex in your code, (before a loop for example), you must compile and save pattern for reuse.

HMAC-SHA256 Algorithm for signature calculation

Here is my solution:

public static String encode(String key, String data) throws Exception {
  Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
  SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
  sha256_HMAC.init(secret_key);

  return Hex.encodeHexString(sha256_HMAC.doFinal(data.getBytes("UTF-8")));
}

public static void main(String [] args) throws Exception {
  System.out.println(encode("key", "The quick brown fox jumps over the lazy dog"));
}

Or you can return the hash encoded in Base64:

Base64.encodeBase64String(sha256_HMAC.doFinal(data.getBytes("UTF-8")));

The output in hex is as expected:

f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8

PL/SQL, how to escape single quote in a string?

EXECUTE IMMEDIATE 'insert into MY_TBL (Col) values(''ER0002'')'; worked for me. closing the varchar/string with two pairs of single quotes did the trick. Other option could be to use using keyword, EXECUTE IMMEDIATE 'insert into MY_TBL (Col) values(:text_string)' using 'ER0002'; Remember using keyword will not work, if you are using EXECUTE IMMEDIATE to execute DDL's with parameters, however, using quotes will work for DDL's.

Two statements next to curly brace in an equation

Or this:

f(x)=\begin{cases}
0, & -\pi\leqslant x <0\\
\pi, & 0 \leqslant x \leqslant +\pi
\end{cases}

String compare in Perl with "eq" vs "=="

Maybe the condition you are using is incorrect:

$str1 == "taste" && $str2 == "waste"

The program will enter into THEN part only when both of the stated conditions are true.

You can try with $str1 == "taste" || $str2 == "waste". This will execute the THEN part if anyone of the above conditions are true.

How to add 10 days to current time in Rails

Try this on Rails

Time.new + 10.days 

Try this on Ruby

require 'date'
DateTime.now.next_day(10).to_time

How do I instantiate a JAXBElement<String> object?

ObjectFactory fact = new ObjectFactory();   
JAXBElement<String> str = fact.createCompositeTypeStringValue("vik");    
comp.setStringValue(str);
CompositeType retcomp = service.getDataUsingDataContract(comp);
System.out.println(retcomp.getStringValue().getValue());

Finding the second highest number in array

public class SecondandThirdHighestElement {
    public static void main(String[] args) {
        int[] arr = {1,1,2,3,8,1,2,3,3,3,2,3,101,6,6,7,8,8,1001,99,1,0};
        // create three temp variable and store arr of first element in that temp variable so that it will compare with other element
        int firsttemp = arr[0];
        int secondtemp = arr[0];
        int thirdtemp = arr[0];
        //check and find first highest value from array by comparing with other elements if found than save in the first temp variable 
        for (int i = 0; i < arr.length; i++) {
            if(firsttemp <arr[i]){
                firsttemp =  arr[i];
            }//if

        }//for
        //check and find the second highest variable by comparing with other elements in an array and find the element and that element should be smaller than first element array
        for (int i = 0; i < arr.length; i++) {
            if(secondtemp < arr[i] && firsttemp>arr[i]){
                secondtemp = arr[i];
            }//if
        }//for
        //check and find the third highest variable by comparing with other elements in an array and find the element and that element should be smaller than second element array

        for (int i = 0; i < arr.length; i++) {
            if(thirdtemp < arr[i] && secondtemp>arr[i]){
                thirdtemp = arr[i];
            }//if
        }//for

        System.out.println("First Highest Value:"+firsttemp);
        System.out.println("Second Highest Value:"+secondtemp);
        System.out.println("Third Highest  Value:"+thirdtemp);

    }//main
}//class

How to load image (and other assets) in Angular an project?

I fixed it. My actual image file name had spaces in it, and for whatever reason Angular did not like that. When I removed the spaces from my file name, assets/images/myimage.png worked.

How can I get the CheckBoxList selected values, what I have doesn't seem to work C#.NET/VisualWebPart

// Page.aspx //

// To count checklist item

  int a = ChkMonth.Items.Count;
        int count = 0;

        for (var i = 0; i < a; i++)
        {
            if (ChkMonth.Items[i].Selected == true)
            {
                count++;
            }
        }

// Page.aspx.cs //

  // To access checkbox list item's value //
   string YrStrList = "";
        foreach (ListItem listItem in ChkMonth.Items)
        {
            if (listItem.Selected)
            {
                YrStrList = YrStrList + "'" + listItem.Value + "'" + ",";
            }

        }

        sMonthStr = YrStrList.ToString();

Can RDP clients launch remote applications and not desktops

Yes, you can change the default shell from Explorer.exe to a specific application.

In Regedit, navigate to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon. The current shell should be Explorer.exe. Change it to YourApp.exe. That will change the shell for all users who log on to the machine. If you only want to change it for a specific user, go to the same key in HKEY_CURRENT_USER instead.

How to set the current working directory?

It work for Mac also

import os
path="/Users/HOME/Desktop/Addl Work/TimeSeries-Done"
os.chdir(path)

To check working directory

os.getcwd()

What is the purpose of the vshost.exe file?

It seems to be a long-running framework process for debugging (to decrease load times?). I discovered that when you start your application twice from the debugger often the same vshost.exe process will be used. It just unloads all user-loaded DLLs first. This does odd things if you are fooling around with API hooks from managed processes.

Change name of folder when cloning from GitHub?

git clone <Repo> <DestinationDirectory>

Clone the repository located at Repo into the folder called DestinationDirectory on the local machine.

Parsing json and searching through it

You can use jsonpipe if you just need the output (and more comfortable with command line):

cat bookmarks.json | jsonpipe |grep uri

Jquery If radio button is checked

jQuery('input[name="inputName"]:checked').val()

Is there an advantage to use a Synchronized Method instead of a Synchronized Block?

Note: static synchronized methods and blocks work on the Class object.

public class MyClass {
   // locks MyClass.class
   public static synchronized void foo() {
// do something
   }

   // similar
   public static void foo() {
      synchronized(MyClass.class) {
// do something
      }
   }
}

Playing a video in VideoView in Android

VideoView can only Stream 3gp videos I recommend this code to stream your video or try a higher version of android. Try Video Online Streaming.

public void onCreate(Bundle savedInstanceState) {
    setContentView(R.layout.main);
    String videourl = "http://something.com/blah.mp4";
    Uri uri = Uri.parse(videourl);
    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
    intent.setDataAndType(uri, "video/mp4");
    startActivity(intent);
}

Or Click here to watch Android Video Streaming Tutorial.

Even though JRE 8 is installed on my MAC -" No Java Runtime present,requesting to install " gets displayed in terminal

If you came across the error when tried to generate a jks file (keystore), so try adding

/Applications/Android\ Studio.app/Contents/jre/jdk/Contents/Home/bin/keytool

before running the command, like so:

/Applications/Android\ Studio.app/Contents/jre/jdk/Contents/Home/bin/keytool -genkey -v -keystore ~/key.jks -keyalg RSA -keysize 2048 -validity 10000 -alias key

Insert string in beginning of another string

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

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

When you write:

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

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


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

How to get the python.exe location programmatically?

This works in Linux & Windows:

Python 3.x

>>> import sys
>>> print(sys.executable)
C:\path\to\python.exe

Python 2.x

>>> import sys
>>> print sys.executable
/usr/bin/python

How do I check what version of Python is running my script?

To check from the command-line, in one single command, but include major, minor, micro version, releaselevel and serial, then invoke the same Python interpreter (i.e. same path) as you're using for your script:

> path/to/your/python -c "import sys; print('{}.{}.{}-{}-{}'.format(*sys.version_info))"

3.7.6-final-0

Note: .format() instead of f-strings or '.'.join() allows you to use arbitrary formatting and separator chars, e.g. to make this a greppable one-word string. I put this inside a bash utility script that reports all important versions: python, numpy, pandas, sklearn, MacOS, xcode, clang, brew, conda, anaconda, gcc/g++ etc. Useful for logging, replicability, troubleshootingm bug-reporting etc.

Regex: match everything but specific pattern

You can put a ^ in the beginning of a character set to match anything but those characters.

[^=]*

will match everything but =

how to add values to an array of objects dynamically in javascript?

You have to instantiate the object first. The simplest way is:

var lab =["1","2","3"];
var val = [42,55,51,22];
var data = [];
for(var i=0; i<4; i++)  {
    data.push({label: lab[i], value: val[i]});
}

Or an other, less concise way, but closer to your original code:

for(var i=0; i<4; i++)  {
   data[i] = {};              // creates a new object
   data[i].label = lab[i];
   data[i].value = val[i];    
}

array() will not create a new array (unless you defined that function). Either Array() or new Array() or just [].

I recommend to read the MDN JavaScript Guide.

React native ERROR Packager can't listen on port 8081

First of all, in your device go to Dev. Option -> ADB over Network after do it:

$ adb connect <your device adb network>
$ react-native run-android 

(or run-ios, by the way)

if this has successfully your device has installed app-debug.apk, open app-debug and go to Dev. Settings -> Debug server host & port for device, type in your machine's IP address (generally, System preference -> Network), as in the example below < your machine's IP address >:8081 (whihout inequality)

finally, execute the command below

$ react-native start --port=8081

try another ports, and verify that you machine and your device are same network.

How to select the rows with maximum values in each group with dplyr?

This more verbose solution provides greater control on what happens in case of duplicate maximum value (in this example, it will take one of the corresponding rows randomly)

library(dplyr)
df %>% group_by(A, B) %>%
  mutate(the_rank  = rank(-value, ties.method = "random")) %>%
  filter(the_rank == 1) %>% select(-the_rank)

ASP.NET MVC 3 Razor: Include JavaScript file in the head tag

You can use Named Sections.

_Layout.cshtml

<head>
    <script type="text/javascript" src="@Url.Content("/Scripts/jquery-1.6.2.min.js")"></script>
    @RenderSection("JavaScript", required: false)
</head>

_SomeView.cshtml

@section JavaScript
{
   <script type="text/javascript" src="@Url.Content("/Scripts/SomeScript.js")"></script>
   <script type="text/javascript" src="@Url.Content("/Scripts/AnotherScript.js")"></script>
}

Difference between Pragma and Cache-Control headers?

There is no difference, except that Pragma is only defined as applicable to the requests by the client, whereas Cache-Control may be used by both the requests of the clients and the replies of the servers.

So, as far as standards go, they can only be compared from the perspective of the client making a requests and the server receiving a request from the client. The http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.32 defines the scenario as follows:

HTTP/1.1 caches SHOULD treat "Pragma: no-cache" as if the client had sent "Cache-Control: no-cache". No new Pragma directives will be defined in HTTP.

  Note: because the meaning of "Pragma: no-cache as a response
  header field is not actually specified, it does not provide a
  reliable replacement for "Cache-Control: no-cache" in a response

The way I would read the above:

  • if you're writing a client and need no-cache:

    • just use Pragma: no-cache in your requests, since you may not know if Cache-Control is supported by the server;
    • but in replies, to decide on whether to cache, check for Cache-Control
  • if you're writing a server:

    • in parsing requests from the clients, check for Cache-Control; if not found, check for Pragma: no-cache, and execute the Cache-Control: no-cache logic;
    • in replies, provide Cache-Control.

Of course, reality might be different from what's written or implied in the RFC!

How to read the Stock CPU Usage data

More about "load average" showing CPU load over 1 minute, 5 minutes and 15 minutes

Linux, Mac, and other Unix-like systems display “load average” numbers. These numbers tell you how busy your system’s CPU, disk, and other resources are. They’re not self-explanatory at first, but it’s easy to become familiar with them.

WIKI: example, one can interpret a load average of "1.73 0.60 7.98" on a single-CPU system as:

during the last minute, the system was overloaded by 73% on average (1.73 runnable processes, so that 0.73 processes had to wait for a turn for a single CPU system on average).
during the last 5 minutes, the CPU was idling 40% of the time on average.
during the last 15 minutes, the system was overloaded 698% on average (7.98 runnable processes, so that 6.98 processes had to wait for a turn for a single CPU system on average) if dual core mean: 798% - 200% = 598%. 

You probably have a system with multiple CPUs or a multi-core CPU. The load average numbers work a bit differently on such a system. For example, if you have a load average of 2 on a single-CPU system, this means your system was overloaded by 100 percent — the entire period of time, one process was using the CPU while one other process was waiting. On a system with two CPUs, this would be complete usage — two different processes were using two different CPUs the entire time. On a system with four CPUs, this would be half usage — two processes were using two CPUs, while two CPUs were sitting idle.

To understand the load average number, you need to know how many CPUs your system has. A load average of 6.03 would indicate a system with a single CPU was massively overloaded, but it would be fine on a computer with 8 CPUs.

more info : Link

Convert NSDate to String in iOS Swift

You can use this extension:

extension Date {

    func toString(withFormat format: String) -> String {
        let formatter = DateFormatter()
        formatter.dateFormat = format
        let myString = formatter.string(from: self)
        let yourDate = formatter.date(from: myString)
        formatter.dateFormat = format

        return formatter.string(from: yourDate!)
    }
}

And use it in your view controller like this (replace <"yyyy"> with your format):

yourString = yourDate.toString(withFormat: "yyyy")

Visual Studio - How to change a project's folder name and solution name without breaking the solution

I found that these instructions were not enough. I also had to search through the code files for models, controllers, and views as well as the AppStart files to change the namespace.

Since I was copying my project not just renaming it, I also had to go into the applicationhost.config for IIS express and recreate the bindings using different port numbers and change the physical directory as well.

Android new Bottom Navigation bar or BottomNavigationView

As Sanf0rd mentioned, Google launched the BottomNavigationView as part of the Design Support Library version 25.0.0. The limitations he mentioned are mostly true, except that you CAN change the background color of the view and even the text color and icon tint color. It also has an animation when you add more than 4 items (sadly it cannot be enabled or disabled manually).

I wrote a detailed tutorial about it with examples and an accompanying repository, which you can read here: https://blog.autsoft.hu/now-you-can-use-the-bottom-navigation-view-in-the-design-support-library/


The gist of it

You have to add these in your app level build.gradle:

compile 'com.android.support:appcompat-v7:25.0.0'  
compile 'com.android.support:design:25.0.0'

You can include it in your layout like this:

<android.support.design.widget.BottomNavigationView  
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/bottom_navigation_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:itemBackground="@color/darkGrey"
        app:itemIconTint="@color/bottom_navigation_item_background_colors"
        app:itemTextColor="@color/bottom_navigation_item_background_colors"
        app:menu="@menu/menu_bottom_navigation" />

You can specify the items via a menu resource like this:

<?xml version="1.0" encoding="utf-8"?>  
<menu  
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/action_one"
        android:icon="@android:drawable/ic_dialog_map"
        android:title="One"/>
    <item
        android:id="@+id/action_two"
        android:icon="@android:drawable/ic_dialog_info"
        android:title="Two"/>
    <item
        android:id="@+id/action_three"
        android:icon="@android:drawable/ic_dialog_email"
        android:title="Three"/>
    <item
        android:id="@+id/action_four"
        android:icon="@android:drawable/ic_popup_reminder"
        android:title="Four"/>
</menu>

And you can set the tint and text color as a color list, so the currently selected item is highlighted:

<?xml version="1.0" encoding="utf-8"?>  
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:color="@color/colorAccent"
        android:state_checked="false"/>
    <item
        android:color="@android:color/white"
        android:state_checked="true"/>

</selector>

Finally, you can handle the selection of the items with an OnNavigationItemSelectedListener:

bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {  
    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        Fragment fragment = null;
        switch (item.getItemId()) {
            case R.id.action_one:
                // Switch to page one
                break;
            case R.id.action_two:
                // Switch to page two
                break;
            case R.id.action_three:
                // Switch to page three
                break;
        }
        return true;
    }
});

How to find locked rows in Oracle

Oracle's locking concept is quite different from that of the other systems.

When a row in Oracle gets locked, the record itself is updated with the new value (if any) and, in addition, a lock (which is essentially a pointer to transaction lock that resides in the rollback segment) is placed right into the record.

This means that locking a record in Oracle means updating the record's metadata and issuing a logical page write. For instance, you cannot do SELECT FOR UPDATE on a read only tablespace.

More than that, the records themselves are not updated after commit: instead, the rollback segment is updated.

This means that each record holds some information about the transaction that last updated it, even if the transaction itself has long since died. To find out if the transaction is alive or not (and, hence, if the record is alive or not), it is required to visit the rollback segment.

Oracle does not have a traditional lock manager, and this means that obtaining a list of all locks requires scanning all records in all objects. This would take too long.

You can obtain some special locks, like locked metadata objects (using v$locked_object), lock waits (using v$session) etc, but not the list of all locks on all objects in the database.

Pass entire form as data in jQuery Ajax function

There's a function that does exactly this:

http://api.jquery.com/serialize/

var data = $('form').serialize();
$.post('url', data);

function declaration isn't a prototype

Try:

extern int testlib(void);

Android Text over image

You can use a TextView and change its background to the image you want to use

Angular JS POST request not sending JSON data

You can use FormData API https://developer.mozilla.org/en-US/docs/Web/API/FormData

var data = new FormData;
data.append('from', from);
data.append('to', to);

$http({
    url: '/path',
    method: 'POST',
    data: data,
    transformRequest: false,
    headers: { 'Content-Type': undefined }
})

This solution from http://uncorkedstudios.com/blog/multipartformdata-file-upload-with-angularjs

Selenium and xPath - locating a link by containing text

@FindBy(xpath = "//span[@class='y2' and contains(text(), 'Your Text')] ") 
private WebElementFacade emailLinkToVerifyAccount;

This approach will work for you, hopefully.

store return json value in input hidden field

just set the hidden field with javascript :

document.getElementById('elementId').value = 'whatever';

or do I miss something?

How can I compare two dates in PHP?

Found the answer on a blog and it's as simple as:

strtotime(date("Y"."-01-01")) -strtotime($newdate))/86400

And you'll get the days between the 2 dates.

vba pass a group of cells as range to function

There is another way to pass multiple ranges to a function, which I think feels much cleaner for the user. When you call your function in the spreadsheet you wrap each set of ranges in brackets, for example: calculateIt( (A1,A3), (B6,B9) )

The above call assumes your two Sessions are in A1 and A3, and your two Customers are in B6 and B9.

To make this work, your function needs to loop through each of the Areas in the input ranges. For example:

Function calculateIt(Sessions As Range, Customers As Range) As Single

    ' check we passed the same number of areas
    If (Sessions.Areas.Count <> Customers.Areas.Count) Then
        calculateIt = CVErr(xlErrNA)
        Exit Function
    End If

    Dim mySession, myCustomers As Range

    ' run through each area and calculate
    For a = 1 To Sessions.Areas.Count

        Set mySession = Sessions.Areas(a)
        Set myCustomers = Customers.Areas(a)

        ' calculate them...
    Next a

End Function

The nice thing is, if you have both your inputs as a contiguous range, you can call this function just as you would a normal one, e.g. calculateIt(A1:A3, B6:B9).

Hope that helps :)

Add Whatsapp function to website, like sms, tel

Rahul's answer gives me an error: You seem to be trying to send a WhatsApp message to a phone number that is not registered with WhatsApp..., even though I'm sending it to a registered WhatsApp number.

This, however works:

<li><a href="intent:0123456789#Intent;scheme=smsto;package=com.whatsapp;action=android.intent.action.SENDTO;end"><i class="fa fa-whatsapp"></i>+237 655 421 621</li>

Upgrading Node.js to latest version

If you are looking in linux..

npm update will not work mostly am not sure reason but following steps will help you to resolve issue...

Terminal process to upgrade node 4.x to 6.x.

 $ node -v
 v4.x

Check node path

$ which node
/usr/bin/node

Download latest(6.x) node files from [Download][1]

[1]: https://nodejs.org/dist/v6.9.2/node-v6.9.2-linux-x64.tar.xz and unzip files keep in /opt/node-v6.9.2-linux-x64/.

Now unlink current node and link with latest as following

$ unlink /usr/bin/node
$ ln -s /opt/node-v6.9.2-linux-x64/bin/node node
$ node -v
$ v6.9.2

MySQL Job failed to start

Check the file permissions, if edited

Fail:

$ sudo chmod 776 /etc/mysql/my.cnf
$ sudo service mysql restart
mysql stop/waiting
start: Job failed to start

Ok:

$ sudo chmod 774 /etc/mysql/my.cnf
$ sudo service mysql restart
stop: Unknown instance:
mysql start/running, process 9564

Pip error: Microsoft Visual C++ 14.0 is required

I faced the same problem. Found the fix here.

Basically just install this.

shasum output:

3e0de8af516c15547602977db939d8c2e44fcc0b  visualcppbuildtools_full.exe

md5sum output:

MD5 (visualcppbuildtools_full.exe) = 8d4afd3b226babecaa4effb10d69eb2e

Run your pip installation command again. If everything works fine, its good. Or you might face the following error like me:

Finished generating code
    LINK : fatal error LNK1158: cannot run 'rc.exe'
    error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\x86_amd64\\link.exe' failed with exit status 1158

Found the fix for the above problem here: Visual Studio can't build due to rc.exe

That basically says

Add this to your PATH environment variables:

C:\Program Files (x86)\Windows Kits\8.1\bin\x86

Copy these files:

rc.exe
rcdll.dll

From

C:\Program Files (x86)\Windows Kits\8.1\bin\x86

To

C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\bin

It works like a charm

How can I create an error 404 in PHP?

Create custom error pages through .htaccess file

1. 404 - page not found

 RewriteEngine On
 ErrorDocument 404 /404.html

2. 500 - Internal Server Error

RewriteEngine On
ErrorDocument 500 /500.html

3. 403 - Forbidden

RewriteEngine On
ErrorDocument 403 /403.html

4. 400 - Bad request

RewriteEngine On
ErrorDocument 400 /400.html

5. 401 - Authorization Required

RewriteEngine On
ErrorDocument 401 /401.html

You can also redirect all error to single page. like

RewriteEngine On
ErrorDocument 404 /404.html
ErrorDocument 500 /404.html
ErrorDocument 403 /404.html
ErrorDocument 400 /404.html
ErrorDocument 401 /401.html

Update Angular model after setting input value with jQuery

I've written this little plugin for jQuery which will make all calls to .val(value) update the angular element if present:

(function($, ng) {
  'use strict';

  var $val = $.fn.val; // save original jQuery function

  // override jQuery function
  $.fn.val = function (value) {
    // if getter, just return original
    if (!arguments.length) {
      return $val.call(this);
    }

    // get result of original function
    var result = $val.call(this, value);

    // trigger angular input (this[0] is the DOM object)
    ng.element(this[0]).triggerHandler('input');

    // return the original result
    return result; 
  }
})(window.jQuery, window.angular);

Just pop this script in after jQuery and angular.js and val(value) updates should now play nice.


Minified version:

!function(n,t){"use strict";var r=n.fn.val;n.fn.val=function(n){if(!arguments.length)return r.call(this);var e=r.call(this,n);return t.element(this[0]).triggerHandler("input"),e}}(window.jQuery,window.angular);

Example:

_x000D_
_x000D_
// the function_x000D_
(function($, ng) {_x000D_
  'use strict';_x000D_
  _x000D_
  var $val = $.fn.val;_x000D_
  _x000D_
  $.fn.val = function (value) {_x000D_
    if (!arguments.length) {_x000D_
      return $val.call(this);_x000D_
    }_x000D_
    _x000D_
    var result = $val.call(this, value);_x000D_
    _x000D_
    ng.element(this[0]).triggerHandler('input');_x000D_
    _x000D_
    return result;_x000D_
    _x000D_
  }_x000D_
})(window.jQuery, window.angular);_x000D_
_x000D_
(function(ng){ _x000D_
  ng.module('example', [])_x000D_
    .controller('ExampleController', function($scope) {_x000D_
      $scope.output = "output";_x000D_
      _x000D_
      $scope.change = function() {_x000D_
        $scope.output = "" + $scope.input;_x000D_
      }_x000D_
    });_x000D_
})(window.angular);_x000D_
_x000D_
(function($){  _x000D_
  $(function() {_x000D_
    var button = $('#button');_x000D_
  _x000D_
    if (button.length)_x000D_
      console.log('hello, button');_x000D_
    _x000D_
    button.click(function() {_x000D_
      var input = $('#input');_x000D_
      _x000D_
      var value = parseInt(input.val());_x000D_
      value = isNaN(value) ? 0 : value;_x000D_
      _x000D_
      input.val(value + 1);_x000D_
    });_x000D_
  });_x000D_
})(window.jQuery);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div ng-app="example" ng-controller="ExampleController">_x000D_
  <input type="number" id="input" ng-model="input" ng-change="change()" />_x000D_
  <span>{{output}}</span>_x000D_
  <button id="button">+</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

What is difference between sleep() method and yield() method of multi threading?

sleep() causes the thread to definitely stop executing for a given amount of time; if no other thread or process needs to be run, the CPU will be idle (and probably enter a power saving mode).

yield() basically means that the thread is not doing anything particularly important and if any other threads or processes need to be run, they should. Otherwise, the current thread will continue to run.

How to check for an empty struct?

You can use == to compare with a zero value composite literal because all fields are comparable:

if (Session{}) == session  {
    fmt.Println("is zero value")
}

playground example

Because of a parsing ambiguity, parentheses are required around the composite literal in the if condition.

The use of == above applies to structs where all fields are comparable. If the struct contains a non-comparable field (slice, map or function), then the fields must be compared one by one to their zero values.

An alternative to comparing the entire value is to compare a field that must be set to a non-zero value in a valid session. For example, if the player id must be != "" in a valid session, use

if session.playerId == "" {
    fmt.Println("is zero value")
}

Converting a view to Bitmap without displaying it in Android?

Layout or view to bitmap:

 private Bitmap createBitmapFromLayout(View tv) {      
    int spec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
    tv.measure(spec, spec);
    tv.layout(0, 0, tv.getMeasuredWidth(), tv.getMeasuredHeight());
    Bitmap b = Bitmap.createBitmap(tv.getMeasuredWidth(), tv.getMeasuredWidth(),
            Bitmap.Config.ARGB_8888);
    Canvas c = new Canvas(b);
    c.translate((-tv.getScrollX()), (-tv.getScrollY()));
    tv.draw(c);
    return b;
}

Calling Method:

Bitmap src = createBitmapFromLayout(View.inflate(this, R.layout.sample, null)/* or pass your view object*/);

window.onload vs document.onload

According to Parsing HTML documents - The end,

  1. The browser parses the HTML source and runs deferred scripts.

  2. A DOMContentLoaded is dispatched at the document when all the HTML has been parsed and have run. The event bubbles to the window.

  3. The browser loads resources (like images) that delay the load event.

  4. A load event is dispatched at the window.

Therefore, the order of execution will be

  1. DOMContentLoaded event listeners of window in the capture phase
  2. DOMContentLoaded event listeners of document
  3. DOMContentLoaded event listeners of window in the bubble phase
  4. load event listeners (including onload event handler) of window

A bubble load event listener (including onload event handler) in document should never be invoked. Only capture load listeners might be invoked, but due to the load of a sub-resource like a stylesheet, not due to the load of the document itself.

_x000D_
_x000D_
window.addEventListener('DOMContentLoaded', function() {_x000D_
  console.log('window - DOMContentLoaded - capture'); // 1st_x000D_
}, true);_x000D_
document.addEventListener('DOMContentLoaded', function() {_x000D_
  console.log('document - DOMContentLoaded - capture'); // 2nd_x000D_
}, true);_x000D_
document.addEventListener('DOMContentLoaded', function() {_x000D_
  console.log('document - DOMContentLoaded - bubble'); // 2nd_x000D_
});_x000D_
window.addEventListener('DOMContentLoaded', function() {_x000D_
  console.log('window - DOMContentLoaded - bubble'); // 3rd_x000D_
});_x000D_
_x000D_
window.addEventListener('load', function() {_x000D_
  console.log('window - load - capture'); // 4th_x000D_
}, true);_x000D_
document.addEventListener('load', function(e) {_x000D_
  /* Filter out load events not related to the document */_x000D_
  if(['style','script'].indexOf(e.target.tagName.toLowerCase()) < 0)_x000D_
    console.log('document - load - capture'); // DOES NOT HAPPEN_x000D_
}, true);_x000D_
document.addEventListener('load', function() {_x000D_
  console.log('document - load - bubble'); // DOES NOT HAPPEN_x000D_
});_x000D_
window.addEventListener('load', function() {_x000D_
  console.log('window - load - bubble'); // 4th_x000D_
});_x000D_
_x000D_
window.onload = function() {_x000D_
  console.log('window - onload'); // 4th_x000D_
};_x000D_
document.onload = function() {_x000D_
  console.log('document - onload'); // DOES NOT HAPPEN_x000D_
};
_x000D_
_x000D_
_x000D_

Write a file on iOS

May be this is useful to you.

//Method writes a string to a text file
-(void) writeToTextFile{
        //get the documents directory:
        NSArray *paths = NSSearchPathForDirectoriesInDomains
            (NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];

        //make a file name to write the data to using the documents directory:
        NSString *fileName = [NSString stringWithFormat:@"%@/textfile.txt", 
                                                      documentsDirectory];
        //create content - four lines of text
        NSString *content = @"One\nTwo\nThree\nFour\nFive";
        //save content to the documents directory
        [content writeToFile:fileName 
                         atomically:NO 
                               encoding:NSUTF8StringEncoding 
                                      error:nil];

}


//Method retrieves content from documents directory and
//displays it in an alert
-(void) displayContent{
        //get the documents directory:
        NSArray *paths = NSSearchPathForDirectoriesInDomains
                        (NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];

        //make a file name to write the data to using the documents directory:
        NSString *fileName = [NSString stringWithFormat:@"%@/textfile.txt", 
                                                      documentsDirectory];
        NSString *content = [[NSString alloc] initWithContentsOfFile:fileName
                                                      usedEncoding:nil
                                                             error:nil];
        //use simple alert from my library (see previous post for details)
        [ASFunctions alert:content];
        [content release];

}

Labeling file upload button

Take a step back! Firstly, you're assuming the user is using a foreign locale on their device, which is not a sound assumption for justifying taking over the button text of the file picker, and making it say what you want it to.

It is reasonable that you want to control every item of language visible on your page. The content of the File Upload control is not part of the HTML though. There is more content behind this control, for example, in WebKit, it also says "No file chosen" next to the button.

There are very hacky workarounds that attempt this (e.g. like those mentioned in @ChristopheD's answer), but none of them truly succeed:

  • To a screen reader, the file control will still say "Browse..." or "Choose File", and a custom file upload will not be announced as a file upload control, but just a button or a text input.
  • Many of them fail to display the chosen file, or to show that the user has no longer chosen a file
  • Many of them look nothing like the native control, so might look strange on non-standard devices.
  • Keyboard support is typically poor.
  • An author-created UI component can never be as fully functional as its native equivalent (and the closer you get it to behave to suppose IE10 on Windows 7, the more it will deviate from other Browser and Operating System combinations).
  • Modern browsers support drag & drop into the native file upload control.
  • Some techniques may trigger heuristics in security software as a potential ‘click-jacking’ attempt to trick the user into uploading file.

Deviating from the native controls is always a risky thing, there is a whole host of different devices your users could be using, and whatever workaround you choose, you will not have tested it in every one of those devices.

However, there is an even bigger reason why all attempts fail from a User Experience perspective: there is even more non-localized content behind this control, the file selection dialog itself. Once the user is subject to traversing their file system or what not to select a file to upload, they will be subjected to the host Operating System locale.

Are you sure you're doing your user any justice by deviating from the native control, just to localize the text, when as soon as they click it, they're just going to get the Operating System locale anyway?

The best you can do for your users is to ensure you have adequate localised guidance surrounding your file input control. (e.g. Form field label, hint text, tooltip text).

Sorry. :-(

--

This answer is for those looking for any justification not to localise the file upload control.

C# ListView Column Width Auto

I believe the author was looking for an equivalent method via the IDE that would generate the code behind and make sure all parameters were in place, etc. Found this from MS:

Creating Event Handlers on the Windows Forms Designer

Coming from a VB background myself, this is what I was looking for, here is the brief version for the click adverse:

  1. Click the form or control that you want to create an event handler for.
  2. In the Properties window, click the Events button
  3. In the list of available events, click the event that you want to create an event handler for.
  4. In the box to the right of the event name, type the name of the handler and press ENTER

css 100% width div not taking up full width of parent

Remove the width:100%; declarations.

Block elements should take up the whole available width by default.

What to return if Spring MVC controller method doesn't return value?

But as your system grows in size and functionality... i think that returning always a json is not a bad idea at all. Is more a architectural / "big scale design" matter.

You can think about returing always a JSON with two know fields : code and data. Where code is a numeric code specifying the success of the operation to be done and data is any aditional data related with the operation / service requested.

Come on, when we use a backend a service provider, any service can be checked to see if it worked well.

So i stick, to not let spring manage this, exposing hybrid returning operations (Some returns data other nothing...).. instaed make sure that your server expose a more homogeneous interface. Is more simple at the end of the day.

Converting array to list in Java

Given Array:

    int[] givenArray = {2,2,3,3,4,5};

Converting integer array to Integer List

One way: boxed() -> returns the IntStream

    List<Integer> givenIntArray1 = Arrays.stream(givenArray)
                                  .boxed()
                                  .collect(Collectors.toList());

Second Way: map each element of the stream to Integer and then collect

NOTE: Using mapToObj you can covert each int element into string stream, char stream etc by casing i to (char)i

    List<Integer> givenIntArray2 = Arrays.stream(givenArray)
                                         .mapToObj(i->i)
                                         .collect(Collectors.toList());

Converting One array Type to Another Type Example:

List<Character> givenIntArray2 = Arrays.stream(givenArray)
                                             .mapToObj(i->(char)i)
                                             .collect(Collectors.toList());

PHP output showing little black diamonds with a question mark

This happened to work in my case:

$text = utf8_decode($text)

I turns the black diamond character into a question mark so you can:

$text = str_replace('?', '', utf8_decode($text));

How to enable and use HTTP PUT and DELETE with Apache2 and PHP?

IIRC the purpose of the form method attribute was to define different transport methods. Consequently, HTML 5.2 only defines GET, POST, and DIALOG methods for transport and dialog action, not how the server should process the data.

Ruby-on-rails solves this problem by using POST/GET for everything and adding a hidden form variable that defines the actual ReST method. This approach is more clumsy and error-prone, but does remove the burden from both the HTML standard and browser developers.

The form method was defined before ReST, so you cannot define ReST in HTML, even after enabling Apache and PHP because the browsers conform to HTML and therefore default to GET/POST for all non-HTML defined values. That means, when you send a form to the browser with a PUT method, the browser changes that to GET and uses that instead. The hidden variable, however, passes through everything unchanged, so you can use that to customise your form handling process.

Hope that helps

GROUP BY and COUNT in PostgreSQL

WITH uniq AS (
        SELECT DISTINCT posts.id as post_id
        FROM posts
        JOIN votes ON votes.post_id = posts.id
        -- GROUP BY not needed anymore
        -- GROUP BY posts.id
        )
SELECT COUNT(*)
FROM uniq;

Python script to do something at the same time every day

You can do that like this:

from datetime import datetime
from threading import Timer

x=datetime.today()
y=x.replace(day=x.day+1, hour=1, minute=0, second=0, microsecond=0)
delta_t=y-x

secs=delta_t.seconds+1

def hello_world():
    print "hello world"
    #...

t = Timer(secs, hello_world)
t.start()

This will execute a function (eg. hello_world) in the next day at 1a.m.

EDIT:

As suggested by @PaulMag, more generally, in order to detect if the day of the month must be reset due to the reaching of the end of the month, the definition of y in this context shall be the following:

y = x.replace(day=x.day, hour=1, minute=0, second=0, microsecond=0) + timedelta(days=1)

With this fix, it is also needed to add timedelta to the imports. The other code lines maintain the same. The full solution, using also the total_seconds() function, is therefore:

from datetime import datetime, timedelta
from threading import Timer

x=datetime.today()
y = x.replace(day=x.day, hour=1, minute=0, second=0, microsecond=0) + timedelta(days=1)
delta_t=y-x

secs=delta_t.total_seconds()

def hello_world():
    print "hello world"
    #...

t = Timer(secs, hello_world)
t.start()