Programs & Examples On #Executable

An executable file causes a computer "to perform indicated tasks according to encoded instructions," as opposed to a data file that must be parsed by a program to be meaningful.

How to disassemble a binary executable in Linux to get the assembly code?

This answer is specific to x86. Portable tools that can disassemble AArch64, MIPS, or whatever machine code include objdump and llvm-objdump.


Agner Fog's disassembler, objconv, is quite nice. It will add comments to the disassembly output for performance problems (like the dreaded LCP stall from instructions with 16bit immediate constants, for example).

objconv  -fyasm a.out /dev/stdout | less

(It doesn't recognize - as shorthand for stdout, and defaults to outputting to a file of similar name to the input file, with .asm tacked on.)

It also adds branch targets to the code. Other disassemblers usually disassemble jump instructions with just a numeric destination, and don't put any marker at a branch target to help you find the top of loops and so on.

It also indicates NOPs more clearly than other disassemblers (making it clear when there's padding, rather than disassembling it as just another instruction.)

It's open source, and easy to compile for Linux. It can disassemble into NASM, YASM, MASM, or GNU (AT&T) syntax.

Sample output:

; Filling space: 0FH
; Filler type: Multi-byte NOP
;       db 0FH, 1FH, 44H, 00H, 00H, 66H, 2EH, 0FH
;       db 1FH, 84H, 00H, 00H, 00H, 00H, 00H

ALIGN   16

foo:    ; Function begin
        cmp     rdi, 1                                  ; 00400620 _ 48: 83. FF, 01
        jbe     ?_026                                   ; 00400624 _ 0F 86, 00000084
        mov     r11d, 1                                 ; 0040062A _ 41: BB, 00000001
?_020:  mov     r8, r11                                 ; 00400630 _ 4D: 89. D8
        imul    r8, r11                                 ; 00400633 _ 4D: 0F AF. C3
        add     r8, rdi                                 ; 00400637 _ 49: 01. F8
        cmp     r8, 3                                   ; 0040063A _ 49: 83. F8, 03
        jbe     ?_029                                   ; 0040063E _ 0F 86, 00000097
        mov     esi, 1                                  ; 00400644 _ BE, 00000001
; Filling space: 7H
; Filler type: Multi-byte NOP
;       db 0FH, 1FH, 80H, 00H, 00H, 00H, 00H

ALIGN   8
?_021:  add     rsi, rsi                                ; 00400650 _ 48: 01. F6
        mov     rax, rsi                                ; 00400653 _ 48: 89. F0
        imul    rax, rsi                                ; 00400656 _ 48: 0F AF. C6
        shl     rax, 2                                  ; 0040065A _ 48: C1. E0, 02
        cmp     r8, rax                                 ; 0040065E _ 49: 39. C0
        jnc     ?_021                                   ; 00400661 _ 73, ED
        lea     rcx, [rsi+rsi]                          ; 00400663 _ 48: 8D. 0C 36
...

Note that this output is ready to be assembled back into an object file, so you can tweak the code at the asm source level, rather than with a hex-editor on the machine code. (So you aren't limited to keeping things the same size.) With no changes, the result should be near-identical. It might not be, though, since disassembly of stuff like

  (from /lib/x86_64-linux-gnu/libc.so.6)

SECTION .plt    align=16 execute                        ; section number 11, code

?_00001:; Local function
        push    qword [rel ?_37996]                     ; 0001F420 _ FF. 35, 003A4BE2(rel)
        jmp     near [rel ?_37997]                      ; 0001F426 _ FF. 25, 003A4BE4(rel)

...    
ALIGN   8
?_00002:jmp     near [rel ?_37998]                      ; 0001F430 _ FF. 25, 003A4BE2(rel)

; Note: Immediate operand could be made smaller by sign extension
        push    11                                      ; 0001F436 _ 68, 0000000B
; Note: Immediate operand could be made smaller by sign extension
        jmp     ?_00001                                 ; 0001F43B _ E9, FFFFFFE0

doesn't have anything in the source to make sure it assembles to the longer encoding that leaves room for relocations to rewrite it with a 32bit offset.


If you don't want to install it objconv, GNU binutils objdump -Mintel -d is very usable, and will already be installed if you have a normal Linux gcc setup.

Executable directory where application is running from?

This is the first post on google so I thought I'd post different ways that are available and how they compare. Unfortunately I can't figure out how to create a table here, so it's an image. The code for each is below the image using fully qualified names.

enter image description here

My.Application.Info.DirectoryPath

Environment.CurrentDirectory

System.Windows.Forms.Application.StartupPath

AppDomain.CurrentDomain.BaseDirectory

System.Reflection.Assembly.GetExecutingAssembly.Location

System.Reflection.Assembly.GetExecutingAssembly.CodeBase

New System.UriBuilder(System.Reflection.Assembly.GetExecutingAssembly.CodeBase)

Path.GetDirectoryName(Uri.UnescapeDataString((New System.UriBuilder(System.Reflection.Assembly.GetExecutingAssembly.CodeBase).Path)))

Uri.UnescapeDataString((New System.UriBuilder(System.Reflection.Assembly.GetExecutingAssembly.CodeBase).Path))

"No such file or directory" but it exists

I had this issue and the reason was EOL in some editors such as Notepad++. You can check it in Edit menu/EOL conversion. Unix(LF) should be selected. I hope it would be useful.

LINK : fatal error LNK1104: cannot open file 'D:\...\MyProj.exe'

Like Jonathan said, yes, renaming can help to work around this problem. But ,e.g. I was forced to rename target executable many times, it's some tedious and not good.

The problem lies there that when you run your project and later get an error that you can't build your project - it's so because this executable (your project) is still runnning (you can check it via task manager.) If you just rename target build, some time later you will get the same error with new name too and if you open a task manager, you will see that you rubbish system with your not finished projects.

Visual studio for making a new build need to remove previous executable and create new instead of old, it can't do it while executable is still runinng. So, if you want to make a new build, process of old executable has to be closed! (it's strange that visual studio doesn't close it by itself and yes, it looks like some buggy behaviour).

enter image description here

It's some tedious to do it manually, so you may just a bat file and just click it when you have such problem:

taskkill /f /im name_of_target_executable.exe

it works for me at least. Like a guess - I don't close my program properly in C++, so may be it's normal for visual studio to hold it running.

ADDITION: There is a great chance to be so , because of not finished application. Check whether you called PostQuitMessage in the end, in order to give know Windows that you are done.

How can I make an EXE file from a Python program?

See a short list of python packaging tools on FreeHackers.org.

How do I create executable Java program?

Take a look at WinRun4J. It's windows only but that's because unix has executable scripts that look (to the user) like bins. You can also easily modify WinRun4J to compile on unix.

It does require a config file, but again, recompile it with hard-coded options and it works like a config-less exe.

Get path of executable

in Unix(including Linux) try 'which', in Windows try 'where'.

#include <stdio.h>

#define _UNIX

int main(int argc, char** argv)
{
        char cmd[128];
        char buf[128];
        FILE* fp = NULL;
#if defined(_UNIX)
        sprintf(cmd, "which %s > my.path", argv[0]);
#else
        sprintf(cmd, "where %s > my.path", argv[0]);
#endif
        system(cmd);
        fp = fopen("my.path", "r");
        fgets(buf, sizeof(buf), fp);
        fclose(fp);

        printf("full path: %s\n", buf);
        unlink("my.path");

        return 0;
}

Finding current executable's path without /proc/self/exe

If you're writing GPLed code and using GNU autotools, then a portable way that takes care of the details on many OSes (including Windows and macOS) is gnulib's relocatable-prog module.

Hide Command Window of .BAT file that Executes Another .EXE File

Using start works for me:

@echo off
copy "C:\Remoting.config-Training" "C:\Remoting.config"
start C:\ThirdParty.exe

EDIT: Ok, looking more closely, start seems to interpret the first parameter as the new window title if quoted. So, if you need to quote the path to your ThirdParty.exe you must supply a title string as well.

Examples:

:: Title not needed:
start C:\ThirdParty.exe

:: Title needed
start "Third Party App" "C:\Program Files\Vendor\ThirdParty.exe"

How to get source code of a Windows executable?

For Any *.Exe file written in any language .You can view the source code with hiew (otherwise Hackers view). You can download it at www.hiew.ru. It will be the demo version but still can view the code.

After this follow these steps:

  1. Press alt+f2 to navigate to the file.

  2. Press enter to see its assembly / c++ code.

How do I make this file.sh executable via double click?

you can change the file executable by using chmod like this

chmod 755 file.sh

and use this command for execute

./file.sh

Start an external application from a Google Chrome Extension?

Question has a good pagerank on google, so for anyone who's looking for answer to this question this might be helpful.

There is an extension in google chrome marketspace to do exactly that: https://chrome.google.com/webstore/detail/hccmhjmmfdfncbfpogafcbpaebclgjcp

run program in Python shell

Use execfile for Python 2:

>>> execfile('C:\\test.py')

Use exec for Python 3

>>> exec(open("C:\\test.py").read())

How can I convert a VBScript to an executable (EXE) file?

Here are a couple possible solutions...

I have not tried all of these myself yet, but I will be trying them all soon.

Note: I do not have any personal or financial connection to any of these tools.

1) VB Script to EXE Converter (NOT Compiler): (Free)
vbs2exe.com.

The exe produced appears to be a true EXE.

From their website:

VBS to EXE is a free online converter that doesn't only convert your vbs files into exe but it also:

1- Encrypt your vbs file source code using 128 bit key.
2- Allows you to call win32 API
3- If you have troubles with windows vista especially when UAC is enabled then you may give VBS to EXE a try.
4- No need for wscript.exe to run your vbs anymore.
5- Your script is never saved to the hard disk like some others converters. it is a TRUE exe not an extractor.

This solution should work even if wscript/cscript is not installed on the computer.

Basically, this creates a true .EXE file. Inside the created .EXE is an "engine" that replaces wscript/cscript, and an encrypted copy of your VB Script code. This replacement engine executes your code IN MEMORY without calling wscript/cscript to do it.


2) Compile and Convert VBS to EXE...:
ExeScript

The current version is 3.5.

This is NOT a Free solution. They have a 15 day trial. After that, you need to buy a license for a hefty $44.96 (Home License/noncommercial), or $89.95 (Business License/commercial usage).

It seems to work in a similar way to the previous solution.

According to a forum post there:
Post: "A Exe file still need Windows Scripting Host (WSH) ??"

WSH is not required if "Compile" option was used, since ExeScript
implements it's own scripting host. ...


3) Encrypt the script with Microsoft's ".vbs to .vbe" encryption tool.

Apparently, this does not work for Windows 7/8, and it is possible there are ways to "decrypt" the .vbe file. At the time of writing this, I could not find a working link to download this. If I find one, I will add it to this answer.

Compiling a java program into an executable

You can convert .jar file to .exe on these ways:
alt text
(source: viralpatel.net)

1- JSmooth .exe wrapper:
JSmooth is a Java Executable Wrapper. It creates native Windows launchers (standard .exe) for your java applications. It makes java deployment much smoother and user-friendly, as it is able to find any installed Java VM by itself. When no VM is available, the wrapper can automatically download and install a suitable JVM, or simply display a message or redirect the user to a web site.

JSmooth provides a variety of wrappers for your java application, each of them having their own behaviour: Choose your flavour!

Download: http://jsmooth.sourceforge.net/

2- JarToExe 1.8
Jar2Exe is a tool to convert jar files into exe files. Following are the main features as describe in their website:

  • Can generate “Console”, “Windows GUI”, “Windows Service” three types of exe files.
  • Generated exe files can add program icons and version information.
  • Generated exe files can encrypt and protect java programs, no temporary files will be generated when program runs.
  • Generated exe files provide system tray icon support.
  • Generated exe files provide record system event log support.
  • Generated windows service exe files are able to install/uninstall itself, and support service pause/continue.
  • New release of x64 version, can create 64 bits executives. (May 18, 2008)
  • Both wizard mode and command line mode supported. (May 18, 2008)

Download: http://www.brothersoft.com/jartoexe-75019.html

3- Executor
Package your Java application as a jar, and Executor will turn the jar into a Windows exe file, indistinguishable from a native application. Simply double-clicking the exe file will invoke the Java Runtime Environment and launch your application.

Download: http://mpowers.net/executor/

EDIT: The above link is broken, but here is the page (with working download) from the Internet Archive. http://web.archive.org/web/20090316092154/http://mpowers.net/executor/

4- Advanced Installer
Advanced Installer lets you create Windows MSI installs in minutes. This also has Windows Vista support and also helps to create MSI packages in other languages.
Download: http://www.advancedinstaller.com/ Let me know other tools that you have used to convert JAR to EXE.

Creating a batch file, for simple javac and java command execution

Create a plain text file (using notepad) and type the exact line you would use to run your Java file with the command prompt. Then change the extension to .bat and you're done.

Double clicking on this file would run your java program.

I reccommend one file for javac, one for java so you can troubleshoot if anything is wrong.

  • Make sure java is in your path, too.. IE typing java in a Dos windows when in your java workspace should bring up the java version message. If java is not in your path the batch file won't work unless you use absolut path to the java binary.

Difference between Groovy Binary and Source release?

The source release is the raw, uncompiled code. You could read it yourself. To use it, it must be compiled on your machine. Binary means the code was compiled into a machine language format that the computer can read, then execute. No human can understand the binary file unless its been dissected, or opened with some program that let's you read the executable as code.

How can I make a Python script standalone executable to run without ANY dependency?

py2exe will make the EXE file you want, but you need to have the same version of MSVCR90.dll on the machine you're going to use your new EXE file.

See Tutorial for more information.

Creating executable files in Linux

What you describe is the correct way to handle this.

You said that you want to stay in the GUI. You can usually set the execute bit through the file properties menu. You could also learn how to create a custom action for the context menu to do this for you if you're so inclined. This depends on your desktop environment of course.

If you use a more advanced editor, you can script the action to happen when the file is saved. For example (I'm only really familiar with vim), you could add this to your .vimrc to make any new file that starts with "#!/*/bin/*" executable.

au BufWritePost * if getline(1) =~ "^#!" | if getline(1) =~ "/bin/" | silent !chmod +x <afile> | endif | endif

How to create an executable .exe file from a .m file

mcc -?

explains that the syntax to make *.exe (Standalone Application) with *.m is:

 mcc -m <matlabFile.m> 

For example:

mcc -m file.m

will create file.exe in the curent directory.

Getting the absolute path of the executable, using C#?

The one that worked for me and isn't above was Process.GetCurrentProcess().MainModule.FileName.

Running an outside program (executable) in Python?

Try

import subprocess
subprocess.call(["C:/Documents and Settings/flow_model/flow.exe"])

Java: export to an .jar file in eclipse

No need for external plugins. In the Export JAR dialog, make sure you select all the necessary resources you want to export. By default, there should be no problem exporting other resource files as well (pictures, configuration files, etc...), see screenshot below. JAR Export Dialog

How can I find out if an .EXE has Command-Line Options?

Just use IDA PRO (https://www.hex-rays.com/products/ida/index.shtml) to disassemble the file, and search for some known command line option (using Search...Text) - in that section you will then typically see all the command line options - for the program (LIB2NIST.exe) in the screenshot below, for example, it shows a documented command line option (/COM2TAG) but also some undocumented ones, like /L. Hope this helps?

enter image description here

Running EXE with parameters

To start the process with parameters, you can use following code:

string filename = Path.Combine(cPath,"HHTCtrlp.exe");
var proc = System.Diagnostics.Process.Start(filename, cParams);

To kill/exit the program again, you can use following code:

proc.CloseMainWindow(); 
proc.Close();

How to compile python script to binary executable

I recommend PyInstaller, a simple python script can be converted to an exe with the following commands:

utils/Makespec.py [--onefile] oldlogs.py

which creates a yourprogram.spec file which is a configuration for building the final exe. Next command builds the exe from the configuration file:

utils/Build.py oldlogs.spec

More can be found here

Pyinstaller setting icons don't change

I think this might have something to do with caching (possibly in Windows Explorer). I was having the old PyInstaller icon show up in a few places too, but when I copied the exe somewhere else, all the old icons were gone.

Running .sh scripts in Git Bash

If your running export command in your bash script the above-given solution may not export anything even if it will run the script. As an alternative for that, you can run your script using

. script.sh 

Now if you try to echo your var it will be shown. Check my the result on my git bash

(coffeeapp) user (master *) capstone
$ . setup.sh
 done
(coffeeapp) user (master *) capstone
$ echo $ALGORITHMS
[RS256]
(coffeeapp) user (master *) capstone
$

Check more detail in this question

JBoss AS 7: How to clean up tmp?

As you know JBoss is a purely filesystem based installation. To install you simply unzip a file and thats it. Once you install a certain folder structure is created by default and as you run the JBoss instance for the first time, it creates additional folders for runtime operation. For comparison here is the structure of JBoss AS 7 before and after you start for the first time

Before

jboss-as-7
 |
 |---> standalone
 |      |----> lib
 |      |----> configuration
 |      |----> deployments
 |      
 |---> domain
 |....

After

jboss-as-7
     |
     |---> standalone
     |      |----> lib
     |      |----> configuration
     |      |----> deployments
     |      |----> tmp
     |      |----> data
     |      |----> log
     |      
     |---> domain
     |....

As you can see 3 new folders are created (log, data & tmp). These folders can all be deleted without effecting the application deployed in deployments folder unless your application generated Data that's stored in those folders. In development, its ok to delete all these 3 new folders assuming you don't have any need for the logs and data stored in "data" directory.

For production, ITS NOT RECOMMENDED to delete these folders as there maybe application generated data that stores certain state of the application. For ex, in the data folder, the appserver can save critical Tx rollback logs. So contact your JBoss Administrator if you need to delete those folders for any reason in production.

Good luck!

Difference between return and exit in Bash functions

The OP's question: What is the difference between the return and exit statement in BASH functions with respect to exit codes?

Firstly, some clarification is required:

  • A (return|exit) statement is not required to terminate execution of a (function|shell). A (function|shell) will terminate when it reaches the end of its code list, even with no (return|exit) statement.

  • A (return|exit) statement is not required to pass a value back from a terminated (function|shell). Every process has a built-in variable $? which always has a numeric value. It is a special variable that cannot be set like "?=1", but it is set only in special ways (see below *).

    The value of $? after the last command to be executed in the (called function | sub shell) is the value that is passed back to the (function caller | parent shell). That is true whether the last command executed is ("return [n]"| "exit [n]") or plain ("return" or something else which happens to be the last command in the called function's code.

In the above bullet list, choose from "(x|y)" either always the first item or always the second item to get statements about functions and return, or shells and exit, respectively.

What is clear is that they both share common usage of the special variable $? to pass values upwards after they terminate.

* Now for the special ways that $? can be set:

  • When a called function terminates and returns to its caller then $? in the caller will be equal to the final value of $? in the terminated function.
  • When a parent shell implicitly or explicitly waits on a single sub shell and is released by termination of that sub shell, then $? in the parent shell will be equal to the final value of $? in the terminated sub shell.
  • Some built-in functions can modify $? depending upon their result. But some don't.
  • Built-in functions "return" and "exit", when followed by a numerical argument both $? with argument, and terminate execution.

It is worth noting that $? can be assigned a value by calling exit in a sub shell, like this:

# (exit 259)
# echo $?
3

How to import local packages without gopath

Since the introduction of go.mod , I think both local and external package management becomes easier. Using go.mod, it is possible to have go project outside the GOPATH as well.

Import local package:

Create a folder demoproject and run following command to generate go.mod file

go mod init demoproject

I have a project structure like below inside the demoproject directory.

+-- go.mod
+-- src
    +-- main.go
    +-- model
        +-- model.go

For the demo purpose, insert the following code in the model.go file.

package model

type Employee struct {
    Id          int32
    FirstName   string
    LastName    string
    BadgeNumber int32
}

In main.go, I imported Employee model by referencing to "demoproject/src/model"

package main

import (
    "demoproject/src/model"
    "fmt"
)

func main() {
    fmt.Printf("Main Function")

    var employee = model.Employee{
        Id:          1,
        FirstName:   "First name",
        LastName:    "Last Name",
        BadgeNumber: 1000,
    }
    fmt.Printf(employee.FirstName)
}

Import external dependency:

Just run go get command inside the project directory.

For example:

go get -u google.golang.org/grpc

It should include module dependency in the go.mod file

module demoproject

go 1.13

require (
    golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa // indirect
    golang.org/x/sys v0.0.0-20200124204421-9fbb57f87de9 // indirect
    golang.org/x/text v0.3.2 // indirect
    google.golang.org/genproto v0.0.0-20200122232147-0452cf42e150 // indirect
    google.golang.org/grpc v1.26.0 // indirect
)

https://blog.golang.org/using-go-modules

Hidden property of a button in HTML

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script>

function showButtons () { $('#b1, #b2, #b3').show(); }

</script>
<style type="text/css">
#b1, #b2, #b3 {
display: none;
}

</style>
</head>
<body>

<a href="#" onclick="showButtons();">Show me the money!</a>

<input type="submit" id="b1" value="B1" />
<input type="submit" id="b2" value="B2"/>
<input type="submit" id="b3" value="B3" />

</body>
</html>

Getting Google+ profile picture url with user_id

Tried everything possible.. here is final piece of working code. Hope it helps someone who is looking for it.

    <?
$url='https://www.googleapis.com/plus/v1/people/116599978027440206136?fields=image%2Furl&key=MY_API_KEY&fields=image';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($ch);
curl_close($ch);
$d = json_decode($response);
$avatar_url = $d->{'image'}->{'url'};
echo $avatar_url;
?>

Trigger css hover with JS

You can't. It's not a trusted event.

Events that are generated by the user agent, either as a result of user interaction, or as a direct result of changes to the DOM, are trusted by the user agent with privileges that are not afforded to events generated by script through the DocumentEvent.createEvent("Event") method, modified using the Event.initEvent() method, or dispatched via the EventTarget.dispatchEvent() method. The isTrusted attribute of trusted events has a value of true, while untrusted events have a isTrusted attribute value of false.

Most untrusted events should not trigger default actions, with the exception of click or DOMActivate events.

You have to add a class and add/remove that on the mouseover/mouseout events manually.


Side note, I'm answering this here after I marked this as a duplicate since no answer here really covers the issue from what I see. Hopefully, one day it'll be merged.

Is it safe to clean docker/overlay2/

Friends, to keep everything clean you can use de commands:

  • docker system prune -a && docker volume prune.

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

From PEP 8 - Style Guide for Python Code:

The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. If necessary, you can add an extra pair of parentheses around an expression, but sometimes using a backslash looks better. Make sure to indent the continued line appropriately.

Example of implicit line continuation:

a = some_function(
    '1' + '2' + '3' - '4')

On the topic of line-breaks around a binary operator, it goes on to say:-

For decades the recommended style was to break after binary operators. But this can hurt readability in two ways: the operators tend to get scattered across different columns on the screen, and each operator is moved away from its operand and onto the previous line.

In Python code, it is permissible to break before or after a binary operator, as long as the convention is consistent locally. For new code Knuth's style (line breaks before the operator) is suggested.

Example of explicit line continuation:

a = '1'   \
    + '2' \
    + '3' \
    - '4'

Restoring database from .mdf and .ldf files of SQL Server 2008

use test
go
alter proc restore_mdf_ldf_main (@database varchar(100), @mdf varchar(100),@ldf varchar(100),@filename varchar(200))
as
begin 
begin try
RESTORE DATABASE @database FROM DISK = @FileName
with norecovery,
MOVE @mdf TO 'D:\sql samples\sample.mdf',
MOVE @ldf TO 'D:\sql samples\sample.ldf'
end try
begin catch
SELECT ERROR_MESSAGE() AS ErrorMessage;
print 'Restoring of the database ' + @database + ' failed';
end catch
end

exec restore_mdf_ldf_main product,product,product_log,'c:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Backup\product.bak'

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

While receiving the stream do these steps.

1st set some reasonable chunk size

Pseudo Code idea:

  1. The first step would be to find all the duplicates and stick them in a dictionary with its count and remove them.
  2. The third step would be to place number that exist in sequence of their algorithmic steps and place them in counters special dictionaries with the first number and their step like n, n+1..., n+2, 2n, 2n+1, 2n+2...
  3. Begin to compress in chunks some reasonable ranges of number like every 1000 or ever 10000 the remaining numbers that appear less often to repeat.
  4. Uncompress that range if a number is found and add it to the range and leave it uncompressed for a while longer.
  5. Otherwise just add that number to a byte[chunkSize]

Continue the first 4 steps while receiving the stream. The final step would be to either fail if you exceeded memory or start outputting the result once all the data is collected by beginning to sort the ranges and spit out the results in order and uncompressing those in order that need to be uncompressed and sort them when you get to them.

JPA or JDBC, how are they different?

JDBC is the predecessor of JPA.

JDBC is a bridge between the Java world and the databases world. In JDBC you need to expose all dirty details needed for CRUD operations, such as table names, column names, while in JPA (which is using JDBC underneath), you also specify those details of database metadata, but with the use of Java annotations.

So JPA creates update queries for you and manages the entities that you looked up or created/updated (it does more as well).

If you want to do JPA without a Java EE container, then Spring and its libraries may be used with the very same Java annotations.

What is the best way to convert an array to a hash in Ruby

if you have array that looks like this -

data = [["foo",1,2,3,4],["bar",1,2],["foobar",1,"*",3,5,:foo]]

and you want the first elements of each array to become the keys for the hash and the rest of the elements becoming value arrays, then you can do something like this -

data_hash = Hash[data.map { |key| [key.shift, key] }]

#=>{"foo"=>[1, 2, 3, 4], "bar"=>[1, 2], "foobar"=>[1, "*", 3, 5, :foo]}

How does the Spring @ResponseBody annotation work?

The first basic thing to understand is the difference in architectures.

One end you have the MVC architecture, which is based on your normal web app, using web pages, and the browser makes a request for a page:

Browser <---> Controller <---> Model
               |      |
               +-View-+

The browser makes a request, the controller (@Controller) gets the model (@Entity), and creates the view (JSP) from the model and the view is returned back to the client. This is the basic web app architecture.

On the other end, you have a RESTful architecture. In this case, there is no View. The Controller only sends back the model (or resource representation, in more RESTful terms). The client can be a JavaScript application, a Java server application, any application in which we expose our REST API to. With this architecture, the client decides what to do with this model. Take for instance Twitter. Twitter as the Web (REST) API, that allows our applications to use its API to get such things as status updates, so that we can use it to put that data in our application. That data will come in some format like JSON.

That being said, when working with Spring MVC, it was first built to handle the basic web application architecture. There are may different method signature flavors that allow a view to be produced from our methods. The method could return a ModelAndView where we explicitly create it, or there are implicit ways where we can return some arbitrary object that gets set into model attributes. But either way, somewhere along the request-response cycle, there will be a view produced.

But when we use @ResponseBody, we are saying that we do not want a view produced. We just want to send the return object as the body, in whatever format we specify. We wouldn't want it to be a serialized Java object (though possible). So yes, it needs to be converted to some other common type (this type is normally dealt with through content negotiation - see link below). Honestly, I don't work much with Spring, though I dabble with it here and there. Normally, I use

@RequestMapping(..., produces = MediaType.APPLICATION_JSON_VALUE)

to set the content type, but maybe JSON is the default. Don't quote me, but if you are getting JSON, and you haven't specified the produces, then maybe it is the default. JSON is not the only format. For instance, the above could easily be sent in XML, but you would need to have the produces to MediaType.APPLICATION_XML_VALUE and I believe you need to configure the HttpMessageConverter for JAXB. As for the JSON MappingJacksonHttpMessageConverter configured, when we have Jackson on the classpath.

I would take some time to learn about Content Negotiation. It's a very important part of REST. It'll help you learn about the different response formats and how to map them to your methods.

The network path was not found

I recently had the same issue. It's more likely that your application can not connect to database server due to the network issues.

In my case I was connected to wrong WiFi.

How can I search sub-folders using glob.glob module?

(The first options are of course mentioned in other answers, here the goal is to show that glob uses os.scandir internally, and provide a direct answer with this).


Using glob

As explained before, with Python 3.5+, it's easy:

import glob
for f in glob.glob('d:/temp/**/*', recursive=True):
    print(f)

#d:\temp\New folder
#d:\temp\New Text Document - Copy.txt
#d:\temp\New folder\New Text Document - Copy.txt
#d:\temp\New folder\New Text Document.txt

Using pathlib

from pathlib import Path
for f in Path('d:/temp').glob('**/*'):
    print(f)

Using os.scandir

os.scandir is what glob does internally. So here is how to do it directly, with a use of yield:

def listpath(path):
    for f in os.scandir(path):
        f2 = os.path.join(path, f)
        if os.path.isdir(f):
            yield f2
            yield from listpath(f2)
        else:
            yield f2

for f in listpath('d:\\temp'):
    print(f)

How to check a boolean condition in EL?

You can have a look at the EL (expression language) description here.

Both your code are correct, but I prefer the second one, as comparing a boolean to true or false is redundant.

For better readibility, you can also use the not operator:

<c:if test="${not theBooleanVariable}">It's false!</c:if>

Select SQL results grouped by weeks

I think this should do it..

Select 
ProductName,
WeekNumber,
sum(sale)
from
(
    SELECT 
    ProductName,
    DATEDIFF(week, '2011-05-30', date) AS WeekNumber,
    sale
    FROM table
)
GROUP BY
ProductName,
WeekNumber

Using .NET, how can you find the mime type of a file based on the file signature not the extension

Edit: Just use Mime Detective

I use byte array sequences to determine the correct MIME type of a given file. The advantage of this over just looking at the file extension of the file name is that if a user were to rename a file to bypass certain file type upload restrictions, the file name extension would fail to catch this. On the other hand, getting the file signature via byte array will stop this mischievous behavior from happening.

Here is an example in C#:

public class MimeType
{
    private static readonly byte[] BMP = { 66, 77 };
    private static readonly byte[] DOC = { 208, 207, 17, 224, 161, 177, 26, 225 };
    private static readonly byte[] EXE_DLL = { 77, 90 };
    private static readonly byte[] GIF = { 71, 73, 70, 56 };
    private static readonly byte[] ICO = { 0, 0, 1, 0 };
    private static readonly byte[] JPG = { 255, 216, 255 };
    private static readonly byte[] MP3 = { 255, 251, 48 };
    private static readonly byte[] OGG = { 79, 103, 103, 83, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0 };
    private static readonly byte[] PDF = { 37, 80, 68, 70, 45, 49, 46 };
    private static readonly byte[] PNG = { 137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82 };
    private static readonly byte[] RAR = { 82, 97, 114, 33, 26, 7, 0 };
    private static readonly byte[] SWF = { 70, 87, 83 };
    private static readonly byte[] TIFF = { 73, 73, 42, 0 };
    private static readonly byte[] TORRENT = { 100, 56, 58, 97, 110, 110, 111, 117, 110, 99, 101 };
    private static readonly byte[] TTF = { 0, 1, 0, 0, 0 };
    private static readonly byte[] WAV_AVI = { 82, 73, 70, 70 };
    private static readonly byte[] WMV_WMA = { 48, 38, 178, 117, 142, 102, 207, 17, 166, 217, 0, 170, 0, 98, 206, 108 };
    private static readonly byte[] ZIP_DOCX = { 80, 75, 3, 4 };

    public static string GetMimeType(byte[] file, string fileName)
    {

        string mime = "application/octet-stream"; //DEFAULT UNKNOWN MIME TYPE

        //Ensure that the filename isn't empty or null
        if (string.IsNullOrWhiteSpace(fileName))
        {
            return mime;
        }

        //Get the file extension
        string extension = Path.GetExtension(fileName) == null
                               ? string.Empty
                               : Path.GetExtension(fileName).ToUpper();

        //Get the MIME Type
        if (file.Take(2).SequenceEqual(BMP))
        {
            mime = "image/bmp";
        }
        else if (file.Take(8).SequenceEqual(DOC))
        {
            mime = "application/msword";
        }
        else if (file.Take(2).SequenceEqual(EXE_DLL))
        {
            mime = "application/x-msdownload"; //both use same mime type
        }
        else if (file.Take(4).SequenceEqual(GIF))
        {
            mime = "image/gif";
        }
        else if (file.Take(4).SequenceEqual(ICO))
        {
            mime = "image/x-icon";
        }
        else if (file.Take(3).SequenceEqual(JPG))
        {
            mime = "image/jpeg";
        }
        else if (file.Take(3).SequenceEqual(MP3))
        {
            mime = "audio/mpeg";
        }
        else if (file.Take(14).SequenceEqual(OGG))
        {
            if (extension == ".OGX")
            {
                mime = "application/ogg";
            }
            else if (extension == ".OGA")
            {
                mime = "audio/ogg";
            }
            else
            {
                mime = "video/ogg";
            }
        }
        else if (file.Take(7).SequenceEqual(PDF))
        {
            mime = "application/pdf";
        }
        else if (file.Take(16).SequenceEqual(PNG))
        {
            mime = "image/png";
        }
        else if (file.Take(7).SequenceEqual(RAR))
        {
            mime = "application/x-rar-compressed";
        }
        else if (file.Take(3).SequenceEqual(SWF))
        {
            mime = "application/x-shockwave-flash";
        }
        else if (file.Take(4).SequenceEqual(TIFF))
        {
            mime = "image/tiff";
        }
        else if (file.Take(11).SequenceEqual(TORRENT))
        {
            mime = "application/x-bittorrent";
        }
        else if (file.Take(5).SequenceEqual(TTF))
        {
            mime = "application/x-font-ttf";
        }
        else if (file.Take(4).SequenceEqual(WAV_AVI))
        {
            mime = extension == ".AVI" ? "video/x-msvideo" : "audio/x-wav";
        }
        else if (file.Take(16).SequenceEqual(WMV_WMA))
        {
            mime = extension == ".WMA" ? "audio/x-ms-wma" : "video/x-ms-wmv";
        }
        else if (file.Take(4).SequenceEqual(ZIP_DOCX))
        {
            mime = extension == ".DOCX" ? "application/vnd.openxmlformats-officedocument.wordprocessingml.document" : "application/x-zip-compressed";
        }

        return mime;
    }


}

Notice I handled DOCX file types differently since DOCX is really just a ZIP file. In this scenario, I simply check the file extension once I verified that it has that sequence. This example is far from complete for some people, but you can easily add your own.

If you want to add more MIME types, you can get the byte array sequences of many different file types from here. Also, here is another good resource concerning file signatures.

What I do a lot of times if all else fails is step through several files of a particular type that I am looking for and look for a pattern in the byte sequence of the files. In the end, this is still basic verification and cannot be used for 100% proof of determining file types.

Is it possible to insert HTML content in XML document?

Just put the html tags with there content and add the xmlns attribute with quotes after the equals and in between the quotes is http://www.w3.org/1999/xhtml

PHP error: Notice: Undefined index:

This are just php notice messages,it seems php.ini configurations are not according vtiger standards, you can disable this message by setting error reporting to E_ALL & ~E_NOTICE in php.ini For example error_reporting(E_ALL&~E_NOTICE) and then restart apache to reflect changes.

How do I create a folder in VB if it doesn't exist?

Under System.IO, there is a class called Directory. Do the following:

If Not Directory.Exists(path) Then
    Directory.CreateDirectory(path)
End If

It will ensure that the directory is there.

Setting PayPal return URL and making it auto return?

You have to enable auto return in your PayPal account, otherwise it will ignore the return field.

From the documentation (updated to reflect new layout Jan 2019):

Auto Return is turned off by default. To turn on Auto Return:

  1. Log in to your PayPal account at https://www.paypal.com or https://www.sandbox.paypal.com The My Account Overview page appears.
  2. Click the gear icon top right. The Profile Summary page appears.
  3. Click the My Selling Preferences link in the left column.
  4. Under the Selling Online section, click the Update link in the row for Website Preferences. The Website Payment Preferences page appears
  5. Under Auto Return for Website Payments, click the On radio button to enable Auto Return.
  6. In the Return URL field, enter the URL to which you want your payers redirected after they complete their payments. NOTE: PayPal checks the Return URL that you enter. If the URL is not properly formatted or cannot be validated, PayPal will not activate Auto Return.
  7. Scroll to the bottom of the page, and click the Save button.

IPN is for instant payment notification. It will give you more reliable/useful information than what you'll get from auto-return.

Documentation for IPN is here: https://www.x.com/sites/default/files/ipnguide.pdf

Online Documentation for IPN: https://developer.paypal.com/docs/classic/ipn/gs_IPN/

The general procedure is that you pass a notify_url parameter with the request, and set up a page which handles and validates IPN notifications, and PayPal will send requests to that page to notify you when payments/refunds/etc. go through. That IPN handler page would then be the correct place to update the database to mark orders as having been paid.

Messagebox with input field

You can do it by making form and displaying it using ShowDialogBox....

Form.ShowDialog Method - Shows the form as a modal dialog box.

Example:

public void ShowMyDialogBox()
{
   Form2 testDialog = new Form2();

   // Show testDialog as a modal dialog and determine if DialogResult = OK.
   if (testDialog.ShowDialog(this) == DialogResult.OK)
   {
      // Read the contents of testDialog's TextBox.
      this.txtResult.Text = testDialog.TextBox1.Text;
   }
   else
   {
      this.txtResult.Text = "Cancelled";
   }
   testDialog.Dispose();
}

Regex to extract URLs from href attribute in HTML with Python

import re

url = '<p>Hello World</p><a href="http://example.com">More Examples</a><a href="http://example2.com">Even More Examples</a>'

urls = re.findall('https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+', url)

>>> print urls
['http://example.com', 'http://example2.com']

jQuery Popup Bubble/Tooltip

Ok, after some work I'm able to get a "bubble" to pop up and go away at all the right times. There is a LOT of styling that needs to happen still but this is basically the code i used.

<script type="text/javascript">
    //--indicates the mouse is currently over a div
    var onDiv = false;
    //--indicates the mouse is currently over a link
    var onLink = false;
    //--indicates that the bubble currently exists
    var bubbleExists = false;
    //--this is the ID of the timeout that will close the window if the user mouseouts the link
    var timeoutID;

    function addBubbleMouseovers(mouseoverClass) {
        $("."+mouseoverClass).mouseover(function(event) {
            if (onDiv || onLink) {
                return false;
            }

            onLink = true;

            showBubble.call(this, event);
        });

        $("." + mouseoverClass).mouseout(function() {
            onLink = false;
            timeoutID = setTimeout(hideBubble, 150);
        });
    }

    function hideBubble() {
        clearTimeout(timeoutID);
        //--if the mouse isn't on the div then hide the bubble
        if (bubbleExists && !onDiv) {
             $("#bubbleID").remove();

             bubbleExists = false;
        }
    }

    function showBubble(event) {
        if (bubbleExists) {
            hideBubble();
        }

        var tPosX = event.pageX + 15;
        var tPosY = event.pageY - 60;
        $('<div ID="bubbleID" style="top:' + tPosY + '; left:' + tPosX + '; position: absolute; display: inline; border: 2px; width: 200px; height: 150px; background-color: Red;">TESTING!!!!!!!!!!!!</div>').mouseover(keepBubbleOpen).mouseout(letBubbleClose).appendTo('body');

        bubbleExists = true;
    }

    function keepBubbleOpen() {
        onDiv = true;
    }

    function letBubbleClose() {
        onDiv = false;

        hideBubble();
    }


    //--TESTING!!!!!
    $("document").ready(function() {
        addBubbleMouseovers("temp1");
    });
</script>

Here is a snippet of the html that goes with it:

<a href="" class="temp1">Mouseover this for a terribly ugly red bubble!</a>

php return 500 error but no error log

You need to enable the PHP error log.

This is due to some random glitch in the web server when you have a php error, it throws a 500 internal error (i have the same issue).

If you look in the PHP error log, you should find your solution.

see here in the doc of how to enable it in the php.ini

How to save a dictionary to a file?

Save and load dict to file:

def save_dict_to_file(dic):
    f = open('dict.txt','w')
    f.write(str(dic))
    f.close()

def load_dict_from_file():
    f = open('dict.txt','r')
    data=f.read()
    f.close()
    return eval(data)

Append integer to beginning of list in Python

Another way of doing the same,

list[0:0] = [a]

How to pass command line arguments to a rake task

In addition to answer by kch (I didn't find how to leave a comment to that, sorry):

You don't have to specify variables as ENV variables before the rake command. You can just set them as usual command line parameters like that:

rake mytask var=foo

and access those from your rake file as ENV variables like such:

p ENV['var'] # => "foo"

javax.naming.NameNotFoundException: Name is not bound in this Context. Unable to find

Ok found out the Tomcat file server.xml must be configured as well for the data source to work. So just add:

<Resource 
auth="Container" 
driverClassName="org.apache.derby.jdbc.EmbeddedDriver" 
maxActive="20" 
maxIdle="10" 
maxWait="-1" 
name="ds/flexeraDS" 
type="javax.sql.DataSource" 
url="jdbc:derby:flexeraDB;create=true" 
  />

How I can get and use the header file <graphics.h> in my C++ program?

<graphics.h> is very old library. It's better to use something that is new

Here are some 2D libraries (platform independent) for C/C++

SDL

GTK+

Qt

Also there is a free very powerful 3D open source graphics library for C++

OGRE

How to find lines containing a string in linux

The usual way to do this is with grep, which uses a pattern to match lines:

grep 'pattern' file

Each line which matches the pattern will be output. If you want to search for fixed strings only, use grep -F 'pattern' file.

How to add multiple font files for the same font?

The solution seems to be to add multiple @font-face rules, for example:

@font-face {
    font-family: "DejaVu Sans";
    src: url("fonts/DejaVuSans.ttf");
}
@font-face {
    font-family: "DejaVu Sans";
    src: url("fonts/DejaVuSans-Bold.ttf");
    font-weight: bold;
}
@font-face {
    font-family: "DejaVu Sans";
    src: url("fonts/DejaVuSans-Oblique.ttf");
    font-style: italic, oblique;
}
@font-face {
    font-family: "DejaVu Sans";
    src: url("fonts/DejaVuSans-BoldOblique.ttf");
    font-weight: bold;
    font-style: italic, oblique;
}

By the way, it would seem Google Chrome doesn't know about the format("ttf") argument, so you might want to skip that.

(This answer was correct for the CSS 2 specification. CSS3 only allows for one font-style rather than a comma-separated list.)

Replacing backslashes with forward slashes with str_replace() in php

Single quoted php string variable works.

$str = 'http://www.domain.com/data/images\flags/en.gif';
$str = str_replace('\\', '/', $str);

Cannot open solution file in Visual Studio Code

But you can open the folder with the .SLN in to edit the code in the project, which will detect the .SLN to select the library that provides Intellisense.

Django upgrading to 1.9 error "AppRegistryNotReady: Apps aren't loaded yet."

Late to the party, but grappelli was the reason for my error as well. I looked up the compatible version on pypi and that fixed it for me.

How to hide UINavigationBar 1px bottom line

As of iOS 13 there is a system API to set or remove the shadow

UIKit uses shadowImage and the shadowColor property to determine the shadow's appearance. When shadowImage is nil, the bar displays a default shadow tinted according to the value in the shadowColor property. If shadowColor is nil or contains the clearColor color, the bar displays no shadow.

    let appearance = UINavigationBarAppearance()
    appearance.shadowImage = nil
    appearance.shadowColor = nil
    navigationController.navigationBar.standardAppearance = appearance

https://developer.apple.com/documentation/uikit/uibarappearance/3198009-shadowimage

How to record phone calls in android?

The answer of pratt is bit uncomplete, because when you restart your device your app will working stop, recording stop, its become useless.

i m adding some line that copy in your project for complete working of Pratt answer.

<receiver
        android:name=".DeviceAdminDemo"
        android:permission="android.permission.BIND_DEVICE_ADMIN">
        <meta-data
            android:name="android.app.admin"
            android:resource="@xml/device_admin" />

        <intent-filter>
            <action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
            <action android:name="android.app.action.DEVICE_ADMIN_DISABLED" />
            <action android:name="android.app.action.DEVICE_ADMIN_DISABLE_REQUESTED" />
            <action android:name="android.intent.action.BOOT_COMPLETED" />
            <category android:name="android.intent.category.HOME" />
        </intent-filter>
    </receiver>

put this code in onReceive of DeviceAdminDemo

@Override
public void onReceive(Context context, Intent intent) {
    super.onReceive(context, intent);

    context.stopService(new Intent(context, TService.class));
    Intent myIntent = new Intent(context, TService.class);
    context.startService(myIntent);

}

C# Set collection?

If you're using .NET 3.5, you can use HashSet<T>. It's true that .NET doesn't cater for sets as well as Java does though.

The Wintellect PowerCollections may help too.

Convert SVG to PNG in Python

Another solution I've just found here How to render a scaled SVG to a QImage?

from PySide.QtSvg import *
from PySide.QtGui import *


def convertSvgToPng(svgFilepath,pngFilepath,width):
    r=QSvgRenderer(svgFilepath)
    height=r.defaultSize().height()*width/r.defaultSize().width()
    i=QImage(width,height,QImage.Format_ARGB32)
    p=QPainter(i)
    r.render(p)
    i.save(pngFilepath)
    p.end()

PySide is easily installed from a binary package in Windows (and I use it for other things so is easy for me).

However, I noticed a few problems when converting country flags from Wikimedia, so perhaps not the most robust svg parser/renderer.

Do HTTP POST methods send data as a QueryString?

A POST request can include a query string, however normally it doesn't - a standard HTML form with a POST action will not normally include a query string for example.

How to use a PHP class from another file?

In this case, it appears that you've already included the file somewhere. But for class files, you should really "include" them using require_once to avoid that sort of thing; it won't include the file if it already has been. (And you should usually use require[_once], not include[_once], the difference being that require will cause a fatal error if the file doesn't exist, instead of just issuing a warning.)

How could others, on a local network, access my NodeJS app while it's running on my machine?

I had the same question and solved the problem. In my case, the Windows Firewall (not the router) was blocking the V8 machine I/O on the hosting machine.

  1. Go to windows button
  2. Search "Firewall"
  3. Choose "Allow programs to communicate through Firewall"
  4. Click Change Setup
  5. Tick all of "Evented I/O for V8 Javascript" OR "Node.js: Server-side Javascript"

My guess is that "Evented I/O for V8 Javascript" is the I/O process that node.js communicates to outside world and we need to free it before it can send packets outside of the local computer. After enabling this program to communicate over Windows firewall, I could use any port numbers to listen.

Android device is not connected to USB for debugging (Android studio)

Try a different cable, ideally an official Samsung one.

I had tried a crappy USB cable I had lying around and then tried another which was Samsung and works perfectly now.

Not sure why they would be different though but worked for me.

Drop-down box dependent on the option selected in another drop-down box

for this, I have noticed that it far better to show and hide the tags instead of adding and removing them for the DOM. It performs better that way.

NumPy array initialization (fill with identical values)

You can use numpy.tile, e.g. :

v = 7
rows = 3
cols = 5
a = numpy.tile(v, (rows,cols))
a
Out[1]: 
array([[7, 7, 7, 7, 7],
       [7, 7, 7, 7, 7],
       [7, 7, 7, 7, 7]])

Although tile is meant to 'tile' an array (instead of a scalar, as in this case), it will do the job, creating pre-filled arrays of any size and dimension.

Address already in use: JVM_Bind

on windows open a cmd.exe window with administrator permissions and use netstat -a -b -o you will get the id of the proccess that holds your port and be able to kill it using task manager.

What's is the difference between include and extend in use case diagram?

Use cases are used to document behavior, e.g. answer this question.

answer the question use case

A behavior extends another if it is in addition to but not necessarily part of the behavior, e.g. research the answer.

Also note that researching the answer doesn't make much sense if you are not trying to answer the question.

research the answer extend

A behavior is included in another if it is part of the including behavior, e.g. login to stack exchange.

login to stack exchange include

To clarify, the illustration is only true if you want to answer here in stack overflow :).

These are the technical definitions from UML 2.5 pages 671-672.

I highlighted what I think are important points.

Extends

An Extend is a relationship from an extending UseCase (the extension) to an extended UseCase (the extendedCase) that specifies how and when the behavior defined in the extending UseCase can be inserted into the behavior defined in the extended UseCase. The extension takes place at one or more specific extension points defined in the extended UseCase.

Extend is intended to be used when there is some additional behavior that should be added, possibly conditionally, to the behavior defined in one or more UseCases.

The extended UseCase is defined independently of the extending UseCase and is meaningful independently of the extending UseCase. On the other hand, the extending UseCase typically defines behavior that may not necessarily be meaningful by itself. Instead, the extending UseCase defines a set of modular behavior increments that augment an execution of the extended UseCase under specific conditions.

...

Includes

Include is a DirectedRelationship between two UseCases, indicating that the behavior of the included UseCase (the addition) is inserted into the behavior of the including UseCase (the includingCase). It is also a kind of NamedElement so that it can have a name in the context of its owning UseCase (the includingCase). The including UseCase may depend on the changes produced by executing the included UseCase. The included UseCase must be available for the behavior of the including UseCase to be completely described.

The Include relationship is intended to be used when there are common parts of the behavior of two or more UseCases. This common part is then extracted to a separate UseCase, to be included by all the base UseCases having this part in common. As the primary use of the Include relationship is for reuse of common parts, what is left in a base UseCase is usually not complete in itself but dependent on the included parts to be meaningful. This is reflected in the direction of the relationship, indicating that the base UseCase depends on the addition but not vice versa.

...

@Cacheable key on multiple method arguments

Use this

@Cacheable(value="bookCache", key="#isbn + '_' + #checkWarehouse + '_' + #includeUsed")

How can I access Google Sheet spreadsheets only with Javascript?

edit: This was answered before the google doc's api was released. See Evan Plaice's answer and Dan Dascalescu's answer for more up-to-date information.

It looks lke you can, but it's a pain to use. It involves using the Google data API.

http://gdatatips.blogspot.com/2008/12/using-javascript-client-library-w-non.html

"The JavaScript client library has helper methods for Calendar, Contacts, Blogger, and Google Finance. However, you can use it with just about any Google Data API to access authenticated/private feeds. This example uses the DocList API."

and an example of writing a gadget that interfaces with spreadsheets: http://code.google.com/apis/spreadsheets/gadgets/

How to Auto resize HTML table cell to fit the text size

You can try this:

HTML

<table>
    <tr>
        <td class="shrink">element1</td>
        <td class="shrink">data</td>
        <td class="shrink">junk here</td>
        <td class="expand">last column</td>
    </tr>
    <tr>
        <td class="shrink">elem</td>
        <td class="shrink">more data</td>
        <td class="shrink">other stuff</td>
        <td class="expand">again, last column</td>
    </tr>
    <tr>
        <td class="shrink">more</td>
        <td class="shrink">of </td>
        <td class="shrink">these</td>
        <td class="expand">rows</td>
    </tr>
</table>

CSS

table {
    border: 1px solid green;
    border-collapse: collapse;
    width:100%;
}

table td {
    border: 1px solid green;
}

table td.shrink {
    white-space:nowrap
}
table td.expand {
    width: 99%
}

Add querystring parameters to link_to

In case you want to pass in a block, say, for a glyphicon button, as in the following:

<%= link_to my_url, class: "stuff" do %>
  <i class="glyphicon glyphicon-inbox></i> Nice glyph-button
<% end %>

Then passing querystrings params could be accomplished through:

<%= link_to url_for(params.merge(my_params: "value")), class: "stuff" do %>
  <i class="glyphicon glyphicon-inbox></i> Nice glyph-button
<% end %>

IntelliJ: Working on multiple projects

Use the button for the add maven projects and go inside the folder of the project. Then, select the pom.xml file and add them in the IntelliJ.

enter image description here

How to force a web browser NOT to cache images

I checked all the answers around the web and the best one seemed to be: (actually it isn't)

<img src="image.png?cache=none">

at first.

However, if you add cache=none parameter (which is static "none" word), it doesn't effect anything, browser still loads from cache.

Solution to this problem was:

<img src="image.png?nocache=<?php echo time(); ?>">

where you basically add unix timestamp to make the parameter dynamic and no cache, it worked.

However, my problem was a little different: I was loading on the fly generated php chart image, and controlling the page with $_GET parameters. I wanted the image to be read from cache when the URL GET parameter stays the same, and do not cache when the GET parameters change.

To solve this problem, I needed to hash $_GET but since it is array here is the solution:

$chart_hash = md5(implode('-', $_GET));
echo "<img src='/images/mychart.png?hash=$chart_hash'>";

Edit:

Although the above solution works just fine, sometimes you want to serve the cached version UNTIL the file is changed. (with the above solution, it disables the cache for that image completely) So, to serve cached image from browser UNTIL there is a change in the image file use:

echo "<img src='/images/mychart.png?hash=" . filemtime('mychart.png') . "'>";

filemtime() gets file modification time.

how to pass variable from shell script to sqlplus

You appear to have a heredoc containing a single SQL*Plus command, though it doesn't look right as noted in the comments. You can either pass a value in the heredoc:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql BUILDING
exit;
EOF

or if BUILDING is $2 in your script:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql $2
exit;
EOF

If your file.sql had an exit at the end then it would be even simpler as you wouldn't need the heredoc:

sqlplus -S user/pass@localhost @/opt/D2RQ/file.sql $2

In your SQL you can then refer to the position parameters using substitution variables:

...
}',SEM_Models('&1'),NULL,
...

The &1 will be replaced with the first value passed to the SQL script, BUILDING; because that is a string it still needs to be enclosed in quotes. You might want to set verify off to stop if showing you the substitutions in the output.


You can pass multiple values, and refer to them sequentially just as you would positional parameters in a shell script - the first passed parameter is &1, the second is &2, etc. You can use substitution variables anywhere in the SQL script, so they can be used as column aliases with no problem - you just have to be careful adding an extra parameter that you either add it to the end of the list (which makes the numbering out of order in the script, potentially) or adjust everything to match:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql total_count BUILDING
exit;
EOF

or:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql total_count $2
exit;
EOF

If total_count is being passed to your shell script then just use its positional parameter, $4 or whatever. And your SQL would then be:

SELECT COUNT(*) as &1
FROM TABLE(SEM_MATCH(
'{
        ?s rdf:type :ProcessSpec .
        ?s ?p ?o
}',SEM_Models('&2'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));

If you pass a lot of values you may find it clearer to use the positional parameters to define named parameters, so any ordering issues are all dealt with at the start of the script, where they are easier to maintain:

define MY_ALIAS = &1
define MY_MODEL = &2

SELECT COUNT(*) as &MY_ALIAS
FROM TABLE(SEM_MATCH(
'{
        ?s rdf:type :ProcessSpec .
        ?s ?p ?o
}',SEM_Models('&MY_MODEL'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));

From your separate question, maybe you just wanted:

SELECT COUNT(*) as &1
FROM TABLE(SEM_MATCH(
'{
        ?s rdf:type :ProcessSpec .
        ?s ?p ?o
}',SEM_Models('&1'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));

... so the alias will be the same value you're querying on (the value in $2, or BUILDING in the original part of the answer). You can refer to a substitution variable as many times as you want.

That might not be easy to use if you're running it multiple times, as it will appear as a header above the count value in each bit of output. Maybe this would be more parsable later:

select '&1' as QUERIED_VALUE, COUNT(*) as TOTAL_COUNT

If you set pages 0 and set heading off, your repeated calls might appear in a neat list. You might also need to set tab off and possibly use rpad('&1', 20) or similar to make that column always the same width. Or get the results as CSV with:

select '&1' ||','|| COUNT(*)

Depends what you're using the results for...

How do I remove duplicate items from an array in Perl?

My usual way of doing this is:

my %unique = ();
foreach my $item (@myarray)
{
    $unique{$item} ++;
}
my @myuniquearray = keys %unique;

If you use a hash and add the items to the hash. You also have the bonus of knowing how many times each item appears in the list.

Fastest way to update 120 Million records

If your int_field is indexed, remove the index before running the update. Then create your index again...

5 hours seem like a lot for 120 million recs.

regular expression for DOT

. matches any character so needs escaping i.e. \., or \\. within a Java string (because \ itself has special meaning within Java strings.)

You can then use \.\. or \.{2} to match exactly 2 dots.

Spark RDD to DataFrame python

See,

There are two ways to convert an RDD to DF in Spark.

toDF() and createDataFrame(rdd, schema)

I will show you how you can do that dynamically.

toDF()

The toDF() command gives you the way to convert an RDD[Row] to a Dataframe. The point is, the object Row() can receive a **kwargs argument. So, there is an easy way to do that.

from pyspark.sql.types import Row

#here you are going to create a function
def f(x):
    d = {}
    for i in range(len(x)):
        d[str(i)] = x[i]
    return d

#Now populate that
df = rdd.map(lambda x: Row(**f(x))).toDF()

This way you are going to be able to create a dataframe dynamically.

createDataFrame(rdd, schema)

Other way to do that is creating a dynamic schema. How?

This way:

from pyspark.sql.types import StructType
from pyspark.sql.types import StructField
from pyspark.sql.types import StringType

schema = StructType([StructField(str(i), StringType(), True) for i in range(32)])

df = sqlContext.createDataFrame(rdd, schema)

This second way is cleaner to do that...

So this is how you can create dataframes dynamically.

JSONDecodeError: Expecting value: line 1 column 1

in my case, some characters like " , :"'{}[] " maybe corrupt the JSON format, so use try json.loads(str) except to check your input

Round up value to nearest whole number in SQL UPDATE

You could use the ceiling function; this portion of SQL code :

select ceiling(45.01), ceiling(45.49), ceiling(45.99);

will get you "46" each time.

For your update, so, I'd say :

Update product SET price = ceiling(45.01)

BTW : On MySQL, ceil is an alias to ceiling ; not sure about other DB systems, so you might have to use one or the other, depending on the DB you are using...

Quoting the documentation :

CEILING(X)

Returns the smallest integer value not less than X.

And the given example :

mysql> SELECT CEILING(1.23);
        -> 2
mysql> SELECT CEILING(-1.23);
        -> -1

How to stop asynctask thread in android?

The reason why things aren't stopping for you is because the process (doInBackground()) runs until it is finished. Therefore you should check if the thread is cancelled or not before doing stuff:

if(!isCancelled()){
// Do your stuff
}

So basically, if the thread is not cancelled, do it, otherwise skip it :) Could be useful to check for this some times during your operation, especially before time taking stuff.

Also it could be useful to "clean up" alittle in

onCancelled();

Documentation for AsyncTask:

http://developer.android.com/reference/android/os/AsyncTask.html

Hope this helps!

How to Logout of an Application Where I Used OAuth2 To Login With Google?

You can simply Create a logout button and add this link to it and it will utimately log you out from the app and will redirect to your desired site:

https://appengine.google.com/_ah/logout?continue=http://www.YOURSITE.com

just toggle YOURSITE with your website

Disable asp.net button after click to prevent double clicking

I have found this, and it works:

btnSave.Attributes.Add(
    "onclick", 
    "this.disabled = true;" + ClientScript.GetPostBackEventReference(btnSave, null) + ";");

How to get a table cell value using jQuery?

try this :

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
    <title>Untitled</title>

<script type="text/javascript"><!--

function getVal(e) {
    var targ;
    if (!e) var e = window.event;
    if (e.target) targ = e.target;
    else if (e.srcElement) targ = e.srcElement;
    if (targ.nodeType == 3) // defeat Safari bug
        targ = targ.parentNode;

    alert(targ.innerHTML);
}

onload = function() {
    var t = document.getElementById("main").getElementsByTagName("td");
    for ( var i = 0; i < t.length; i++ )
        t[i].onclick = getVal;
}

</script>



<body>

<table id="main"><tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
    <td>4</td>
</tr><tr>
    <td>5</td>
    <td>6</td>
    <td>7</td>
    <td>8</td>
</tr><tr>
    <td>9</td>
    <td>10</td>
    <td>11</td>
    <td>12</td>
</tr></table>

</body>
</html>

Clearing coverage highlighting in Eclipse

Click the "Remove all Sessions" button in the toolbar of the "Coverage" view.

enter image description here

C#: How to access an Excel cell?

Simple.

To open a workbook. Use xlapp.workbooks.Open()

where you have previously declared and instanitated xlapp as so.. Excel.Application xlapp = new Excel.Applicaton();

parameters are correct.

Next make sure you use the property Value2 when assigning a value to the cell using either the cells property or the range object.

Capture screenshot of active window?

Here is a snippet to capture either the desktop or the active window. It has no reference to Windows Forms.

public class ScreenCapture
{
    [DllImport("user32.dll")]
    private static extern IntPtr GetForegroundWindow();

    [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
    public static extern IntPtr GetDesktopWindow();

    [StructLayout(LayoutKind.Sequential)]
    private struct Rect
    {
        public int Left;
        public int Top;
        public int Right;
        public int Bottom;
    }   

    [DllImport("user32.dll")]
    private static extern IntPtr GetWindowRect(IntPtr hWnd, ref Rect rect);

    public static Image CaptureDesktop()
    {
        return CaptureWindow(GetDesktopWindow());
    }

    public static Bitmap CaptureActiveWindow()
    {
        return CaptureWindow(GetForegroundWindow());
    }

    public static Bitmap CaptureWindow(IntPtr handle)
    {
        var rect = new Rect();
        GetWindowRect(handle, ref rect);
        var bounds = new Rectangle(rect.Left, rect.Top, rect.Right - rect.Left, rect.Bottom - rect.Top);
        var result = new Bitmap(bounds.Width, bounds.Height);

        using (var graphics = Graphics.FromImage(result))
        {
            graphics.CopyFromScreen(new Point(bounds.Left, bounds.Top), Point.Empty, bounds.Size);
        }

        return result;
    }
}

How to capture the whole screen:

var image = ScreenCapture.CaptureDesktop();
image.Save(@"C:\temp\snippetsource.jpg", ImageFormat.Jpeg);

How to capture the active window:

var image = ScreenCapture.CaptureActiveWindow();
image.Save(@"C:\temp\snippetsource.jpg", ImageFormat.Jpeg);

Originally found here: http://www.snippetsource.net/Snippet/158/capture-screenshot-in-c

Creating a Custom Event

Yes you can do like this :

Creating advanced C# custom events

or

The Simplest C# Events Example Imaginable

public class Metronome
{
    public event TickHandler Tick;
    public EventArgs e = null;
    public delegate void TickHandler(Metronome m, EventArgs e);
    public void Start()
    {
        while (true)
        {
            System.Threading.Thread.Sleep(3000);
            if (Tick != null)
            {
                Tick(this, e);
            }
        }
    }
}
public class Listener
{
    public void Subscribe(Metronome m)
    {
        m.Tick += new Metronome.TickHandler(HeardIt);
    }

    private void HeardIt(Metronome m, EventArgs e)
    {
        System.Console.WriteLine("HEARD IT");
    }
}
class Test
{
    static void Main()
    {
        Metronome m = new Metronome();
        Listener l = new Listener();
        l.Subscribe(m);
        m.Start();
    }
}

What "wmic bios get serialnumber" actually retrieves?

the wmic bios get serialnumber command call the Win32_BIOS wmi class and get the value of the SerialNumber property, which retrieves the serial number of the BIOS Chip of your system.

Make a negative number positive

You want to wrap each number into Math.abs(). e.g.

System.out.println(Math.abs(-1));

prints out "1".

If you want to avoid writing the Math.-part, you can include the Math util statically. Just write

import static java.lang.Math.abs;

along with your imports, and you can refer to the abs()-function just by writing

System.out.println(abs(-1));

ORA-12154 could not resolve the connect identifier specified

I had the same issue. In my case I was using a web service which was build using AnyCPU settings. Since the WCF was using 32 bit Oracle data access components therefore it was raising the same error when I tried to call it from a console client. So when I compiled the WCF service using the x86 based setting the client was able to successfully get data from the web service.

If you compile as "Any CPU" and run on an x64 platform, then you won't be able to load 32-bit dlls (which in our case were the Oracle Data Access components), because our app wasn't started in WOW64 (Windows32 on Windows 64). So in order to allow the 32 bit dependency of Oracle Data Access components I compilee the web service with Platform target of x86 and that solved it for me

As an alternative if you have 64bit ODAC drivers installed on the machine that also caused the problem to go away.

SQLite in Android How to update a specific row

//Here is some simple sample code for update

//First declare this

private DatabaseAppHelper dbhelper;
private SQLiteDatabase db;

//initialize the following

dbhelper=new DatabaseAppHelper(this);
        db=dbhelper.getWritableDatabase();

//updation code

 ContentValues values= new ContentValues();
                values.put(DatabaseAppHelper.KEY_PEDNAME, ped_name);
                values.put(DatabaseAppHelper.KEY_PEDPHONE, ped_phone);
                values.put(DatabaseAppHelper.KEY_PEDLOCATION, ped_location);
                values.put(DatabaseAppHelper.KEY_PEDEMAIL, ped_emailid);
                db.update(DatabaseAppHelper.TABLE_NAME, values,  DatabaseAppHelper.KEY_ID + "=" + ?, null);

//put ur id instead of the 'question mark' is a function in my shared preference.

Avoid dropdown menu close on click inside

You may have some problems if you use return false or stopPropagation() method because your events will be interrupted. Try this code, it's works fine:

$(function() {
    $('.dropdown').on("click", function (e) {
            $('.keep-open').removeClass("show");
    });
    $('.dropdown-toggle').on("click", function () {
            $('.keep-open').addClass("show");
    });

    $( ".closeDropdown" ).click(function() {
        $('.dropdown').closeDropdown();
    });
});
jQuery.fn.extend({
    closeDropdown: function() {
        this.addClass('show')
            .removeClass("keep-open")
            .click()
            .addClass("keep-open");
    }
  });

In HTML:

<div class="dropdown keep-open" id="search-menu" >
    <button  class="btn dropdown-toggle btn  btn-primary" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    <i class="fa fa-filter fa-fw"></i> 
    </button>
    <div class="dropdown-menu">
        <button class="dropdown-item" id="opt1" type="button">Option 1</button>
        <button class="dropdown-item" id="opt2" type="button">Option 2</button>
        <button type="button" class="btn btn-primary closeDropdown">Close</button>
    </div>
</div>

If you want to close the dropdrown:

`$('#search-menu').closeDropdown();`

Get the current user, within an ApiController action, without passing the userID as a parameter

You can also access the principal using the User property on ApiController.

So the following two statements are basically the same:

string id;
id = User.Identity.GetUserId();
id = RequestContext.Principal.Identity.GetUserId();

Maven Unable to locate the Javac Compiler in:

Though there are a few non-Eclipse answers above for this question that does not mention Eclipse, they require path variable changes. An alternative is to use the command line option, java.home, e.g.:

mvn package -Djava.home="C:\Program Files\Java\jdk1.8.0_161\jre"

Notice the \jre at the end - a surprising necessity.

How can I make a TextBox be a "password box" and display stars when using MVVM?

The problem with using the PasswordBox is that it is not very MVVM friendly due to the fact that it works with SecureString and therefore requires a shim to bind it to a String. You also cannot use the clipboard. While all these things are there for a reason, you may not require that level of security. Here is an alternative approach that works with the clipboard, nothing fancy. You make the TextBox text and background transparent and bind the text to a TextBlock underneath it. This textblock converts characters to * using the converter specified.

<Window.Resources>
    <local:TextToPasswordCharConverter x:Key="TextToPasswordCharConverter" />
</Window.Resources>

<Grid Width="200">
    <TextBlock Margin="5,0,0,0" Text="{Binding Text, Converter={StaticResource TextToPasswordCharConverter}, UpdateSourceTrigger=PropertyChanged, Mode=OneWay}" FontFamily="Consolas" VerticalAlignment="Center" />
    <TextBox Foreground="Transparent" Text="{Binding Text, UpdateSourceTrigger=PropertyChanged}" FontFamily="Consolas" Background="Transparent" />
</Grid>

And here is the Value Converter:

class TextToPasswordCharConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return new String('*', value?.ToString().Length ?? 0);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

Make sure your Text property on your viewmodel implements INotifyPropertyChanged

How to find where gem files are installed

gem env works just like gem environment. Saves some typing.

# gem env
RubyGems Environment:
  - RUBYGEMS VERSION: 2.0.14
  - RUBY VERSION: 2.0.0 (2014-02-24 patchlevel 451) [i686-linux]
  - INSTALLATION DIRECTORY: /usr/local/lib/ruby/gems/2.0.0
  - RUBY EXECUTABLE: /usr/local/bin/ruby
  - EXECUTABLE DIRECTORY: /usr/local/bin
  - RUBYGEMS PLATFORMS:
    - ruby
    - x86-linux
  - GEM PATHS:
     - /usr/local/lib/ruby/gems/2.0.0
     - /root/.gem/ruby/2.0.0
  - GEM CONFIGURATION:
     - :update_sources => true
     - :verbose => true
     - :backtrace => false
     - :bulk_threshold => 1000
  - REMOTE SOURCES:
     - https://rubygems.org/

java.lang.IllegalAccessError: tried to access method

This happened to me when I had a class in one jar trying to access a private method in a class from another jar. I simply changed the private method to public, recompiled and deployed, and it worked ok afterwards.

How to load my app from Eclipse to my Android phone instead of AVD

The USB drivers in \extras\google\usb_driver didn't work for me.

However the official drivers from Samsung did: http://developer.samsung.com/android/tools-sdks/Samsung-Andorid-USB-Driver-for-Windows

Note: I'm using a Samsung Galaxy S2 with Android 4.0 on Windows 7 64bit

Android: Creating a Circular TextView?

1.Create an xml circle_text_bg.xml in your res/drawable folder with the code below

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
     <solid android:color="#fff" />

    <stroke
        android:width="1dp"
        android:color="#98AFC7" />
    <corners
         android:bottomLeftRadius="50dp"
         android:bottomRightRadius="50dp"
         android:topLeftRadius="50dp"
         android:topRightRadius="50dp" />
    <size
         android:height="20dp"
         android:width="20dp" />
</shape>

2.Use circle_text_bg as the background for your textview. NB: In order to get a perfect circle your textview height and width should be the same.Preview of what your textview with text 1, 2, 3 with this background should look like this

How to get the Android device's primary e-mail address

This could be useful to others:

Using AccountPicker to get user's email address without any global permissions, and allowing the user to be aware and authorize or cancel the process.

What's the difference between a mock & stub?

Stub

I believe the biggest distinction is that a stub you have already written with predetermined behavior. So you would have a class that implements the dependency (abstract class or interface most likely) you are faking for testing purposes and the methods would just be stubbed out with set responses. They would not do anything fancy and you would have already written the stubbed code for it outside of your test.

Mock

A mock is something that as part of your test you have to setup with your expectations. A mock is not setup in a predetermined way so you have code that does it in your test. Mocks in a way are determined at runtime since the code that sets the expectations has to run before they do anything.

Difference between Mocks and Stubs

Tests written with mocks usually follow an initialize -> set expectations -> exercise -> verify pattern to testing. While the pre-written stub would follow an initialize -> exercise -> verify.

Similarity between Mocks and Stubs

The purpose of both is to eliminate testing all the dependencies of a class or function so your tests are more focused and simpler in what they are trying to prove.

C# - Insert a variable number of spaces into a string? (Formatting an output file)

Use String.Format:

string title1 = "Sample Title One";
string element1 = "Element One";
string format = "{0,-20} {1,-10}";

string result = string.Format(format, title1, element1);
//or you can print to Console directly with
//Console.WriteLine(format, title1, element1);

In the format {0,-20} means the first argument has a fixed length 20, and the negative sign guarantees the string is printed from left to right.

Most efficient conversion of ResultSet to JSON?

This answer may not be the most efficient, but it sure is dynamic. Pairing native JDBC with Google's Gson library, I easily can convert from an SQL result to a JSON stream.

I have included the converter, example DB properties file, SQL table generation, and a Gradle build file (with dependencies used).

QueryApp.java

import java.io.PrintWriter;

import com.oracle.jdbc.ResultSetConverter;

public class QueryApp {
    public static void main(String[] args) {
        PrintWriter writer = new PrintWriter(System.out);
        String dbProps = "/database.properties";
        String indent = "    ";

        writer.println("Basic SELECT:");
        ResultSetConverter.queryToJson(writer, dbProps, "SELECT * FROM Beatles", indent, false);

        writer.println("\n\nIntermediate SELECT:");
        ResultSetConverter.queryToJson(writer, dbProps, "SELECT first_name, last_name, getAge(date_of_birth) as age FROM Beatles", indent, true);
    }
}

ResultSetConverter.java

package com.oracle.jdbc;

import java.io.*;
import java.lang.reflect.Type;
import java.sql.*;
import java.util.*;

import com.google.common.reflect.TypeToken;
import com.google.gson.GsonBuilder;
import com.google.gson.stream.JsonWriter;

public class ResultSetConverter {
    public static final Type RESULT_TYPE = new TypeToken<List<Map<String, Object>>>() {
        private static final long serialVersionUID = -3467016635635320150L;
    }.getType();

    public static void queryToJson(Writer writer, String connectionProperties, String query, String indent, boolean closeWriter) {
        Connection conn = null;
        Statement stmt = null;
        GsonBuilder gson = new GsonBuilder();
        JsonWriter jsonWriter = new JsonWriter(writer);

        if (indent != null) jsonWriter.setIndent(indent);

        try {
            Properties props = readConnectionInfo(connectionProperties);
            Class.forName(props.getProperty("driver"));

            conn = openConnection(props);
            stmt = conn.createStatement();

            gson.create().toJson(QueryHelper.select(stmt, query), RESULT_TYPE, jsonWriter);

            if (closeWriter) jsonWriter.close();

            stmt.close();
            conn.close();
        } catch (SQLException se) {
            se.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
            try {
                if (stmt != null) stmt.close();
            } catch (SQLException se2) {
            }
            try {
                if (conn != null) conn.close();
            } catch (SQLException se) {
                se.printStackTrace();
            }
            try {
                if (closeWriter && jsonWriter != null) jsonWriter.close();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }

    private static Properties readConnectionInfo(String resource) throws IOException {
        Properties properties = new Properties();
        InputStream in = ResultSetConverter.class.getResourceAsStream(resource);
        properties.load(in);
        in.close();

        return properties;
    }

    private static Connection openConnection(Properties connectionProperties) throws IOException, SQLException {
        String database = connectionProperties.getProperty("database");
        String username = connectionProperties.getProperty("username");
        String password = connectionProperties.getProperty("password");

        return DriverManager.getConnection(database, username, password);
    }
}

QueryHelper.java

package com.oracle.jdbc;

import java.sql.*;
import java.text.*;
import java.util.*;

import com.google.common.base.CaseFormat;

public class QueryHelper {
    static DateFormat DATE_FORMAT = new SimpleDateFormat("YYYY-MM-dd");

    public static List<Map<String, Object>> select(Statement stmt, String query) throws SQLException {
        ResultSet resultSet = stmt.executeQuery(query);
        List<Map<String, Object>> records = mapRecords(resultSet);

        resultSet.close();

        return records;
    }

    public static List<Map<String, Object>> mapRecords(ResultSet resultSet) throws SQLException {
        List<Map<String, Object>> records = new ArrayList<Map<String, Object>>();
        ResultSetMetaData metaData = resultSet.getMetaData();

        while (resultSet.next()) {
            records.add(mapRecord(resultSet, metaData));
        }

        return records;
    }

    public static Map<String, Object> mapRecord(ResultSet resultSet, ResultSetMetaData metaData) throws SQLException {
        Map<String, Object> record = new HashMap<String, Object>();

        for (int c = 1; c <= metaData.getColumnCount(); c++) {
            String columnType = metaData.getColumnTypeName(c);
            String columnName = formatPropertyName(metaData.getColumnName(c));
            Object value = resultSet.getObject(c);

            if (columnType.equals("DATE")) {
                value = DATE_FORMAT.format(value);
            }

            record.put(columnName, value);
        }

        return record;
    }

    private static String formatPropertyName(String property) {
        return CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, property);
    }
}

database.properties

driver=com.mysql.jdbc.Driver
database=jdbc:mysql://localhost/JDBC_Tutorial
username=root
password=

JDBC_Tutorial.sql

-- phpMyAdmin SQL Dump
-- version 4.5.1
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: Jan 12, 2016 at 07:40 PM
-- Server version: 10.1.8-MariaDB
-- PHP Version: 5.6.14

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `jdbc_tutorial`
--
CREATE DATABASE IF NOT EXISTS `jdbc_tutorial` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;
USE `jdbc_tutorial`;

DELIMITER $$
--
-- Functions
--
DROP FUNCTION IF EXISTS `getAge`$$
CREATE DEFINER=`root`@`localhost` FUNCTION `getAge` (`in_dob` DATE) RETURNS INT(11) NO SQL
BEGIN
DECLARE l_age INT;
   IF DATE_FORMAT(NOW(),'00-%m-%d') >= DATE_FORMAT(in_dob,'00-%m-%d') THEN
      -- This person has had a birthday this year
      SET l_age=DATE_FORMAT(NOW(),'%Y')-DATE_FORMAT(in_dob,'%Y');
   ELSE
      -- Yet to have a birthday this year
      SET l_age=DATE_FORMAT(NOW(),'%Y')-DATE_FORMAT(in_dob,'%Y')-1;
   END IF;
      RETURN(l_age);
END$$

DELIMITER ;

-- --------------------------------------------------------

--
-- Table structure for table `beatles`
--

DROP TABLE IF EXISTS `beatles`;
CREATE TABLE IF NOT EXISTS `beatles` (
  `id` int(11) NOT NULL,
  `first_name` varchar(255) DEFAULT NULL,
  `last_name` varchar(255) DEFAULT NULL,
  `date_of_birth` date DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Truncate table before insert `beatles`
--

TRUNCATE TABLE `beatles`;
--
-- Dumping data for table `beatles`
--

INSERT INTO `beatles` (`id`, `first_name`, `last_name`, `date_of_birth`) VALUES(100, 'John', 'Lennon', '1940-10-09');
INSERT INTO `beatles` (`id`, `first_name`, `last_name`, `date_of_birth`) VALUES(101, 'Paul', 'McCartney', '1942-06-18');
INSERT INTO `beatles` (`id`, `first_name`, `last_name`, `date_of_birth`) VALUES(102, 'George', 'Harrison', '1943-02-25');
INSERT INTO `beatles` (`id`, `first_name`, `last_name`, `date_of_birth`) VALUES(103, 'Ringo', 'Starr', '1940-07-07');

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

build.gradle

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'application'

mainClassName = 'com.oracle.jdbc.QueryApp'

repositories {
    maven  {
        url "http://repo1.maven.org/maven2"
    }
}

jar {
    baseName = 'jdbc-tutorial'
    version =  '1.0.0'
}

sourceCompatibility = 1.7
targetCompatibility = 1.7

dependencies {
    compile 'mysql:mysql-connector-java:5.1.16'
    compile 'com.google.guava:guava:18.0'
    compile 'com.google.code.gson:gson:1.7.2'
}

task wrapper(type: Wrapper) {
    gradleVersion = '2.9'
}

Results

Basic SELECT

[
    {
        "firstName": "John",
        "lastName": "Lennon",
        "dateOfBirth": "1940-10-09",
        "id": 100
    },
    {
        "firstName": "Paul",
        "lastName": "McCartney",
        "dateOfBirth": "1942-06-18",
        "id": 101
    },
    {
        "firstName": "George",
        "lastName": "Harrison",
        "dateOfBirth": "1943-02-25",
        "id": 102
    },
    {
        "firstName": "Ringo",
        "lastName": "Starr",
        "dateOfBirth": "1940-07-07",
        "id": 103
    }
]

Intermediate SELECT

[
    {
        "firstName": "John",
        "lastName": "Lennon",
        "age": 75
    },
    {
        "firstName": "Paul",
        "lastName": "McCartney",
        "age": 73
    },
    {
        "firstName": "George",
        "lastName": "Harrison",
        "age": 72
    },
    {
        "firstName": "Ringo",
        "lastName": "Starr",
        "age": 75
    }
]

Python constructor and default value

I would try:

self.wordList = list(wordList)

to force it to make a copy instead of referencing the same object.

AngularJS access scope from outside js function

Another way to do that is:

var extScope;
var app = angular.module('myApp', []);
app.controller('myController',function($scope, $http){
    extScope = $scope;
})
//below you do what you want to do with $scope as extScope
extScope.$apply(function(){
    extScope.test = 'Hello world';
})

How to store JSON object in SQLite database

An alternative could be to use the new JSON extension for SQLite. I've only just come across this myself: https://www.sqlite.org/json1.html This would allow you to perform a certain level of querying the stored JSON. If you used VARCHAR or TEXT to store a JSON string you would have no ability to query it. This is a great article showing its usage (in python) http://charlesleifer.com/blog/using-the-sqlite-json1-and-fts5-extensions-with-python/

Copy mysql database from remote server to local computer

C:\Users\>mysqldump -u root -p -h ip address --databases database_name -r sql_file.sql
Enter password: your_password

Why my regexp for hyphenated words doesn't work?

You can use this:

r'[a-z]+(?:-[a-z]+)*' 

How do I use Safe Area Layout programmatically?

Swift 4.2 and 5.0. Suppose you wan to add Leading, Trailing, Top and Bottom constraints on viewBg. So, you can use the below code.

let guide = self.view.safeAreaLayoutGuide
viewBg.trailingAnchor.constraint(equalTo: guide.trailingAnchor).isActive = true
viewBg.leadingAnchor.constraint(equalTo: guide.leadingAnchor).isActive = true
viewBg.topAnchor.constraint(equalTo: guide.topAnchor).isActive = true
viewBg.bottomAnchor.constraint(equalTo: guide.bottomAnchor).isActive = true

Get random boolean in Java

Why not use the Random class, which has a method nextBoolean:

import java.util.Random;

/** Generate 10 random booleans. */
public final class MyProgram {

  public static final void main(String... args){

    Random randomGenerator = new Random();
    for (int idx = 1; idx <= 10; ++idx){
      boolean randomBool = randomGenerator.nextBoolean();
      System.out.println("Generated : " + randomBool);
    }
  }
}

Node.js: Gzip compression?

Use gzip compression

Gzip compressing can greatly decrease the size of the response body and hence increase the speed of a web app. Use the compression middleware for gzip compression in your Express app. For example:

var compression = require('compression');
var express = require('express')
var app = express()
app.use(compression())

Eliminate space before \begin{itemize}

Use \vspace{-\topsep} before \begin{itemize}.

Use \setlength{\parskip}{0pt} \setlength{\itemsep}{0pt plus 1pt} after \begin{itemize}.

And for the space after the list, use \vspace{-\topsep} after \end{itemize}.

\vspace{-\topsep}
\begin{itemize}
  \setlength{\parskip}{0pt}
  \setlength{\itemsep}{0pt plus 1pt}
  \item ...
  \item ...
\end{itemize}
\vspace{-\topsep}

How to format background color using twitter bootstrap?

Move your row before <div class="container marketing"> and wrap it with a new container, because current container width is 1170px (not 100%):

<div class='hero'>
  <div class="row">
   ...
  </div>
</div>

CSS:

.hero {
  background-color: #2ba6cb;
  padding: 0 90px;
}

PHP 7 simpleXML

For Alpine (in docker), you can use apk add php7-simplexml.

If that doesn't work for you, you can run apk add --no-cache php7-simplexml. This is in case you aren't updating the package index first.

How to dump a table to console?

--~ print a table
function printTable(list, i)

    local listString = ''
--~ begin of the list so write the {
    if not i then
        listString = listString .. '{'
    end

    i = i or 1
    local element = list[i]

--~ it may be the end of the list
    if not element then
        return listString .. '}'
    end
--~ if the element is a list too call it recursively
    if(type(element) == 'table') then
        listString = listString .. printTable(element)
    else
        listString = listString .. element
    end

    return listString .. ', ' .. printTable(list, i + 1)

end


local table = {1, 2, 3, 4, 5, {'a', 'b'}, {'G', 'F'}}
print(printTable(table))

Hi man, I wrote a siple code that do this in pure Lua, it has a bug (write a coma after the last element of the list) but how i wrote it quickly as a prototype I will let it to you adapt it to your needs.

Why isn't textarea an input[type="textarea"]?

So that its value can easily contain quotes and <> characters and respect whitespace and newlines.

The following HTML code successfully pass the w3c validator and displays <,> and & without the need to encode them. It also respects the white spaces.

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Yes I can</title>
</head>
<body>
    <textarea name="test">
        I can put < and > and & signs in 
        my textarea without any problems.
    </textarea>
</body>
</html>

onKeyPress Vs. onKeyUp and onKeyDown

Just wanted to share a curiosity:

when using the onkeydown event to activate a JS method, the charcode for that event is NOT the same as the one you get with onkeypress!

For instance the numpad keys will return the same charcodes as the number keys above the letter keys when using onkeypress, but NOT when using onkeydown !

Took me quite a few seconds to figure out why my script which checked for certain charcodes failed when using onkeydown!

Demo: https://www.w3schools.com/code/tryit.asp?filename=FMMBXKZLP1MK

and yes. I do know the definition of the methods are different.. but the thing that is very confusing is that in both methods the result of the event is retrieved using event.keyCode.. but they do not return the same value.. not a very declarative implementation.

Request string without GET arguments

Edit: @T.Todua provided a newer answer to this question using parse_url.

(please upvote that answer so it can be more visible).

Edit2: Someone has been spamming and editing about extracting scheme, so I've added that at the bottom.

parse_url solution

The simplest solution would be:

echo parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);

Parse_url is a built-in php function, who's sole purpose is to extract specific components from a url, including the PATH (everything before the first ?). As such, it is my new "best" solution to this problem.

strtok solution

Stackoverflow: How to remove the querystring and get only the url?

You can use strtok to get string before first occurence of ?

$url=strtok($_SERVER["REQUEST_URI"],'?');

Performance Note: This problem can also be solved using explode.

  • Explode tends to perform better for cases splitting the sring only on a single delimiter.
  • Strtok tends to perform better for cases utilizing multiple delimiters.

This application of strtok to return everything in a string before the first instance of a character will perform better than any other method in PHP, though WILL leave the querystring in memory.

An aside about Scheme (http/https) and $_SERVER vars

While OP did not ask about it, I suppose it is worth mentioning: parse_url should be used to extract any specific component from the url, please see the documentation for that function:

parse_url($actual_link, PHP_URL_SCHEME); 

Of note here, is that getting the full URL from a request is not a trivial task, and has many security implications. $_SERVER variables are your friend here, but they're a fickle friend, as apache/nginx configs, php environments, and even clients, can omit or alter these variables. All of this is well out of scope for this question, but it has been thoroughly discussed:

https://stackoverflow.com/a/6768831/1589379

It is important to note that these $_SERVER variables are populated at runtime, by whichever engine is doing the execution (/var/run/php/ or /etc/php/[version]/fpm/). These variables are passed from the OS, to the webserver (apache/nginx) to the php engine, and are modified and amended at each step. The only such variables that can be relied on are REQUEST_URI (because it's required by php), and those listed in RFC 3875 (see: PHP: $_SERVER ) because they are required of webservers.

please note: spaming links to your answers across other questions is not in good taste.

How to copy selected lines to clipboard in vim

First check if your vim installation has clipboard support.

vim --version

If clipboard support is installed you will see:

+clipboard
+X11
+xterm_clipboard

If clipboard support is not installed you will see:

-clipboard
-X11
-xterm_clipboard

To install clipboard support:

apt-get install vim-gnome

Once you have verified that clipboard support is installed do the following:

  1. Position your cursor to the first line you want to copy.
  2. Press Shiftv to enter visual mode.
  3. Press ? to select multiple lines
  4. Press "+y to copy the selected text to system clipboard.
  5. Now you can copy the selected text to browser, text editor etc.
  6. Press "+p if you want to copy system clipboard text to vim.

Above steps might get tedious if you have to repeatedly copy from vim to system clipboard and vice versa. You can create vim shortcuts so that when you press Ctrlc selected text will be copied to system clipboard. And when you press Ctrlp system clipboard text is copied to vim. To create shortcuts :

  1. Open .vimrc file and add following text at the end of file:

     nnoremap <C-c> "+y
     vnoremap <C-c> "+y
     nnoremap <C-p> "+p
     vnoremap <C-p> "+p
    
  2. Save and reload your .vimrc to apply the new changes.

  3. Position your cursor to the first line you want to copy.

  4. Press Shiftv to enter visual mode.

  5. Press ? to select multiple lines

  6. Press Ctrlc to copy the selected text to system clipboard.

  7. Now you can copy the selected text to browser, text editor etc.

  8. Press Ctrlp if you want to copy system clipboard text to vim.

Note: This is for ubuntu systems.

LINQ to SQL: Multiple joins ON multiple Columns. Is this possible?

Joining on multiple columns in Linq to SQL is a little different.

var query =
    from t1 in myTABLE1List // List<TABLE_1>
    join t2 in myTABLE1List
      on new { t1.ColumnA, t1.ColumnB } equals new { t2.ColumnA, t2.ColumnB }
    ...

You have to take advantage of anonymous types and compose a type for the multiple columns you wish to compare against.

This seems confusing at first but once you get acquainted with the way the SQL is composed from the expressions it will make a lot more sense, under the covers this will generate the type of join you are looking for.

EDIT Adding example for second join based on comment.

var query =
    from t1 in myTABLE1List // List<TABLE_1>
    join t2 in myTABLE1List
      on new { A = t1.ColumnA, B = t1.ColumnB } equals new { A = t2.ColumnA, B = t2.ColumnB }
    join t3 in myTABLE1List
      on new { A = t2.ColumnA, B =  t2.ColumnB } equals new { A = t3.ColumnA, B = t3.ColumnB }
    ...

jquery remove "selected" attribute of option?

Another alternative:

$('option:selected', $('#mySelectParent')).removeAttr("selected");

Hope it helps

Use -notlike to filter out multiple strings in PowerShell

Easiest way I find for multiple searches is to pipe them all (probably heavier CPU use) but for your example user:

Get-EventLog -LogName Security | where {$_.UserName -notlike "*user1"} |  where {$_.UserName -notlike "*user2"}

Create a basic matrix in C (input by user !)

How about the following?

First ask the user for the number of rows and columns, store that in say, nrows and ncols (i.e. scanf("%d", &nrows);) and then allocate memory for a 2D array of size nrows x ncols. Thus you can have a matrix of a size specified by the user, and not fixed at some dimension you've hardcoded!

Then store the elements with for(i = 0;i < nrows; ++i) ... and display the elements in the same way except you throw in newlines after every row, i.e.

for(i = 0; i < nrows; ++i)
{
   for(j = 0; j < ncols ; ++j) 
   {
      printf("%d\t",mat[i][j]);
   }
printf("\n");
}

Authenticating in PHP using LDAP through Active Directory

I like the Zend_Ldap Class, you can use only this class in your project, without the Zend Framework.

Python read-only property

Notice that instance methods are also attributes (of the class) and that you could set them at the class or instance level if you really wanted to be a badass. Or that you may set a class variable (which is also an attribute of the class), where handy readonly properties won't work neatly out of the box. What I'm trying to say is that the "readonly attribute" problem is in fact more general than it's usually perceived to be. Fortunately there are conventional expectations at work that are so strong as to blind us wrt these other cases (after all, almost everything is an attribute of some sort in python).

Building upon these expectations I think the most general and lightweight approach is to adopt the convention that "public" (no leading underscore) attributes are readonly except when explicitly documented as writeable. This subsumes the usual expectation that methods won't be patched and class variables indicating instance defaults are better let alone. If you feel really paranoid about some special attribute, use a readonly descriptor as a last resource measure.

Angular pass callback function to child component as @Input similar to AngularJS way

Use Observable pattern. You can put Observable value (not Subject) into Input parameter and manage it from parent component. You do not need callback function.

See example: https://stackoverflow.com/a/49662611/4604351

Non-static method requires a target

I face this error on testing WebAPI in Postman tool.

After building the code, If we remove any line (For Example: In my case when I remove one Commented line this error was occur...) in debugging mode then the "Non-static method requires a target" error will occur.

Again, I tried to send the same request. This time code working properly. And I get the response properly in Postman.

I hope it will use to someone...

Delete specific values from column with where condition?

UPDATE myTable 
   SET myColumn = NULL 
 WHERE myCondition

Get all parameters from JSP page

Even though this is an old question, I had to do something similar today but I prefer JSTL:

<c:forEach var="par" items="${paramValues}">
    <c:if test="${fn:startsWith(par.key, 'question')}"> 
${par.key} = ${par.value[0]}; //whatever
    </c:if>
</c:forEach>

Uses of content-disposition in an HTTP response header

Note that RFC 6266 supersedes the RFCs referenced below. Section 7 outlines some of the related security concerns.

The authority on the content-disposition header is RFC 1806 and RFC 2183. People have also devised content-disposition hacking. It is important to note that the content-disposition header is not part of the HTTP 1.1 standard.

The HTTP 1.1 Standard (RFC 2616) also mentions the possible security side effects of content disposition:

15.5 Content-Disposition Issues

RFC 1806 [35], from which the often implemented Content-Disposition
(see section 19.5.1) header in HTTP is derived, has a number of very
serious security considerations. Content-Disposition is not part of
the HTTP standard, but since it is widely implemented, we are
documenting its use and risks for implementors. See RFC 2183 [49]
(which updates RFC 1806) for details.

How to reset or change the passphrase for a GitHub SSH key?

In short there's no way to recover the passphrase for a pair of SSH keys. Why? Because it was intended this way in the first place for security reasons. The answers the other people gave you are all correct ways to CHANGE the password of your keys, not to recover them. So if you've forgotten your passphrase, the best you can do is create a new pair of SSH keys. Here's how to generate SSH keys and add it to your GitHub account.

Running AngularJS initialization code when view is loaded

I use the following template in my projects:

angular.module("AppName.moduleName", [])

/**
 * @ngdoc controller
 * @name  AppName.moduleName:ControllerNameController
 * @description Describe what the controller is responsible for.
 **/
    .controller("ControllerNameController", function (dependencies) {

        /* type */ $scope.modelName = null;
        /* type */ $scope.modelName.modelProperty1 = null;
        /* type */ $scope.modelName.modelPropertyX = null;

        /* type */ var privateVariable1 = null;
        /* type */ var privateVariableX = null;

        (function init() {
            // load data, init scope, etc.
        })();

        $scope.modelName.publicFunction1 = function () /* -> type  */ {
            // ...
        };

        $scope.modelName.publicFunctionX = function () /* -> type  */ {
            // ...
        };

        function privateFunction1() /* -> type  */ {
            // ...
        }

        function privateFunctionX() /* -> type  */ {
            // ...
        }

    });

Selecting a row of pandas series/dataframe by integer index

I would normally go for .loc/.iloc as suggested by Ted, but one may also select a row by tranposing the DataFrame. To stay in the example above, df.T[2] gives you row 2 of df.

What does "yield break;" do in C#?

It specifies that an iterator has come to an end. You can think of yield break as a return statement which does not return a value.

For example, if you define a function as an iterator, the body of the function may look like this:

for (int i = 0; i < 5; i++)
{
    yield return i;
}

Console.Out.WriteLine("You will see me");

Note that after the loop has completed all its cycles, the last line gets executed and you will see the message in your console app.

Or like this with yield break:

int i = 0;
while (true)
{
    if (i < 5)
    {
        yield return i;
    }
    else
    {
        // note that i++ will not be executed after this
        yield break;
    }
    i++;
}

Console.Out.WriteLine("Won't see me");

In this case the last statement is never executed because we left the function early.

How to install requests module in Python 3.4, instead of 2.7

i was facing same issue in beautiful soup , I solved this issue by this command , your issue will also get rectified . You are unable to install requests in python 3.4 because your python libraries are not updated . use this command apt-get install python3-requests Just run it will ask you to add 222 MB space in your hard disk , just press Y and wait for completing process, after ending up whole process . check your problem will be resolved.

Opacity of div's background without affecting contained element in IE 8?

Try setting the z-index higher on the contained element.

How to execute AngularJS controller function on page load?

On the one hand as @Mark-Rajcok said you can just get away with private inner function:

// at the bottom of your controller
var init = function () {
   // check if there is query in url
   // and fire search in case its value is not empty
};
// and fire it after definition
init();

Also you can take a look at ng-init directive. Implementation will be much like:

// register controller in html
<div data-ng-controller="myCtrl" data-ng-init="init()"></div>

// in controller
$scope.init = function () {
    // check if there is query in url
    // and fire search in case its value is not empty
};

But take care about it as angular documentation implies (since v1.2) to NOT use ng-init for that. However imo it depends on architecture of your app.

I used ng-init when I wanted to pass a value from back-end into angular app:

<div data-ng-controller="myCtrl" data-ng-init="init('%some_backend_value%')"></div>

How to Make A Chevron Arrow Using CSS?

Just use before and after Pseudo-elements - CSS

_x000D_
_x000D_
*{box-sizing: border-box; padding: 0; margin: 0}_x000D_
:root{background: white; transition: background .3s ease-in-out}_x000D_
:root:hover{background: red }_x000D_
div{_x000D_
  margin: 20px auto;_x000D_
  width: 150px;_x000D_
  height: 150px;_x000D_
  position:relative_x000D_
}_x000D_
_x000D_
div:before, div:after{_x000D_
  content: '';_x000D_
  position: absolute;_x000D_
  width: 75px;_x000D_
  height: 20px;_x000D_
  background: black;_x000D_
  left: 40px_x000D_
}_x000D_
_x000D_
div:before{_x000D_
  top: 45px;_x000D_
  transform: rotateZ(45deg)_x000D_
}_x000D_
_x000D_
div:after{_x000D_
  bottom: 45px;_x000D_
  transform: rotateZ(-45deg)_x000D_
}
_x000D_
<div/>
_x000D_
_x000D_
_x000D_

How can I write data attributes using Angular?

About access

<ol class="viewer-nav">
    <li *ngFor="let section of sections" 
        [attr.data-sectionvalue]="section.value"
        (click)="get_data($event)">
        {{ section.text }}
    </li>  
</ol>

And

get_data(event) {
   console.log(event.target.dataset.sectionvalue)
}

Bootstrap css hides portion of container below navbar navbar-fixed-top

It happens because with navbar-fixed-top class the navbar gets the position:fixed. This in turns take the navbar out of the document flow leaving the body to take up the space behind the navbar.

You need to apply padding-top or margin-top to your container, based on your requirements with values >= 50px. (or play around with different values)

The basic bootstrap navbar takes height around 40px. So if you give a padding-top or margin-top of 50px or more, you will always have that breathing space between your container and the navbar.

Transparent background in JPEG image

JPG does not support a transparent background, you can easily convert it to a PNG which does support a transparent background by opening it in near any photo editor and save it as a.PNG

How to install plugins to Sublime Text 2 editor?

The instruction has been tested on Mac OSx Catalina.

After installing Sublime Text 3, install Package Control through Tools > Package Control. Use the following instructions to install package or theme:

  1. press CMD + SHIFT + P

  2. choose Package Control: Install Package---or any other options you require. package control

  3. enter the name of required package or theme and press enter.

installing package

What is the difference between tree depth and height?

Simple Answer:
Depth:
1. Tree: Number of edges/arc from the root node to the leaf node of the tree is called as the Depth of the Tree.
2. Node: Number of edges/arc from the root node to that node is called as the Depth of that node.

Disable activity slide-in animation when launching new activity?

IMHO this answer here solve issue in the most elegant way..

Developer should create a style,

<style name="noAnimTheme" parent="android:Theme">
  <item name="android:windowAnimationStyle">@null</item>
</style>

then in manifest set it as theme for activity or whole application.

<activity android:name=".ui.ArticlesActivity" android:theme="@style/noAnimTheme">
</activity>

Voila! Nice and easy..

P.S. credits to original author please

Skipping Incompatible Libraries at compile

That message isn't actually an error - it's just a warning that the file in question isn't of the right architecture (e.g. 32-bit vs 64-bit, wrong CPU architecture). The linker will keep looking for a library of the right type.

Of course, if you're also getting an error along the lines of can't find lPI-Http then you have a problem :-)

It's hard to suggest what the exact remedy will be without knowing the details of your build system and makefiles, but here are a couple of shots in the dark:

  1. Just to check: usually you would add flags to CFLAGS rather than CTAGS - are you sure this is correct? (What you have may be correct - this will depend on your build system!)
  2. Often the flag needs to be passed to the linker too - so you may also need to modify LDFLAGS

If that doesn't help - can you post the full error output, plus the actual command (e.g. gcc foo.c -m32 -Dxxx etc) that was being executed?

What can MATLAB do that R cannot do?

With the sqldf package, R is capable of not only statistics, but serious data mining as well - assuming there is enough RAM on your machine.

And with the RServe package R becomes a regular TCP/IP server; so you can call R out of java (or any other language if you have the api). There is also a package in R to call java out or R.

How to add a TextView to a LinearLayout dynamically in Android?

Here is a more general answer for future viewers of this question. The layout we will make is below:

enter image description here

Method 1: Add TextView to existing LinearLayout

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

    LinearLayout linearLayout = (LinearLayout) findViewById(R.id.ll_example);

    // Add textview 1
    TextView textView1 = new TextView(this);
    textView1.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT));
    textView1.setText("programmatically created TextView1");
    textView1.setBackgroundColor(0xff66ff66); // hex color 0xAARRGGBB
    textView1.setPadding(20, 20, 20, 20);// in pixels (left, top, right, bottom)
    linearLayout.addView(textView1);

    // Add textview 2
    TextView textView2 = new TextView(this);
    LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT);
    layoutParams.gravity = Gravity.RIGHT;
    layoutParams.setMargins(10, 10, 10, 10); // (left, top, right, bottom)
    textView2.setLayoutParams(layoutParams);
    textView2.setText("programmatically created TextView2");
    textView2.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
    textView2.setBackgroundColor(0xffffdbdb); // hex color 0xAARRGGBB
    linearLayout.addView(textView2);
}

Note that for LayoutParams you must specify the kind of layout for the import, as in

import android.widget.LinearLayout.LayoutParams;

Otherwise you need to use LinearLayout.LayoutParams in the code.

Here is the xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ll_example"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ff99ccff"
    android:orientation="vertical" >

</LinearLayout>

Method 2: Create both LinearLayout and TextView programmatically

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // NOTE: setContentView is below, not here

    // Create new LinearLayout
    LinearLayout linearLayout = new LinearLayout(this);
    linearLayout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
            LayoutParams.MATCH_PARENT));
    linearLayout.setOrientation(LinearLayout.VERTICAL);
    linearLayout.setBackgroundColor(0xff99ccff);

    // Add textviews
    TextView textView1 = new TextView(this);
    textView1.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT));
    textView1.setText("programmatically created TextView1");
    textView1.setBackgroundColor(0xff66ff66); // hex color 0xAARRGGBB
    textView1.setPadding(20, 20, 20, 20); // in pixels (left, top, right, bottom)
    linearLayout.addView(textView1);

    TextView textView2 = new TextView(this);
    LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT);
    layoutParams.gravity = Gravity.RIGHT;
    layoutParams.setMargins(10, 10, 10, 10); // (left, top, right, bottom)
    textView2.setLayoutParams(layoutParams);
    textView2.setText("programmatically created TextView2");
    textView2.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
    textView2.setBackgroundColor(0xffffdbdb); // hex color 0xAARRGGBB
    linearLayout.addView(textView2);

    // Set context view
    setContentView(linearLayout);
}

Method 3: Programmatically add one xml layout to another xml layout

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

    LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(
            Context.LAYOUT_INFLATER_SERVICE);
    View view = inflater.inflate(R.layout.dynamic_linearlayout_item, null);
    FrameLayout container = (FrameLayout) findViewById(R.id.flContainer);
    container.addView(view);
}

Here is dynamic_linearlayout.xml:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/flContainer"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

</FrameLayout>

And here is the dynamic_linearlayout_item.xml to add:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ll_example"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ff99ccff"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#ff66ff66"
        android:padding="20px"
        android:text="programmatically created TextView1" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#ffffdbdb"
        android:layout_gravity="right"
        android:layout_margin="10px"
        android:textSize="18sp"
        android:text="programmatically created TextView2" />

</LinearLayout>

NSNotificationCenter addObserver in Swift

I'm able to do one of the following to successfully use a selector - without annotating anything with @objc:

NSNotificationCenter.defaultCenter().addObserver(self,
    selector:"batteryLevelChanged:" as Selector,
    name:"UIDeviceBatteryLevelDidChangeNotification",
    object:nil)    

OR

let notificationSelector: Selector = "batteryLevelChanged:"

NSNotificationCenter.defaultCenter().addObserver(self,
    selector: notificationSelector,
    name:"UIDeviceBatteryLevelDidChangeNotification",
    object:nil)    

My xcrun version shows Swift 1.2, and this works on Xcode 6.4 and Xcode 7 beta 2 (which I thought would be using Swift 2.0):

$xcrun swift --version

Apple Swift version 1.2 (swiftlang-602.0.53.1 clang-602.0.53)

What is the easiest way to remove all packages installed by pip?

On Windows if your path is configured correctly, you can use:

pip freeze > unins && pip uninstall -y -r unins && del unins

It should be a similar case for Unix-like systems:

pip freeze > unins && pip uninstall -y -r unins && rm unins

Just a warning that this isn't completely solid as you may run into issues such as 'File not found' but it may work in some cases nonetheless

EDIT: For clarity: unins is an arbitrary file which has data written out to it when this command executes: pip freeze > unins

That file that it written in turn is then used to uninstall the aforementioned packages with implied consent/prior approval via pip uninstall -y -r unins

The file is finally deleted upon completion.

How to tell whether a point is to the right or left side of a line

@AVB's answer in ruby

det = Matrix[
  [(x2 - x1), (x3 - x1)],
  [(y2 - y1), (y3 - y1)]
].determinant

If det is positive its above, if negative its below. If 0, its on the line.

CSS center display inline block?

You don't need to use "display: table". The reason your margin: 0 auto centering attempt doesn't work is because you didn't specify a width.

This will work just fine:

.wrap {
    background: #aaa;
    margin: 0 auto;
    width: some width in pixels since it's the container;
}

You don't need to specify display: block since that div will be block by default. You can also probably lose the overflow: hidden.

Convert String to Float in Swift

to convert string to Float in Xcode 11 as previous methods need modification

func stringToFloat(value : String) -> Float {
    let numberFormatter = NumberFormatter()
    let number = numberFormatter.number(from: value)
    let numberFloatValue = number?.floatValue
    return numberFloatValue!
}

How to set Spring profile from system variable?

SPRING_PROFILES_ACTIVE is the environment variable to override/pick Spring profile

Convert list to dictionary using linq and not worrying about duplicates

You can create an extension method similar to ToDictionary() with the difference being that it allows duplicates. Something like:

    public static Dictionary<TKey, TElement> SafeToDictionary<TSource, TKey, TElement>(
        this IEnumerable<TSource> source, 
        Func<TSource, TKey> keySelector, 
        Func<TSource, TElement> elementSelector, 
        IEqualityComparer<TKey> comparer = null)
    {
        var dictionary = new Dictionary<TKey, TElement>(comparer);

        if (source == null)
        {
            return dictionary;
        }

        foreach (TSource element in source)
        {
            dictionary[keySelector(element)] = elementSelector(element);
        }

        return dictionary; 
    }

In this case, if there are duplicates, then the last value wins.

How to convert all tables in database to one collation?

If you want a copy-paste bash script:

var=$(mysql -e 'SELECT CONCAT("ALTER TABLE ", TABLE_NAME," CONVERT TO CHARACTER SET utf8 COLLATE utf8_czech_ci;") AS execTabs FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA="zabbix" AND TABLE_TYPE="BASE TABLE"' -uroot -p )

var+='ALTER DATABASE zabbix CHARACTER SET utf8 COLLATE utf8_general_ci;'

echo $var | cut -d " " -f2- | mysql -uroot -p zabbix

Change zabbix to your database name.

Convert comma separated string to array in PL/SQL

Simple Code

    create or replace function get_token(text_is varchar2, token_in number, delim_is varchar2 := ';') return varchar2 is
       text_ls varchar2(2000);
       spos_ln number;
       epos    _ln number;
    begin
       text_ls := delim_is || text_is || rpad(delim_is, token_in, delim_is);
       spos_ln := instr(text_ls, delim_is, 1, token_in);
       epos_ln := instr(text_ls, delim_is, 1, token_in+1);
       return substr(text_ls, spos_ln+1, epos_ln-spos_ln-1);
    end get_token;

What is a segmentation fault?

According to Wikipedia:

A segmentation fault occurs when a program attempts to access a memory location that it is not allowed to access, or attempts to access a memory location in a way that is not allowed (for example, attempting to write to a read-only location, or to overwrite part of the operating system).

How to fix "Referenced assembly does not have a strong name" error?

For me my issue was that I had two of the same NuGet Packages installed with different Versions.

How to fix System.NullReferenceException: Object reference not set to an instance of an object

If the problem is 100% here

EffectSelectorForm effectSelectorForm = new EffectSelectorForm(Effects);

There's only one possible explanation: property/variable "Effects" is not initialized properly... Debug your code to see what you pass to your objects.

EDIT after several hours

There were some problems:

  • MEF attribute [Import] didn't work as expected, so we replaced it for the time being with a manually populated List<>. While the collection was null, it was causing exceptions later in the code, when the method tried to get the type of the selected item and there was none.

  • several event handlers weren't wired up to control events

Some problems are still present, but I believe OP's original problem has been fixed. Other problems are not related to this one.

Retina displays, high-res background images

Here's a solution that also includes High(er)DPI (MDPI) devices > ~160 dots per inch like quite a few non-iOS Devices (f.e.: Google Nexus 7 2012):

.box {
    background: url( 'img/box-bg.png' ) no-repeat top left;
    width: 200px;
    height: 200px;
}
@media only screen and ( -webkit-min-device-pixel-ratio: 1.3 ),
       only screen and (    min--moz-device-pixel-ratio: 1.3 ),
       only screen and (      -o-min-device-pixel-ratio: 2.6/2 ), /* returns 1.3, see Dev.Opera */
       only screen and (         min-device-pixel-ratio: 1.3 ),
       only screen and ( min-resolution: 124.8dpi ),
       only screen and ( min-resolution: 1.3dppx ) {

       .box {
           background: url( 'img/[email protected]' ) no-repeat top left / 200px 200px;
       }

}

As @3rror404 included in his edit after receiving feedback from the comments, there's a world beyond Webkit/iPhone. One thing that bugs me with most solutions around so far like the one referenced as source above at CSS-Tricks, is that this isn't taken fully into account.
The original source went already further.

As an example the Nexus 7 (2012) screen is a TVDPI screen with a weird device-pixel-ratio of 1.325. When loading the images with normal resolution they are upscaled via interpolation and therefore blurry. For me applying this rule in the media query to include those devices succeeded in best customer feedback.

Finding a substring within a list in Python

Use a simple for loop:

seq = ['abc123', 'def456', 'ghi789']
sub = 'abc'

for text in seq:
    if sub in text:
        print(text)

yields

abc123

Visual Studio keyboard shortcut to automatically add the needed 'using' statement

It's ctrl + . when, for example, you try to type List you need to type < at the end and press ctrl + . for it to work.

How to format a java.sql.Timestamp(yyyy-MM-dd HH:mm:ss.S) to a date(yyyy-MM-dd HH:mm:ss)

You do not need to use substring at all since your format doesn't hold that info.

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String fechaStr = "2013-10-10 10:49:29.10000";  
Date fechaNueva = format.parse(fechaStr);

System.out.println(format.format(fechaNueva)); // Prints 2013-10-10 10:49:29

Refresh or force redraw the fragment

This worked for me from within Fragment:

Fragment frg = null;
Class fragmentClass;
fragmentClass = MainFragment.class;

try {
    frg = (android.support.v4.app.Fragment)     
    fragmentClass.newInstance();
} catch(Exception ex) {
    ex.printStackTrace();
}

getFragmentManager()
    .beginTransaction()
    .replace(R.id.flContent, frg)
    .commit();

Spring MVC How take the parameter value of a GET HTTP Request in my controller method?

As explained in the documentation, by using an @RequestParam annotation:

public @ResponseBody String byParameter(@RequestParam("foo") String foo) {
    return "Mapped by path + method + presence of query parameter! (MappingController) - foo = "
           + foo;
}

How to get .app file of a xcode application

The application will appear in your projects Build directory. In the source pane on the left of the Xcode window you should see a section called 'Products'. Listed under there will be your application name. If you right-click on this you can select 'Reveal in Finder' to be taken to the application in the Finder. You can send this to your friend directly and he can just copy it into his Applications folder. Most applications do not require an installer package on Mac OS X.

Passing arguments to angularjs filters

From what I understand you can't pass an arguments to a filter function (when using the 'filter' filter). What you would have to do is to write a custom filter, sth like this:

.filter('weDontLike', function(){

return function(items, name){

    var arrayToReturn = [];        
    for (var i=0; i<items.length; i++){
        if (items[i].name != name) {
            arrayToReturn.push(items[i]);
        }
    }

    return arrayToReturn;
};

Here is the working jsFiddle: http://jsfiddle.net/pkozlowski_opensource/myr4a/1/

The other simple alternative, without writing custom filters is to store a name to filter out in a scope and then write:

$scope.weDontLike = function(item) {
  return item.name != $scope.name;
};

How to add a line to a multiline TextBox?

Try this

textBox1.Text += "SomeText\r\n" 

you can also try

textBox1.Text += "SomeText" + Environment.NewLine;

Where \r is carriage return and \n is new line

In a unix shell, how to get yesterday's date into a variable?

On Linux, you can use

date -d "-1 days" +"%a %d/%m/%Y"

error: command 'gcc' failed with exit status 1 while installing eventlet

Your install is failing because you don't have the python development headers installed. You can do this through apt on ubuntu/debian with:

sudo apt-get install python-dev 

for python3 use:

sudo apt-get install python3-dev

For eventlet you might also need the libevent libraries installed so if you get an error talking about that you can install libevent with:

sudo apt-get install libevent-dev

PHP: How can I determine if a variable has a value that is between two distinct constant values?

if (($value >= 1 && $value <= 10) || ($value >= 20 && $value <= 40)) {
   // A value between 1 to 10, or 20 to 40.
}

How do I compile a .cpp file on Linux?

Just type the code and save it in .cpp format. then try "gcc filename.cpp" . This will create the object file. then try "./a.out" (This is the default object file name). If you want to know about gcc you can always try "man gcc"

Can you call ko.applyBindings to bind a partial view?

While Niemeyer's answer is a more correct answer to the question, you could also do the following:

<div>
  <input data-bind="value: VMA.name" />
</div>

<div>
  <input data-bind="value: VMB.name" />
</div>

<script type="text/javascript">
  var viewModels = {
     VMA: {name: ko.observable("Bob")},
     VMB: {name: ko.observable("Ted")}
  };

  ko.applyBindings(viewModels);
</script>

This means you don't have to specify the DOM element, and you can even bind multiple models to the same element, like this:

<div>
  <input data-bind="value: VMA.name() + ' and ' + VMB.name()" />
</div>

Disable sorting on last column when using jQuery DataTables

Try to use minus sign for count from backside

<script>
    $(document).ready(function () {
        $('#example-2').DataTable({               
            'order':[],
            'columnDefs': [{
                "targets": [-1],
                "orderable": false
            }]
        });
    });
</script>

Git: Cannot see new remote branch

What ended up finally working for me was to add the remote repository name to the git fetch command, like this:

git fetch core

Now you can see all of them like this:

git branch --all

Sending images using Http Post

I usually do this in the thread handling the json response:

try {
  Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(imageUrl).getContent());
} catch (MalformedURLException e) {
  e.printStackTrace();
} catch (IOException e) {
  e.printStackTrace();
}

If you need to do transformations on the image, you'll want to create a Drawable instead of a Bitmap.

Shared folder between MacOSX and Windows on Virtual Box

You should map your virtual network drive in Windows.

  1. Open command prompt in Windows (VirtualBox)
  2. Execute: net use x: \\vboxsvr\<your_shared_folder_name>
  3. You should see new drive X: in My Computer

In your case execute net use x: \\vboxsvr\win7

Redirect form to different URL based on select option element

Just use a onchnage Event for select box.

<select id="selectbox" name="" onchange="javascript:location.href = this.value;">
    <option value="https://www.yahoo.com/" selected>Option1</option>
    <option value="https://www.google.co.in/">Option2</option>
    <option value="https://www.gmail.com/">Option3</option>

</select>

And if selected option to be loaded at the page load then add some javascript code

<script type="text/javascript">
    window.onload = function(){
        location.href=document.getElementById("selectbox").value;
    }       
</script>

for jQuery: Remove the onchange event from <select> tag

jQuery(function () {
    // remove the below comment in case you need chnage on document ready
    // location.href=jQuery("#selectbox").val(); 
    jQuery("#selectbox").change(function () {
        location.href = jQuery(this).val();
    })
})

Fastest way to get the first object from a queryset in django?

It can be like this

obj = model.objects.filter(id=emp_id)[0]

or

obj = model.objects.latest('id')

SQL Server FOR EACH Loop

[CREATE PROCEDURE [rat].[GetYear]

AS
BEGIN

-- variable for storing start date
Declare @StartYear as int
-- Variable for the End date 
Declare @EndYear as int 

-- Setting the value in strat Date
select @StartYear = Value from   rat.Configuration where Name = 'REPORT_START_YEAR'; 

-- Setting the End date 
select @EndYear = Value from   rat.Configuration where Name = 'REPORT_END_YEAR'; 


-- Creating Tem table 
    with [Years] as
    (
        --Selecting the Year
        select @StartYear [Year] 
        --doing Union 
        union all
         -- doing the loop in Years table 
         select Year+1 Year from [Years] where Year < @EndYear
     )
    --Selecting the Year table 
selec]

Bulk Record Update with SQL

Your way is correct, and here is another way you can do it:

update      Table1
set         Description = t2.Description
from        Table1 t1
inner join  Table2 t2
on          t1.DescriptionID = t2.ID

The nested select is the long way of just doing a join.

How can I echo a newline in a batch file?

why not use substring/replace space to echo;?

set "_line=hello world"
echo\%_line: =&echo;%
  • Results:
hello
world
  • Or, replace \n to echo;
set "_line=hello\nworld"
echo\%_line:\n=&echo;%

WPF: Create a dialog / prompt

I just add a static method to call it like a MessageBox:

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    x:Class="utils.PromptDialog"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    WindowStartupLocation="CenterScreen" 
    SizeToContent="WidthAndHeight"
    MinWidth="300"
    MinHeight="100"
    WindowStyle="SingleBorderWindow"
    ResizeMode="CanMinimize">
<StackPanel Margin="5">
    <TextBlock Name="txtQuestion" Margin="5"/>
    <TextBox Name="txtResponse" Margin="5"/>
    <PasswordBox Name="txtPasswordResponse" />
    <StackPanel Orientation="Horizontal" Margin="5" HorizontalAlignment="Right">
        <Button Content="_Ok" IsDefault="True" Margin="5" Name="btnOk" Click="btnOk_Click" />
        <Button Content="_Cancel" IsCancel="True" Margin="5" Name="btnCancel" Click="btnCancel_Click" />
    </StackPanel>
</StackPanel>
</Window>

And the code behind:

public partial class PromptDialog : Window
{
    public enum InputType
    {
        Text,
        Password
    }

    private InputType _inputType = InputType.Text;

    public PromptDialog(string question, string title, string defaultValue = "", InputType inputType = InputType.Text)
    {
        InitializeComponent();
        this.Loaded += new RoutedEventHandler(PromptDialog_Loaded);
        txtQuestion.Text = question;
        Title = title;
        txtResponse.Text = defaultValue;
        _inputType = inputType;
        if (_inputType == InputType.Password)
            txtResponse.Visibility = Visibility.Collapsed;
        else
            txtPasswordResponse.Visibility = Visibility.Collapsed;
    }

    void PromptDialog_Loaded(object sender, RoutedEventArgs e)
    {
        if (_inputType == InputType.Password)
            txtPasswordResponse.Focus();
        else
            txtResponse.Focus();
    }

    public static string Prompt(string question, string title, string defaultValue = "", InputType inputType = InputType.Text)
    {
        PromptDialog inst = new PromptDialog(question, title, defaultValue, inputType);
        inst.ShowDialog();
        if (inst.DialogResult == true)
            return inst.ResponseText;
        return null;
    }

    public string ResponseText
    {
        get
        {
            if (_inputType == InputType.Password)
                return txtPasswordResponse.Password;
            else
                return txtResponse.Text;
        }
    }

    private void btnOk_Click(object sender, RoutedEventArgs e)
    {
        DialogResult = true;
        Close();
    }

    private void btnCancel_Click(object sender, RoutedEventArgs e)
    {
        Close();
    }
}

So you can call it like:

string repeatPassword = PromptDialog.Prompt("Repeat password", "Password confirm", inputType: PromptDialog.InputType.Password);

How do I detect if Python is running as a 64-bit application?

While it may work on some platforms, be aware that platform.architecture is not always a reliable way to determine whether python is running in 32-bit or 64-bit. In particular, on some OS X multi-architecture builds, the same executable file may be capable of running in either mode, as the example below demonstrates. The quickest safe multi-platform approach is to test sys.maxsize on Python 2.6, 2.7, Python 3.x.

$ arch -i386 /usr/local/bin/python2.7
Python 2.7.9 (v2.7.9:648dcafa7e5f, Dec 10 2014, 10:10:46)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import platform, sys
>>> platform.architecture(), sys.maxsize
(('64bit', ''), 2147483647)
>>> ^D
$ arch -x86_64 /usr/local/bin/python2.7
Python 2.7.9 (v2.7.9:648dcafa7e5f, Dec 10 2014, 10:10:46)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import platform, sys
>>> platform.architecture(), sys.maxsize
(('64bit', ''), 9223372036854775807)

How can I delay a method call for 1 second?

You could also use a block

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
    [object method]; 
});

Most of time you will want to use dispatch_get_main_queue, although if there is no UI in the method you could use a global queue.

Edit:

Swift 3 version:

DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
    object.method()
}

Equally, DispatchQueue.global().asyncAfter(... might also be a good option.

How to download Google Play Services in an Android emulator?

To the latest setup and information if you have installed the Android Studio (i.e. 1.5) and trying to target SDK 4.0 then you may not be able to locate and setup the and AVD Emulator with SDK-vX.XX (with Google API's).

See following steps in order to download the required library and start with that. AVD Emulator setup -setting up Emulator for SDK4.0 with GoogleAPI so Map application can work- In Android Studio

But unfortunately above method did not work well on my side. And was not able to created Emulator with API Level 17 (SDK 4.2). So I followed this post that worked on my side well. The reason seems that the Android Studio Emulator creation window has limited options/features.

Google Play Services in emulator, implementing Google Plus login button etc

plot different color for different categorical levels using matplotlib

You can convert the categorical column into a numerical one by using the commands:

#we converting it into categorical data
cat_col = df['column_name'].astype('categorical') 

#we are getting codes for it 
cat_col = cat_col.cat.codes 

# we are using c parameter to change the color.
plt.scatter(df['column1'],df['column2'], c=cat_col) 

Process.start: how to get the output?

  1. It is possible to get the command line shell output of a process as described here : http://www.c-sharpcorner.com/UploadFile/edwinlima/SystemDiagnosticProcess12052005035444AM/SystemDiagnosticProcess.aspx

  2. This depends on mencoder. If it ouputs this status on the command line then yes :)

How to copy Docker images from one host to another without using a repository

First save the Docker image to a zip file:

docker save <docker image name> | gzip > <docker image name>.tar.gz

Then load the exported image to Docker using the below command:

zcat <docker image name>.tar.gz | docker load

How to sort an ArrayList in Java

Implement Comparable interface to Fruit.

public class Fruit implements Comparable<Fruit> {

It implements the method

@Override
    public int compareTo(Fruit fruit) {
        //write code here for compare name
    }

Then do call sort method

Collections.sort(fruitList);

How to allow only a number (digits and decimal point) to be typed in an input?

I wrote a working CodePen example to demonstrate a great way of filtering numeric user input. The directive currently only allows positive integers, but the regex can easily be updated to support any desired numeric format.

My directive is easy to use:

<input type="text" ng-model="employee.age" valid-number />

The directive is very easy to understand:

var app = angular.module('myApp', []);

app.controller('MainCtrl', function($scope) {
});

app.directive('validNumber', function() {
  return {
    require: '?ngModel',
    link: function(scope, element, attrs, ngModelCtrl) {
      if(!ngModelCtrl) {
        return; 
      }

      ngModelCtrl.$parsers.push(function(val) {
        if (angular.isUndefined(val)) {
            var val = '';
        }
        var clean = val.replace( /[^0-9]+/g, '');
        if (val !== clean) {
          ngModelCtrl.$setViewValue(clean);
          ngModelCtrl.$render();
        }
        return clean;
      });

      element.bind('keypress', function(event) {
        if(event.keyCode === 32) {
          event.preventDefault();
        }
      });
    }
  };
});

I want to emphasize that keeping model references out of the directive is important.

I hope you find this helpful.

Big thanks to Sean Christe and Chris Grimes for introducing me to the ngModelController

How to install cron

Cron is so named "deamon" (same as service under Win).

Most likely cron is already installed on your system (if it is a Linux/Unix system).

Look here: http://www.comptechdoc.org/os/linux/startupman/linux_sucron.html

or there http://en.wikipedia.org/wiki/Cron

for more details.

Error:(1, 0) Plugin with id 'com.android.application' not found

In my case, I download the project from GitHub and the Gradle file was missing. So I just create a new project with success build. Then copy-paste the Gradle missing file. And re-build the project is working for me.

enter image description here

Python Pandas iterate over rows and access column names

I also like itertuples()

for row in df.itertuples():
    print(row.A)
    print(row.Index)

since row is a named tuples, if you meant to access values on each row this should be MUCH faster

speed run :

df = pd.DataFrame([x for x in range(1000*1000)], columns=['A'])
st=time.time()
for index, row in df.iterrows():
    row.A
print(time.time()-st)
45.05799984931946

st=time.time()
for row in df.itertuples():
    row.A
print(time.time() - st)
0.48400020599365234

How to get a random number in Ruby

Simplest answer to the question:

rand(0..n)

Table with 100% width with equal size columns

table {
    width: 100%;

    th, td {
        width: 1%;
    }
}

SCSS syntax

JSON.Net Self referencing loop detected

The fix is to ignore loop references and not to serialize them. This behaviour is specified in JsonSerializerSettings.

Single JsonConvert with an overload:

JsonConvert.SerializeObject((from a in db.Events where a.Active select a).ToList(), Formatting.Indented,
    new JsonSerializerSettings() {
        ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
    }
);

If you'd like to make this the default behaviour, add a Global Setting with code in Application_Start() in Global.asax.cs:

JsonConvert.DefaultSettings = () => new JsonSerializerSettings {
     Formatting = Newtonsoft.Json.Formatting.Indented,
     ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
};

Reference: https://github.com/JamesNK/Newtonsoft.Json/issues/78

Can jQuery check whether input content has changed?

I had to use this kind of code for a scanner that pasted stuff into the field

$(document).ready(function() {
  var tId,oldVal;
  $("#fieldId").focus(function() {
     oldVal = $("#fieldId").val();
     tId=setInterval(function() { 
      var newVal = $("#fieldId").val(); 
      if (oldVal!=newVal) oldVal=newVal;
      someaction() },100);
  });
  $("#fieldId").blur(function(){ clearInterval(tId)});
});

Not tested...

What steps are needed to stream RTSP from FFmpeg?

FWIW, I was able to setup a local RTSP server for testing purposes using simple-rtsp-server and ffmpeg following these steps:

  1. Create a configuration file for the RTSP server called rtsp-simple-server.yml with this single line:
    protocols: [tcp]
    
  2. Start the RTSP server as a Docker container:
    $ docker run --rm -it -v $PWD/rtsp-simple-server.yml:/rtsp-simple-server.yml -p 8554:8554 aler9/rtsp-simple-server
    
  3. Use ffmpeg to stream a video file (looping forever) to the server:
    $ ffmpeg -re -stream_loop -1 -i test.mp4 -f rtsp -rtsp_transport tcp rtsp://localhost:8554/live.stream
    

Once you have that running you can use ffplay to view the stream:

$ ffplay -rtsp_transport tcp rtsp://localhost:8554/live.stream

Note that simple-rtsp-server can also handle UDP streams (i.s.o. TCP) but that's tricky running the server as a Docker container.

Bootstrap fixed header and footer with scrolling body-content area in fluid-container

Another option would be using flexbox.

While it's not supported by IE8 and IE9, you could consider:

  • Not minding about those old IE versions
  • Providing a fallback
  • Using a polyfill

Despite some additional browser-specific style prefixing would be necessary for full cross-browser support, you can see the basic usage either on this fiddle and on the following snippet:

_x000D_
_x000D_
html {_x000D_
  height: 100%;_x000D_
}_x000D_
html body {_x000D_
  height: 100%;_x000D_
  overflow: hidden;_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
}_x000D_
html body .container-fluid.body-content {_x000D_
  width: 100%;_x000D_
  overflow-y: auto;_x000D_
}_x000D_
header {_x000D_
    background-color: #4C4;_x000D_
    min-height: 50px;_x000D_
    width: 100%;_x000D_
}_x000D_
footer {_x000D_
    background-color: #4C4;_x000D_
    min-height: 30px;_x000D_
    width: 100%;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<header></header>_x000D_
<div class="container-fluid body-content">_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
</div>_x000D_
<footer></footer>
_x000D_
_x000D_
_x000D_

What is the difference between npm install and npm run build?

  • npm install installs the depedendencies in your package.json config.
  • npm run build runs the script "build" and created a script which runs your application - let's say server.js
  • npm start runs the "start" script which will then be "node server.js"

It's difficult to tell exactly what the issue was but basically if you look at your scripts configuration, I would guess that "build" uses some kind of build tool to create your application while "start" assumes the build has been done but then fails if the file is not there.

You are probably using bower or grunt - I seem to remember that a typical grunt application will have defined those scripts as well as a "clean" script to delete the last build.

Build tools tend to create a file in a bin/, dist/, or build/ folder which the start script then calls - e.g. "node build/server.js". When your npm start fails, it is probably because you called npm clean or similar to delete the latest build so your application file is not present causing npm start to fail.

npm build's source code - to touch on the discussion in this question - is in github for you to have a look at if you like. If you run npm build directly and you have a "build" script defined, it will exit with an error asking you to call your build script as npm run-script build so it's not the same as npm run script.

I'm not quite sure what npm build does, but it seems to be related to postinstall and packaging scripts in dependencies. I assume that this might be making sure that any CLI build scripts's or native libraries required by dependencies are built for the specific environment after downloading the package. This will be why link and install call this script.

Find what 2 numbers add to something and multiply to something

Come on guys, there is no need to loop, just use simple math to solve this equation system:

a*b = i;

a+b = j;

a = j/b;

a = i-b;

j/b = i-b; so:

b + j/b + i = 0

b^2 + i*b + j = 0

From here, its a quadratic equation, and it's trivial to find b (just implement the quadratic equation formula) and from there get the value for a.

EDIT:

There you go:

function finder($add,$product)
{

 $inside_root = $add*$add - 4*$product;

 if($inside_root >=0)
 {

     $b = ($add + sqrt($inside_root))/2;
     $a = $add - $b;

     echo "$a+$b = $add and $a*$b=$product\n";

 }else
 {
   echo "No real solution\n";
 }
}

Real live action:

http://codepad.org/JBxMgHBd

How can I use async/await at the top level?

i like this clever syntax to do async work from an entrypoint

void async function main() {
  await doSomeWork()
  await doMoreWork()
}()

Why is System.Web.Mvc not listed in Add References?

You can also add this from the Nuget Package Manager Console, something like:

Install-Package Microsoft.AspNet.Mvc -Version 4.0.20710.0 -ProjectName XXXXX

Microsoft.AspNet.Mvc has dependencies on:

  • 'Microsoft.AspNet.WebPages (= 2.0.20710.0 && < 2.1)'
  • 'Microsoft.Web.Infrastructure (= 1.0.0.0)'
  • 'Microsoft.AspNet.Razor (= 2.0.20710.0 && < 2.1)'

...which seems like no biggie to me. In our case, this is a class library that exists solely to provide support for our Mvc apps. So, we figure it's a benign dependency at worst.

I definitely prefer this to pointing to an assembly on the file system or in the GAC, since updating the package in the future will likely be a lot less painful than experiences I've had with the GAC and file system assembly references in the past.

Indexing vectors and arrays with +:

This is another way to specify the range of the bit-vector.

x +: N, The start position of the vector is given by x and you count up from x by N.

There is also

x -: N, in this case the start position is x and you count down from x by N.

N is a constant and x is an expression that can contain iterators.

It has a couple of benefits -

  1. It makes the code more readable.

  2. You can specify an iterator when referencing bit-slices without getting a "cannot have a non-constant value" error.

Reading NFC Tags with iPhone 6 / iOS 8

The ability to read an NFC tag has been added to iOS 11 which only support iPhone 7 and 7 plus

As a test drive I made this repo

First: We need to initiate NFCNDEFReaderSession class

var session: NFCNDEFReaderSession? 
session = NFCNDEFReaderSession(delegate: self, queue: nil, invalidateAfterFirstRead: false)

Then we need to start the session by:

session?.begin()

and when done:

session?.invalidate()

The delegate (which self should implement) has basically two functions:

func readerSession(_ session: NFCNDEFReaderSession, didDetectNDEFs messages: [NFCNDEFMessage])
func readerSession(_ session: NFCNDEFReaderSession, didInvalidateWithError error: Error)

here is my reference Apple docs

compare two files in UNIX

There are 3 basic commands to compare files in unix:

  1. cmp : This command is used to compare two files byte by byte and as any mismatch occurs,it echoes it on the screen.if no mismatch occurs i gives no response. syntax:$cmp file1 file2.

  2. comm : This command is used to find out the records available in one but not in another

  3. diff

Python: Generate random number between x and y which is a multiple of 5

The simplest way is to generate a random nuber between 0-1 then strech it by multiplying, and shifting it.
So yo would multiply by (x-y) so the result is in the range of 0 to x-y,
Then add x and you get the random number between x and y.

To get a five multiplier use rounding. If this is unclear let me know and I'll add code snippets.

CSS3 Transition - Fade out effect

You forgot to add a position property to the .dummy-wrap class, and the top/left/bottom/right values don't apply to statically positioned elements (the default)

http://jsfiddle.net/dYBD2/2/

How to change Angular CLI favicon

Navigating to the file finally fixed this for me. In my case: http://localhost:4200/favicon.ico

I had tried to refresh, stop and start ng serve again, and "Empty Cache and Hard Reload", none worked.

How to stop Python closing immediately when executed in Microsoft Windows

The reason why it is closing is because the program is not running anymore, simply add any sort of loop or input to fix this (or you could just run it through idle.)

Mixed mode assembly is built against version ‘v2.0.50727' of the runtime

I actually had this identical issue with the inverse solution. I had upgraded a .NET project to .NET 4.0 and then reverted back to .NET 3.5. The app.config in my project continued to have the following which was causing the above error in question:

<startup>
  <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>

The solution to solve the error for this was to revert it back to the proper 2.0 reference as follows:

<startup>
  <supportedRuntime version="v2.0.50727"/>
</startup>

So if a downgrade is producing the above error, you might need to back up the .NET Framework supported version.

How do I keep two side-by-side divs the same height?

I have tried almost all the mentioned methods above, but the flexbox solution won't work correctly with Safari, and the grid layout methods won't work correctly with older versions of IE.

This solution fits all screens and is cross-browser compatible:

.container {margin:15px auto;}
.container ul {margin:0 10px;}
.container li {width:30%; display: table-cell; background-color:#f6f7f7;box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.25);}

@media (max-width: 767px){
    .container li { display: inline-block; width:100%; min-height:auto!important;}
}

The above method will equal cells height, and for the smaller screens like mobile or tablet, we can use the @media method mentioned above.

How do I render a Word document (.doc, .docx) in the browser using JavaScript?

The answers by Brandon and fatbotdesigns are both correct, but having implemented the Google docs preview, we found multiple .docx files that couldn't be handled by Google. Switched to the MS Office Online preview and works likes a charm.

My recommendation would be to use the MS Office Preview URL over Google's.

https://view.officeapps.live.com/op/embed.aspx?src=http://remote.url.tld/path/to/document.doc'