Programs & Examples On #Detailtextlabel

Returns the secondary label of the table cell if one exists. (read-only)

Add swipe to delete UITableViewCell

For > ios 13 tableViewCell swipe left to action tableViewCell swipe right to action https://gist.github.com/andreconghau/de574bdbb468e001c404a7270017bef5#file-swipe_to_action_ios13-swift

/*
     SWIPE to Action
     */
    
    func tableView(_ tableView: UITableView,
                   editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
        return .none
    }
    // Right Swipe
    func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        
        let action = UIContextualAction(style: .normal,
                                        title: "Favourite") { [weak self] (action, view, completionHandler) in
                                            self?.handleMarkAsFavourite()
                                            completionHandler(true)
        }
        action.backgroundColor = .systemBlue
        
        return UISwipeActionsConfiguration(actions: [action])
    }
    
    func tableView(_ tableView: UITableView,
                       trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        // Archive action
        let archive = UIContextualAction(style: .normal,
                                         title: "Archive") { [weak self] (action, view, completionHandler) in
                                            self?.handleMoveToArchive()
                                            completionHandler(true)
        }
        archive.backgroundColor = .systemGreen

        // Trash action
        let trash = UIContextualAction(style: .destructive,
                                       title: "Trash") { [weak self] (action, view, completionHandler) in
            self?.handleMoveToTrash(book: (self?.books![indexPath.row]) as! BookItem)
                                        completionHandler(true)
        }
        trash.backgroundColor = .systemRed

        // Unread action
        let unread = UIContextualAction(style: .normal,
                                       title: "Mark as Unread") { [weak self] (action, view, completionHandler) in
                                        self?.handleMarkAsUnread()
                                        completionHandler(true)
        }
        unread.backgroundColor = .systemOrange

        let configuration = UISwipeActionsConfiguration(actions: [trash, archive, unread])
        // If you do not want an action to run with a full swipe
        configuration.performsFirstActionWithFullSwipe = false
        return configuration
    }
    
    
    
    private func handleMarkAsFavourite() {
        print("Marked as favourite")
    }

    private func handleMarkAsUnread() {
        print("Marked as unread")
    }

    private func handleMoveToTrash(book: BookItem) {
        print("Moved to trash")
        print(book)
        let alert = UIAlertController(title: "Hi!", message: "B?n có mu?n xóa \(book.name)", preferredStyle: .alert)
            
             let ok = UIAlertAction(title: "Xóa", style: .default, handler: { action in
                book.delete()
                self.listBook.reloadData()
             })
             alert.addAction(ok)
             let cancel = UIAlertAction(title: "H?y", style: .default, handler: { action in
             })
             alert.addAction(cancel)
             DispatchQueue.main.async(execute: {
                self.present(alert, animated: true)
        })
        
    }

    private func handleMoveToArchive() {
        print("Moved to archive")
    }

UITableView with fixed section headers

Swift 3.0

Create a ViewController with the UITableViewDelegate and UITableViewDataSource protocols. Then create a tableView inside it, declaring its style to be UITableViewStyle.grouped. This will fix the headers.

lazy var tableView: UITableView = {
    let view = UITableView(frame: UIScreen.main.bounds, style: UITableViewStyle.grouped)
    view.delegate = self
    view.dataSource = self
    view.separatorStyle = .none
    return view
}()

Creating a UITableView Programmatically

You might be do that its works 100% .

- (void)viewDidLoad
{
    [super viewDidLoad];
    // init table view
    tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];

    // must set delegate & dataSource, otherwise the the table will be empty and not responsive
    tableView.delegate = self;
    tableView.dataSource = self;

    tableView.backgroundColor = [UIColor cyanColor];

    // add to canvas
    [self.view addSubview:tableView];
}

#pragma mark - UITableViewDataSource
// number of section(s), now I assume there is only 1 section
- (NSInteger)numberOfSectionsInTableView:(UITableView *)theTableView
{
    return 1;
}

// number of row in the section, I assume there is only 1 row
- (NSInteger)tableView:(UITableView *)theTableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

// the cell will be returned to the tableView
- (UITableViewCell *)tableView:(UITableView *)theTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"HistoryCell";

    // Similar to UITableViewCell, but 
    JSCustomCell *cell = (JSCustomCell *)[theTableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[JSCustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    // Just want to test, so I hardcode the data
    cell.descriptionLabel.text = @"Testing";

    return cell;
}

#pragma mark - UITableViewDelegate
// when user tap the row, what action you want to perform
- (void)tableView:(UITableView *)theTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"selected %d row", indexPath.row);
}

@end

How to unstash only certain files?

I think VonC's answer is probably what you want, but here's a way to do a selective "git apply":

git show stash@{0}:MyFile.txt > MyFile.txt

Android: resizing imageview in XML

for example:

<ImageView android:id="@+id/image_view"     
  android:layout_width="wrap_content"  
  android:layout_height="wrap_content"  
  android:adjustViewBounds="true"  
  android:maxWidth="42dp"  
  android:maxHeight="42dp"  
  android:scaleType="fitCenter"  
  android:layout_marginLeft="3dp"  
  android:src="@drawable/icon"  
  /> 

Add property android:scaleType="fitCenter" and android:adjustViewBounds="true".

How do I set up IntelliJ IDEA for Android applications?

The 5th step in "New Project' has apparently changed slightly since.

Where it says android sdk then has the drop down menu that says none, there is no longer a 'new' button.

  • 5.)

    • a.)click the ... to the right of none.
    • b.)click the + in the top left of new window dialog. (Add new Sdk)
    • c.)click android sdk from drop down menu
    • d.)select home directory for your android sdk
    • e.)select java sdk version you want to use
    • f.)select android build target.
    • g.)hit ok!

cpp / c++ get pointer value or depointerize pointer

To get the value of a pointer, just de-reference the pointer.

int *ptr;
int value;
*ptr = 9;

value = *ptr;

value is now 9.

I suggest you read more about pointers, this is their base functionality.

How do I evenly add space between a label and the input field regardless of length of text?

You can always use the 'pre' tag inside the label, and just enter the blank spaces in it, So you can always add the same or different number of spaces you require

<form>
<label>First Name :<pre>Here just enter number of spaces you want to use(I mean using spacebar to enter blank spaces)</pre>
<input type="text"></label>
<label>Last Name :<pre>Now Enter enter number of spaces to match above number of 
spaces</pre>
<input type="text"></label>
</form>

Hope you like my answer, It's a simple and efficient hack

Running a cron every 30 seconds

Use watch:

$ watch --interval .30 script_to_run_every_30_sec.sh

How to change the default message of the required field in the popover of form-control in bootstrap?

And for all input and select:

$("input[required], select[required]").attr("oninvalid", "this.setCustomValidity('Required!')");
$("input[required], select[required]").attr("oninput", "setCustomValidity('')");

How do I iterate and modify Java Sets?

You could create a mutable wrapper of the primitive int and create a Set of those:

class MutableInteger
{
    private int value;
    public int getValue()
    {
        return value;
    }
    public void setValue(int value)
    {
        this.value = value;
    }
}

class Test
{
    public static void main(String[] args)
    {
        Set<MutableInteger> mySet = new HashSet<MutableInteger>();
        // populate the set
        // ....

        for (MutableInteger integer: mySet)
        {
            integer.setValue(integer.getValue() + 1);
        }
    }
}

Of course if you are using a HashSet you should implement the hash, equals method in your MutableInteger but that's outside the scope of this answer.

How to set HttpResponse timeout for Android in Java

An option is to use the OkHttp client, from Square.

Add the library dependency

In the build.gradle, include this line:

compile 'com.squareup.okhttp:okhttp:x.x.x'

Where x.x.x is the desired library version.

Set the client

For example, if you want to set a timeout of 60 seconds, do this way:

final OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.setReadTimeout(60, TimeUnit.SECONDS);
okHttpClient.setConnectTimeout(60, TimeUnit.SECONDS);

ps: If your minSdkVersion is greater than 8, you can use TimeUnit.MINUTES. So, you can simply use:

okHttpClient.setReadTimeout(1, TimeUnit.MINUTES);
okHttpClient.setConnectTimeout(1, TimeUnit.MINUTES);

For more details about the units, see TimeUnit.

Cannot load 64-bit SWT libraries on 32-bit JVM ( replacing SWT file )

So , just make sure that you are on the right environment i.e 32 bit SWT LIBRARIES should match 32 bit JVM , vice versa.

I solved this problem by installing 64-bit jdk ,64-bit jre and finally by adding setting the jdk path in environment variables adn adding jre to the eclipse.

How to open Visual Studio Code from the command line on OSX?

The instruction given at VS Code Command Line for launching a path are incorrect; the leading colon shown in the example doesn't work. However, launching with a backslash terminated directory name opens the specified directory as expected.

So, for example,

code C:\Users\DAVE\Documents\Programming\Angular\StringCalculator\src\

opens the Visual Studio Code editor in directory C:\Users\DAVE\Documents\Programming\Angular\StringCalculator\src.

Important: The terminal backslash, though optional, is useful, as it makes clear that the intend is to open a directory, as opposed to a file. Bear in mind that file name extensions are, and always have been, optional.

Beware: The directory that gets appended to the PATH list is the \bin directory, and the shell command code launches a Windows NT Command script.

Hence, when incorporated into another shell script, code must be called or started if you expect the remainder of the script to run. Thankfully, I discovered this before my first test of a new shell script that I am creating to start an Angular 2 project in a local Web server, my default Web browser, and Visual Studio Code, all at once.

Following is my Angular startup script, adapted to eliminate a dependency on one of my system utilities that is published elsewhere, but not strictly required.


@echo off

goto SKIPREM

=========================================================================

Name:               StartAngularApp.CMD

Synopsis:           Start the Angular 2 application installed in a specified
                     directory.

Arguments:          %1 = OPTIONAL: Name of directory in which to application
                          is installed

Remarks:            If no argument is specified, the application must be in
                    the current working directory.

                    This is a completely generalized Windows NT command
                    script (shell script) that uses the NPM Angular CLI to
                    load an Angular 2 application into a Node development
                    Web server, the default Web browser, and the Visual
                    Studio Code text editor.

Dependencies:       Unless otherwise specified in the command line, the
                    application is created in the current working directory.

                    All of the following shell scripts and programs must be
                    installed in a directory that is on the Windows PATH
                    directory list.

                    1)  ShowTime.CMD

                    2)  WWPause.exe

                    3)  WWSleep.exe

                    4)  npm (the Node Package Manager) and its startup 
                        script, npm.cmd, must be accessible via the Windows
                        PATH environment string. By default, this goes into
                        directory C:\Program Files\nodejs.

                    5)  The Angular 2 startup script, ng.cmd, and the Node
                        Modules library must be installed for global access.
                        By default, these go into directory %AppData%\npm.

Author:             David A. Gray

Created:            Monday, 23 April 2017

-----------------------------------------------------------------------
Revision History
-----------------------------------------------------------------------

Date       By  Synopsis
---------- --- --------------------------------------------------------
2017/04/23 DAG Script created, tested, and deployed.
=======================================================================

:SKIPREM

echo BOJ %~0, version %~t0
echo.
echo -------------------------------------------------------
echo Displaying the current node.js version:
echo -------------------------------------------------------
echo.
node -v
echo.
echo -------------------------------------------------------
echo Displaying the current Node Package Manager version:
echo -------------------------------------------------------
echo.
call npm -v
echo.
echo -------------------------------------------------------
echo Loading Angular starter application %1
echo into a local Web server, the default Web browser, and
echo the Visual Studio Code text editor.
echo -------------------------------------------------------
echo.

if "%1" neq "" (
    echo.
    echo -------------------------------------------------------
    echo Starting the Angular application in directory %1
    echo -------------------------------------------------------
    echo.
    cd "%~1"
    call code %1\src\
) else (
    echo.
    echo -------------------------------------------------------
    echo Starting the Angular application in directory %CD%
    echo -------------------------------------------------------
    echo.
    call code %CD%\src\
)

call ng serve --open

echo.
echo -------------------------------------------------------
echo %~nx0 Done!
echo -------------------------------------------------------
echo.
Pause

Display all items in array using jquery

You can do it like this by iterating through the array in a loop, accumulating the new HTML into it's own array and then joining the HTML all together and inserting it into the DOM at the end:

var array = [...];
var newHTML = [];
for (var i = 0; i < array.length; i++) {
    newHTML.push('<span>' + array[i] + '</span>');
}
$(".element").html(newHTML.join(""));

Some people prefer to use jQuery's .each() method instead of the for loop which would work like this:

var array = [...];
var newHTML = [];
$.each(array, function(index, value) {
    newHTML.push('<span>' + value + '</span>');
});
$(".element").html(newHTML.join(""));

Or because the output of the array iteration is itself an array with one item derived from each item in the original array, jQuery's .map can be used like this:

var array = [...];
var newHTML = $.map(array, function(value) {
    return('<span>' + value + '</span>');
});
$(".element").html(newHTML.join(""));

Which you should use is a personal choice depending upon your preferred coding style, sensitivity to performance and familiarity with .map(). My guess is that the for loop would be the fastest since it has fewer function calls, but if performance was the main criteria, then you would have to benchmark the options to actually measure.

FYI, in all three of these options, the HTML is accumulated into an array, then joined together at the end and the inserted into the DOM all at once. This is because DOM operations are usually the slowest part of an operation like this so it's best to minimize the number of separate DOM operations. The results are accumulated into an array because adding items to an array and then joining them at the end is usually faster than adding strings as you go.


And, if you can live with IE9 or above (or install an ES5 polyfill for .map()), you can use the array version of .map like this:

var array = [...];
$(".element").html(array.map(function(value) {
    return('<span>' + value + '</span>');
}).join(""));

Note: this version also gets rid of the newHTML intermediate variable in the interest of compactness.

Google Maps: How to create a custom InfoWindow?

Here is a pure CSS solution based on the current infowindow example on google:

https://developers.google.com/maps/documentation/javascript/examples/infowindow-simple

#map *{
  overflow: visible;
}
#content{
  display: block;
  position: absolute;
  bottom: -8px;
  left: -20px;
  background-color: white;
  z-index: 10001;
}

This is a quick solution that will work well for small info windows. Don't forget to up vote if it helps :P

Listening for variable changes in JavaScript

Using Prototype: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty

_x000D_
_x000D_
// Console_x000D_
function print(t) {_x000D_
  var c = document.getElementById('console');_x000D_
  c.innerHTML = c.innerHTML + '<br />' + t;_x000D_
}_x000D_
_x000D_
// Demo_x000D_
var myVar = 123;_x000D_
_x000D_
Object.defineProperty(this, 'varWatch', {_x000D_
  get: function () { return myVar; },_x000D_
  set: function (v) {_x000D_
    myVar = v;_x000D_
    print('Value changed! New value: ' + v);_x000D_
  }_x000D_
});_x000D_
_x000D_
print(varWatch);_x000D_
varWatch = 456;_x000D_
print(varWatch);
_x000D_
<pre id="console">_x000D_
</pre>
_x000D_
_x000D_
_x000D_

Other example

_x000D_
_x000D_
// Console_x000D_
function print(t) {_x000D_
  var c = document.getElementById('console');_x000D_
  c.innerHTML = c.innerHTML + '<br />' + t;_x000D_
}_x000D_
_x000D_
// Demo_x000D_
var varw = (function (context) {_x000D_
  return function (varName, varValue) {_x000D_
    var value = varValue;_x000D_
  _x000D_
    Object.defineProperty(context, varName, {_x000D_
      get: function () { return value; },_x000D_
      set: function (v) {_x000D_
        value = v;_x000D_
        print('Value changed! New value: ' + value);_x000D_
      }_x000D_
    });_x000D_
  };_x000D_
})(window);_x000D_
_x000D_
varw('varWatch'); // Declare_x000D_
print(varWatch);_x000D_
varWatch = 456;_x000D_
print(varWatch);_x000D_
_x000D_
print('---');_x000D_
_x000D_
varw('otherVarWatch', 123); // Declare with initial value_x000D_
print(otherVarWatch);_x000D_
otherVarWatch = 789;_x000D_
print(otherVarWatch);
_x000D_
<pre id="console">_x000D_
</pre>
_x000D_
_x000D_
_x000D_

How does Content Security Policy (CSP) work?

The Content-Security-Policy meta-tag allows you to reduce the risk of XSS attacks by allowing you to define where resources can be loaded from, preventing browsers from loading data from any other locations. This makes it harder for an attacker to inject malicious code into your site.

I banged my head against a brick wall trying to figure out why I was getting CSP errors one after another, and there didn't seem to be any concise, clear instructions on just how does it work. So here's my attempt at explaining some points of CSP briefly, mostly concentrating on the things I found hard to solve.

For brevity I won’t write the full tag in each sample. Instead I'll only show the content property, so a sample that says content="default-src 'self'" means this:

<meta http-equiv="Content-Security-Policy" content="default-src 'self'">

1. How can I allow multiple sources?

You can simply list your sources after a directive as a space-separated list:

content="default-src 'self' https://example.com/js/"

Note that there are no quotes around parameters other than the special ones, like 'self'. Also, there's no colon (:) after the directive. Just the directive, then a space-separated list of parameters.

Everything below the specified parameters is implicitly allowed. That means that in the example above these would be valid sources:

https://example.com/js/file.js
https://example.com/js/subdir/anotherfile.js

These, however, would not be valid:

http://example.com/js/file.js
^^^^ wrong protocol

https://example.com/file.js
                   ^^ above the specified path

2. How can I use different directives? What do they each do?

The most common directives are:

  • default-src the default policy for loading javascript, images, CSS, fonts, AJAX requests, etc
  • script-src defines valid sources for javascript files
  • style-src defines valid sources for css files
  • img-src defines valid sources for images
  • connect-src defines valid targets for to XMLHttpRequest (AJAX), WebSockets or EventSource. If a connection attempt is made to a host that's not allowed here, the browser will emulate a 400 error

There are others, but these are the ones you're most likely to need.

3. How can I use multiple directives?

You define all your directives inside one meta-tag by terminating them with a semicolon (;):

content="default-src 'self' https://example.com/js/; style-src 'self'"

4. How can I handle ports?

Everything but the default ports needs to be allowed explicitly by adding the port number or an asterisk after the allowed domain:

content="default-src 'self' https://ajax.googleapis.com http://example.com:123/free/stuff/"

The above would result in:

https://ajax.googleapis.com:123
                           ^^^^ Not ok, wrong port

https://ajax.googleapis.com - OK

http://example.com/free/stuff/file.js
                 ^^ Not ok, only the port 123 is allowed

http://example.com:123/free/stuff/file.js - OK

As I mentioned, you can also use an asterisk to explicitly allow all ports:

content="default-src example.com:*"

5. How can I handle different protocols?

By default, only standard protocols are allowed. For example to allow WebSockets ws:// you will have to allow it explicitly:

content="default-src 'self'; connect-src ws:; style-src 'self'"
                                         ^^^ web Sockets are now allowed on all domains and ports.

6. How can I allow the file protocol file://?

If you'll try to define it as such it won’t work. Instead, you'll allow it with the filesystem parameter:

content="default-src filesystem"

7. How can I use inline scripts and style definitions?

Unless explicitly allowed, you can't use inline style definitions, code inside <script> tags or in tag properties like onclick. You allow them like so:

content="script-src 'unsafe-inline'; style-src 'unsafe-inline'"

You'll also have to explicitly allow inline, base64 encoded images:

content="img-src data:"

8. How can I allow eval()?

I'm sure many people would say that you don't, since 'eval is evil' and the most likely cause for the impending end of the world. Those people would be wrong. Sure, you can definitely punch major holes into your site's security with eval, but it has perfectly valid use cases. You just have to be smart about using it. You allow it like so:

content="script-src 'unsafe-eval'"

9. What exactly does 'self' mean?

You might take 'self' to mean localhost, local filesystem, or anything on the same host. It doesn't mean any of those. It means sources that have the same scheme (protocol), same host, and same port as the file the content policy is defined in. Serving your site over HTTP? No https for you then, unless you define it explicitly.

I've used 'self' in most examples as it usually makes sense to include it, but it's by no means mandatory. Leave it out if you don't need it.

But hang on a minute! Can't I just use content="default-src *" and be done with it?

No. In addition to the obvious security vulnerabilities, this also won’t work as you'd expect. Even though some docs claim it allows anything, that's not true. It doesn't allow inlining or evals, so to really, really make your site extra vulnerable, you would use this:

content="default-src * 'unsafe-inline' 'unsafe-eval'"

... but I trust you won’t.

Further reading:

http://content-security-policy.com

http://en.wikipedia.org/wiki/Content_Security_Policy

Why doesn't git recognize that my file has been changed, therefore git add not working

well we don't have enough to answer this question so I will give you several guesses:

1) you stashed your changes, to fix type: git stash pop

2) you had changes and you committed them, you should be able to see your commit in git log

3) you had changes did some sort of git reset --hard or other, your changes may be there in the reflog, type git reflog --all followed by checking out or cherry-picking the ref if you ever do find it.

4) you have checked out the same repo several times, and you are in the wrong one.

WCF Service Client: The content type text/html; charset=utf-8 of the response message does not match the content type of the binding

NOTE: If your target server endpoint is using secure socket layer (SSL) certificate

Change your .config setting from basicHttpBinding to basicHttpsBinding

I am sure, It will resolve your problem.

Mercurial stuck "waiting for lock"

I encountered this problem on Mac OS X 10.7.5 and Mercurial 2.6.2 when trying to push. After upgrading to Mercurial 3.2.1, I got "no changes found" instead of "waiting for lock on repository". I found out that somehow the default path had gotten set to point to the same repository, so it's not too surprising that Mercurial would get confused.

How do I get unique elements in this array?

Instead of using an Array, consider using either a Hash or a Set.

Sets behave similar to an Array, only they contain unique values only, and, under the covers, are built on Hashes. Sets don't retain the order that items are put into them unlike Arrays. Hashes don't retain the order either but can be accessed via a key so you don't have to traverse the hash to find a particular item.

I favor using Hashes. In your application the user_id could be the key and the value would be the entire object. That will automatically remove any duplicates from the hash.

Or, only extract unique values from the database, like John Ballinger suggested.

How to empty ("truncate") a file on linux that already exists and is protected in someway?

Since sudo will not work with redirection >, I like the tee command for this purpose

echo "" | sudo tee fileName

How to delete empty folders using windows command prompt?

@echo off
set /p "ipa= ENTER FOLDER NAME TO DELETE> "
set ipad="%ipa%"
IF not EXIST %ipad% GOTO notfound
IF EXIST %ipad% GOTO found
:found
echo DONOT CLOSE THIS WINDOW
md ccooppyy
xcopy %ipad%\*.* ccooppyy /s > NUL
rd %ipad% /s /q
ren ccooppyy %ipad%
cls
echo SUCCESS, PRESS ANY KEY TO EXIT
pause > NUL
exit 
:notfound
echo I COULDN'T FIND THE FOLDER %ipad%
pause
exit

Is SQL syntax case sensitive?

I don't think SQL Server is case-sensitive, at least not by default.

When I'm querying manually via Management Studio, I mess up case all the time and it cheerfully accepts it:

select cOL1, col2 FrOM taBLeName WheRE ...

Assign output of a program to a variable using a MS batch file

Some macros to set the output of a command to a variable/

For directly in the command prompt

c:\>doskey assign=for /f "tokens=1,2 delims=," %a in ("$*") do @for /f "tokens=* delims=" %# in ('"%a"') do @set "%b=%#"

c:\>assign WHOAMI /LOGONID,my-id

c:\>echo %my-id%

Macro with arguments

As this macro accepts arguments as a function i think it is the neatest macro to be used in a batch file:

@echo off

::::: ---- defining the assign macro ---- ::::::::
setlocal DisableDelayedExpansion
(set LF=^
%=EMPTY=%
)
set ^"\n=^^^%LF%%LF%^%LF%%LF%^^"

::set argv=Empty
set assign=for /L %%n in (1 1 2) do ( %\n%
   if %%n==2 (%\n%
      setlocal enableDelayedExpansion%\n%
      for /F "tokens=1,2 delims=," %%A in ("!argv!") do (%\n%
         for /f "tokens=* delims=" %%# in ('%%~A') do endlocal^&set "%%~B=%%#" %\n%
      ) %\n%
   ) %\n%
) ^& set argv=,

::::: -------- ::::::::


:::EXAMPLE
%assign% "WHOAMI /LOGONID",result
echo %result%

FOR /F macro

not so easy to read as the previous macro.

::::::::::::::::::::::::::::::::::::::::::::::::::
;;set "{{=for /f "tokens=* delims=" %%# in ('" &::
;;set "--=') do @set ""                        &::
;;set "}}==%%#""                               &::
::::::::::::::::::::::::::::::::::::::::::::::::::

:: --examples

::assigning ver output to %win-ver% variable
%{{% ver %--%win-ver%}}%
echo 3: %win-ver%


::assigning hostname output to %my-host% variable
%{{% hostname %--%my-host%}}%
echo 4: %my-host%

Macro using a temp file

Easier to read , it is not so slow if you have a SSD drive but still it creates a temp file.

@echo off

:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
;;set "[[=>"#" 2>&1&set/p "&set "]]==<# & del /q # >nul 2>&1" &::
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

chcp %[[%code-page%]]%
echo ~~%code-page%~~

whoami %[[%its-me%]]%
echo ##%its-me%##

How to get the last character of a string in a shell?

I know this is a very old thread, but no one mentioned which to me is the cleanest answer:

echo -n $str | tail -c 1

Note the -n is just so the echo doesn't include a newline at the end.

Simple state machine example in C#?

Today i deep in State Design Pattern. I did and tested ThreadState, which equal (+/-) to Threading in C#, as described in picture from Threading in C#

enter image description here

You can easly add new states, configure moves from one state to other is very easy becouse it incapsulated in state implementation

Implementation and using at: Implements .NET ThreadState by State Design Pattern

How to add an event after close the modal window?

Few answers that may be useful, especially if you have dynamic content.

$('#dialogueForm').live("dialogclose", function(){
   //your code to run on dialog close
});

Or, when opening the modal, have a callback.

$( "#dialogueForm" ).dialog({
              autoOpen: false,
              height: "auto",
              width: "auto",
              modal: true,
                my: "center",
                at: "center",
                of: window,
              close : function(){
                  // functionality goes here
              }  
              });

Saving the PuTTY session logging

To set permanent PuTTY session parameters do:

  1. Create sessions in PuTTY. Name it as "MyskinPROD"

  2. Configure the path for this session to point to "C:\dir\&Y&M&D&T_&H_putty.log".

  3. Create a Windows "Shortcut" to C:...\Putty.exe.

  4. Open "Shortcut" Properties and append "Target" line with parameters as shown below:

    "C:\Program Files (x86)\UTL\putty.exe" -ssh -load MyskinPROD user@ServerIP -pw password
    

Now, your PuTTY shortcut will bring in the "MyskinPROD" configuration every time you open the shortcut.

Check the screenshots and details on how I did it in my environment:

http://www.evernote.com/shard/s184/sh/93ebf08f-fde2-4dad-bccf-961c98fb614b/983d2ff8f2d1e6184318825d68b0b829

In JavaScript can I make a "click" event fire programmatically for a file input element?

This will now be possible in Firefox 4, with the caveat that it counts as a pop-up window and will therefore be blocked whenever a pop-up window would have been.

Playing sound notifications using Javascript?

First things first, i'd not like that as a user.

The best way to do is probably using a small flash applet that plays your sound in the background.

Also answered here: Cross-platform, cross-browser way to play sound from Javascript?

How do you rename a MongoDB database?

You could do this:

db.copyDatabase("db_to_rename","db_renamed","localhost")
use db_to_rename
db.dropDatabase();

Editorial Note: this is the same approach used in the question itself but has proven useful to others regardless.

TypeError: $.browser is undefined

Just include this script

http://code.jquery.com/jquery-migrate-1.0.0.js

after you include your jquery javascript file.

How can I get the current directory name in Javascript?

For both / and \:

window.location.pathname.replace(/[^\\\/]*$/, '');

To return without the trailing slash, do:

window.location.pathname.replace(/[\\\/][^\\\/]*$/, '');

Nginx - Customizing 404 page

These answers are no longer recommended since try_files works faster than if in this context. Simply add try_files in your php location block to test if the file exists, otherwise return a 404.

location ~ \.php {
    try_files $uri =404;
    ...
}

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

Here's a nice form of a loop I often use. You create the iterated variable from the for statement and you don't need to check the length property, which can be expensive specially when iterating through a NodeList. However, you must be careful, you can't use it if any of the values in array could be "falsy". In practice, I only use it when iterating over an array of objects that does not contain nulls (like a NodeList). But I love its syntactic sugar.

var list = [{a:1,b:2}, {a:3,b:5}, {a:8,b:2}, {a:4,b:1}, {a:0,b:8}];

for (var i=0, item; item = list[i]; i++) {
  // Look no need to do list[i] in the body of the loop
  console.log("Looping: index ", i, "item" + item);
}

Note that this can also be used to loop backwards (as long as your list doesn't have a ['-1'] property)

var list = [{a:1,b:2}, {a:3,b:5}, {a:8,b:2}, {a:4,b:1}, {a:0,b:8}];

for (var i = list.length - 1, item; item = list[i]; i--) {
  console.log("Looping: index ", i, "item", item);
}

ES6 Update

for...of gives you the name but not the index, available since ES6

for (let item of list) {
    console.log("Looping: index ", "Sorry!!!", "item" + item);
}

Displaying one div on top of another

Here is the jsFiddle

#backdrop{
    border: 2px solid red;
    width: 400px;
    height: 200px;
    position: absolute;
}

#curtain {
    border: 1px solid blue;
    width: 400px;
    height: 200px;
    position: absolute;
}

Use Z-index to move the one you want on top.

Import pandas dataframe column as string not int

This probably isn't the most elegant way to do it, but it gets the job done.

In[1]: import numpy as np

In[2]: import pandas as pd

In[3]: df = pd.DataFrame(np.genfromtxt('/Users/spencerlyon2/Desktop/test.csv', dtype=str)[1:], columns=['ID'])

In[4]: df
Out[4]: 
                       ID
0  00013007854817840016671868
1  00013007854817840016749251
2  00013007854817840016754630
3  00013007854817840016781876
4  00013007854817840017028824
5  00013007854817840017963235
6  00013007854817840018860166

Just replace '/Users/spencerlyon2/Desktop/test.csv' with the path to your file

iPhone - Grand Central Dispatch main thread

Swift 3, 4 & 5

Running code on the main thread

DispatchQueue.main.async {
    // Your code here
}

Using dig to search for SPF records

I believe that I found the correct answer through this dig How To. I was able to look up the SPF records on a specific DNS, by using the following query:

dig @ns1.nameserver1.com domain.com txt

How to create a md5 hash of a string in C?

I don't know this particular library, but I've used very similar calls. So this is my best guess:

unsigned char digest[16];
const char* string = "Hello World";
struct MD5Context context;
MD5Init(&context);
MD5Update(&context, string, strlen(string));
MD5Final(digest, &context);

This will give you back an integer representation of the hash. You can then turn this into a hex representation if you want to pass it around as a string.

char md5string[33];
for(int i = 0; i < 16; ++i)
    sprintf(&md5string[i*2], "%02x", (unsigned int)digest[i]);

Regular expression to extract URL from an HTML link

Regexes are fundamentally bad at parsing HTML (see Can you provide some examples of why it is hard to parse XML and HTML with a regex? for why). What you need is an HTML parser. See Can you provide an example of parsing HTML with your favorite parser? for examples using a variety of parsers.

In particular you will want to look at the Python answers: BeautifulSoup, HTMLParser, and lxml.

curl usage to get header

You need to add the -i flag to the first command, to include the HTTP header in the output. This is required to print headers.

curl -X HEAD -i http://www.google.com

More here: https://serverfault.com/questions/140149/difference-between-curl-i-and-curl-x-head

How to create an 2D ArrayList in java?

1st of all, when you declare a variable in java, you should declare it using Interfaces even if you specify the implementation when instantiating it

ArrayList<ArrayList<String>> listOfLists = new ArrayList<ArrayList<String>>();

should be written

List<List<String>> listOfLists = new ArrayList<List<String>>(size); 

Then you will have to instantiate all columns of your 2d array

    for(int i = 0; i < size; i++)  {
        listOfLists.add(new ArrayList<String>());
    }

And you will use it like this :

listOfLists.get(0).add("foobar");

But if you really want to "create a 2D array that each cell is an ArrayList!"

Then you must go the dijkstra way.

Change the background color of a row in a JTable

Resumee of Richard Fearn's answer , to make each second line gray:

jTable.setDefaultRenderer(Object.class, new DefaultTableCellRenderer()
{
    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
    {
        final Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
        c.setBackground(row % 2 == 0 ? Color.LIGHT_GRAY : Color.WHITE);
        return c;
    }
});

Create SQLite Database and table

The next link will bring you to a great tutorial, that helped me a lot!

How to SQLITE in C#

I nearly used everything in that article to create the SQLite database for my own C# Application.

Don't forget to download the SQLite.dll, and add it as a reference to your project. This can be done using NuGet and by adding the dll manually.

After you added the reference, refer to the dll from your code using the following line on top of your class:

using System.Data.SQLite;

You can find the dll's here:

SQLite DLL's

You can find the NuGet way here:

NuGet

Up next is the create script. Creating a database file:

SQLiteConnection.CreateFile("MyDatabase.sqlite");

SQLiteConnection m_dbConnection = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");
m_dbConnection.Open();

string sql = "create table highscores (name varchar(20), score int)";

SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();

sql = "insert into highscores (name, score) values ('Me', 9001)";

command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();

m_dbConnection.Close();

After you created a create script in C#, I think you might want to add rollback transactions, it is safer and it will keep your database from failing, because the data will be committed at the end in one big piece as an atomic operation to the database and not in little pieces, where it could fail at 5th of 10 queries for example.

Example on how to use transactions:

 using (TransactionScope tran = new TransactionScope())
 {
     //Insert create script here.

     //Indicates that creating the SQLiteDatabase went succesfully, so the database can be committed.
     tran.Complete();
 }

The controller for path was not found or does not implement IController

Embarrassingly, the problem in my case is that I haven't rebuilt the code after adding the controller.

So maybe the first thing to check is that your controller was built and is present (and public) in the binaries. It might save you few minutes of debugging if you're like me.

nginx error:"location" directive is not allowed here in /etc/nginx/nginx.conf:76

The server directive has to be in the http directive. It should not be outside of it.

Incase if you need detailed information, refer this.

Is the 'as' keyword required in Oracle to define an alias?

(Tested on Oracle 11g)

About AS:

  • When used on result column, AS is optional.
  • When used on table name, AS shouldn't be added, otherwise it's an error.

About double quote:

  • It's optional & valid for both result column & table name.

e.g

-- 'AS' is optional for result column
select (1+1) as result from dual;
select (1+1) result from dual;


-- 'AS' shouldn't be used for table name
select 'hi' from dual d;


-- Adding double quotes for alias name is optional, but valid for both result column & table name,
select (1+1) as "result" from dual;
select (1+1) "result" from dual;

select 'hi' from dual "d";

Can I have an onclick effect in CSS?

TylerH made a really good answer, I just had to give that last button a visual update.

_x000D_
_x000D_
.btn {
    border-radius: 5px;
    padding: 10px 30px;
    box-shadow: 1px 1px 1px #000;
    background-image: linear-gradient(to bottom, #eee, #ddd);
}

.btn:hover {
    background-image: linear-gradient(to top, #adf, #8bf);
}

.btn:active {
    margin: 1px 1px 0;
    box-shadow: -1px -1px 1px #000;
}

#btnControl {
    display: block;
    visibility: hidden;
}
_x000D_
<input type="checkbox" id="btnControl"/>
<label class="btn" for="btnControl">Click me!</label>
_x000D_
_x000D_
_x000D_

endsWith in JavaScript

if you dont want to use lasIndexOf or substr then why not just look at the string in its natural state (ie. an array)

String.prototype.endsWith = function(suffix) {
    if (this[this.length - 1] == suffix) return true;
    return false;
}

or as a standalone function

function strEndsWith(str,suffix) {
    if (str[str.length - 1] == suffix) return true;
    return false;
}

jQuery append() - return appended elements

var newElementsAppended = $(newHtml).appendTo("#myDiv");
newElementsAppended.effects("highlight", {}, 2000);

string.split - by multiple character delimiter

To show both string.Split and Regex usage:

string input = "abc][rfd][5][,][.";
string[] parts1 = input.Split(new string[] { "][" }, StringSplitOptions.None);
string[] parts2 = Regex.Split(input, @"\]\[");

Print a list of space-separated elements in Python 3

list = [1, 2, 3, 4, 5]
for i in list[0:-1]:
    print(i, end=', ')
print(list[-1])

do for loops really take that much longer to run?

was trying to make something that printed all str values in a list separated by commas, inserting "and" before the last entry and came up with this:

spam = ['apples', 'bananas', 'tofu', 'cats']
for i in spam[0:-1]:
    print(i, end=', ')
print('and ' + spam[-1])

how to display full stored procedure code?

If anyone wonders how to quickly query catalog tables and make use of the pg_get_functiondef() function here's the sample query:

SELECT n.nspname AS schema
      ,proname AS fname
      ,proargnames AS args
      ,t.typname AS return_type
      ,d.description
      ,pg_get_functiondef(p.oid) as definition
--      ,CASE WHEN NOT p.proisagg THEN pg_get_functiondef(p.oid)
--            ELSE 'pg_get_functiondef() can''t be used with aggregate functions'
--       END as definition
  FROM pg_proc p
  JOIN pg_type t
    ON p.prorettype = t.oid
  LEFT OUTER
  JOIN pg_description d
    ON p.oid = d.objoid
  LEFT OUTER
  JOIN pg_namespace n
    ON n.oid = p.pronamespace
 WHERE NOT p.proisagg
   AND n.nspname~'<$SCHEMA_NAME_PATTERN>'
   AND proname~'<$FUNCTION_NAME_PATTERN>'

How to tell if JRE or JDK is installed

Normally a jdk installation has javac in the environment path variables ... so if you check for javac in the path, that's pretty much a good indicator that you have a jdk installed.

PHP simple foreach loop with HTML

This will work although when embedding PHP in HTML it is better practice to use the following form:

<table>
    <?php foreach($array as $key=>$value): ?>
    <tr>
        <td><?= $key; ?></td>
    </tr>
    <?php endforeach; ?>
</table>

You can find the doc for the alternative syntax on PHP.net

Code for best fit straight line of a scatter plot in python

You can use numpy's polyfit. I use the following (you can safely remove the bit about coefficient of determination and error bounds, I just think it looks nice):

#!/usr/bin/python3

import numpy as np
import matplotlib.pyplot as plt
import csv

with open("example.csv", "r") as f:
    data = [row for row in csv.reader(f)]
    xd = [float(row[0]) for row in data]
    yd = [float(row[1]) for row in data]

# sort the data
reorder = sorted(range(len(xd)), key = lambda ii: xd[ii])
xd = [xd[ii] for ii in reorder]
yd = [yd[ii] for ii in reorder]

# make the scatter plot
plt.scatter(xd, yd, s=30, alpha=0.15, marker='o')

# determine best fit line
par = np.polyfit(xd, yd, 1, full=True)

slope=par[0][0]
intercept=par[0][1]
xl = [min(xd), max(xd)]
yl = [slope*xx + intercept  for xx in xl]

# coefficient of determination, plot text
variance = np.var(yd)
residuals = np.var([(slope*xx + intercept - yy)  for xx,yy in zip(xd,yd)])
Rsqr = np.round(1-residuals/variance, decimals=2)
plt.text(.9*max(xd)+.1*min(xd),.9*max(yd)+.1*min(yd),'$R^2 = %0.2f$'% Rsqr, fontsize=30)

plt.xlabel("X Description")
plt.ylabel("Y Description")

# error bounds
yerr = [abs(slope*xx + intercept - yy)  for xx,yy in zip(xd,yd)]
par = np.polyfit(xd, yerr, 2, full=True)

yerrUpper = [(xx*slope+intercept)+(par[0][0]*xx**2 + par[0][1]*xx + par[0][2]) for xx,yy in zip(xd,yd)]
yerrLower = [(xx*slope+intercept)-(par[0][0]*xx**2 + par[0][1]*xx + par[0][2]) for xx,yy in zip(xd,yd)]

plt.plot(xl, yl, '-r')
plt.plot(xd, yerrLower, '--r')
plt.plot(xd, yerrUpper, '--r')
plt.show()

What are all the uses of an underscore in Scala?

There is one usage I can see everyone here seems to have forgotten to list...

Rather than doing this:

List("foo", "bar", "baz").map(n => n.toUpperCase())

You could can simply do this:

List("foo", "bar", "baz").map(_.toUpperCase())

Sending multipart/formdata with jQuery.ajax

I just built this function based on some info I read.

Use it like using .serialize(), instead just put .serializefiles();.
Working here in my tests.

//USAGE: $("#form").serializefiles();
(function($) {
$.fn.serializefiles = function() {
    var obj = $(this);
    /* ADD FILE TO PARAM AJAX */
    var formData = new FormData();
    $.each($(obj).find("input[type='file']"), function(i, tag) {
        $.each($(tag)[0].files, function(i, file) {
            formData.append(tag.name, file);
        });
    });
    var params = $(obj).serializeArray();
    $.each(params, function (i, val) {
        formData.append(val.name, val.value);
    });
    return formData;
};
})(jQuery);

How to redirect Valgrind's output to a file?

valgrind --log-file="filename"

How to delete a character from a string using Python

If you want to delete/ignore characters in a string, and, for instance, you have this string,

"[11:L:0]"

from a web API response or something like that, like a CSV file, let's say you are using requests

import requests
udid = 123456
url = 'http://webservices.yourserver.com/action/id-' + udid
s = requests.Session()
s.verify = False
resp = s.get(url, stream=True)
content = resp.content

loop and get rid of unwanted chars:

for line in resp.iter_lines():
  line = line.replace("[", "")
  line = line.replace("]", "")
  line = line.replace('"', "")

Optional split, and you will be able to read values individually:

listofvalues = line.split(':')

Now accessing each value is easier:

print listofvalues[0]
print listofvalues[1]
print listofvalues[2]

This will print

11

L

0

Python Script execute commands in Terminal

You could import the 'os' module and use it like this :

import os
os.system('#DesiredAction')

JavaFX - create custom button with image

You just need to create your own class inherited from parent. Place an ImageView on that, and on the mousedown and mouse up events just change the images of the ImageView.

public class ImageButton extends Parent {

    private static final Image NORMAL_IMAGE = ...;
    private static final Image PRESSED_IMAGE = ...;

    private final ImageView iv;

    public ImageButton() {
        this.iv = new ImageView(NORMAL_IMAGE);
        this.getChildren().add(this.iv);

        this.iv.setOnMousePressed(new EventHandler<MouseEvent>() {

            public void handle(MouseEvent evt) {
                iv.setImage(PRESSED_IMAGE);
            }

        });

        // TODO other event handlers like mouse up

    } 

}

Add quotation at the start and end of each line in Notepad++

  • One simple way is replace \n(newline) with ","(double-quote comma double-quote) after this append double-quote in the start and end of file.

example:

      AliceBlue
      AntiqueWhite
      Aqua
      Aquamarine
      Beige
  • Replcae \n with ","

      AliceBlue","AntiqueWhite","Aqua","Aquamarine","Beige
    
  • Now append "(double-quote) at the start and end

     "AliceBlue","AntiqueWhite","Aqua","Aquamarine","Beige"
    

If your text contains blank lines in between you can use regular expression \n+ instead of \n

example:

      AliceBlue

      AntiqueWhite
      Aqua


      Aquamarine
      Beige
  • Replcae \n+ with "," (in regex mode)

      AliceBlue","AntiqueWhite","Aqua","Aquamarine","Beige
    
  • Now append "(double-quote) at the start and end

     "AliceBlue","AntiqueWhite","Aqua","Aquamarine","Beige"
    

Dynamic require in RequireJS, getting "Module name has not been loaded yet for context" error?

Answering to myself. From the RequireJS website:

//THIS WILL FAIL
define(['require'], function (require) {
    var namedModule = require('name');
});

This fails because requirejs needs to be sure to load and execute all dependencies before calling the factory function above. [...] So, either do not pass in the dependency array, or if using the dependency array, list all the dependencies in it.

My solution:

// Modules configuration (modules that will be used as Jade helpers)
define(function () {
    return {
        'moment':   'path/to/moment',
        'filesize': 'path/to/filesize',
        '_':        'path/to/lodash',
        '_s':       'path/to/underscore.string'
    };
});

The loader:

define(['jade', 'lodash', 'config'], function (Jade, _, Config) {
    var deps;

    // Dynamic require
    require(_.values(Config), function () {
        deps = _.object(_.keys(Config), arguments);

        // Use deps...
    });
});

Byte Array and Int conversion in Java

/*sorry this is the correct */

     public byte[] IntArrayToByteArray(int[] iarray , int sizeofintarray)
     {
       final ByteBuffer bb ;
       bb = ByteBuffer.allocate( sizeofintarray * 4);
       for(int k = 0; k < sizeofintarray ; k++)
       bb.putInt(k * 4, iar[k]);
       return bb.array();
     }

How do you 'redo' changes after 'undo' with Emacs?

For those wanting to have the more common undo/redo functionality, someone has written undo-tree.el. It provides the look and feel of non-Emacs undo, but provides access to the entire 'tree' of undo history.

I like Emacs' built-in undo system, but find this package to be very intuitive.

Here's the commentary from the file itself:

Emacs has a powerful undo system. Unlike the standard undo/redo system in most software, it allows you to recover any past state of a buffer (whereas the standard undo/redo system can lose past states as soon as you redo). However, this power comes at a price: many people find Emacs' undo system confusing and difficult to use, spawning a number of packages that replace it with the less powerful but more intuitive undo/redo system.

Both the loss of data with standard undo/redo, and the confusion of Emacs' undo, stem from trying to treat undo history as a linear sequence of changes. It's not. The `undo-tree-mode' provided by this package replaces Emacs' undo system with a system that treats undo history as what it is: a branching tree of changes. This simple idea allows the more intuitive behaviour of the standard undo/redo system to be combined with the power of never losing any history. An added side bonus is that undo history can in some cases be stored more efficiently, allowing more changes to accumulate before Emacs starts discarding history.

Update Row if it Exists Else Insert Logic with Entity Framework

If you know that you're using the same context and not detaching any entities, you can make a generic version like this:

public void InsertOrUpdate<T>(T entity, DbContext db) where T : class
{
    if (db.Entry(entity).State == EntityState.Detached)
        db.Set<T>().Add(entity);

    // If an immediate save is needed, can be slow though
    // if iterating through many entities:
    db.SaveChanges(); 
}

db can of course be a class field, or the method can be made static and an extension, but this is the basics.

YAML mapping values are not allowed in this context

This is valid YAML:

jobs:
 - name: A
   schedule: "0 0/5 * 1/1 * ? *"
   type: mongodb.cluster
   config:
     host: mongodb://localhost:27017/admin?replicaSet=rs
     minSecondaries: 2
     minOplogHours: 100
     maxSecondaryDelay: 120
 - name: B
   schedule: "0 0/5 * 1/1 * ? *"
   type: mongodb.cluster
   config:
     host: mongodb://localhost:27017/admin?replicaSet=rs
     minSecondaries: 2
     minOplogHours: 100
     maxSecondaryDelay: 120

Note, that every '-' starts new element in the sequence. Also, indentation of keys in the map should be exactly same.

How to document a method with parameter(s)?

The mainstream is, as other answers here already pointed out, probably going with the Sphinx way so that you can use Sphinx to generate those fancy documents later.

That being said, I personally go with inline comment style occasionally.

def complex(  # Form a complex number
        real=0.0,  # the real part (default 0.0)
        imag=0.0  # the imaginary part (default 0.0)
        ):  # Returns a complex number.
    """Form a complex number.

    I may still use the mainstream docstring notation,
    if I foresee a need to use some other tools
    to generate an HTML online doc later
    """
    if imag == 0.0 and real == 0.0:
        return complex_zero
    other_code()

One more example here, with some tiny details documented inline:

def foo(  # Note that how I use the parenthesis rather than backslash "\"
          # to natually break the function definition into multiple lines.
        a_very_long_parameter_name,
            # The "inline" text does not really have to be at same line,
            # when your parameter name is very long.
            # Besides, you can use this way to have multiple lines doc too.
            # The one extra level indentation here natually matches the
            # original Python indentation style.
            #
            # This parameter represents blah blah
            # blah blah
            # blah blah
        param_b,  # Some description about parameter B.
            # Some more description about parameter B.
            # As you probably noticed, the vertical alignment of pound sign
            # is less a concern IMHO, as long as your docs are intuitively
            # readable.
        last_param,  # As a side note, you can use an optional comma for
                     # your last parameter, as you can do in multi-line list
                     # or dict declaration.
        ):  # So this ending parenthesis occupying its own line provides a
            # perfect chance to use inline doc to document the return value,
            # despite of its unhappy face appearance. :)
    pass

The benefits (as @mark-horvath already pointed out in another comment) are:

  • Most importantly, parameters and their doc always stay together, which brings the following benefits:
  • Less typing (no need to repeat variable name)
  • Easier maintenance upon changing/removing variable. There will never be some orphan parameter doc paragraph after you rename some parameter.
  • and easier to find missing comment.

Now, some may think this style looks "ugly". But I would say "ugly" is a subjective word. A more neutual way is to say, this style is not mainstream so it may look less familiar to you, thus less comfortable. Again, "comfortable" is also a subjective word. But the point is, all the benefits described above are objective. You can not achieve them if you follow the standard way.

Hopefully some day in the future, there will be a doc generator tool which can also consume such inline style. That will drive the adoption.

PS: This answer is derived from my own preference of using inline comments whenever I see fit. I use the same inline style to document a dictionary too.

How to update Python?

The best solution is to install the different Python versions in multiple paths.

eg. C:\Python27 for 2.7, and C:\Python33 for 3.3.

Read this for more info: How to run multiple Python versions on Windows

Show Youtube video source into HTML5 video tag?

The <video> tag is meant to load in a video of a supported format (which may differ by browser).

YouTube embed links are not just videos, they are typically webpages that contain logic to detect what your user supports and how they can play the youtube video, using HTML5, or flash, or some other plugin based on what is available on the users PC. This is why you are having a difficult time using the video tag with youtube videos.

YouTube does offer a developer API to embed a youtube video into your page.

I made a JSFiddle as a live example: http://jsfiddle.net/zub16fgt/

And you can read more about the YouTube API here: https://developers.google.com/youtube/iframe_api_reference#Getting_Started

The Code can also be found below

In your HTML:

<div id="player"></div>

In your Javascript:

var onPlayerReady = function(event) {
    event.target.playVideo();  
};

// The first argument of YT.Player is an HTML element ID. 
// YouTube API will replace my <div id="player"> tag 
// with an iframe containing the youtube video.

var player = new YT.Player('player', {
    height: 320,
    width: 400,
    videoId : '6Dc1C77nra4',
    events : {
        'onReady' : onPlayerReady
    }
});

Match the path of a URL, minus the filename extension

Like this:

if (preg_match('/(?<=net).*(?=\.php)/', $subject, $regs)) {
    $result = $regs[0];
}

Explanation:

"
(?<=      # Assert that the regex below can be matched, with the match ending at this position (positive lookbehind)
   net       # Match the characters “net” literally
)
.         # Match any single character that is not a line break character
   *         # Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
(?=       # Assert that the regex below can be matched, starting at this position (positive lookahead)
   \.        # Match the character “.” literally
   php       # Match the characters “php” literally
)
"

What is the difference between --save and --save-dev?

Clear answers are already provided. But it's worth mentioning how devDependencies affects installing packages:

By default, npm install will install all modules listed as dependencies in package.json . With the --production flag (or when the NODE_ENV environment variable is set to production ), npm will not install modules listed in devDependencies .

See: https://docs.npmjs.com/cli/install

How do I include a newline character in a string in Delphi?

Here's an even shorter approach:

my_string := 'Hello,'#13#10' world!';

How to find out which processes are using swap space in Linux?

I don't know of any direct answer as how to find exactly what process is using the swap space, however, this link may be helpful. Another good one is over here

Also, use a good tool like htop to see which processes are using a lot of memory and how much swap overall is being used.

Apache redirect to another port

Apache supports name based and IP based virtual hosts. It looks like you are using both, which is probably not what you need.

I think you're actually trying to set up name-based virtual hosting, and for that you don't need to specify the IP address.

Try < VirtualHost *:80> to bind to all IP addresses, unless you really want ip based virtual hosting. This may be the case if the server has several IP addresses, and you want to serve different sites on different addresses. The most common setup is (I would guess) name based virtual hosts.

How to use GROUP BY to concatenate strings in SQL Server?

This kind of question is asked here very often, and the solution is going to depend a lot on the underlying requirements:

https://stackoverflow.com/search?q=sql+pivot

and

https://stackoverflow.com/search?q=sql+concatenate

Typically, there is no SQL-only way to do this without either dynamic sql, a user-defined function, or a cursor.

navigator.geolocation.getCurrentPosition sometimes works sometimes doesn't

This happened to me when using Firefox's responsive design mode. There has been a bug report filed. For now, just don't use responsive design mode while using the Geolocation API.

Why use a READ UNCOMMITTED isolation level?

This will give you dirty reads, and show you transactions that's not committed yet. That is the most obvious answer. I don't think its a good idea to use this just to speed up your reads. There is other ways of doing that if you use a good database design.

Its also interesting to note whats not happening. READ UNCOMMITTED does not only ignore other table locks. It's also not causing any locks in its own.

Consider you are generating a large report, or you are migrating data out of your database using a large and possibly complex SELECT statement. This will cause a shared lock that's may be escalated to a shared table lock for the duration of your transaction. Other transactions may read from the table, but updates are impossible. This may be a bad idea if its a production database since the production may stop completely.

If you are using READ UNCOMMITTED you will not set a shared lock on the table. You may get the result from some new transactions or you may not depending where it the table the data were inserted and how long your SELECT transaction have read. You may also get the same data twice if for example a page split occurs (the data will be copied to another location in the data file).

So, if its very important for you that data can be inserted while doing your SELECT, READ UNCOMMITTED may make sense. You have to consider that your report may contain some errors, but if its based on millions of rows and only a few of them are updated while selecting the result this may be "good enough". Your transaction may also fail all together since the uniqueness of a row may not be guaranteed.

A better way altogether may be to use SNAPSHOT ISOLATION LEVEL but your applications may need some adjustments to use this. One example of this is if your application takes an exclusive lock on a row to prevent others from reading it and go into edit mode in the UI. SNAPSHOT ISOLATION LEVEL does also come with a considerable performance penalty (especially on disk). But you may overcome that by throwing hardware on the problem. :)

You may also consider restoring a backup of the database to use for reporting or loading data into a data warehouse.

How to get the URL of the current page in C#

if you just want the part between http:// and the first slash

string url = Request.Url.Host;

would return stackoverflow.com if called from this page

Here's the complete breakdown

Checking if a variable is initialized

Since MyClass is a POD class type, those non-static data members will have indeterminate initial values when you create a non-static instance of MyClass, so no, that is not a valid way to check if they have been initialized to a specific non-zero value ... you are basically assuming they will be zero-initialized, which is not going to be the case since you have not value-initialized them in a constructor.

If you want to zero-initialize your class's non-static data members, it would be best to create an initialization list and class-constructor. For example:

class MyClass
{
    void SomeMethod();

    char mCharacter;
    double mDecimal;

    public:
        MyClass();
};

MyClass::MyClass(): mCharacter(0), mDecimal(0) {}

The initialization list in the constructor above value-initializes your data-members to zero. You can now properly assume that any non-zero value for mCharacter and mDecimal must have been specifically set by you somewhere else in your code, and contain non-zero values you can properly act on.

Remove blank attributes from an Object in Javascript

Functional and immutable approach, without .filter and without creating more objects than needed

Object.keys(obj).reduce((acc, key) => (obj[key] === undefined ? acc : {...acc, [key]: obj[key]}), {})

PHP - find entry by object property from an array of objects

$arr = [
  [
    'ID' => 1
  ]
];

echo array_search(1, array_column($arr, 'ID')); // prints 0 (!== false)

Above code echoes the index of the matching element, or false if none.

To get the corresponding element, do something like:

$i = array_search(1, array_column($arr, 'ID'));
$element = ($i !== false ? $arr[$i] : null);

array_column works both on an array of arrays, and on an array of objects.

How can I call the 'base implementation' of an overridden virtual method?

I konow it's history question now. But for other googlers: you could write something like this. But this requires change in base class what makes it useless with external libraries.

class A
{
  void protoX() { Console.WriteLine("x"); }
  virtual void X() { protoX(); }
}

class B : A
{
  override void X() { Console.WriteLine("y"); }
}

class Program
{
  static void Main()
  {
    A b = new B();
    // Call A.X somehow, not B.X...
    b.protoX();


  }

getch and arrow codes

The keypad will allow the keyboard of the user's terminal to allow for function keys to be interpreted as a single value (i.e. no escape sequence).

As stated in the man page:

The keypad option enables the keypad of the user's terminal. If enabled (bf is TRUE), the user can press a function key (such as an arrow key) and wgetch returns a single value representing the function key, as in KEY_LEFT. If disabled (bf is FALSE), curses does not treat function keys specially and the program has to interpret the escape sequences itself. If the keypad in the terminal can be turned on (made to transmit) and off (made to work locally), turning on this option causes the terminal keypad to be turned on when wgetch is called. The default value for keypad is false.

Python - 'ascii' codec can't decode byte

"??".encode('utf-8')

encode converts a unicode object to a string object. But here you have invoked it on a string object (because you don't have the u). So python has to convert the string to a unicode object first. So it does the equivalent of

"??".decode().encode('utf-8')

But the decode fails because the string isn't valid ascii. That's why you get a complaint about not being able to decode.

Section vs Article HTML5

Sounds like you should wrap each of the "sections" (as you call them) in <article> tags and entries in the article in <section> tags.

The HTML5 spec says (Section):

The section element represents a generic section of a document or application. A section, in this context, is a thematic grouping of content, typically with a heading. [...]

Examples of sections would be chapters, the various tabbed pages in a tabbed dialog box, or the numbered sections of a thesis. A Web site's home page could be split into sections for an introduction, news items, and contact information.

Note: Authors are encouraged to use the article element instead of the section element when it would make sense to syndicate the contents of the element.

And for Article

The article element represents a self-contained composition in a document, page, application, or site and that is, in principle, independently distributable or reusable, e.g. in syndication. This could be a forum post, a magazine or newspaper article, a blog entry, a user-submitted comment, an interactive widget or gadget, or any other independent item of content.

I think what you call "sections" in the OP fit the definition of article as I can see them being independently distributable or reusable.

Update: Some minor text changes for article in the latest editors draft for HTML 5.1 (changes in italic):

The article element represents a complete, or self-contained, composition in a document, page, application, or site and that is, in principle, independently distributable or reusable, e.g. in syndication. This could be a forum post, a magazine or newspaper article, a blog entry, a user-submitted comment, an interactive widget or gadget, or any other independent item of content.

Also, discussion on the Public HTML mailing list about article in January and February of 2013.

How to add Date Picker Bootstrap 3 on MVC 5 project using the Razor engine?

1.make sure you ref jquery.js at first
2.check layout,make sure you call "~/bundles/bootstrap"
3.check layout,see render section Scripts position,it must be after "~/bundles/bootstrap"
4.add class "datepicker" to textbox
5.put $('.datepicker').datepicker(); in $(function(){...});

Javamail Could not convert socket to TLS GMail

I disabled avast antivirus for 10 minutes and get it working.

Why do I need 'b' to encode a string with Base64?

base64 encoding takes 8-bit binary byte data and encodes it uses only the characters A-Z, a-z, 0-9, +, /* so it can be transmitted over channels that do not preserve all 8-bits of data, such as email.

Hence, it wants a string of 8-bit bytes. You create those in Python 3 with the b'' syntax.

If you remove the b, it becomes a string. A string is a sequence of Unicode characters. base64 has no idea what to do with Unicode data, it's not 8-bit. It's not really any bits, in fact. :-)

In your second example:

>>> encoded = base64.b64encode('data to be encoded')

All the characters fit neatly into the ASCII character set, and base64 encoding is therefore actually a bit pointless. You can convert it to ascii instead, with

>>> encoded = 'data to be encoded'.encode('ascii')

Or simpler:

>>> encoded = b'data to be encoded'

Which would be the same thing in this case.


* Most base64 flavours may also include a = at the end as padding. In addition, some base64 variants may use characters other than + and /. See the Variants summary table at Wikipedia for an overview.

What are best practices for REST nested resources?

I've tried both design strategies - nested and non-nested endpoints. I've found that:

  1. if the nested resource has a primary key and you don't have its parent primary key, the nested structure requires you to get it, even though the system doesn't actually require it.

  2. nested endpoints typically require redundant endpoints. In other words, you will more often than not, need the additional /employees endpoint so you can get a list of employees across departments. If you have /employees, what exactly does /companies/departments/employees buy you?

  3. nesting endpoints don't evolve as nicely. E.g. you might not need to search for employees now but you might later and if you have a nested structure, you have no choice but to add another endpoint. With a non-nested design, you just add more parameters, which is simpler.

  4. sometimes a resource could have multiple types of parents. Resulting in multiple endpoints all returning the same resource.

  5. redundant endpoints makes the docs harder to write and also makes the api harder to learn.

In short, the non-nested design seems to allow a more flexible and simpler endpoint schema.

How to make code wait while calling asynchronous calls like Ajax

Why didn't it work for you using Deferred Objects? Unless I misunderstood something this may work for you.

/* AJAX success handler */
var echo = function() {
    console.log('Pass1');
};

var pass = function() {
  $.when(
    /* AJAX requests */
    $.post("/echo/json/", { delay: 1 }, echo),
    $.post("/echo/json/", { delay: 2 }, echo),
    $.post("/echo/json/", { delay: 3 }, echo)
  ).then(function() {
    /* Run after all AJAX */
    console.log('Pass2');
  });
};?

See it here.


UPDATE

Based on your input it seems what your quickest alternative is to use synchronous requests. You can set the property async to false in your $.ajax requests to make them blocking. This will hang your browser until the request is finished though.

Notice I don't recommend this and I still consider you should fix your code in an event-based workflow to not depend on it.

Recommended way to get hostname in Java

Environment variables may also provide a useful means -- COMPUTERNAME on Windows, HOSTNAME on most modern Unix/Linux shells.

See: https://stackoverflow.com/a/17956000/768795

I'm using these as "supplementary" methods to InetAddress.getLocalHost().getHostName(), since as several people point out, that function doesn't work in all environments.

Runtime.getRuntime().exec("hostname") is another possible supplement. At this stage, I haven't used it.

import java.net.InetAddress;
import java.net.UnknownHostException;

// try InetAddress.LocalHost first;
//      NOTE -- InetAddress.getLocalHost().getHostName() will not work in certain environments.
try {
    String result = InetAddress.getLocalHost().getHostName();
    if (StringUtils.isNotEmpty( result))
        return result;
} catch (UnknownHostException e) {
    // failed;  try alternate means.
}

// try environment properties.
//      
String host = System.getenv("COMPUTERNAME");
if (host != null)
    return host;
host = System.getenv("HOSTNAME");
if (host != null)
    return host;

// undetermined.
return null;

formatFloat : convert float number to string

Try this

package main

import "fmt"
import "strconv"

func FloatToString(input_num float64) string {
    // to convert a float number to a string
    return strconv.FormatFloat(input_num, 'f', 6, 64)
}

func main() {
    fmt.Println(FloatToString(21312421.213123))
}

If you just want as many digits precision as possible, then the special precision -1 uses the smallest number of digits necessary such that ParseFloat will return f exactly. Eg

strconv.FormatFloat(input_num, 'f', -1, 64)

Personally I find fmt easier to use. (Playground link)

fmt.Printf("x = %.6f\n", 21312421.213123)

Or if you just want to convert the string

fmt.Sprintf("%.6f", 21312421.213123)

Saving timestamp in mysql table using php

Hey there, use the FROM_UNIXTIME() function for this.

Like this:

INSERT INTO table_name
(id,d_id,l_id,connection,s_time,upload_items_count,download_items_count,t_time,status)
VALUES
(1,5,9,'2',FROM_UNIXTIME(1299762201428),5,10,20,'1'), 
(2,5,9,'2',FROM_UNIXTIME(1299762201428),5,10,20,'1')

Standard deviation of a list

I would put A_Rank et al into a 2D NumPy array, and then use numpy.mean() and numpy.std() to compute the means and the standard deviations:

In [17]: import numpy

In [18]: arr = numpy.array([A_rank, B_rank, C_rank])

In [20]: numpy.mean(arr, axis=0)
Out[20]: 
array([ 0.7       ,  2.2       ,  1.8       ,  2.13333333,  3.36666667,
        5.1       ])

In [21]: numpy.std(arr, axis=0)
Out[21]: 
array([ 0.45460606,  1.29614814,  1.37355985,  1.50628314,  1.15566239,
        1.2083046 ])

CSS Resize/Zoom-In effect on Image while keeping Dimensions

You could achieve that simply by wrapping the image by a <div> and adding overflow: hidden to that element:

<div class="img-wrapper">
    <img src="..." />
</div>
.img-wrapper {
    display: inline-block; /* change the default display type to inline-block */
    overflow: hidden;      /* hide the overflow */
}

WORKING DEMO.


Also it's worth noting that <img> element (like the other inline elements) sits on its baseline by default. And there would be a 4~5px gap at the bottom of the image.

That vertical gap belongs to the reserved space of descenders like: g j p q y. You could fix the alignment issue by adding vertical-align property to the image with a value other than baseline.

Additionally for a better user experience, you could add transition to the images.

Thus we'll end up with the following:

.img-wrapper img {
    transition: all .2s ease;
    vertical-align: middle;
}

UPDATED DEMO.

Press Enter to move to next control

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        if (keyData == (Keys.Enter))
        {
            SendKeys.Send("{TAB}");
        }

        return base.ProcessCmdKey(ref msg, keyData);
    }

goto the design form and View-> tab(as like picture shows) Order then you ordered all the control[That's it] enter image description here

Get unique values from arraylist in java

you can use this for making a list Unique

ArrayList<String> listWithDuplicateValues = new ArrayList<>();
list.add("first");
list.add("first");
list.add("second");

ArrayList uniqueList = (ArrayList) listWithDuplicateValues.stream().distinct().collect(Collectors.toList());

Python, remove all non-alphabet chars from string

If you prefer not to use regex, you might try

''.join([i for i in s if i.isalpha()])

Display milliseconds in Excel

First represent the epoch of the millisecond time as a date (usually 1/1/1970), then add your millisecond time divided by the number of milliseconds in a day (86400000):

=DATE(1970,1,1)+(A1/86400000)

If your cell is properly formatted, you should see a human-readable date/time.

Git cli: get user info from username

Add my two cents, if you're using windows commnad line:

git config --list | findstr user.name will give username directly.

The findstr here is quite similar to grep in linux.

How can I increment a date by one day in Java?

If you are using Java 8, java.time.LocalDate and java.time.format.DateTimeFormatter can make this work quite simple.

public String nextDate(String date){
      LocalDate parsedDate = LocalDate.parse(date);
      LocalDate addedDate = parsedDate.plusDays(1);
      DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-mm-dd");
      return addedDate.format(formatter); 
}

How to play only the audio of a Youtube video using HTML 5?

The answer is simple: Use a 3rd party product like jwplayer or similar, then set it to the minimal player size which is the audio player size (only shows player controls).

Voila.

Been using this for over 8 years.

jQuery Validate Required Select

The solution mentioned by @JMP worked in my case with a little modification: I use element.value instead of value in the addmethod.

$.validator.addMethod("valueNotEquals", function(value, element, arg){
    // I use element.value instead value here, value parameter was always null
    return arg != element.value; 
}, "Value must not equal arg.");

// configure your validation
$("form").validate({
    rules: {
        SelectName: { valueNotEquals: "0" }
    },
    messages: {
        SelectName: { valueNotEquals: "Please select an item!" }
    }  
});

It could be possible, that I have a special case here, but didn't track down the cause. But @JMP's solution should work in regular cases.

How to copy text to the client's clipboard using jQuery?

Copying to the clipboard is a tricky task to do in Javascript in terms of browser compatibility. The best way to do it is using a small flash. It will work on every browser. You can check it in this article.

Here's how to do it for Internet Explorer:

function copy (str)
{
    //for IE ONLY!
    window.clipboardData.setData('Text',str);
}

EditorFor() and html properties

You can define attributes for your properties.

[StringLength(100)]
public string Body { get; set; }

This is known as System.ComponentModel.DataAnnotations. If you can't find the ValidationAttribute that you need you can allways define custom attributes.

Best Regards, Carlos

How to force a web browser NOT to cache images

You must use a unique filename(s). Like this

<img src="cars.png?1287361287" alt="">

But this technique means high server usage and bandwidth wastage. Instead, you should use the version number or date. Example:

<img src="cars.png?2020-02-18" alt="">

But you want it to never serve image from cache. For this, if the page does not use page cache, it is possible with PHP or server side.

<img src="cars.png?<?php echo time();?>" alt="">

However, it is still not effective. Reason: Browser cache ... The last but most effective method is Native JAVASCRIPT. This simple code finds all images with a "NO-CACHE" class and makes the images almost unique. Put this between script tags.

var items = document.querySelectorAll("img.NO-CACHE");
for (var i = items.length; i--;) {
    var img = items[i];
    img.src = img.src + '?' + Date.now();
}

USAGE

<img class="NO-CACHE" src="https://upload.wikimedia.org/wikipedia/commons/6/6a/JavaScript-logo.png" alt="">

RESULT(s) Like This

https://example.com/image.png?1582018163634

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

My exact problem was (Fatal error in launcher: Unable to create process using '"') on windows 10. So I navigated to the "C:\Python33\Lib\site-packages" and deleted django folder and pip folders then reinstalled django using pip and my problem was solved.

C# "must declare a body because it is not marked abstract, extern, or partial"

You DO NOT have to provide a body for getters and setters IF you'd like the automated compiler to provide a basic implementation.

This DOES however require you to make sure you're using the v3.5 compiler by updating your web.config to something like

 <compilers>
   <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CSharp.CSharpCodeProvider,System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" warningLevel="4">
    <providerOption name="CompilerVersion" value="v3.5"/>
    <providerOption name="WarnAsError" value="false"/>
  </compiler>
</compilers>

Codeigniter LIKE with wildcard(%)

Searching multiple fields at once can be done like so...

function search($search)
{
    $sql = "SELECT * FROM some_table
    WHERE UPPER(a_name) LIKE ?
    OR
    UPPER(a_full_name) LIKE ?
    OR
    UPPER(a_city) LIKE ?
    OR
    UPPER(a_code) LIKE ?
    ";
    $arr = array_map(array($this,"wrapLIKE"),array($search, $search, $search, $search));
    $r = $this->db->query($sql, $arr);
    return $r;
}

function wrapLIKE($string)
{
    return strtoupper("%$string%");
}

Good Linux (Ubuntu) SVN client

I'm very happy with kdesvn - integrates very well with konqueror, much like trortousesvn with windows explorer, and supports most of the functionality of tortoisesvn.

Of course, you'll benefit from this integration, if you use kubunto, and not ubuntu.

Which websocket library to use with Node.js?

Getting the ball rolling with this community wiki answer. Feel free to edit me with your improvements.

  • ws WebSocket server and client for node.js. One of the fastest libraries if not the fastest one.

  • websocket-node WebSocket server and client for node.js

  • websocket-driver-node WebSocket server and client protocol parser node.js - used in faye-websocket-node

  • faye-websocket-node WebSocket server and client for node.js - used in faye and sockjs

  • socket.io WebSocket server and client for node.js + client for browsers + (v0 has newest to oldest fallbacks, v1 of Socket.io uses engine.io) + channels - used in stack.io. Client library tries to reconnect upon disconnection.

  • sockjs WebSocket server and client for node.js and others + client for browsers + newest to oldest fallbacks

  • faye WebSocket server and client for node.js and others + client for browsers + fallbacks + support for other server-side languages

  • deepstream.io clusterable realtime server that handles WebSockets & TCP connections and provides data-sync, pub/sub and request/response

  • socketcluster WebSocket server cluster which makes use of all CPU cores on your machine. For example, if you were to use an xlarge Amazon EC2 instance with 32 cores, you would be able to handle almost 32 times the traffic on a single instance.

  • primus Provides a common API for most of the libraries above for easy switching + stability improvements for all of them.

When to use:

  • use the basic WebSocket servers when you want to use the native WebSocket implementations on the clientside, beware of the browser incompatabilities

  • use the fallback libraries when you care about browser fallbacks

  • use the full featured libraries when you care about channels

  • use primus when you have no idea about what to use, are not in the mood for rewriting your application when you need to switch frameworks because of changing project requirements or need additional connection stability.

Where to test:

Firecamp is a GUI testing environment for SocketIO, WS and all major real-time technology. Debug the real-time events while you're developing it.

How does String substring work in Swift

Swift 4+

extension String {
    func take(_ n: Int) -> String {
        guard n >= 0 else {
            fatalError("n should never negative")
        }
        let index = self.index(self.startIndex, offsetBy: min(n, self.count))
        return String(self[..<index])
    }
}

Returns a subsequence of the first n characters, or the entire string if the string is shorter. (inspired by: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/take.html)

Example:

let text = "Hello, World!"
let substring = text.take(5) //Hello

How do I upload a file to an SFTP server in C# (.NET)?

Maybe you can script/control winscp?

Update: winscp now has a .NET library available as a nuget package that supports SFTP, SCP, and FTPS

how to run python files in windows command prompt?

First go to the directory where your python script is present by using-

cd path/to/directory

then simply do:

python file_name.py

How does a Breadth-First Search work when looking for Shortest Path?

Visiting this thread after some period of inactivity, but given that I don't see a thorough answer, here's my two cents.

Breadth-first search will always find the shortest path in an unweighted graph. The graph may be cyclic or acyclic.

See below for pseudocode. This pseudocode assumes that you are using a queue to implement BFS. It also assumes you can mark vertices as visited, and that each vertex stores a distance parameter, which is initialized as infinity.

mark all vertices as unvisited
set the distance value of all vertices to infinity
set the distance value of the start vertex to 0
if the start vertex is the end vertex, return 0
push the start vertex on the queue
while(queue is not empty)   
    dequeue one vertex (we’ll call it x) off of the queue
    if x is not marked as visited:
        mark it as visited
        for all of the unmarked children of x:
            set their distance values to be the distance of x + 1
            if the value of x is the value of the end vertex: 
                return the distance of x
            otherwise enqueue it to the queue
if here: there is no path connecting the vertices

Note that this approach doesn't work for weighted graphs - for that, see Dijkstra's algorithm.

Transfer git repositories from GitLab to GitHub - can we, how to and pitfalls (if any)?

If you have MFA enabled on GitLab you should go to Repository Settings/Repository ->Deploy Keys and create one, then use it as login while importing repo on GitHub

Laravel Migration Error: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes

I have found two solutions for this error

OPTION 1:

Open your user and password_reset table in database/migrations folder

And just change the length of the email:

$table->string('email',191)->unique();

OPTION 2:

Open your app/Providers/AppServiceProvider.php file and inside the boot() method set a default string length:

use Illuminate\Support\Facades\Schema;

public function boot()
{
    Schema::defaultStringLength(191);
}

Add and remove attribute with jquery

It's because you've removed the id which is how you're finding the element. This line of code is trying to add id="page_navigation1" to an element with the id named page_navigation1, but it doesn't exist (because you deleted the attribute):

$("#page_navigation1").attr("id","page_navigation1");

Demo: jsFiddle

If you want to add and remove a class that makes your <div> red use:

$( '#page_navigation1' ).addClass( 'red-class' );

And:

$( '#page_navigation1' ).removeClass( 'red-class' );

Where red-class is:

.red-class {
    background-color: red;
}

Function to get yesterday's date in Javascript in format DD/MM/YYYY

You override $today in the if statement.

if($dd<10){$dd='0'+dd} if($mm<10){$mm='0'+$mm} $today = $dd+'/'+$mm+'/'+$yyyy;

It is then not a Date() object anymore - hence the error.

Should I put #! (shebang) in Python scripts, and what form should it take?

Answer: Only if you plan to make it a command-line executable script.

Here is the procedure:

Start off by verifying the proper shebang string to use:

which python

Take the output from that and add it (with the shebang #!) in the first line.

On my system it responds like so:

$which python
/usr/bin/python

So your shebang will look like:

#!/usr/bin/python

After saving, it will still run as before since python will see that first line as a comment.

python filename.py

To make it a command, copy it to drop the .py extension.

cp filename.py filename

Tell the file system that this will be executable:

chmod +x filename

To test it, use:

./filename

Best practice is to move it somewhere in your $PATH so all you need to type is the filename itself.

sudo cp filename /usr/sbin

That way it will work everywhere (without the ./ before the filename)

How to convert a string to number in TypeScript?

Here is a modified version of the StrToNumber function. As before,

  1. It allows an optional sign to appear in front or behind the numeric value.
  2. It performs a check to verify there is only one sign at the head or tail of the string.
  3. If an error occurs, a "passed" default value is returned.

This response is a possible solution that is better suited to the initial question than my previous post.

_x000D_
_x000D_
   static StrToNumber(val: string, defaultVal:number = 0): number_x000D_
   {        _x000D_
      let result:number = defaultVal;      _x000D_
      if(val == null) _x000D_
         return result;            _x000D_
      if(val.length == 0) _x000D_
         return result;      _x000D_
      val = val.trim();_x000D_
      if(val.length == 0) _x000D_
         return(result);_x000D_
      let sign:number = 1;     _x000D_
      //_x000D_
      // . obtain sign from string, and place result in "sign" local variable. The Sign naturally defaults to positive_x000D_
      //     1 for positive, -1 for negative._x000D_
      // . remove sign character from val. _x000D_
      //      Note, before the function returns, the result is multiplied by the sign local variable to reflect the sign._x000D_
      // . error check for multiple sign characters_x000D_
      // . error check to make sure sign character is at the head or tail of the string_x000D_
      //              _x000D_
      {  _x000D_
         let positiveSignIndex = val.indexOf('+');_x000D_
         let negativeSignIndex = val.indexOf('-');_x000D_
         let nTailIndex = val.length-1;_x000D_
         //_x000D_
         // make sure both negative and positive signs are not in the string_x000D_
         //_x000D_
         if( (positiveSignIndex != -1) && (negativeSignIndex != -1) ) _x000D_
             return result;_x000D_
         //_x000D_
         // handle postive sign_x000D_
         //_x000D_
         if (positiveSignIndex != -1)_x000D_
         {_x000D_
            //_x000D_
            // make sure there is only one sign character_x000D_
            //_x000D_
            if( (positiveSignIndex != val.lastIndexOf('+')) )_x000D_
             return result;     _x000D_
             //_x000D_
             // make sure the sign is at the head or tail_x000D_
             //_x000D_
             if( (positiveSignIndex > 0) && (positiveSignIndex < nTailIndex )  )_x000D_
                 return result;_x000D_
             //_x000D_
             // remove sign from string_x000D_
             //_x000D_
             val = val.replace("+","").trim();                 _x000D_
         }    _x000D_
         //_x000D_
         // handle negative sign_x000D_
         //_x000D_
         if (negativeSignIndex != -1)_x000D_
         {_x000D_
            //_x000D_
            // make sure there is only one sign character_x000D_
            //_x000D_
            if( (negativeSignIndex != val.lastIndexOf('-')) )_x000D_
             return result;     _x000D_
             //_x000D_
             // make sure the sign is at the head or tail_x000D_
             //_x000D_
             if( (negativeSignIndex > 0) && (negativeSignIndex < nTailIndex )  )_x000D_
                 return result;_x000D_
             //_x000D_
             // remove sign from string_x000D_
             //_x000D_
             val = val.replace("-","").trim();  _x000D_
             sign = -1;                 _x000D_
         }               _x000D_
         //_x000D_
         // make sure text length is greater than 0_x000D_
         //       _x000D_
         if(val.length == 0) _x000D_
            return result;                             _x000D_
      }   _x000D_
      //_x000D_
      // convert string to a number_x000D_
      //_x000D_
      var r = +(<any>val);_x000D_
      if( (r != null) && (!isNaN(r)) )_x000D_
      {          _x000D_
         result = r*sign;         _x000D_
      }_x000D_
      return(result);    _x000D_
   }
_x000D_
_x000D_
_x000D_

Python: tf-idf-cosine: to find document similarity

Here is a function that compares your test data against the training data, with the Tf-Idf transformer fitted with the training data. Advantage is that you can quickly pivot or group by to find the n closest elements, and that the calculations are down matrix-wise.

def create_tokenizer_score(new_series, train_series, tokenizer):
    """
    return the tf idf score of each possible pairs of documents
    Args:
        new_series (pd.Series): new data (To compare against train data)
        train_series (pd.Series): train data (To fit the tf-idf transformer)
    Returns:
        pd.DataFrame
    """

    train_tfidf = tokenizer.fit_transform(train_series)
    new_tfidf = tokenizer.transform(new_series)
    X = pd.DataFrame(cosine_similarity(new_tfidf, train_tfidf), columns=train_series.index)
    X['ix_new'] = new_series.index
    score = pd.melt(
        X,
        id_vars='ix_new',
        var_name='ix_train',
        value_name='score'
    )
    return score

train_set = pd.Series(["The sky is blue.", "The sun is bright."])
test_set = pd.Series(["The sun in the sky is bright."])
tokenizer = TfidfVectorizer() # initiate here your own tokenizer (TfidfVectorizer, CountVectorizer, with stopwords...)
score = create_tokenizer_score(train_series=train_set, new_series=test_set, tokenizer=tokenizer)
score

   ix_new   ix_train    score
0   0       0       0.617034
1   0       1       0.862012

When creating a service with sc.exe how to pass in context parameters?

This command works:

sc create startSvn binPath= "\"C:\Subversion\bin\svnserve.exe\" --service -r \"C:\SVN_Repository\"" displayname= "MyServer" depend= tcpip start= auto

What is difference between XML Schema and DTD?

Differences between an XML Schema Definition (XSD) and Document Type Definition (DTD) include:

  • XML schemas are written in XML while DTD are derived from SGML syntax.
  • XML schemas define datatypes for elements and attributes while DTD doesn't support datatypes.
  • XML schemas allow support for namespaces while DTD does not.
  • XML schemas define number and order of child elements, while DTD does not.
  • XML schemas can be manipulated on your own with XML DOM but it is not possible in case of DTD.
  • using XML schema user need not to learn a new language but working with DTD is difficult for a user.
  • XML schema provides secure data communication i.e sender can describe the data in a way that receiver will understand, but in case of DTD data can be misunderstood by the receiver.
  • XML schemas are extensible while DTD is not extensible.

Not all these bullet points are 100% accurate, but you get the gist.

On the other hand:

  • DTD lets you define new ENTITY values for use in your XML file.
  • DTD lets you extend it local to an individual XML file.

C programming: Dereferencing pointer to incomplete type error

You haven't defined struct stasher_file by your first definition. What you have defined is an nameless struct type and a variable stasher_file of that type. Since there's no definition for such type as struct stasher_file in your code, the compiler complains about incomplete type.

In order to define struct stasher_file, you should have done it as follows

struct stasher_file {
 char name[32];
 int  size;
 int  start;
 int  popularity;
};

Note where the stasher_file name is placed in the definition.

How can I convert a long to int in Java?

If you want to make a safe conversion and enjoy the use of Java8 with Lambda expression You can use it like:

val -> Optional.ofNullable(val).map(Long::intValue).orElse(null)

How can I switch views programmatically in a view controller? (Xcode, iPhone)

Swift 3.0 in

one view controller to secondviewcontroller go:

let loginVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "MsgViewController") as! MsgViewController
        self.navigationController?.pushViewController(loginVC, animated: true)

2nd viewcontroller to 1stviewcontroller(back)for: back button on action event:-

self.navigationController?.popViewController(animated:true)

3rdviewcontroller to 1st viewcontroller jump for

self.navigationController?.popToRootViewController(animated:true)

and most important storyboard in navigation bar unclicked make sure than this back action perform

How can I check if a user is logged-in in php?

Almost all of the answers on this page rely on checking a session variable's existence to validate a user login. That is absolutely fine, but it is important to consider that the PHP session state is not unique to your application if there are multiple virtual hosts/sites on the same bare metal.

If you have two PHP applications on a webserver, both checking a user's login status with a boolean flag in a session variable called 'isLoggedIn', then a user could log into one of the applications and then automagically gain access to the second without credentials.

I suspect even the most dinosaur of commercial shared hosting wouldn't let virtual hosts share the same PHP environment in such a way that this could happen across multiple customers site's (anymore), but its something to consider in your own environments.

The very simple solution is to use a session variable that identifies the app rather than a boolean flag. e.g $SESSION["isLoggedInToExample.com"].

Source: I'm a penetration tester, with a lot of experience on how you shouldn't do stuff.

Groovy: How to check if a string contains any element of an array?

def valid = pointAddress.findAll { a ->
    validPointTypes.any { a.contains(it) }
}

Should do it

File Upload ASP.NET MVC 3.0

to transfer to byte[] (e.g. for saving to DB):

using (MemoryStream ms = new MemoryStream()) {
    file.InputStream.CopyTo(ms);
    byte[] array = ms.GetBuffer();
}

To transfer the input stream directly into the database, without storing it in the memory you can use this class taken from here and a bit changed:

public class VarbinaryStream : Stream {
private SqlConnection _Connection;

private string _TableName;
private string _BinaryColumn;
private string _KeyColumn;
private int _KeyValue;

private long _Offset;

private SqlDataReader _SQLReader;
private long _SQLReadPosition;

private bool _AllowedToRead = false;

public VarbinaryStream(
    string ConnectionString,
    string TableName,
    string BinaryColumn,
    string KeyColumn,
    int KeyValue,
    bool AllowRead = false)
{
  // create own connection with the connection string.
  _Connection = new SqlConnection(ConnectionString);

  _TableName = TableName;
  _BinaryColumn = BinaryColumn;
  _KeyColumn = KeyColumn;
  _KeyValue = KeyValue;


  // only query the database for a result if we are going to be reading, otherwise skip.
  _AllowedToRead = AllowRead;
  if (_AllowedToRead == true)
  {
    try
    {
      if (_Connection.State != ConnectionState.Open)
        _Connection.Open();

      SqlCommand cmd = new SqlCommand(
                      @"SELECT TOP 1 [" + _BinaryColumn + @"]
                            FROM [dbo].[" + _TableName + @"]
                            WHERE [" + _KeyColumn + "] = @id",
                  _Connection);

      cmd.Parameters.Add(new SqlParameter("@id", _KeyValue));

      _SQLReader = cmd.ExecuteReader(
          CommandBehavior.SequentialAccess |
          CommandBehavior.SingleResult |
          CommandBehavior.SingleRow |
          CommandBehavior.CloseConnection);

      _SQLReader.Read();
    }
    catch (Exception e)
    {
      // log errors here
    }
  }
}

// this method will be called as part of the Stream ímplementation when we try to write to our VarbinaryStream class.
public override void Write(byte[] buffer, int index, int count)
{
  try
  {
    if (_Connection.State != ConnectionState.Open)
      _Connection.Open();

    if (_Offset == 0)
    {
      // for the first write we just send the bytes to the Column
      SqlCommand cmd = new SqlCommand(
                                  @"UPDATE [dbo].[" + _TableName + @"]
                                            SET [" + _BinaryColumn + @"] = @firstchunk 
                                        WHERE [" + _KeyColumn + "] = @id",
                              _Connection);

      cmd.Parameters.Add(new SqlParameter("@firstchunk", buffer));
      cmd.Parameters.Add(new SqlParameter("@id", _KeyValue));

      cmd.ExecuteNonQuery();

      _Offset = count;
    }
    else
    {
      // for all updates after the first one we use the TSQL command .WRITE() to append the data in the database
      SqlCommand cmd = new SqlCommand(
                              @"UPDATE [dbo].[" + _TableName + @"]
                                        SET [" + _BinaryColumn + @"].WRITE(@chunk, NULL, @length)
                                    WHERE [" + _KeyColumn + "] = @id",
                           _Connection);

      cmd.Parameters.Add(new SqlParameter("@chunk", buffer));
      cmd.Parameters.Add(new SqlParameter("@length", count));
      cmd.Parameters.Add(new SqlParameter("@id", _KeyValue));

      cmd.ExecuteNonQuery();

      _Offset += count;
    }
  }
  catch (Exception e)
  {
    // log errors here
  }
}

// this method will be called as part of the Stream ímplementation when we try to read from our VarbinaryStream class.
public override int Read(byte[] buffer, int offset, int count)
{
  try
  {
    long bytesRead = _SQLReader.GetBytes(0, _SQLReadPosition, buffer, offset, count);
    _SQLReadPosition += bytesRead;
    return (int)bytesRead;
  }
  catch (Exception e)
  {
    // log errors here
  }
  return -1;
}
public override bool CanRead
{
  get { return _AllowedToRead; }
}

protected override void Dispose(bool disposing)
{
  if (_Connection != null)
  {
    if (_Connection.State != ConnectionState.Closed)
      try { _Connection.Close();           }
      catch { }
    _Connection.Dispose();
  }
  base.Dispose(disposing);
}

#region unimplemented methods
public override bool CanSeek
{
  get { return false; }
}

public override bool CanWrite
{
  get { return true; }
}

public override void Flush()
{
  throw new NotImplementedException();
}

public override long Length
{
  get { throw new NotImplementedException(); }
}

public override long Position
{
  get
  {
    throw new NotImplementedException();
  }
  set
  {
    throw new NotImplementedException();
  }
}
public override long Seek(long offset, SeekOrigin origin)
{
  throw new NotImplementedException();
}

public override void SetLength(long value)
{
  throw new NotImplementedException();
}
#endregion unimplemented methods  }

and the usage:

  using (var filestream = new VarbinaryStream(
                            "Connection_String",
                            "Table_Name",
                            "Varbinary_Column_name",
                            "Key_Column_Name",
                            keyValueId,
                            true))
  {
    postedFile.InputStream.CopyTo(filestream);
  }

Why does MSBuild look in C:\ for Microsoft.Cpp.Default.props instead of c:\Program Files (x86)\MSBuild? ( error MSB4019)

I have had the same problem recently and after installing different packages in different order it was just getting very messy. Then I have found this repo - https://github.com/felixrieseberg/windows-build-tools

npm install --global windows-build-tools

It installs Python & VS Build tools that are required to compile most node modules. It worked a treat!

Equivalent of Clean & build in Android Studio?

In latest releases of Android Studio one more option has been added dedicatedly for Clean.

Build > Clean Project 

Error executing command 'ant' on Mac OS X 10.9 Mavericks when building for Android with PhoneGap/Cordova

it don't needed port and brew! because you have android sdk package.

.1 edit your .bash_profile

export ANT_HOME="[your android_sdk_path/eclipse/plugins/org.apache.ant_1.8.3.v201301120609]" 

// its only my org.apache.ant version, check your org.apache.ant version

export PATH=$PATH:$ANT_HOME/bin

.2 make ant command that can executed

chmod 770 [your ANT_HOME/bin/ant]

.3 test if you see below message. that's success!

command line execute: ant

Buildfile: build.xml does not exist!

Build failed

Simple way to unzip a .zip file using zlib

Minizip does have an example programs to demonstrate its usage - the files are called minizip.c and miniunz.c.

Update: I had a few minutes so I whipped up this quick, bare bones example for you. It's very smelly C, and I wouldn't use it without major improvements. Hopefully it's enough to get you going for now.

// uzip.c - Simple example of using the minizip API.
// Do not use this code as is! It is educational only, and probably
// riddled with errors and leaks!
#include <stdio.h>
#include <string.h>

#include "unzip.h"

#define dir_delimter '/'
#define MAX_FILENAME 512
#define READ_SIZE 8192

int main( int argc, char **argv )
{
    if ( argc < 2 )
    {
        printf( "usage:\n%s {file to unzip}\n", argv[ 0 ] );
        return -1;
    }

    // Open the zip file
    unzFile *zipfile = unzOpen( argv[ 1 ] );
    if ( zipfile == NULL )
    {
        printf( "%s: not found\n" );
        return -1;
    }

    // Get info about the zip file
    unz_global_info global_info;
    if ( unzGetGlobalInfo( zipfile, &global_info ) != UNZ_OK )
    {
        printf( "could not read file global info\n" );
        unzClose( zipfile );
        return -1;
    }

    // Buffer to hold data read from the zip file.
    char read_buffer[ READ_SIZE ];

    // Loop to extract all files
    uLong i;
    for ( i = 0; i < global_info.number_entry; ++i )
    {
        // Get info about current file.
        unz_file_info file_info;
        char filename[ MAX_FILENAME ];
        if ( unzGetCurrentFileInfo(
            zipfile,
            &file_info,
            filename,
            MAX_FILENAME,
            NULL, 0, NULL, 0 ) != UNZ_OK )
        {
            printf( "could not read file info\n" );
            unzClose( zipfile );
            return -1;
        }

        // Check if this entry is a directory or file.
        const size_t filename_length = strlen( filename );
        if ( filename[ filename_length-1 ] == dir_delimter )
        {
            // Entry is a directory, so create it.
            printf( "dir:%s\n", filename );
            mkdir( filename );
        }
        else
        {
            // Entry is a file, so extract it.
            printf( "file:%s\n", filename );
            if ( unzOpenCurrentFile( zipfile ) != UNZ_OK )
            {
                printf( "could not open file\n" );
                unzClose( zipfile );
                return -1;
            }

            // Open a file to write out the data.
            FILE *out = fopen( filename, "wb" );
            if ( out == NULL )
            {
                printf( "could not open destination file\n" );
                unzCloseCurrentFile( zipfile );
                unzClose( zipfile );
                return -1;
            }

            int error = UNZ_OK;
            do    
            {
                error = unzReadCurrentFile( zipfile, read_buffer, READ_SIZE );
                if ( error < 0 )
                {
                    printf( "error %d\n", error );
                    unzCloseCurrentFile( zipfile );
                    unzClose( zipfile );
                    return -1;
                }

                // Write data to file.
                if ( error > 0 )
                {
                    fwrite( read_buffer, error, 1, out ); // You should check return of fwrite...
                }
            } while ( error > 0 );

            fclose( out );
        }

        unzCloseCurrentFile( zipfile );

        // Go the the next entry listed in the zip file.
        if ( ( i+1 ) < global_info.number_entry )
        {
            if ( unzGoToNextFile( zipfile ) != UNZ_OK )
            {
                printf( "cound not read next file\n" );
                unzClose( zipfile );
                return -1;
            }
        }
    }

    unzClose( zipfile );

    return 0;
}

I built and tested it with MinGW/MSYS on Windows like this:

contrib/minizip/$ gcc -I../.. -o unzip uzip.c unzip.c ioapi.c ../../libz.a
contrib/minizip/$ ./unzip.exe /j/zlib-125.zip

trim left characters in sql server?

To remove the left-most word, you'll need to use either RIGHT or SUBSTRING. Assuming you know how many characters are involved, that would look either of the following:

SELECT RIGHT('Hello World', 5)
SELECT SUBSTRING('Hello World', 6, 100)

If you don't know how many characters that first word has, you'll need to find out using CHARINDEX, then substitute that value back into SUBSTRING:

SELECT SUBSTRING('Hello World', CHARINDEX(' ', 'Hello World') + 1, 100)

This finds the position of the first space, then takes the remaining characters to the right.

Linking to an external URL in Javadoc?

This creates a "See Also" heading containing the link, i.e.:

/**
 * @see <a href="http://google.com">http://google.com</a>
 */

will render as:

See Also:
           http://google.com

whereas this:

/**
 * See <a href="http://google.com">http://google.com</a>
 */

will create an in-line link:

See http://google.com

How does inline Javascript (in HTML) work?

using javascript:

here input element is used

<input type="text" id="fname" onkeyup="javascript:console.log(window.event.key)">

if you want to use multiline code use curly braces after javascript:

<input type="text" id="fname" onkeyup="javascript:{ console.log(window.event.key); alert('hello'); }">

Grouping switch statement cases together?

#include <stdio.h>
int n = 2;
int main()
{
     switch(n)
     {
          case 0: goto _4;break;
          case 1: goto _4;break;
          case 2: goto _4;break;
          case 3: goto _4;break;
          case 4:
              _4:
                printf("Funny and easy!\n");
                break;
          default:
                printf("Search on StackOverflow!\n");
                break;
     }
}

Should I use alias or alias_method?

Apart from the syntax, the main difference is in the scoping:

# scoping with alias_method
class User

  def full_name
    puts "Johnnie Walker"
  end

  def self.add_rename
    alias_method :name, :full_name
  end

end

class Developer < User
  def full_name
    puts "Geeky geek"
  end
  add_rename
end

Developer.new.name #=> 'Geeky geek'

In the above case method “name” picks the method “full_name” defined in “Developer” class. Now lets try with alias.

class User

  def full_name
    puts "Johnnie Walker"
  end

  def self.add_rename
    alias name full_name
  end
end

class Developer < User
  def full_name
    puts "Geeky geek"
  end
  add_rename
end

Developer.new.name #=> 'Johnnie Walker'

With the usage of alias the method “name” is not able to pick the method “full_name” defined in Developer.

This is because alias is a keyword and it is lexically scoped. It means it treats self as the value of self at the time the source code was read . In contrast alias_method treats self as the value determined at the run time.

Source: http://blog.bigbinary.com/2012/01/08/alias-vs-alias-method.html

HTML5 form required attribute. Set custom validation message?

The solution for preventing Google Chrome error messages on input each symbol:

_x000D_
_x000D_
<p>Click the 'Submit' button with empty input field and you will see the custom error message. Then put "-" sign in the same input field.</p>_x000D_
<form method="post" action="#">_x000D_
  <label for="text_number_1">Here you will see browser's error validation message on input:</label><br>_x000D_
  <input id="test_number_1" type="number" min="0" required="true"_x000D_
         oninput="this.setCustomValidity('')"_x000D_
         oninvalid="this.setCustomValidity('This is my custom message.')"/>_x000D_
  <input type="submit"/>_x000D_
</form>_x000D_
_x000D_
<form method="post" action="#">_x000D_
  <p></p>_x000D_
  <label for="text_number_1">Here you will see no error messages on input:</label><br>_x000D_
  <input id="test_number_2" type="number" min="0" required="true"_x000D_
         oninput="(function(e){e.setCustomValidity(''); return !e.validity.valid && e.setCustomValidity(' ')})(this)"_x000D_
         oninvalid="this.setCustomValidity('This is my custom message.')"/>_x000D_
  <input type="submit"/>_x000D_
</form>
_x000D_
_x000D_
_x000D_

In AngularJS, what's the difference between ng-pristine and ng-dirty?

ng-pristine ($pristine)

Boolean True if the form/input has not been used yet (not modified by the user)

ng-dirty ($dirty)

Boolean True if the form/input has been used (modified by the user)


$setDirty(); Sets the form to a dirty state. This method can be called to add the 'ng-dirty' class and set the form to a dirty state (ng-dirty class). This method will propagate current state to parent forms.

$setPristine(); Sets the form to its pristine state. This method sets the form's $pristine state to true, the $dirty state to false, removes the ng-dirty class and adds the ng-pristine class. Additionally, it sets the $submitted state to false. This method will also propagate to all the controls contained in this form.

Setting a form back to a pristine state is often useful when we want to 'reuse' a form after saving or resetting it.

How to check a radio button with jQuery?

Some times above solutions do not work, then you can try below:

jQuery.uniform.update(jQuery("#yourElementID").attr('checked',true));
jQuery.uniform.update(jQuery("#yourElementID").attr('checked',false));

Another way you can try is:

jQuery("input:radio[name=yourElementName]:nth(0)").attr('checked',true);

C# HttpWebRequest of type "application/x-www-form-urlencoded" - how to send '&' character in content body?

Since your content-type is application/x-www-form-urlencoded you'll need to encode the POST body, especially if it contains characters like & which have special meaning in a form.

Try passing your string through HttpUtility.UrlEncode before writing it to the request stream.

Here are a couple links for reference.

Compare integer in bash, unary operator expected

Judging from the error message the value of i was the empty string when you executed it, not 0.

Install pip in docker

While T. Arboreus's answer might fix the issues with resolving 'archive.ubuntu.com', I think the last error you're getting says that it doesn't know about the packages php5-mcrypt and python-pip. Nevertheless, the reduced Dockerfile of you with just these two packages worked for me (using Debian 8.4 and Docker 1.11.0), but I'm not quite sure if that could be the case because my host system is different than yours.

FROM ubuntu:14.04

# Install dependencies
RUN apt-get update && apt-get install -y \
    php5-mcrypt \
    python-pip

However, according to this answer you should think about installing the python3-pip package instead of the python-pip package when using Python 3.x.

Furthermore, to make the php5-mcrypt package installation working, you might want to add the universe repository like it's shown right here. I had trouble with the add-apt-repository command missing in the Ubuntu Docker image so I installed the package software-properties-common at first to make the command available.

Splitting up the statements and putting apt-get update and apt-get install into one RUN command is also recommended here.

Oh and by the way, you actually don't need the -y flag at apt-get update because there is nothing that has to be confirmed automatically.

Finally:

FROM ubuntu:14.04

# Install dependencies
RUN apt-get update && apt-get install -y \
    software-properties-common
RUN add-apt-repository universe
RUN apt-get update && apt-get install -y \
    apache2 \
    curl \
    git \
    libapache2-mod-php5 \
    php5 \
    php5-mcrypt \
    php5-mysql \
    python3.4 \
    python3-pip

Remark: The used versions (e.g. of Ubuntu) might be outdated in the future.

Chrome hangs after certain amount of data transfered - waiting for available socket

Explanation:

This problem occurs because Chrome allows up to 6 open connections by default. So if you're streaming multiple media files simultaneously from 6 <video> or <audio> tags, the 7th connection (for example, an image) will just hang, until one of the sockets opens up. Usually, an open connection will close after 5 minutes of inactivity, and that's why you're seeing your .pngs finally loading at that point.

Solution 1:

You can avoid this by minimizing the number of media tags that keep an open connection. And if you need to have more than 6, make sure that you load them last, or that they don't have attributes like preload="auto".

Solution 2:

If you're trying to use multiple sound effects for a web game, you could use the Web Audio API. Or to simplify things, just use a library like SoundJS, which is a great tool for playing a large amount of sound effects / music tracks simultaneously.

Solution 3: Force-open Sockets (Not recommended)

If you must, you can force-open the sockets in your browser (In Chrome only):

  1. Go to the address bar and type chrome://net-internals.
  2. Select Sockets from the menu.
  3. Click on the Flush socket pools button.

This solution is not recommended because you shouldn't expect your visitors to follow these instructions to be able to view your site.

How to get date, month, year in jQuery UI datepicker?

You can use method getDate():

$('#calendar').datepicker({
    dateFormat: 'yy-m-d',
    inline: true,
    onSelect: function(dateText, inst) { 
        var date = $(this).datepicker('getDate'),
            day  = date.getDate(),  
            month = date.getMonth() + 1,              
            year =  date.getFullYear();
        alert(day + '-' + month + '-' + year);
    }
});

FIDDLE

ERROR! MySQL manager or server PID file could not be found! QNAP

After doing setup of PHPMyAdmin, I was also facing the same problem,

Something . Like this

  • Then I just stopped the MYSQL server by going into System settings, and then started again, and it worked.

Getting a list of associative array keys

I am currently using Rob de la Cruz's reply:

Object.keys(obj)

And in a file loaded early on I have some lines of code borrowed from elsewhere on the Internet which cover the case of old versions of script interpreters that do not have Object.keys built in.

if (!Object.keys) {
    Object.keys = function(object) {
        var keys = [];
        for (var o in object) {
            if (object.hasOwnProperty(o)) {
                keys.push(o);
            }
        }
        return keys;
    };
}

I think this is the best of both worlds for large projects: simple modern code and backwards compatible support for old versions of browsers, etc.

Effectively it puts JW's solution into the function when Rob de la Cruz's Object.keys(obj) is not natively available.

How can I list ALL DNS records?

I've improved Josh's answer. I've noticed that dig only shows entries already present in the queried nameserver's cache, so it's better to pull an authoritative nameserver from the SOA (rather than rely on the default nameserver). I've also disabled the filtering of wildcard IPs because usually I'm usually more interested in the correctness of the setup.

The new script takes a -x argument for expanded output and a -s NS argument to choose a specific nameserver: dig -x example.com

#!/bin/bash
set -e; set -u
COMMON_SUBDOMAINS="www mail mx a.mx smtp pop imap blog en ftp ssh login"
EXTENDED=""

while :; do case "$1" in
  --) shift; break ;;
  -x) EXTENDED=y; shift ;;
  -s) NS="$2"; shift 2 ;;
  *) break ;;
esac; done
DOM="$1"; shift
TYPE="${1:-any}"

test "${NS:-}" || NS=$(dig +short  SOA "$DOM" | awk '{print $1}')
test "$NS" && NS="@$NS"

if test "$EXTENDED"; then
  dig +nocmd $NS "$DOM" +noall +answer "$TYPE"
  wild_ips=$(dig +short "$NS" "*.$DOM" "$TYPE" | tr '\n' '|')
  wild_ips="${wild_ips%|}"
  for sub in $COMMON_SUBDOMAINS; do
    dig +nocmd $NS "$sub.$DOM" +noall +answer "$TYPE"
  done | cat  #grep -vE "${wild_ips}"
  dig +nocmd $NS "*.$DOM" +noall +answer "$TYPE"
else
  dig +nocmd $NS "$DOM" +noall +answer "$TYPE"
fi

Converting a string to a date in DB2

You can use:

select VARCHAR_FORMAT(creationdate, 'MM/DD/YYYY') from table name

What is the origin of foo and bar?

tl;dr

  • "Foo" and "bar" as metasyntactic variables were popularised by MIT and DEC, the first references are in work on LISP and PDP-1 and Project MAC from 1964 onwards.

  • Many of these people were in MIT's Tech Model Railroad Club, where we find the first documented use of "foo" in tech circles in 1959 (and a variant in 1958).

  • Both "foo" and "bar" (and even "baz") were well known in popular culture, especially from Smokey Stover and Pogo comics, which will have been read by many TMRC members.

  • Also, it seems likely the military FUBAR contributed to their popularity.


The use of lone "foo" as a nonsense word is pretty well documented in popular culture in the early 20th century, as is the military FUBAR. (Some background reading: FOLDOC FOLDOC Jargon File Jargon File Wikipedia RFC3092)


OK, so let's find some references.

STOP PRESS! After posting this answer, I discovered this perfect article about "foo" in the Friday 14th January 1938 edition of The Tech ("MIT's oldest and largest newspaper & the first newspaper published on the web"), Volume LVII. No. 57, Price Three Cents:

On Foo-ism

The Lounger thinks that this business of Foo-ism has been carried too far by its misguided proponents, and does hereby and forthwith take his stand against its abuse. It may be that there's no foo like an old foo, and we're it, but anyway, a foo and his money are some party. (Voice from the bleachers- "Don't be foo-lish!")

As an expletive, of course, "foo!" has a definite and probably irreplaceable position in our language, although we fear that the excessive use to which it is currently subjected may well result in its falling into an early (and, alas, a dark) oblivion. We say alas because proper use of the word may result in such happy incidents as the following.

It was an 8.50 Thermodynamics lecture by Professor Slater in Room 6-120. The professor, having covered the front side of the blackboard, set the handle that operates the lift mechanism, turning meanwhile to the class to continue his discussion. The front board slowly, majestically, lifted itself, revealing the board behind it, and on that board, writ large, the symbols that spelled "FOO"!

The Tech newspaper, a year earlier, the Letter to the Editor, September 1937:

By the time the train has reached the station the neophytes are so filled with the stories of the glory of Phi Omicron Omicron, usually referred to as Foo, that they are easy prey.

...

It is not that I mind having lost my first four sons to the Grand and Universal Brotherhood of Phi Omicron Omicron, but I do wish that my fifth son, my baby, should at least be warned in advance.

Hopefully yours,

Indignant Mother of Five.

And The Tech in December 1938:

General trend of thought might be best interpreted from the remarks made at the end of the ballots. One vote said, '"I don't think what I do is any of Pulver's business," while another merely added a curt "Foo."


The first documented "foo" in tech circles is probably 1959's Dictionary of the TMRC Language:

FOO: the sacred syllable (FOO MANI PADME HUM); to be spoken only when under inspiration to commune with the Deity. Our first obligation is to keep the Foo Counters turning.

These are explained at FOLDOC. The dictionary's compiler Pete Samson said in 2005:

Use of this word at TMRC antedates my coming there. A foo counter could simply have randomly flashing lights, or could be a real counter with an obscure input.

And from 1996's Jargon File 4.0.0:

Earlier versions of this lexicon derived 'baz' as a Stanford corruption of bar. However, Pete Samson (compiler of the TMRC lexicon) reports it was already current when he joined TMRC in 1958. He says "It came from "Pogo". Albert the Alligator, when vexed or outraged, would shout 'Bazz Fazz!' or 'Rowrbazzle!' The club layout was said to model the (mythical) New England counties of Rowrfolk and Bassex (Rowrbazzle mingled with (Norfolk/Suffolk/Middlesex/Essex)."

A year before the TMRC dictionary, 1958's MIT Voo Doo Gazette ("Humor suplement of the MIT Deans' office") (PDF) mentions Foocom, in "The Laws of Murphy and Finagle" by John Banzhaf (an electrical engineering student):

Further research under a joint Foocom and Anarcom grant expanded the law to be all embracing and universally applicable: If anything can go wrong, it will!

Also 1964's MIT Voo Doo (PDF) references the TMRC usage:

Yes! I want to be an instant success and snow customers. Send me a degree in: ...

  • Foo Counters

  • Foo Jung


Let's find "foo", "bar" and "foobar" published in code examples.

So, Jargon File 4.4.7 says of "foobar":

Probably originally propagated through DECsystem manuals by Digital Equipment Corporation (DEC) in 1960s and early 1970s; confirmed sightings there go back to 1972.

The first published reference I can find is from February 1964, but written in June 1963, The Programming Language LISP: its Operation and Applications by Information International, Inc., with many authors, but including Timothy P. Hart and Michael Levin:

Thus, since "FOO" is a name for itself, "COMITRIN" will treat both "FOO" and "(FOO)" in exactly the same way.

Also includes other metasyntactic variables such as: FOO CROCK GLITCH / POOT TOOR / ON YOU / SNAP CRACKLE POP / X Y Z

I expect this is much the same as this next reference of "foo" from MIT's Project MAC in January 1964's AIM-064, or LISP Exercises by Timothy P. Hart and Michael Levin:

car[((FOO . CROCK) . GLITCH)]

It shares many other metasyntactic variables like: CHI / BOSTON NEW YORK / SPINACH BUTTER STEAK / FOO CROCK GLITCH / POOT TOOP / TOOT TOOT / ISTHISATRIVIALEXCERCISE / PLOOP FLOT TOP / SNAP CRACKLE POP / ONE TWO THREE / PLANE SUB THRESHER

For both "foo" and "bar" together, the earliest reference I could find is from MIT's Project MAC in June 1966's AIM-098, or PDP-6 LISP by none other than Peter Samson:

EXPLODE, like PRIN1, inserts slashes, so (EXPLODE (QUOTE FOO/ BAR)) PRIN1's as (F O O // / B A R) or PRINC's as (F O O / B A R).


Some more recallations.

@Walter Mitty recalled on this site in 2008:

I second the jargon file regarding Foo Bar. I can trace it back at least to 1963, and PDP-1 serial number 2, which was on the second floor of Building 26 at MIT. Foo and Foo Bar were used there, and after 1964 at the PDP-6 room at project MAC.

John V. Everett recalls in 1996:

When I joined DEC in 1966, foobar was already being commonly used as a throw-away file name. I believe fubar became foobar because the PDP-6 supported six character names, although I always assumed the term migrated to DEC from MIT. There were many MIT types at DEC in those days, some of whom had worked with the 7090/7094 CTSS. Since the 709x was also a 36 bit machine, foobar may have been used as a common file name there.

Foo and bar were also commonly used as file extensions. Since the text editors of the day operated on an input file and produced an output file, it was common to edit from a .foo file to a .bar file, and back again.

It was also common to use foo to fill a buffer when editing with TECO. The text string to exactly fill one disk block was IFOO$HXA127GA$$. Almost all of the PDP-6/10 programmers I worked with used this same command string.

Daniel P. B. Smith in 1998:

Dick Gruen had a device in his dorm room, the usual assemblage of B-battery, resistors, capacitors, and NE-2 neon tubes, which he called a "foo counter." This would have been circa 1964 or so.

Robert Schuldenfrei in 1996:

The use of FOO and BAR as example variable names goes back at least to 1964 and the IBM 7070. This too may be older, but that is where I first saw it. This was in Assembler. What would be the FORTRAN integer equivalent? IFOO and IBAR?

Paul M. Wexelblat in 1992:

The earliest PDP-1 Assembler used two characters for symbols (18 bit machine) programmers always left a few words as patch space to fix problems. (Jump to patch space, do new code, jump back) That space conventionally was named FU: which stood for Fxxx Up, the place where you fixed Fxxx Ups. When spoken, it was known as FU space. Later Assemblers ( e.g. MIDAS allowed three char tags so FU became FOO, and as ALL PDP-1 programmers will tell you that was FOO space.

Bruce B. Reynolds in 1996:

On the IBM side of FOO(FU)BAR is the use of the BAR side as Base Address Register; in the middle 1970's CICS programmers had to worry out the various xxxBARs...I think one of those was FRACTBAR...

Here's a straight IBM "BAR" from 1955.


Other early references:


I haven't been able to find any references to foo bar as "inverted foo signal" as suggested in RFC3092 and elsewhere.

Here are a some of even earlier F00s but I think they're coincidences/false positives:

macOS on VMware doesn't recognize iOS device

If you went throught alot of pain installing macos on vmware I recommend this tutorial which also provides you with all the file you need. it's straight forward tutorial and works all the way without any problem.

The I/O operation has been aborted because of either a thread exit or an application request

I had the same issue with RS232 communication. The reason, is that your program executes much faster than the comport (or slow serial communication).

To fix it, I had to check if the IAsyncResult.IsCompleted==true. If not completed, then IAsyncResult.AsyncWaitHandle.WaitOne()

Like this :

Stream s = this.GetStream();
IAsyncResult ar = s.BeginWrite(data, 0, data.Length, SendAsync, state);
if (!ar.IsCompleted)
    ar.AsyncWaitHandle.WaitOne();

Most of the time, ar.IsCompleted will be true.

Code coverage for Jest built on top of Jasmine

UPDATE: 7/20/2018 - Added links and updated name for coverageReporters.

UPDATE: 8/14/2017 - This answer is totally outdated. Just look at the Jest docs now. They have official support and documentation about how to do this.

@hankhsiao has got a forked repo where Istanbul is working with Jest. Add this to your dev dependencies

 "devDependencies": {
     "jest-cli": "git://github.com/hankhsiao/jest.git"
 }

Also make sure coverage is enabled in your package.json jest entry and you can also specify formats you want. (The html is pretty bad ass).

 "jest": {
     "collectCoverage": true,
     "coverageReporters": ["json", "html"],
 }

See Jest documentation for coverageReporters (default is ["json", "lcov", "text"])

Or add --coverage when you invoke jest.

How to enable cross-origin resource sharing (CORS) in the express.js framework on node.js

Try to this cors npm modules.

var cors = require('cors')

var app = express()
app.use(cors())

This module provides many features to fine tune cors setting such as domain whitelisting, enabling cors for specific apis etc.

ExpressJS How to structure an application?

I recently embraced modules as independent mini-apps.

|-- src
  |--module1
  |--module2
     |--www
       |--img
       |--js
       |--css
     |--#.js
     |--index.ejs
  |--module3
  |--www
     |--bower_components
     |--img
     |--js
     |--css
  |--#.js
  |--header.ejs
  |--index.ejs
  |--footer.ejs

Now for any module routing (#.js), views (*.ejs), js, css and assets are next to each other. submodule routing is set up in the parent #.js with two additional lines

router.use('/module2', opt_middleware_check, require('./module2/#'));
router.use(express.static(path.join(__dirname, 'www')));

This way even subsubmodules are possible.

Don't forget to set view to the src directory

app.set('views', path.join(__dirname, 'src'));

How to position a table at the center of div horizontally & vertically

I discovered that I had to include

body { width:100%; }

for "margin: 0 auto" to work for tables.

What is the difference between an interface and abstract class?

The only difference is that one can participate in multiple inheritance and other cannot.

The definition of an interface has changed over time. Do you think an interface just has method declarations only and are just contracts? What about static final variables and what about default definitions after Java 8?

Interfaces were introduced to Java because of the diamond problem with multiple inheritance and that's what they actually intend to do.

Interfaces are the constructs that were created to get away with the multiple inheritance problem and can have abstract methods, default definitions and static final variables.

See Why does Java allow static final variables in interfaces when they are only intended to be contracts?.

How do I install Python libraries in wheel format?

Simple steps to install python in Ubuntu:

  1. Download Python

    $ cd /usr/src 
    $ wget  https://www.python.org/ftp/python/3.6.0/Python-3.6.0.tgz
    
  2. Extract the downloaded package

    $ sudo tar xzf Python-3.6.0.tgz
    
  3. Compile Python source

    $ cd Python-3.6.0
    $ sudo ./configure
    $ sudo make altinstall 
    

    Note make altinstall is used to prevent replacing the default python binary file /usr/bin/python.

  4. check the python version

    # python3.6 -V
    

How to get all checked checkboxes

For a simple two- (or one) liner this code can be:

checkboxes = document.getElementsByName("NameOfCheckboxes");
selectedCboxes = Array.prototype.slice.call(checkboxes).filter(ch => ch.checked==true);

Here the Array.prototype.slice.call() part converts the object NodeList of all the checkboxes holding that name ("NameOfCheckboxes") into a new array, on which you then use the filter method. You can then also, for example, extract the values of the checkboxes by adding a .map(ch => ch.value) on the end of line 2. The => is javascript's arrow function notation.

CSS: 100% font size - 100% of what?

As you showed convincingly, the font-size: 100%; will not render the same in all browsers. However, you will set your font face in your CSS file, so this will be the same (or a fallback) in all browsers.

I believe font-size: 100%; can be very useful when combining it with em-based design. As this article shows, this will create a very flexible website.

When is this useful? When your site needs to adapt to the visitors' wishes. Take for example an elderly man that puts his default font-size at 24 px. Or someone with a small screen with a large resolution that increases his default font-size because he otherwise has to squint. Most sites would break, but em-based sites are able to cope with these situations.

Why do access tokens expire?

A couple of scenarios might help illustrate the purpose of access and refresh tokens and the engineering trade-offs in designing an oauth2 (or any other auth) system:

Web app scenario

In the web app scenario you have a couple of options:

  1. if you have your own session management, store both the access_token and refresh_token against your session id in session state on your session state service. When a page is requested by the user that requires you to access the resource use the access_token and if the access_token has expired use the refresh_token to get the new one.

Let's imagine that someone manages to hijack your session. The only thing that is possible is to request your pages.

  1. if you don't have session management, put the access_token in a cookie and use that as a session. Then, whenever the user requests pages from your web server send up the access_token. Your app server could refresh the access_token if need be.

Comparing 1 and 2:

In 1, access_token and refresh_token only travel over the wire on the way between the authorzation server (google in your case) and your app server. This would be done on a secure channel. A hacker could hijack the session but they would only be able to interact with your web app. In 2, the hacker could take the access_token away and form their own requests to the resources that the user has granted access to. Even if the hacker gets a hold of the access_token they will only have a short window in which they can access the resources.

Either way the refresh_token and clientid/secret are only known to the server making it impossible from the web browser to obtain long term access.

Let's imagine you are implementing oauth2 and set a long timeout on the access token:

In 1) There's not much difference here between a short and long access token since it's hidden in the app server. In 2) someone could get the access_token in the browser and then use it to directly access the user's resources for a long time.

Mobile scenario

On the mobile, there are a couple of scenarios that I know of:

  1. Store clientid/secret on the device and have the device orchestrate obtaining access to the user's resources.

  2. Use a backend app server to hold the clientid/secret and have it do the orchestration. Use the access_token as a kind of session key and pass it between the client and the app server.

Comparing 1 and 2

In 1) Once you have clientid/secret on the device they aren't secret any more. Anyone can decompile and then start acting as though they are you, with the permission of the user of course. The access_token and refresh_token are also in memory and could be accessed on a compromised device which means someone could act as your app without the user giving their credentials. In this scenario the length of the access_token makes no difference to the hackability since refresh_token is in the same place as access_token. In 2) the clientid/secret nor the refresh token are compromised. Here the length of the access_token expiry determines how long a hacker could access the users resources, should they get hold of it.

Expiry lengths

Here it depends upon what you're securing with your auth system as to how long your access_token expiry should be. If it's something particularly valuable to the user it should be short. Something less valuable, it can be longer.

Some people like google don't expire the refresh_token. Some like stackflow do. The decision on the expiry is a trade-off between user ease and security. The length of the refresh token is related to the user return length, i.e. set the refresh to how often the user returns to your app. If the refresh token doesn't expire the only way they are revoked is with an explicit revoke. Normally, a log on wouldn't revoke.

Hope that rather length post is useful.

Can we execute a java program without a main() method?

You should also be able to accomplish a similar thing using the premain method of a Java agent.

The manifest of the agent JAR file must contain the attribute Premain-Class. The value of this attribute is the name of the agent class. The agent class must implement a public static premain method similar in principle to the main application entry point. After the Java Virtual Machine (JVM) has initialized, each premain method will be called in the order the agents were specified, then the real application main method will be called. Each premain method must return in order for the startup sequence to proceed.

Postgres user does not exist?

psql -U postgres

Worked fine for me in case of db name: postgres & username: postgres. So you do not need to write sudo.

And in the case other db, you may try

psql -U yourdb postgres

As it is given in Postgres help:

psql [OPTION]... [DBNAME [USERNAME]]

Polling the keyboard (detect a keypress) in python

Ok, since my attempt to post my solution in a comment failed, here's what I was trying to say. I could do exactly what I wanted from native Python (on Windows, not anywhere else though) with the following code:

import msvcrt 

def kbfunc(): 
   x = msvcrt.kbhit()
   if x: 
      ret = ord(msvcrt.getch()) 
   else: 
      ret = 0 
   return ret

How to position text over an image in css

Why not set sample.png as background image of text or h2 css class? This will give effect as you have written over an image.

How to automate browsing using python?

You can also take a look at mechanize. Its meant to handle "stateful programmatic web browsing" (as per their site).

Android Emulator Error Message: "PANIC: Missing emulator engine program for 'x86' CPUS."

Adding a virtual device with the lowest possible Android version that was acceptable in my case worked for me. (Before that I'd tried several recent Android versions and had been getting the Missing emulator engine program for 'x86_64' CPUS error.)

Combine several images horizontally with Python

Based on DTing's answer I created a function that is easier to use:

from PIL import Image


def append_images(images, direction='horizontal',
                  bg_color=(255,255,255), aligment='center'):
    """
    Appends images in horizontal/vertical direction.

    Args:
        images: List of PIL images
        direction: direction of concatenation, 'horizontal' or 'vertical'
        bg_color: Background color (default: white)
        aligment: alignment mode if images need padding;
           'left', 'right', 'top', 'bottom', or 'center'

    Returns:
        Concatenated image as a new PIL image object.
    """
    widths, heights = zip(*(i.size for i in images))

    if direction=='horizontal':
        new_width = sum(widths)
        new_height = max(heights)
    else:
        new_width = max(widths)
        new_height = sum(heights)

    new_im = Image.new('RGB', (new_width, new_height), color=bg_color)


    offset = 0
    for im in images:
        if direction=='horizontal':
            y = 0
            if aligment == 'center':
                y = int((new_height - im.size[1])/2)
            elif aligment == 'bottom':
                y = new_height - im.size[1]
            new_im.paste(im, (offset, y))
            offset += im.size[0]
        else:
            x = 0
            if aligment == 'center':
                x = int((new_width - im.size[0])/2)
            elif aligment == 'right':
                x = new_width - im.size[0]
            new_im.paste(im, (x, offset))
            offset += im.size[1]

    return new_im

It allows choosing a background color and image alignment. It's also easy to do recursion:

images = map(Image.open, ['hummingbird.jpg', 'tiger.jpg', 'monarch.png'])

combo_1 = append_images(images, direction='horizontal')
combo_2 = append_images(images, direction='horizontal', aligment='top',
                        bg_color=(220, 140, 60))
combo_3 = append_images([combo_1, combo_2], direction='vertical')
combo_3.save('combo_3.png')

Example concatenated image

Draw a connecting line between two elements

I also had the same requirement few days back

I used an full width and height svg and added it below all my divs and added lines to these svg dynamically.

Checkout the how I did it here using svg

HTML

<div id="ui-browser"><div class="anchor"></div>
     <div id="control-library" class="library">
       <div class="name-title">Control Library</div>
       <ul>
         <li>Control A</li>
         <li>Control B</li>
         <li>Control C</li>
         <li>Control D</li>
       </ul>
     </div><!--
--></div><!--
--><div id="canvas">
     <svg id='connector_canvas'></svg>
     <div class="ui-item item-1"><div class="con_anchor"></div></div>
     <div class="ui-item item-2"><div class="con_anchor"></div></div>
     <div class="ui-item item-3"><div class="con_anchor"></div></div>
     <div class="ui-item item-1"><div class="con_anchor"></div></div>
     <div class="ui-item item-2"><div class="con_anchor"></div></div>
     <div class="ui-item item-3"><div class="con_anchor"></div></div>
   </div><!--
--><div id="property-browser"></div>

https://jsfiddle.net/kgfamo4b/

    $('.anchor').on('click',function(){
   var width = parseInt($(this).parent().css('width'));
   if(width==10){
     $(this).parent().css('width','20%');
     $('#canvas').css('width','60%');
   }else{
      $(this).parent().css('width','10px');
     $('#canvas').css('width','calc( 80% - 10px)');
   }
});

$('.ui-item').draggable({
  drag: function( event, ui ) {
           var lines = $(this).data('lines');
           var con_item =$(this).data('connected-item');
           var con_lines = $(this).data('connected-lines');

           if(lines) {
             lines.forEach(function(line,id){
                    $(line).attr('x1',$(this).position().left).attr('y1',$(this).position().top+1);  
             }.bind(this));
           }

           if(con_lines){
               con_lines.forEach(function(con_line,id){
                  $(con_line).attr('x2',$(this).position().left)
                        .attr('y2',$(this).position().top+(parseInt($(this).css('height'))/2)+(id*5));
               }.bind(this));

           }

       }
});

$('.ui-item').droppable({
  accept: '.con_anchor',
  drop: function(event,ui){
     var item = ui.draggable.closest('.ui-item');
     $(this).data('connected-item',item);
     ui.draggable.css({top:-2,left:-2});
     item.data('lines').push(item.data('line'));

     if($(this).data('connected-lines')){
        $(this).data('connected-lines').push(item.data('line'));

         var y2_ = parseInt(item.data('line').attr('y2'));
         item.data('line').attr('y2',y2_+$(this).data('connected-lines').length*5);

     }else $(this).data('connected-lines',[item.data('line')]);

     item.data('line',null);
    console.log('dropped');
  }
});


$('.con_anchor').draggable({drag: function( event, ui ) {
     var _end = $(event.target).parent().position();
     var end = $(event.target).position();
     if(_end&&end)  
     $(event.target).parent().data('line')
                                                    .attr('x2',end.left+_end.left+5).attr('y2',end.top+_end.top+2);
},stop: function(event,ui) {
        if(!ui.helper.closest('.ui-item').data('line')) return;
        ui.helper.css({top:-2,left:-2});
        ui.helper.closest('.ui-item').data('line').remove();
        ui.helper.closest('.ui-item').data('line',null);
        console.log('stopped');
      }
});


$('.con_anchor').on('mousedown',function(e){
    var cur_ui_item = $(this).closest('.ui-item');
    var connector = $('#connector_canvas');
    var cur_con;

  if(!$(cur_ui_item).data('lines')) $(cur_ui_item).data('lines',[]);

  if(!$(cur_ui_item).data('line')){
         cur_con = $(document.createElementNS('http://www.w3.org/2000/svg','line'));
         cur_ui_item.data('line',cur_con);
    } else cur_con = cur_ui_item.data('line');

    connector.append(cur_con);
    var start = cur_ui_item.position();
     cur_con.attr('x1',start.left).attr('y1',start.top+1);
     cur_con.attr('x2',start.left+1).attr('y2',start.top+1);
});

Positioning the colorbar

The best way to get good control over the colorbar position is to give it its own axis. Like so:

# What I imagine your plotting looks like so far
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(your_data)

# Now adding the colorbar
cbaxes = fig.add_axes([0.8, 0.1, 0.03, 0.8]) 
cb = plt.colorbar(ax1, cax = cbaxes)  

The numbers in the square brackets of add_axes refer to [left, bottom, width, height], where the coordinates are just fractions that go from 0 to 1 of the plotting area.

"Sources directory is already netbeans project" error when opening a project from existing sources

This is what I did to solve this error:

1) I copied a folder named "folder1" (and I called the new folder "folder2"). "folder1" was a Netbeans project so it had a folder called "nbproject" inside it.

2) When I tried to create a project out of the "folder2", Netbeans threw an error "Sources directory is already netbeans project (maybe only in memory)."

3) Inside Netbeans delete the project of "folder1". Then, delete the two folders named "nbproject" (one is inside "folder1" and the other is inside "folder2").

4) Inside Netbeans, create two new projects: one for "folder1" and another for "folder2". The error should not appear anymore.

Code-first vs Model/Database-first

Code-first appears to be the rising star. I had a quick look at Ruby on Rails, and their standard is code-first, with database migrations.

If you are building an MVC3 application, I believe Code first has the following advantages:

  • Easy attribute decoration - You can decorate fields with validation, require, etc.. attributes, it's quite awkward with EF modelling
  • No weird modelling errors - EF modelling often has weird errors, such as when you try to rename an association property, it needs to match the underlying meta-data - very inflexible.
  • Not awkward to merge - When using code version control tools such as mercurial, merging .edmx files is a pain. You're a programmer used to C#, and there you are merging a .edmx. Not so with code-first.
  • Contrast back to Code first and you have complete control without all the hidden complexities and unknowns to deal with.
  • I recommend you use the Package Manager command line tool, don't even use the graphical tools to add a new controller to scaffold views.
  • DB-Migrations - Then you can also Enable-Migrations. This is so powerful. You make changes to your model in code, and then the framework can keep track of schema changes, so you can seamlessly deploy upgrades, with schema versions automatically upgraded (and downgraded if required). (Not sure, but this probably does work with model-first too)

Update

The question also asks for a comparison of code-first to EDMX model/db-first. Code-first can be used for both of these approaches too:

Curl not recognized as an internal or external command, operable program or batch file

Method 1:\

add "C:\Program Files\cURL\bin" path into system variables Path right-click My Computer and click Properties >advanced > Environment Variables enter image description here

Method 2: (if method 1 not work then)

simple open command prompt with "run as administrator"

VBA array sort function?

Heapsort implementation. An O(n log(n)) (both average and worst case), in place, unstable sorting algorithm.

Use with: Call HeapSort(A), where A is a one dimensional array of variants, with Option Base 1.

Sub SiftUp(A() As Variant, I As Long)
    Dim K As Long, P As Long, S As Variant
    K = I
    While K > 1
        P = K \ 2
        If A(K) > A(P) Then
            S = A(P): A(P) = A(K): A(K) = S
            K = P
        Else
            Exit Sub
        End If
    Wend
End Sub

Sub SiftDown(A() As Variant, I As Long)
    Dim K As Long, L As Long, S As Variant
    K = 1
    Do
        L = K + K
        If L > I Then Exit Sub
        If L + 1 <= I Then
            If A(L + 1) > A(L) Then L = L + 1
        End If
        If A(K) < A(L) Then
            S = A(K): A(K) = A(L): A(L) = S
            K = L
        Else
            Exit Sub
        End If
    Loop
End Sub

Sub HeapSort(A() As Variant)
    Dim N As Long, I As Long, S As Variant
    N = UBound(A)
    For I = 2 To N
        Call SiftUp(A, I)
    Next I
    For I = N To 2 Step -1
        S = A(I): A(I) = A(1): A(1) = S
        Call SiftDown(A, I - 1)
    Next
End Sub

How to SFTP with PHP?

The ssh2 functions aren't very good. Hard to use and harder yet to install, using them will guarantee that your code has zero portability. My recommendation would be to use phpseclib, a pure PHP SFTP implementation.

default select option as blank

Today (2015-02-25)

This is valid HTML5 and sends a blank (not a space) to the server:

<option label=" "></option>

Verified validity on http://validator.w3.org/check

Verified behavior with Win7(IE11 IE10 IE9 IE8 FF35 Safari5.1) Ubuntu14.10(Chrome40, FF35) OSX_Yosemite(Safari8, Chrome40) Android(Samsung-Galaxy-S5)

The following also passes validation today, but passes some sort of space character too the server from most browsers (probably not desirable) and a blank on others (Chrome40/Linux passes a blank):

<option>&#160;</option>

Previously (2013-08-02)

According to my notes, the non-breaking-space entity inside the option tags shown above produced the following error in 2013:

Error: W3C Markup Validaton Service (Public): The first child option element of a select element with a required attribute and without a multiple attribute, and whose size is 1, must have either an empty value attribute, or must have no text content.

At that time, a regular space was valid XHTML4 and sent a blank (not a space) to the server from every browser:

<option> </option>

Future

It would make my heart glad if the spec was updated to explicitly allow a blank option. Preferably using the briefest syntax. Either of the following would be great:

<option />
<option></option>

Test File

<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <title>Test</title>
</head>
<body>
  <form action="index.html" method="post">
    <select name="sel">
      <option label=" "></option>
    </select>
  </form>
</body>
</html>

How to set width to 100% in WPF

It is the container of the Grid that is imposing on its width. In this case, that's a ListBoxItem, which is left-aligned by default. You can set it to stretch as follows:

<ListBox>
    <!-- other XAML omitted, you just need to add the following bit -->
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Setter Property="HorizontalAlignment" Value="Stretch"/>
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>

How can I calculate an md5 checksum of a directory?

If you want one md5sum spanning the whole directory, I would do something like

cat *.py | md5sum 

Returning Month Name in SQL Server Query

Without hitting db we can fetch all months name.

WITH CTE_Sample1 AS
(
    Select 0 as MonthNumber

    UNION ALL

    select MonthNumber+1 FROM CTE_Sample1
        WHERE MonthNumber+1<12
)

Select DateName( month , DateAdd( month , MonthNumber ,0 ) ) from CTE_Sample1

Set initially selected item in Select list in Angular2

Update to angular 4.X.X, there is a new way to mark an option selected:

<select [compareWith]="byId" [(ngModel)]="selectedItem">
  <option *ngFor="let item of items" [ngValue]="item">{{item.name}}
  </option>
</select>

byId(item1: ItemModel, item2: ItemModel) {
  return item1.id === item2.id;
}

Some tutorial here

How can I set a custom baud rate on Linux?

You can set a custom baud rate using the stty command on Linux. For example, to set a custom baud rate of 567890 on your serial port /dev/ttyX0, use the command:

stty -F /dev/ttyX0 567890

Is Django for the frontend or backend?

Neither.

Django is a framework, not a language. Python is the language in which Django is written.

Django is a collection of Python libs allowing you to quickly and efficiently create a quality Web application, and is suitable for both frontend and backend.

However, Django is pretty famous for its "Django admin", an auto generated backend that allows you to manage your website in a blink for a lot of simple use cases without having to code much.

More precisely, for the front end, Django helps you with data selection, formatting, and display. It features URL management, a templating language, authentication mechanisms, cache hooks, and various navigation tools such as paginators.

For the backend, Django comes with an ORM that lets you manipulate your data source with ease, forms (an HTML independent implementation) to process user input and validate data and signals, and an implementation of the observer pattern. Plus a tons of use-case specific nifty little tools.

For the rest of the backend work Django doesn't help with, you just use regular Python. Business logic is a pretty broad term.

You probably want to know as well that Django comes with the concept of apps, a self contained pluggable Django library that solves a problem. The Django community is huge, and so there are numerous apps that do specific business logic that vanilla Django doesn't.

It is more efficient to use if-return-return or if-else-return?

With any sensible compiler, you should observe no difference; they should be compiled to identical machine code as they're equivalent.

Quick-and-dirty way to ensure only one instance of a shell script is running at a time

Create a lock file in a known location and check for existence on script start? Putting the PID in the file might be helpful if someone's attempting to track down an errant instance that's preventing execution of the script.

Onclick event to remove default value in a text input field

In addition to placeholder="your text" you could also do onclick="this.value='';

So it would look something like:

<input name="Name" value="Enter Your Name" onclick="this.value='';>

PHP append one array to another (not array_push or +)

Another way to do this in PHP 5.6+ would be to use the ... token

$a = array('a', 'b');
$b = array('c', 'd');

array_push($a, ...$b);

// $a is now equals to array('a','b','c','d');

This will also work with any Traversable

$a = array('a', 'b');
$b = new ArrayIterator(array('c', 'd'));

array_push($a, ...$b);

// $a is now equals to array('a','b','c','d');

A warning though:

  • in PHP versions before 7.3 this will cause a fatal error if $b is an empty array or not traversable e.g. not an array
  • in PHP 7.3 a warning will be raised if $b is not traversable

No serializer found for class org.hibernate.proxy.pojo.javassist.Javassist?

This Exception

org.springframework.http.converter.HttpMessageNotWritableException

getting because, I hope so, your are sending response output as Serializable object.
This is problem occurring in spring. To over come this issue, send POJO object as response output.

Example :

    @Entity
    @Table(name="user_details")
    public class User implements Serializable{

        @Id
        @GeneratedValue(strategy= GenerationType.IDENTITY)
        @Column(name="id")
        private Integer id;

        @Column(name="user_name")
        private String userName;

        @Column(name="email_id")
        private String emailId;

        @Column(name="phone_no")
        private String phone;

//setter and getters

POJO class:

public class UserVO {

    private int Id;
    private String userName;
    private String emailId;
    private String phone;
    private Integer active;

//setter and getters

In controller convert the serilizable object fields to POJO class fields and return pojo class as output.

         User u= userService.getdetials(); // get data from database

        UserVO userVo= new UserVO();  // created pojo class object

        userVo.setId(u.getId());
        userVo.setEmailId(u.getEmailId());
        userVo.setActive(u.getActive());
        userVo.setPhone(u.getPhone());
        userVo.setUserName(u.getUserName());
       retunr userVo;  //finally send pojo object as output.

How to check if a line is blank using regex

Well...I tinkered around (using notepadd++) and this is the solution I found

\n\s

\n for end of line (where you start matching) -- the caret would not be of help in my case as the beginning of the row is a string \s takes any space till the next string

hope it helps

How to secure database passwords in PHP?

If you're hosting on someone else's server and don't have access outside your webroot, you can always put your password and/or database connection in a file and then lock the file using a .htaccess:

<files mypasswdfile>
order allow,deny
deny from all
</files>

Python lookup hostname from IP with 1 second timeout

What you're trying to accomplish is called Reverse DNS lookup.

socket.gethostbyaddr("IP") 
# => (hostname, alias-list, IP)

http://docs.python.org/library/socket.html?highlight=gethostbyaddr#socket.gethostbyaddr

However, for the timeout part I have read about people running into problems with this. I would check out PyDNS or this solution for more advanced treatment.

Closing Excel Application Process in C# after Data Access

Most of the methods works, but the excel process always stay until close the appliation.

When kill excel process once it can't be executed once again in the same thread - don't know why.

Variable not accessible when initialized outside function

Declare systemStatus in an outer scope and assign it in an onload handler.

systemStatus = null;

function onloadHandler(evt) {
    systemStatus = document.getElementById("....");
}

Or if you don't want the onload handler, put your script tag at the bottom of your HTML.

How to install pkg config in windows?

  1. Install mingw64 from https://sourceforge.net/projects/mingw-w64/. Avoid program files/(x86) folder for installation. Ex. c:/mingw-w64
  2. Download pkg-config__win64.zip from here
  3. Extract above zip file and copy paste all the files from pkg-config/bin folder to mingw-w64. In my case its 'C:\mingw-w64\i686-8.1.0-posix-dwarf-rt_v6-rev0\mingw32\bin'
  4. Now set path = C:\mingw-w64\i686-8.1.0-posix-dwarf-rt_v6-rev0\mingw32\bin taddaaa you are done.

If you find any security issue then follow steps as well

  1. Search for windows defender security center in system
  2. Navigate to apps & browser control> Exploit protection settings> Program setting> Click on '+add program customize'
  3. Select add program by name
  4. Enter program name: pkgconf.exe
  5. OK
  6. Now check all the settings and set it all the settings to off and apply.

Thats DONE!

jQuery : select all element with custom attribute

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

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

works (playable example).

Style input element to fill remaining width of its container

you can try this :

_x000D_
_x000D_
div#panel {_x000D_
    border:solid;_x000D_
    width:500px;_x000D_
    height:300px;_x000D_
}_x000D_
div#content {_x000D_
 height:90%;_x000D_
 background-color:#1ea8d1; /*light blue*/_x000D_
}_x000D_
div#panel input {_x000D_
 width:100%;_x000D_
 height:10%;_x000D_
 /*make input doesnt overflow inside div*/_x000D_
 -webkit-box-sizing: border-box;_x000D_
       -moz-box-sizing: border-box;_x000D_
            box-sizing: border-box;_x000D_
 /*make input doesnt overflow inside div*/_x000D_
}
_x000D_
<div id="panel">_x000D_
  <div id="content"></div>_x000D_
  <input type="text" placeholder="write here..."/>_x000D_
</div>
_x000D_
_x000D_
_x000D_