Programs & Examples On #Urlscan

Why is it that "No HTTP resource was found that matches the request URI" here?

WebApiConfig.Register(GlobalConfiguration.Configuration); should be on top.

Dots in URL causes 404 with ASP.NET mvc and IIS

Super easy answer for those that only have this on one webpage. Edit your actionlink and a + "/" on the end of it.

  @Html.ActionLink("Edit", "Edit", new { id = item.name + "/" }) |

PHP compare time

To see of the curent time is greater or equal to 14:08:10 do this:

if (time() >= strtotime("14:08:10")) {
  echo "ok";
}

Depending on your input sources, make sure to account for timezone.

See PHP time() and PHP strtotime()

Removing all unused references from a project in Visual Studio projects

The following method does not depend on any 'add-on's and is not very painful.

Step through each of your source files and

  1. Select all (Ctrl-A)
  2. Toggle outline expansion (Ctrl-M, M). This will reduce the file to two lines.
  3. Click on the namespace's '+'. This will show each of the file's classes as a single line. Scan each class's reference count, looking for unreferenced classes.
  4. Click on each of the classes' '+'. This will show each of the class functions as a single line. Scan each function's reference count, looking for unreferenced functions.

Scanning each file looking for '0 reference' takes only a second.

Scanning an entire project takes only a couple of minutes.

How to find out if a file exists in C# / .NET?

Give full path as input. Avoid relative paths.

 return File.Exists(FinalPath);

CSS vertical alignment of inline/inline-block elements

Give vertical-align:top; in a & span. Like this:

a, span{
 vertical-align:top;
}

Check this http://jsfiddle.net/TFPx8/10/

onchange event on input type=range is not triggering in firefox while dragging

Yet another approach - just set a flag on an element signaling which type of event should be handled:

function setRangeValueChangeHandler(rangeElement, handler) {
    rangeElement.oninput = (event) => {
        handler(event);
        // Save flag that we are using onInput in current browser
        event.target.onInputHasBeenCalled = true;
    };

    rangeElement.onchange = (event) => {
        // Call only if we are not using onInput in current browser
        if (!event.target.onInputHasBeenCalled) {
            handler(event);
        }
    };
}

Adding padding to a tkinter widget only on one side

There are multiple ways of doing that you can use either place or grid or even the packmethod.

Sample code:

from tkinter import *
root = Tk()

l = Label(root, text="hello" )
l.pack(padx=6, pady=4) # where padx and pady represent the x and y axis respectively
# well you can also use side=LEFT inside the pack method of the label widget.

To place a widget to on basis of columns and rows , use the grid method:

but = Button(root, text="hello" )
but.grid(row=0, column=1)

Is it possible to refresh a single UITableViewCell in a UITableView?

reloadRowsAtIndexPaths: is fine, but still will force UITableViewDelegate methods to fire.

The simplest approach I can imagine is:

UITableViewCell* cell = [self.tableView cellForRowAtIndexPath:indexPath];
[self configureCell:cell forIndexPath:indexPath];

It's important to invoke your configureCell: implementation on main thread, as it wont work on non-UI thread (the same story with reloadData/reloadRowsAtIndexPaths:). Sometimes it might be helpful to add:

dispatch_async(dispatch_get_main_queue(), ^
{
    [self configureCell:cell forIndexPath:indexPath];
});

It's also worth to avoid work that would be done outside of the currently visible view:

BOOL cellIsVisible = [[self.tableView indexPathsForVisibleRows] indexOfObject:indexPath] != NSNotFound;
if (cellIsVisible)
{
    ....
}

How to create a file on Android Internal Storage?

You should use ContextWrapper like this:

ContextWrapper cw = new ContextWrapper(context);
File directory = cw.getDir("media", Context.MODE_PRIVATE);

As always, refer to documentation, ContextWrapper has a lot to offer.

How do you resize a form to fit its content automatically?

I User this Code in my project, Useful for me.

    private void Form1_Resize(object sender, EventArgs e)
    {
        int w = MainPanel.Width; // you can use form.width when you don't use panels

        w = (w - 120)/4; // 120 because set 15px for each side of panels
                         // and put panels in FlowLayoutPanel
                         // 4 because i have 4 panel boxes
        panel1.Width = w;
        panel2.Width = w;
        panel3.Width = w;
        panel4.Width = w;
    }

enter image description here

Remove all special characters, punctuation and spaces from string

#!/usr/bin/python
import re

strs = "how much for the maple syrup? $20.99? That's ricidulous!!!"
print strs
nstr = re.sub(r'[?|$|.|!]',r'',strs)
print nstr
nestr = re.sub(r'[^a-zA-Z0-9 ]',r'',nstr)
print nestr

you can add more special character and that will be replaced by '' means nothing i.e they will be removed.

How do you get the current text contents of a QComboBox?

You can convert the QString type to python string by just using the str function. Assuming you are not using any Unicode characters you can get a python string as below:

text = str(combobox1.currentText())

If you are using any unicode characters, you can do:

text = unicode(combobox1.currentText())

How to change package name in flutter?

Changing name manually doesn't seem to work, throws gradle errors, well in my case it does throw error.

So I usually create a new flutter project.

I use below mentioned command to create a new flutter app

flutter create --org com.yourdomain appname

your project will have the package name as -> com.yourdomain.appname


if you just want to keep your package name as com.appname then make some changes as below

flutter create --org com appname

to add java instead of kotlin for android add -a java

flutter create -a java --org com.yourdomain appname

EDIT


If you have already created a project you can use change_app_package_name package to change the package name.

flutter pub run change_app_package_name:main com.package.appname

HTTP status code for update and delete?

Here are some Tips:

DELETE

  • 200 (if you want send some additional data in the Response) or 204 (recommended).

  • 202 Operation deleted has not been committed yet.

  • If there's nothing to delete, use 204 or 404 (DELETE operation is idempotent, delete an already deleted item is operation successful, so you can return 204, but it's true that idempotent doesn't necessarily imply the same response)

Other errors:

  • 400 Bad Request (Malformed syntax or a bad query is strange but possible).
  • 401 Unauthorized Authentication failure
  • 403 Forbidden: Authorization failure or invalid Application ID.
  • 405 Not Allowed. Sure.
  • 409 Resource Conflict can be possible in complex systems.
  • And 501, 502 in case of errors.

PUT

If you're updating an element of a collection

  • 200/204 with the same reasons as DELETE above.
  • 202 if the operation has not been commited yet.

The referenced element doesn't exists:

  • PUT can be 201 (if you created the element because that is your behaviour)

  • 404 If you don't want to create elements via PUT.

  • 400 Bad Request (Malformed syntax or a bad query more common than in case of DELETE).

  • 401 Unauthorized

  • 403 Forbidden: Authentication failure or invalid Application ID.

  • 405 Not Allowed. Sure.

  • 409 Resource Conflict can be possible in complex systems, as in DELETE.

  • 422 Unprocessable entity It helps to distinguish between a "Bad request" (e.g. malformed XML/JSON) and invalid field values

  • And 501, 502 in case of errors.

How to disable PHP Error reporting in CodeIgniter?

Here is the typical structure of new Codeigniter project:

- application/
- system/
- user_guide/
- index.php <- this is the file you need to change

I usually use this code in my CI index.php. Just change local_server_name to the name of your local webserver.

With this code you can deploy your site to your production server without changing index.php each time.

// Domain-based environment
if ($_SERVER['SERVER_NAME'] == 'local_server_name') {
    define('ENVIRONMENT', 'development');
} else {
    define('ENVIRONMENT', 'production');
}

/*
 *---------------------------------------------------------------
 * ERROR REPORTING
 *---------------------------------------------------------------
 *
 * Different environments will require different levels of error reporting.
 * By default development will show errors but testing and live will hide them.
 */

if (defined('ENVIRONMENT')) {
    switch (ENVIRONMENT) {
        case 'development':
            error_reporting(E_ALL);
            break;
        case 'testing':
        case 'production':
            error_reporting(0);
            ini_set('display_errors', 0);  
            break;
        default:
            exit('The application environment is not set correctly.');
    }
}

How to Calculate Jump Target Address and Branch Target Address?

Usually you don't have to worry about calculating them as your assembler (or linker) will take of getting the calculations right. Let's say you have a small function:


func:
  slti $t0, $a0, 2
  beq $t0, $zero, cont
  ori $v0, $zero, 1
  jr $ra
cont:
  ...
  jal func
  ... 

When translating the above code into a binary stream of instructions the assembler (or linker if you first assembled into an object file) it will be determined where in memory the function will reside (let's ignore position independent code for now). Where in memory it will reside is usually specified in the ABI or given to you if you're using a simulator (like SPIM which loads the code at 0x400000 - note the link also contains a good explanation of the process).

Assuming we're talking about the SPIM case and our function is first in memory, the slti instruction will reside at 0x400000, the beq at 0x400004 and so on. Now we're almost there! For the beq instruction the branch target address is that of cont (0x400010) looking at a MIPS instruction reference we see that it is encoded as a 16-bit signed immediate relative to the next instruction (divided by 4 as all instructions must reside on a 4-byte aligned address anyway).

That is:

Current address of instruction + 4 = 0x400004 + 4 = 0x400008
Branch target = 0x400010
Difference = 0x400010 - 0x400008 = 0x8
To encode = Difference / 4 = 0x8 / 4 = 0x2 = 0b10

Encoding of beq $t0, $zero, cont

0001 00ss ssst tttt iiii iiii iiii iiii
---------------------------------------
0001 0001 0000 0000 0000 0000 0000 0010

As you can see you can branch to within -0x1fffc .. 0x20000 bytes. If for some reason, you need to jump further you can use a trampoline (an unconditional jump to the real target placed placed within the given limit).

Jump target addresses are, unlike branch target addresses, encoded using the absolute address (again divided by 4). Since the instruction encoding uses 6 bits for the opcode, this only leaves 26 bits for the address (effectively 28 given that the 2 last bits will be 0) therefore the 4 bits most significant bits of the PC register are used when forming the address (won't matter unless you intend to jump across 256 MB boundaries).

Returning to the above example the encoding for jal func is:

Destination address = absolute address of func = 0x400000
Divided by 4 = 0x400000 / 4 = 0x100000
Lower 26 bits = 0x100000 & 0x03ffffff = 0x100000 = 0b100000000000000000000

0000 11ii iiii iiii iiii iiii iiii iiii
---------------------------------------
0000 1100 0001 0000 0000 0000 0000 0000

You can quickly verify this, and play around with different instructions, using this online MIPS assembler i ran across (note it doesn't support all opcodes, for example slti, so I just changed that to slt here):

00400000: <func>    ; <input:0> func:
00400000: 0000002a  ; <input:1> slt $t0, $a0, 2
00400004: 11000002  ; <input:2> beq $t0, $zero, cont
00400008: 34020001  ; <input:3> ori $v0, $zero, 1
0040000c: 03e00008  ; <input:4> jr $ra
00400010: <cont>    ; <input:5> cont:
00400010: 0c100000  ; <input:7> jal func

Watching variables in SSIS during debug

Visual Studio 2013: Yes to both adding to the watch windows during debugging and dragging variables or typing them in without "user::". But before any of that would work I also needed to go to Tools > Options, then Debugging > General and had to scroll right down to the bottom of the right hand pane to be able to tick "Use Managed Compatibility Mode". Then I had to stop and restart debugging. Finally the above advice worked. Many thanks to the above and to this article: Visual Studio 2015 Debugging: Can't expand local variables?

When or Why to use a "SET DEFINE OFF" in Oracle Database

By default, SQL Plus treats '&' as a special character that begins a substitution string. This can cause problems when running scripts that happen to include '&' for other reasons:

SQL> insert into customers (customer_name) values ('Marks & Spencers Ltd');
Enter value for spencers: 
old   1: insert into customers (customer_name) values ('Marks & Spencers Ltd')
new   1: insert into customers (customer_name) values ('Marks  Ltd')

1 row created.

SQL> select customer_name from customers;

CUSTOMER_NAME
------------------------------
Marks  Ltd

If you know your script includes (or may include) data containing '&' characters, and you do not want the substitution behaviour as above, then use set define off to switch off the behaviour while running the script:

SQL> set define off
SQL> insert into customers (customer_name) values ('Marks & Spencers Ltd');

1 row created.

SQL> select customer_name from customers;

CUSTOMER_NAME
------------------------------
Marks & Spencers Ltd

You might want to add set define on at the end of the script to restore the default behaviour.

PHP, Get tomorrows date from date

By strange it can seem it works perfectly fine: date_create( '2016-02-01 + 1 day' );

echo date_create( $your_date . ' + 1 day' )->format( 'Y-m-d' );

Should do it

How to script FTP upload and download?

This script generates the command file then pipes the command file to the ftp program, creating a log along the way. Finally print the original bat file, the command files and the log of this session.

@echo on
@echo off > %0.ftp
::== GETmy!dir.bat
>> %0.ftp echo a00002t
>> %0.ftp echo iasdad$2
>> %0.ftp echo help
>> %0.ftp echo prompt
>> %0.ftp echo ascii
>> %0.ftp echo !dir REPORT.CP1C.ROLLEDUP.TXT
>> %0.ftp echo get REPORT.CP1C.ROLLEDUP.TXT
>> %0.ftp echo !dir REPORT.CP1C.ROLLEDUP.TXT
>> %0.ftp echo *************************************************   
>> %0.ftp echo !dir CONTENT.CP1C.ROLLEDUP.TXT
>> %0.ftp echo get CONTENT.CP1C.ROLLEDUP.TXT
>> %0.ftp echo !dir CONTENT.CP1C.ROLLEDUP.TXT
>> %0.ftp echo *************************************************   
>> %0.ftp echo !dir WORKLOAD.CP1c.ROLLEDUP.TXT
>> %0.ftp echo get WORKLOAD.CP1C.ROLLEDUP.TXT
>> %0.ftp echo !dir WORKLOAD.CP1C.ROLLEDUP.TXT
>> %0.ftp echo *************************************************   
>> %0.ftp echo !dir REPORT.TMMC.ROLLEDUP.TXT
>> %0.ftp echo get REPORT.TMMC.ROLLEDUP.TXT
>> %0.ftp echo !dir REPORT.TMMC.ROLLEDUP.TXT
>> %0.ftp echo *************************************************   
>> %0.ftp echo !dir CONTENT.TMMC.ROLLEDUP.TXT
>> %0.ftp echo get CONTENT.TMMC.ROLLEDUP.TXT
>> %0.ftp echo !dir CONTENT.TMMC.ROLLEDUP.TXT
>> %0.ftp echo **************************************************   
>> %0.ftp echo !dir WORKLOAD.TMMC.ROLLEDUP.TXT
>> %0.ftp echo get WORKLOAD.TMMC.ROLLEDUP.TXT
>> %0.ftp echo !dir WORKLOAD.TMMC.ROLLEDUP.TXT
>> %0.ftp echo quit
ftp -d -v -s:%0.ftp 150.45.12.18 > %0.log
type %0.bat 
type %0.ftp 
type %0.log 

HTML5 File API read as text and binary

Note in 2018: readAsBinaryString is outdated. For use cases where previously you'd have used it, these days you'd use readAsArrayBuffer (or in some cases, readAsDataURL) instead.


readAsBinaryString says that the data must be represented as a binary string, where:

...every byte is represented by an integer in the range [0..255].

JavaScript originally didn't have a "binary" type (until ECMAScript 5's WebGL support of Typed Array* (details below) -- it has been superseded by ECMAScript 2015's ArrayBuffer) and so they went with a String with the guarantee that no character stored in the String would be outside the range 0..255. (They could have gone with an array of Numbers instead, but they didn't; perhaps large Strings are more memory-efficient than large arrays of Numbers, since Numbers are floating-point.)

If you're reading a file that's mostly text in a western script (mostly English, for instance), then that string is going to look a lot like text. If you read a file with Unicode characters in it, you should notice a difference, since JavaScript strings are UTF-16** (details below) and so some characters will have values above 255, whereas a "binary string" according to the File API spec wouldn't have any values above 255 (you'd have two individual "characters" for the two bytes of the Unicode code point).

If you're reading a file that's not text at all (an image, perhaps), you'll probably still get a very similar result between readAsText and readAsBinaryString, but with readAsBinaryString you know that there won't be any attempt to interpret multi-byte sequences as characters. You don't know that if you use readAsText, because readAsText will use an encoding determination to try to figure out what the file's encoding is and then map it to JavaScript's UTF-16 strings.

You can see the effect if you create a file and store it in something other than ASCII or UTF-8. (In Windows you can do this via Notepad; the "Save As" as an encoding drop-down with "Unicode" on it, by which looking at the data they seem to mean UTF-16; I'm sure Mac OS and *nix editors have a similar feature.) Here's a page that dumps the result of reading a file both ways:

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Show File Data</title>
<style type='text/css'>
body {
    font-family: sans-serif;
}
</style>
<script type='text/javascript'>

    function loadFile() {
        var input, file, fr;

        if (typeof window.FileReader !== 'function') {
            bodyAppend("p", "The file API isn't supported on this browser yet.");
            return;
        }

        input = document.getElementById('fileinput');
        if (!input) {
            bodyAppend("p", "Um, couldn't find the fileinput element.");
        }
        else if (!input.files) {
            bodyAppend("p", "This browser doesn't seem to support the `files` property of file inputs.");
        }
        else if (!input.files[0]) {
            bodyAppend("p", "Please select a file before clicking 'Load'");
        }
        else {
            file = input.files[0];
            fr = new FileReader();
            fr.onload = receivedText;
            fr.readAsText(file);
        }

        function receivedText() {
            showResult(fr, "Text");

            fr = new FileReader();
            fr.onload = receivedBinary;
            fr.readAsBinaryString(file);
        }

        function receivedBinary() {
            showResult(fr, "Binary");
        }
    }

    function showResult(fr, label) {
        var markup, result, n, aByte, byteStr;

        markup = [];
        result = fr.result;
        for (n = 0; n < result.length; ++n) {
            aByte = result.charCodeAt(n);
            byteStr = aByte.toString(16);
            if (byteStr.length < 2) {
                byteStr = "0" + byteStr;
            }
            markup.push(byteStr);
        }
        bodyAppend("p", label + " (" + result.length + "):");
        bodyAppend("pre", markup.join(" "));
    }

    function bodyAppend(tagName, innerHTML) {
        var elm;

        elm = document.createElement(tagName);
        elm.innerHTML = innerHTML;
        document.body.appendChild(elm);
    }

</script>
</head>
<body>
<form action='#' onsubmit="return false;">
<input type='file' id='fileinput'>
<input type='button' id='btnLoad' value='Load' onclick='loadFile();'>
</form>
</body>
</html>

If I use that with a "Testing 1 2 3" file stored in UTF-16, here are the results I get:

Text (13):

54 65 73 74 69 6e 67 20 31 20 32 20 33

Binary (28):

ff fe 54 00 65 00 73 00 74 00 69 00 6e 00 67 00 20 00 31 00 20 00 32 00 20 00 33 00

As you can see, readAsText interpreted the characters and so I got 13 (the length of "Testing 1 2 3"), and readAsBinaryString didn't, and so I got 28 (the two-byte BOM plus two bytes for each character).


* XMLHttpRequest.response with responseType = "arraybuffer" is supported in HTML 5.

** "JavaScript strings are UTF-16" may seem like an odd statement; aren't they just Unicode? No, a JavaScript string is a series of UTF-16 code units; you see surrogate pairs as two individual JavaScript "characters" even though, in fact, the surrogate pair as a whole is just one character. See the link for details.

Manually install Gradle and use it in Android Studio

Follow these steps

  1. Download gradle
  2. Extract the file to a specific location you desire
  3. Open android studio Click on setting and on build, execution and deployment, then gradle
  4. Enable work offline and change service directory to the location of the extracted filed.

This is what worked for me. I hope it helps.

How to make java delay for a few seconds?

If you want to pause then use java.util.concurrent.TimeUnit:

TimeUnit.SECONDS.sleep(1);

To sleep for one second or for 10 minutes

TimeUnit.MINUTES.sleep(10);

Or Thread Sleep

try        
{
    Thread.sleep(1000);
} 
catch(InterruptedException ex) 
{
    Thread.currentThread().interrupt();
}

see also the official documentation

TimeUnit.SECONDS.sleep() will call Thread.sleep. The only difference is readability and using TimeUnit is probably easier to understand for non obvious durations.

but if you want to solve your issue

        int timeToWait = 10; //second
        System.out.print("Scanning")
        try {
            for (int i=0; i<timeToWait ; i++) {
                Thread.sleep(1000);
                System.out.print(".")
            }
        } catch (InterruptedException ie)
        {
            Thread.currentThread().interrupt();
        }

Make Https call using HttpClient

Add the below declarations to your class:

public const SslProtocols _Tls12 = (SslProtocols)0x00000C00;
public const SecurityProtocolType Tls12 = (SecurityProtocolType)_Tls12;

After:

var client = new HttpClient();

And:

ServicePointManager.SecurityProtocol = Tls12;
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 /*| SecurityProtocolType.Tls */| Tls12;

Happy? :)

In Bash, how do I add a string after each line in a file?

If your sed allows in place editing via the -i parameter:

sed -e 's/$/string after each line/' -i filename

If not, you have to make a temporary file:

typeset TMP_FILE=$( mktemp )

touch "${TMP_FILE}"
cp -p filename "${TMP_FILE}"
sed -e 's/$/string after each line/' "${TMP_FILE}" > filename

How can I use JavaScript in Java?

Rhino is what you are looking for.

Rhino is an open-source implementation of JavaScript written entirely in Java. It is typically embedded into Java applications to provide scripting to end users.

Update: Now Nashorn, which is more performant JavaScript Engine for Java, is available with jdk8.

Twitter bootstrap float div right

You can assign the class name like text-center, left or right. The text will align accordingly to these class name. You don't need to make extra class name separately. These classes are built in BootStrap 3 and bootstrap 4.

Bootstrap 3

v3 Text Alignment Docs

<p class="text-left">Left aligned text.</p>
<p class="text-center">Center aligned text.</p>
<p class="text-right">Right aligned text.</p>
<p class="text-justify">Justified text.</p>
<p class="text-nowrap">No wrap text.</p>

Bootstrap 4

v4 Text Alignment Docs

<p class="text-xs-left">Left aligned text on all viewport sizes.</p>
<p class="text-xs-center">Center aligned text on all viewport sizes.</p>
<p class="text-xs-right">Right aligned text on all viewport sizes.</p>

<p class="text-sm-left">Left aligned text on viewports sized SM (small) or wider.</p>
<p class="text-md-left">Left aligned text on viewports sized MD (medium) or wider.</p>
<p class="text-lg-left">Left aligned text on viewports sized LG (large) or wider.</p>
<p class="text-xl-left">Left aligned text on viewports sized XL (extra-large) or wider.</p>

What's the difference between window.location= and window.location.replace()?

window.location adds an item to your history in that you can (or should be able to) click "Back" and go back to the current page.

window.location.replace replaces the current history item so you can't go back to it.

See window.location:

assign(url): Load the document at the provided URL.

replace(url):Replace the current document with the one at the provided URL. The difference from the assign() method is that after using replace() the current page will not be saved in session history, meaning the user won't be able to use the Back button to navigate to it.

Oh and generally speaking:

window.location.href = url;

is favoured over:

window.location = url;

Adding Git-Bash to the new Windows Terminal

There are below things to do.

  1. Make sure your git command can be run successfully in CMD

That means you need to add git to path when install git or add it to system environment later.

enter image description here

  1. Update the config file profile.json

Open Settings, add following snippet inside the word profiles:

        { 
            "tabTitle": "Git Bash",
            "acrylicOpacity" : 0.75, 
            "closeOnExit" : true, 
            "colorScheme" : "Campbell", 
            "commandline" : "C:/Program Files/Git/bin/bash.exe --login", 
            "cursorColor" : "#FFFFFF", 
            "cursorShape" : "bar", 
            "fontFace" : "Consolas", 
            "fontSize" : 12, 
            "guid" : "{14ad203f-52cc-4110-90d6-d96e0f41b64d}", 
            "historySize" : 9001, 
            "icon": "ms-appdata:///roaming/git-bash_32px.ico",
            "name" : "Git Bash", 
            "padding" : "0, 0, 0, 0", 
            "snapOnInput" : true, 
            "useAcrylic" : true 
        }

The icon can be obtained here: git-bash_32px.ico

You can add icons for Tab to this location:

%LOCALAPPDATA%\packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\RoamingState

Put 32x32 PNG/icons in this folder, and then in profile.json you can reference the image resource with the path starting with ms-appdata:// .

Note that, please make sure the Guidis correct and it matches the corresponding correct configs.

  1. Test git bash works well in Windows Terminal

The final result is below: enter image description here

Selenium WebDriver.get(url) does not open the URL

A spent a lot of time on this issue and finally found that selenium 2.44 not working with node version 0.12. Use node version 0.10.38.

Hiding and Showing TabPages in tabControl

I have my sample code working but want to make it somewhat more better refrencing the tab from list:

Public Class Form1
    Dim State1 As Integer = 1
    Dim AllTabs As List(Of TabPage) = New List(Of TabPage)

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Check1(State1)
        State1 = CInt(IIf(State1 = 1, 0, 1))
    End Sub

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        AllTabs.Add(TabControl1.TabPages("TabPage1"))
        AllTabs.Add(TabControl1.TabPages("TabPage2"))
    End Sub

    Sub Check1(ByVal No As Integer)
        If TabControl1.TabPages.ContainsKey("TabPage1") Then
            TabControl1.TabPages.Remove(TabControl1.TabPages("TabPage1"))
        End If
        If TabControl1.TabPages.ContainsKey("TabPage2") Then
            TabControl1.TabPages.Remove(TabControl1.TabPages("TabPage2"))
        End If
        TabControl1.TabPages.Add(AllTabs(No))
    End Sub
End Class

Java: Find .txt files in specified folder

It's really useful, I used it with a slight change:

filename=directory.list(new FilenameFilter() { 
    public boolean accept(File dir, String filename) { 
        return filename.startsWith(ipro); 
    }
});

Spring: @Component versus @Bean

Both approaches aim to register target type in Spring container.

The difference is that @Bean is applicable to methods, whereas @Component is applicable to types.

Therefore when you use @Bean annotation you control instance creation logic in method's body (see example above). With @Component annotation you cannot.

Binding a Button's visibility to a bool value in ViewModel

Assuming AdvancedFormat is a bool, you need to declare and use a BooleanToVisibilityConverter:

<!-- In your resources section of the XAML -->
<BooleanToVisibilityConverter x:Key="BoolToVis" />

<!-- In your Button declaration -->
<Button
 Height="50" Width="50"
 Style="{StaticResource MyButtonStyle}"
 Command="{Binding SmallDisp}" CommandParameter="{Binding}" 
Cursor="Hand" Visibility="{Binding Path=AdvancedFormat, Converter={StaticResource BoolToVis}}"/>

Note the added Converter={StaticResource BoolToVis}.

This is a very common pattern when working with MVVM. In theory you could do the conversion yourself on the ViewModel property (i.e. just make the property itself of type Visibility) though I would prefer not to do that, since now you are messing with the separation of concerns. An item's visbility should really be up to the View.

How can I detect keydown or keypress event in angular.js?

Update:

ngKeypress, ngKeydown and ngKeyup are now part of AngularJS.

<!-- you can, for example, specify an expression to evaluate -->
<input ng-keypress="count = count + 1" ng-init="count=0">

<!-- or call a controller/directive method and pass $event as parameter.
     With access to $event you can now do stuff like 
     finding which key was pressed -->
<input ng-keypress="changed($event)">

Read more here:

https://docs.angularjs.org/api/ng/directive/ngKeypress https://docs.angularjs.org/api/ng/directive/ngKeydown https://docs.angularjs.org/api/ng/directive/ngKeyup

Earlier solutions:

Solution 1: Use ng-change with ng-model

<input type="text" placeholder="+639178983214" ng-model="mobileNumber" 
ng-controller="RegisterDataController" ng-change="keydown()">

JS:

function RegisterDataController($scope) {       
   $scope.keydown = function() {
        /* validate $scope.mobileNumber here*/
   };
}

Solution 2. Use $watch

<input type="text" placeholder="+639178983214" ng-model="mobileNumber" 
ng-controller="RegisterDataController">
    

JS:

$scope.$watch("mobileNumber", function(newValue, oldValue) {
    /* change noticed */
});

How can I convert integer into float in Java?

Here is how you can do it :

public static void main(String[] args) {
    // TODO Auto-generated method stub
    int x = 3;
    int y = 2;
    Float fX = new Float(x);
    float res = fX.floatValue()/y;
    System.out.println("res = "+res);
}

See you !

Centering a button vertically in table cell, using Twitter Bootstrap

Add vertical-align: middle; to the td element that contains the button

<td style="vertical-align:middle;">  <--add this to center vertically
  <a href="#" class="btn btn-primary">
    <i class="icon-check icon-white"></i>
  </a>
</td>

How to create a secure random AES key in Java?

Lots of good advince in the other posts. This is what I use:

Key key;
SecureRandom rand = new SecureRandom();
KeyGenerator generator = KeyGenerator.getInstance("AES");
generator.init(256, rand);
key = generator.generateKey();

If you need another randomness provider, which I sometime do for testing purposes, just replace rand with

MySecureRandom rand = new MySecureRandom();

Which language uses .pde extension?

Software application written with Arduino, an IDE used for prototyping electronics; contains source code written in the Arduino programming language; enables developers to control the electronics on an Arduino circuit board.

To avoid file association conflicts with the Processing software, Arduino changed the Sketch file extension to .INO with the version 1.0 release. Therefore, while Arduino can still open ".pde" files, the ".ino" file extension should be used instead.

Each PDE file is stored in its own folder when saved from the Processing IDE. It is saved with any other program assets, such as images. The project folder and PDE filename prefix have the same name. When the PDE file is run, it is opened in a Java display window, which renders and runs the resulting program.

Processing is commonly used in educational settings for teaching basic programming skills in a visual environment.

jQuery detect if textarea is empty

$.each(["input[type=text][value=]", "textarea[value=]"], function (index, element) {
              //only empty input and textarea will come here
});

Show/hide forms using buttons and JavaScript

There's the global attribute called hidden. But I'm green to all this and maybe there was a reason it wasn't mentioned yet?

_x000D_
_x000D_
var someCondition = true;_x000D_
_x000D_
if (someCondition == true){_x000D_
    document.getElementById('hidden div').hidden = false;_x000D_
}
_x000D_
<div id="hidden div" hidden>_x000D_
    stuff hidden by default_x000D_
</div>
_x000D_
_x000D_
_x000D_

https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/hidden

Check date with todays date

Does this help?

Calendar c = Calendar.getInstance();

// set the calendar to start of today
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);

// and get that as a Date
Date today = c.getTime();

// or as a timestamp in milliseconds
long todayInMillis = c.getTimeInMillis();

// user-specified date which you are testing
// let's say the components come from a form or something
int year = 2011;
int month = 5;
int dayOfMonth = 20;

// reuse the calendar to set user specified date
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
c.set(Calendar.DAY_OF_MONTH, dayOfMonth);

// and get that as a Date
Date dateSpecified = c.getTime();

// test your condition
if (dateSpecified.before(today)) {
  System.err.println("Date specified [" + dateSpecified + "] is before today [" + today + "]");
} else {
  System.err.println("Date specified [" + dateSpecified + "] is NOT before today [" + today + "]");
}

How to have image and text side by side

It's always worth grouping elements into sections that are relevant. In your case, a parent element that contains two columns;

  1. icon
  2. text.

http://jsfiddle.net/qMdfC/10/

HTML:

<div class='container2'>
    <img src='http://ecx.images-amazon.com/images/I/21-leKb-zsL._SL500_AA300_.png' class='iconDetails' />

    <div class="text">
        <h4>Facebook</h4>
        <p>
            fine location, GPS, coarse location
            <span>0 mins ago</span>
        </p>
    </div>
</div>

CSS:

* {
    padding:0;
    margin:0;
}
.iconDetails {
    margin:0 2%;
    float:left;
    height:40px;
    width:40px;
}
.container2 {
    width:100%;
    height:auto;
    padding:1%;
}
.text {
    float:left;
}
.text h4, .text p {
    width:100%;
    float:left;
    font-size:0.6em;
}
.text p span {
    color:#666;
}

Are there pointers in php?

entryId is an instance property of the current class ($this) And $entryId is a local variable

How do I capture all of my compiler's output to a file?

In a bourne shell:

make > my.log 2>&1

I.e. > redirects stdout, 2>&1 redirects stderr to the same place as stdout

How to enable C++11/C++0x support in Eclipse CDT?

I had a similar problem using Eclipse C++ 2019-03 for a mixed C and C++ project that used std::optional and std::swap. What worked for me was this.

In the project Properties->C/C++ Build->Settings->Tool Settings->Cross G++ Compiler, remove -std=gnu++17 from Miscellaneous and put it in Dialect->Other Dialect Flags instead.

Netbeans installation doesn't find JDK

This is only due to javahome path missing.

Use the command line below:--

For Windows OS- Open your command prompt

netbeans-6.5.1-windows.exe --javahome "C:\\Program Files\Java\jdk1.5.0"

For Linux OS- Open your Terminal

netbeans-6.5.1-windows.sh --javahome /usr/jdk/jdk1.6.0_04

The problem solved.

How can I style the border and title bar of a window in WPF?

You need to set

WindowStyle="None", AllowsTransparency="True" and optionally ResizeMode="NoResize"
and then set the Style property of the window to your custom window style, where you design the appearance of the window (title bar, buttons, border) to anything you want and display the window contents in a ContentPresenter.

This seems to be a good article on how you can achieve this, but there are many other articles on the internet.

Remove first Item of the array (like popping from stack)

const a = [1, 2, 3]; // -> [2, 3]

// Mutable solutions: update array 'a', 'c' will contain the removed item
const c = a.shift(); // prefered mutable way
const [c] = a.splice(0, 1);

// Immutable solutions: create new array 'b' and leave array 'a' untouched
const b = a.slice(1); // prefered immutable way
const b = a.filter((_, i) => i > 0);
const [c, ...b] = a; // c: the removed item

Node.js: Python not found exception due to node-sass and node-gyp

I had node 15.x.x , and "node-sass": "^4.11.0". I saw in the release notes from node-sass and saw the node higest version compatible with node-sass 4.11.0 was 11, so I uninstalled node and reinstall 11.15.0 version (I'm working with Windows). Check node-sass releases. (this is what you should see in the node-sass releases.)

Hope that helps and sorry for my english :)

Increment value in mysql update query

You can do this without having to query the actual amount of points, so it will save you some time and resources during the script execution.

mysql_query("UPDATE `member_profile` SET `points`= `points` + 1 WHERE `user_id` = '".intval($userid)."'");

Else, what you were doing wrong is that you passed the old amount of points as a string (points='5'+1), and you can't add a number to a string. ;)

java Arrays.sort 2d array

Welcome Java 8:

Arrays.sort(myArr, (a, b) -> Double.compare(a[0], b[0]));

How to convert upper case letters to lower case

str.lower() converts all cased characters to lowercase.

Swift - iOS - Dates and times in different format

I used the a similar approach as @iod07, but as an extension. Also, I added some explanations in the comments to understand how it works.

Basically, just add this at the top or bottom of your view controller.

extension NSString {

class func convertFormatOfDate(date: String, originalFormat: String, destinationFormat: String) -> String! {

    // Orginal format :
    let dateOriginalFormat = NSDateFormatter()
    dateOriginalFormat.dateFormat = originalFormat      // in the example it'll take "yy MM dd" (from our call)

    // Destination format :
    let dateDestinationFormat = NSDateFormatter()
    dateDestinationFormat.dateFormat = destinationFormat // in the example it'll take "EEEE dd MMMM yyyy" (from our call)

    // Convert current String Date to NSDate
    let dateFromString = dateOriginalFormat.dateFromString(date)

    // Convert new NSDate created above to String with the good format
    let dateFormated = dateDestinationFormat.stringFromDate(dateFromString!)

    return dateFormated

}
}

Example

Let's say you want to convert "16 05 05" to "Thursday 05 May 2016" and your date is declared as follow let date = "16 06 05"

Then simply call call it with :

let newDate = NSString.convertFormatOfDate(date, originalFormat: "yy MM dd", destinationFormat: "EEEE dd MMMM yyyy")

Hope it helps !

GitLab git user password

You may usually if you have multiple keys setup via ssh on your system (my device is running Windows 10), you will encounter this issue, the fix is to:

Precondition: Setup up your SSH Keys as indicated by GitLab

  1. open /c/Users//.ssh/config file with Notepad++ or your favourite editor
  2. paste the following inside it. Host IdentityFile ~/.ssh/

Please note, there is a space before the second line, very important to avoid this solution not working.

Convert array to JSON

because my array was like below: and I used .push function to create it dynamically

my_array = ["234", "23423"];

The only way I converted my array into json is

json = Object.assign({}, my_array);

How does Java handle integer underflows and overflows and how would you check for it?

static final int safeAdd(int left, int right)
                 throws ArithmeticException {
  if (right > 0 ? left > Integer.MAX_VALUE - right
                : left < Integer.MIN_VALUE - right) {
    throw new ArithmeticException("Integer overflow");
  }
  return left + right;
}

static final int safeSubtract(int left, int right)
                 throws ArithmeticException {
  if (right > 0 ? left < Integer.MIN_VALUE + right
                : left > Integer.MAX_VALUE + right) {
    throw new ArithmeticException("Integer overflow");
  }
  return left - right;
}

static final int safeMultiply(int left, int right)
                 throws ArithmeticException {
  if (right > 0 ? left > Integer.MAX_VALUE/right
                  || left < Integer.MIN_VALUE/right
                : (right < -1 ? left > Integer.MIN_VALUE/right
                                || left < Integer.MAX_VALUE/right
                              : right == -1
                                && left == Integer.MIN_VALUE) ) {
    throw new ArithmeticException("Integer overflow");
  }
  return left * right;
}

static final int safeDivide(int left, int right)
                 throws ArithmeticException {
  if ((left == Integer.MIN_VALUE) && (right == -1)) {
    throw new ArithmeticException("Integer overflow");
  }
  return left / right;
}

static final int safeNegate(int a) throws ArithmeticException {
  if (a == Integer.MIN_VALUE) {
    throw new ArithmeticException("Integer overflow");
  }
  return -a;
}
static final int safeAbs(int a) throws ArithmeticException {
  if (a == Integer.MIN_VALUE) {
    throw new ArithmeticException("Integer overflow");
  }
  return Math.abs(a);
}

Drawing Circle with OpenGL

Here is a code to draw a fill elipse, you can use the same method but replacing de xcenter and y center with radius

void drawFilledelipse(GLfloat x, GLfloat y, GLfloat xcenter,GLfloat ycenter) {
    int i;
    int triangleAmount = 20; //# of triangles used to draw circle

    //GLfloat radius = 0.8f; //radius
    GLfloat twicePi = 2.0f * PI;

    glBegin(GL_TRIANGLE_FAN);
    glVertex2f(x, y); // center of circle
    for (i = 0; i <= triangleAmount; i++) {
        glVertex2f(
            x + ((xcenter+1)* cos(i * twicePi / triangleAmount)),
            y + ((ycenter-1)* sin(i * twicePi / triangleAmount))
        );
    }
    glEnd();
}

How can I sort an ArrayList of Strings in Java?

You might sort the helper[] array directly:

java.util.Arrays.sort(helper, 1, helper.length);

Sorts the array from index 1 to the end. Leaves the first item at index 0 untouched.

See Arrays.sort(Object[] a, int fromIndex, int toIndex)

How to improve a case statement that uses two columns

Just change your syntax ever so slightly:

CASE WHEN STATE = 2 AND RetailerProcessType = 1 THEN '"AUTHORISED"'
     WHEN STATE = 1 AND RetailerProcessType = 2 THEN '"PENDING"'
     WHEN STATE = 2 AND RetailerProcessType = 2 THEN '"AUTHORISED"'
     ELSE '"DECLINED"'
END

If you don't put the field expression before the CASE statement, you can put pretty much any fields and comparisons in there that you want. It's a more flexible method but has slightly more verbose syntax.

Send File Attachment from Form Using phpMailer and PHP

This code help me in Attachment sending....

$mail->AddAttachment($_FILES['file']['tmp_name'], $_FILES['file']['name']);

Replace your AddAttachment(...) Code with above code

Warning: Failed propType: Invalid prop `component` supplied to `Route`

In my case i leave my .js file empty means i never write anything in my .js file after that i was using it in my route so make function component or class component and finally export it will work

Select the first row by group

(1) SQLite has a built in rowid pseudo-column so this works:

sqldf("select min(rowid) rowid, id, string 
               from test 
               group by id")

giving:

  rowid id string
1     1  1      A
2     3  2      B
3     5  3      C
4     7  4      D
5     9  5      E

(2) Also sqldf itself has a row.names= argument:

sqldf("select min(cast(row_names as real)) row_names, id, string 
              from test 
              group by id", row.names = TRUE)

giving:

  id string
1  1      A
3  2      B
5  3      C
7  4      D
9  5      E

(3) A third alternative which mixes the elements of the above two might be even better:

sqldf("select min(rowid) row_names, id, string 
               from test 
               group by id", row.names = TRUE)

giving:

  id string
1  1      A
3  2      B
5  3      C
7  4      D
9  5      E

Note that all three of these rely on a SQLite extension to SQL where the use of min or max is guaranteed to result in the other columns being chosen from the same row. (In other SQL-based databases that may not be guaranteed.)

pandas three-way joining multiple dataframes on columns

In python 3.6.3 with pandas 0.22.0 you can also use concat as long as you set as index the columns you want to use for the joining

pd.concat(
    (iDF.set_index('name') for iDF in [df1, df2, df3]),
    axis=1, join='inner'
).reset_index()

where df1, df2, and df3 are defined as in John Galt's answer

import pandas as pd
df1 = pd.DataFrame(np.array([
    ['a', 5, 9],
    ['b', 4, 61],
    ['c', 24, 9]]),
    columns=['name', 'attr11', 'attr12']
)
df2 = pd.DataFrame(np.array([
    ['a', 5, 19],
    ['b', 14, 16],
    ['c', 4, 9]]),
    columns=['name', 'attr21', 'attr22']
)
df3 = pd.DataFrame(np.array([
    ['a', 15, 49],
    ['b', 4, 36],
    ['c', 14, 9]]),
    columns=['name', 'attr31', 'attr32']
)

Read the current full URL with React?

To get the current router instance or current location you have to create a Higher order component with withRouter from react-router-dom. otherwise, when you are trying to access this.props.location it will return undefined

Example

import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';

class className extends Component {

      render(){
           return(
                ....
                  )
              }
}

export default withRouter(className)

How to change button background image on mouseOver?

In the case of winforms:

If you include the images to your resources you can do it like this, very simple and straight forward:

public Form1()
          {
               InitializeComponent();
               button1.MouseEnter += new EventHandler(button1_MouseEnter);
               button1.MouseLeave += new EventHandler(button1_MouseLeave);
          }

          void button1_MouseLeave(object sender, EventArgs e)
          {
               this.button1.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.img1));
          }


          void button1_MouseEnter(object sender, EventArgs e)
          {
               this.button1.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.img2));
          }

I would not recommend hardcoding image paths.

As you have altered your question ...

There is no (on)MouseOver in winforms afaik, there are MouseHover and MouseMove events, but if you change image on those, it will not change back, so the MouseEnter + MouseLeave are what you are looking for I think. Anyway, changing the image on Hover or Move :

in the constructor:
button1.MouseHover += new EventHandler(button1_MouseHover); 
button1.MouseMove += new MouseEventHandler(button1_MouseMove);

void button1_MouseMove(object sender, MouseEventArgs e)
          {
               this.button1.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.img2));
          }

          void button1_MouseHover(object sender, EventArgs e)
          {
               this.button1.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.img2));
          }

To add images to your resources: Projectproperties/resources/add/existing file

CORS with POSTMAN

CORS (Cross-Origin Resource Sharing) and SOP (Same-Origin Policy) are server-side configurations that clients decide to enforce or not.

Related to clients

  • Most Browsers do enforce it to prevent issues related to CSRF attack.
  • Most Development tools don't care about it.

tell pip to install the dependencies of packages listed in a requirement file

Any way to do this without manually re-installing the packages in a new virtualenv to get their dependencies ? This would be error-prone and I'd like to automate the process of cleaning the virtualenv from no-longer-needed old dependencies.

That's what pip-tools package is for (from https://github.com/jazzband/pip-tools):

Installation

$ pip install --upgrade pip  # pip-tools needs pip==6.1 or higher (!)
$ pip install pip-tools

Example usage for pip-compile

Suppose you have a Flask project, and want to pin it for production. Write the following line to a file:

# requirements.in
Flask

Now, run pip-compile requirements.in:

$ pip-compile requirements.in
#
# This file is autogenerated by pip-compile
# Make changes in requirements.in, then run this to update:
#
#    pip-compile requirements.in
#
flask==0.10.1
itsdangerous==0.24        # via flask
jinja2==2.7.3             # via flask
markupsafe==0.23          # via jinja2
werkzeug==0.10.4          # via flask

And it will produce your requirements.txt, with all the Flask dependencies (and all underlying dependencies) pinned. Put this file under version control as well and periodically re-run pip-compile to update the packages.

Example usage for pip-sync

Now that you have a requirements.txt, you can use pip-sync to update your virtual env to reflect exactly what's in there. Note: this will install/upgrade/uninstall everything necessary to match the requirements.txt contents.

$ pip-sync
Uninstalling flake8-2.4.1:
  Successfully uninstalled flake8-2.4.1
Collecting click==4.1
  Downloading click-4.1-py2.py3-none-any.whl (62kB)
    100% |¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 65kB 1.8MB/s
  Found existing installation: click 4.0
    Uninstalling click-4.0:
      Successfully uninstalled click-4.0
Successfully installed click-4.1

How to align footer (div) to the bottom of the page?

This will make the div fixed at the bottom of the page but in case the page is long it will only be visible when you scroll down.

<style type="text/css">
  #footer {
    position : absolute;
    bottom : 0;
    height : 40px;
    margin-top : 40px;
  }
</style>
<div id="footer">I am footer</div>

The height and margin-top should be the same so that the footer doesnt show over the content.

SQL Server - Convert date field to UTC

If they're all local to you, then here's the offset:

SELECT GETDATE() AS CurrentTime, GETUTCDATE() AS UTCTime

and you should be able to update all the data using:

UPDATE SomeTable
   SET DateTimeStamp = DATEADD(hh, DATEDIFF(hh, GETDATE(), GETUTCDATE()), DateTimeStamp)

Would that work, or am I missing another angle of this problem?

Getting All Variables In Scope

No. "In scope" variables are determined by the "scope chain", which is not accessible programmatically.

For detail (quite a lot of it), check out the ECMAScript (JavaScript) specification. Here's a link to the official page where you can download the canonical spec (a PDF), and here's one to the official, linkable HTML version.

Update based on your comment to Camsoft

The variables in scope for your event function are determined by where you define your event function, not how they call it. But, you may find useful information about what's available to your function via this and arguments by doing something along the lines of what KennyTM pointed out (for (var propName in ____)) since that will tell you what's available on various objects provided to you (this and arguments; if you're not sure what arguments they give you, you can find out via the arguments variable that's implicitly defined for every function).

So in addition to whatever's in-scope because of where you define your function, you can find out what else is available by other means by doing:

var n, arg, name;
alert("typeof this = " + typeof this);
for (name in this) {
    alert("this[" + name + "]=" + this[name]);
}
for (n = 0; n < arguments.length; ++n) {
    arg = arguments[n];
    alert("typeof arguments[" + n + "] = " + typeof arg);
    for (name in arg) {
        alert("arguments[" + n + "][" + name + "]=" + arg[name]);
    }
}

(You can expand on that to get more useful information.)

Instead of that, though, I'd probably use a debugger like Chrome's dev tools (even if you don't normally use Chrome for development) or Firebug (even if you don't normally use Firefox for development), or Dragonfly on Opera, or "F12 Developer Tools" on IE. And read through whatever JavaScript files they provide you. And beat them over the head for proper docs. :-)

Customizing the template within a Directive

The above answers unfortunately don't quite work. In particular, the compile stage does not have access to scope, so you can't customize the field based on dynamic attributes. Using the linking stage seems to offer the most flexibility (in terms of asynchronously creating dom, etc.) The below approach addresses that:

<!-- Usage: -->
<form>
  <form-field ng-model="formModel[field.attr]" field="field" ng-repeat="field in fields">
</form>
// directive
angular.module('app')
.directive('formField', function($compile, $parse) {
  return { 
    restrict: 'E', 
    compile: function(element, attrs) {
      var fieldGetter = $parse(attrs.field);

      return function (scope, element, attrs) {
        var template, field, id;
        field = fieldGetter(scope);
        template = '..your dom structure here...'
        element.replaceWith($compile(template)(scope));
      }
    }
  }
})

I've created a gist with more complete code and a writeup of the approach.

How to view table contents in Mysql Workbench GUI?

Open a connection to your server first (SQL IDE) from the home screen. Then use the context menu in the schema tree to run a query that simply selects rows from the selected table. The LIMIT attached to that is to avoid reading too many rows by accident. This limit can be switched off (or adjusted) in the preferences dialog.

enter image description here

This quick way to select rows is however not very flexible. Normally you would run a query (File / New Query Tab) in the editor with additional conditions, like a sort order:

enter image description here

scatter plot in matplotlib

Maybe something like this:

import matplotlib.pyplot
import pylab

x = [1,2,3,4]
y = [3,4,8,6]

matplotlib.pyplot.scatter(x,y)

matplotlib.pyplot.show()

EDIT:

Let me see if I understand you correctly now:

You have:

       test1 | test2 | test3
test3 |   1   |   0  |  1

test4 |   0   |   1  |  0

test5 |   1   |   1  |  0

Now you want to represent the above values in in a scatter plot, such that value of 1 is represented by a dot.

Let's say you results are stored in a 2-D list:

results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]

We want to transform them into two variables so we are able to plot them.

And I believe this code will give you what you are looking for:

import matplotlib
import pylab


results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]

x = []
y = []

for ind_1, sublist in enumerate(results):
    for ind_2, ele in enumerate(sublist):
        if ele == 1:
            x.append(ind_1)
            y.append(ind_2)       


matplotlib.pyplot.scatter(x,y)

matplotlib.pyplot.show()

Notice that I do need to import pylab, and you would have play around with the axis labels. Also this feels like a work around, and there might be (probably is) a direct method to do this.

How to read if a checkbox is checked in PHP?

$is_checked = isset($_POST['your_checkbox_name']) &&
              $_POST['your_checkbox_name'] == 'on';

Short circuit evaluation will take care so that you don't access your_checkbox_name when it was not submitted.

YouTube iframe embed - full screen

If I understand correctly you have an iframe that contains a second iframe (the youtube one).
Try adding the allowfullscreen attribute to the "parent" iframe.

For full browser support it should look like this:

<iframe src="your_page_url" 
        allowfullscreen="allowfullscreen"
        mozallowfullscreen="mozallowfullscreen" 
        msallowfullscreen="msallowfullscreen" 
        oallowfullscreen="oallowfullscreen" 
        webkitallowfullscreen="webkitallowfullscreen"> </iframe> 

Subtract two dates in SQL and get days of the result

SELECT (to_date('02-JAN-2013') - to_date('02-JAN-2012')) days_between
FROM dual
/

How do I make a simple crawler in PHP?

With some little changes to hobodave's code, here is a codesnippet you can use to crawl pages. This needs the curl extension to be enabled in your server.

<?php
//set_time_limit (0);
function crawl_page($url, $depth = 5){
$seen = array();
if(($depth == 0) or (in_array($url, $seen))){
    return;
}   
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
$result = curl_exec ($ch);
curl_close ($ch);
if( $result ){
    $stripped_file = strip_tags($result, "<a>");
    preg_match_all("/<a[\s]+[^>]*?href[\s]?=[\s\"\']+"."(.*?)[\"\']+.*?>"."([^<]+|.*?)?<\/a>/", $stripped_file, $matches, PREG_SET_ORDER ); 
    foreach($matches as $match){
        $href = $match[1];
            if (0 !== strpos($href, 'http')) {
                $path = '/' . ltrim($href, '/');
                if (extension_loaded('http')) {
                    $href = http_build_url($href , array('path' => $path));
                } else {
                    $parts = parse_url($href);
                    $href = $parts['scheme'] . '://';
                    if (isset($parts['user']) && isset($parts['pass'])) {
                        $href .= $parts['user'] . ':' . $parts['pass'] . '@';
                    }
                    $href .= $parts['host'];
                    if (isset($parts['port'])) {
                        $href .= ':' . $parts['port'];
                    }
                    $href .= $path;
                }
            }
            crawl_page($href, $depth - 1);
        }
}   
echo "Crawled {$href}";
}   
crawl_page("http://www.sitename.com/",3);
?>

I have explained this tutorial in this crawler script tutorial

Maven home (M2_HOME) not being picked up by IntelliJ IDEA

Another option is to add the M2_HOME variable at: IntelliJ IDEA=>Preferences=>IDE Settings=>Path Variables

After a restart of IntelliJ, IntelliJ IDEA=>Preferences=>Project Settings=>Maven=>Maven home directory should be set to your M2_HOME variable.

How to add directory to classpath in an application run profile in IntelliJ IDEA?

You can try -Xbootclasspath/a:path option of java application launcher. By description it specifies "a colon-separated path of directires, JAR archives, and ZIP archives to append to the default bootstrap class path."

How do I convert a org.w3c.dom.Document object to a String?

If you are ok to do transformation, you may try this.

DocumentBuilderFactory domFact = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = domFact.newDocumentBuilder();
Document doc = builder.parse(st);
DOMSource domSource = new DOMSource(doc);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(domSource, result);
System.out.println("XML IN String format is: \n" + writer.toString());

How do I link a JavaScript file to a HTML file?

You can add script tags in your HTML document, ideally inside the which points to your javascript files. Order of the script tags are important. Load the jQuery before your script files if you want to use jQuery from your script.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="relative/path/to/your/javascript.js"></script>

Then in your javascript file you can refer to jQuery either using $ sign or jQuery. Example:

jQuery.each(arr, function(i) { console.log(i); }); 

Return only string message from Spring MVC 3 Controller

@ResponseBody
@RequestMapping(value="/get-text", produces="text/plain")
public String myMethod() {
     return "Response!";
}
  • You see that @ResponseBody ?

It's telling that the method returns some text and not to interpret it as a view etc.

  • You see that produces="text/plain" ?

It's just a good practice as it tells what will be returned from the method :)

fatal error: mpi.h: No such file or directory #include <mpi.h>

On my system Ubuntu 16.04. I installed :

sudo apt install libopenmpi-dev

after I used mpiCC to compile and it works

How to make html <select> element look like "disabled", but pass values?

Add a class .disabled and use this CSS:

?.disabled {border: 1px solid #999; color: #333; opacity: 0.5;}
.disabled option {color: #000; opacity: 1;}?

Demo: http://jsfiddle.net/ZCSRq/

There has been an error processing your request, Error log record number

Clear your cache and your website will be work well.

'Java' is not recognized as an internal or external command

I had the same problem. Just Install the exact bit of java as of your computer. If your PC is 64 bit then install 64 bit java. If it is 32 bit then vice versa :)

You can't specify target table for update in FROM clause

Other workarounds include using SELECT DISTINCT or LIMIT in the subquery, although these are not as explicit in their effect on materialization. this worked for me

as mentioned in MySql Doc

Best way to convert string to bytes in Python 3?

Answer for a slightly different problem:

You have a sequence of raw unicode that was saved into a str variable:

s_str: str = "\x00\x01\x00\xc0\x01\x00\x00\x00\x04"

You need to be able to get the byte literal of that unicode (for struct.unpack(), etc.)

s_bytes: bytes = b'\x00\x01\x00\xc0\x01\x00\x00\x00\x04'

Solution:

s_new: bytes = bytes(s, encoding="raw_unicode_escape")

Reference (scroll up for standard encodings):

Python Specific Encodings

IOException: Too many open files

You can handle the fds yourself. The exec in java returns a Process object. Intermittently check if the process is still running. Once it has completed close the processes STDERR, STDIN, and STDOUT streams (e.g. proc.getErrorStream.close()). That will mitigate the leaks.

Which is fastest? SELECT SQL_CALC_FOUND_ROWS FROM `table`, or SELECT COUNT(*)

Removing some unnecessary SQL and then COUNT(*) will be faster than SQL_CALC_FOUND_ROWS. Example:

SELECT Person.Id, Person.Name, Job.Description, Card.Number
FROM Person
JOIN Job ON Job.Id = Person.Job_Id
LEFT JOIN Card ON Card.Person_Id = Person.Id
WHERE Job.Name = 'WEB Developer'
ORDER BY Person.Name

Then count without unnecessary part:

SELECT COUNT(*)
FROM Person
JOIN Job ON Job.Id = Person.Job_Id
WHERE Job.Name = 'WEB Developer'

Auto increment primary key in SQL Server Management Studio 2012

CREATE TABLE Persons (
    Personid int IDENTITY(1,1) PRIMARY KEY,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
    Age int
);

The MS SQL Server uses the IDENTITY keyword to perform an auto-increment feature.

In the example above, the starting value for IDENTITY is 1, and it will increment by 1 for each new record.

Tip: To specify that the "Personid" column should start at value 10 and increment by 5, change it to IDENTITY(10,5).

To insert a new record into the "Persons" table, we will NOT have to specify a value for the "Personid" column (a unique value will be added automatically):

Where can I set environment variables that crontab will use?

Setting vars in /etc/environment also worked for me in Ubuntu. As of 12.04, variables in /etc/environment are loaded for cron.

How to import existing Android project into Eclipse?

Updating @JamesWald's answer, and incorporating other comments. Assuming you want to create a cfesh copy from, say, a backup in your new workspace:

  1. Put the existing project in a directory not inside the destination workspace.
  2. In Eclipse: File->Import->Android->Existing Android Code into Workspace, Next
  3. Select root directory: /path/to/project/from/step/1
  4. Projects->Select All (or not, as the case may be)
  5. Make sure you set the new project name correctly - To change one click on the old project name (left column) and then click on the new project name (right column) and then edit. It will default to the class name of the Default Activity.
  6. Assuming you want a copy in the destination workspace, check "Copy projects into workspace"
  7. uncheck "Add project to working sets"
  8. Finish

TypeScript error TS1005: ';' expected (II)

Just try to without changing anything npm install [email protected] X.X.X is your current version

Safe String to BigDecimal conversion

Old topic but maybe the easiest is to use Apache commons NumberUtils which has a method createBigDecimal (String value)....

I guess (hope) it takes locales into account or else it would be rather useless.

SAP Crystal Reports runtime for .Net 4.0 (64-bit)

I have found a variety of runtimes including Visual Studio(VS) versions are available at http://scn.sap.com/docs/DOC-7824

How to select a directory and store the location using tkinter in Python

This code may be helpful for you.

from tkinter import filedialog
from tkinter import *
root = Tk()
root.withdraw()
folder_selected = filedialog.askdirectory()

How do I check in JavaScript if a value exists at a certain array index?

With Lodash, you can do:

if(_.has(req,'documents')){
      if (req.documents.length)
      _.forEach(req.documents, function(document){
        records.push(document);
      });
} else {
}

if(_.has(req,'documents')) is to check whether our request object has a property named documents and if it has that prop, the next if (req.documents.length) is to validate if it is not an empty array, so the other stuffs like forEach can be proceeded.

Name attribute in @Entity and @Table

@Entity(name = "someThing") => this name will be used to identify the domain ..this name will only be identified by hql queries ..ie ..name of the domain object

@Table(name = "someThing") => this name will be used to which table referred by domain object..ie ..name of the table

SQL Server 2008 - Login failed. The login is from an untrusted domain and cannot be used with Windows authentication

Just found this thread and posted an alternative answer (copied below) here: https://stackoverflow.com/a/37853766/1948625

Specifically on this question, if the dot "." used in the -S value of the command line means the same as 127.0.0.1, then it could be the same issue as the connection string of the other question. Use the hostname instead, or check your hosts file.


Old question, and my symptoms are slightly different, but same error. My connection string was correct (Integrated security, and I don't provide user and pwd) with data source set to 127.0.0.1. It worked fine for years.

But recently I added a line in the static host file for testing purposes (C:\Windows\System32\drivers\etc\hosts)

127.0.0.1           www.blablatestsite.com

Removing this line and the error is gone.

I got a clue from this article (https://support.microsoft.com/en-gb/kb/896861) which talks about hostnames and loopback.

Other possible fix (if you need to keep that line in the hosts file) is to use the hostname (like MYSERVER01) instead of 127.0.0.1 in the data source of the connection string.

MSVCP120d.dll missing

I had the same problem in Visual Studio Pro 2017: missing MSVCP120.dll file in Release mode and missing MSVCP120d.dll file in Debug mode. I installed Visual C++ Redistributable Packages for Visual Studio 2013 and Update for Visual C++ 2013 and Visual C++ Redistributable Package as suggested here Microsoft answer this fixed the release mode. For the debug mode what eventually worked was to copy msvcp120d.dll and msvcr120d.dll from a different computer (with Visual studio 2013) into C:\Windows\System32

What is an unhandled promise rejection?

Try not closing the connection before you send data to your database. Remove client.close(); from your code and it'll work fine.

link with target="_blank" does not open in new tab in Chrome

For Some reason it is not working so we can do this by another way

just remove the line and add this :-

<a onclick="window.open ('http://www.foracure.org.au', ''); return false" href="javascript:void(0);"></a>

Good luck.

Visual studio code terminal, how to run a command with administrator rights?

Option 1 - Easier & Persistent

Running Visual Studio Code as Administrator should do the trick.

If you're on Windows you can:

  1. Right click the shortcut or app/exe
  2. Go to properties
  3. Compatibility tab
  4. Check "Run this program as an administrator"
There is a caveat to it though

Make sure you have all other instances of VS Code closed and then try to run as Administrator. The electron framework likes to stall processes when closing them so it's best to check your task manager and kill the remaining processes.

Related Changes in Codebase

Option 2 - More like Sudo

If for some weird reason this is not running your commands as an Administrator you can try the runas command. Microsoft: runas command

Examples
  • runas /user:Administrator myCommand
  • runas "/user:First Last" "my command"
Notes
  • Just don't forget to put double quotes around anything that has a space in it.
  • Also it's quite possible that you have never set the password on the Administrator account, as it will ask you for the password when trying to run the command. You can always use an account without the username of Administrator if it has administrator access rights/permissions.

How to clone ArrayList and also clone its contents?

The other posters are correct: you need to iterate the list and copy into a new list.

However... If the objects in the list are immutable - you don't need to clone them. If your object has a complex object graph - they will need to be immutable as well.

The other benefit of immutability is that they are threadsafe as well.

How do you run a Python script as a service in Windows?

Yes you can. I do it using the pythoncom libraries that come included with ActivePython or can be installed with pywin32 (Python for Windows extensions).

This is a basic skeleton for a simple service:

import win32serviceutil
import win32service
import win32event
import servicemanager
import socket


class AppServerSvc (win32serviceutil.ServiceFramework):
    _svc_name_ = "TestService"
    _svc_display_name_ = "Test Service"

    def __init__(self,args):
        win32serviceutil.ServiceFramework.__init__(self,args)
        self.hWaitStop = win32event.CreateEvent(None,0,0,None)
        socket.setdefaulttimeout(60)

    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.hWaitStop)

    def SvcDoRun(self):
        servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
                              servicemanager.PYS_SERVICE_STARTED,
                              (self._svc_name_,''))
        self.main()

    def main(self):
        pass

if __name__ == '__main__':
    win32serviceutil.HandleCommandLine(AppServerSvc)

Your code would go in the main() method—usually with some kind of infinite loop that might be interrupted by checking a flag, which you set in the SvcStop method

How to split a list by comma not space

Read: http://linuxmanpages.com/man1/sh.1.php & http://www.gnu.org/s/hello/manual/autoconf/Special-Shell-Variables.html

IFS The Internal Field Separator that is used for word splitting after expansion and to split lines into words with the read builtin command. The default value is ``''.

IFS is a shell environment variable so it will remain unchanged within the context of your Shell script but not otherwise, unless you EXPORT it. ALSO BE AWARE, that IFS will not likely be inherited from your Environment at all: see this gnu post for the reasons and more info on IFS.

You're code written like this:

IFS=","
for word in $(cat tmptest | sed -n 1'p' | tr ',' '\n'); do echo $word; done;

should work, I tested it on command line.

sh-3.2#IFS=","
sh-3.2#for word in $(cat tmptest | sed -n 1'p' | tr ',' '\n'); do echo $word; done;
World
Questions
Answers
bash shell
script

Regular expression \p{L} and \p{N}

\p{L} matches a single code point in the category "letter".
\p{N} matches any kind of numeric character in any script.

Source: regular-expressions.info

If you're going to work with regular expressions a lot, I'd suggest bookmarking that site, it's very useful.

How do I schedule a task to run at periodic intervals?

Advantage of ScheduledExecutorService over Timer

I wish to offer you an alternative to Timer using - ScheduledThreadPoolExecutor, an implementation of the ScheduledExecutorService interface. It has some advantages over the Timer class, according to "Java in Concurrency":

A Timer creates only a single thread for executing timer tasks. If a timer task takes too long to run, the timing accuracy of other TimerTask can suffer. If a recurring TimerTask is scheduled to run every 10 ms and another Timer-Task takes 40 ms to run, the recurring task either (depending on whether it was scheduled at fixed rate or fixed delay) gets called four times in rapid succession after the long-running task completes, or "misses" four invocations completely. Scheduled thread pools address this limitation by letting you provide multiple threads for executing deferred and periodic tasks.

Another problem with Timer is that it behaves poorly if a TimerTask throws an unchecked exception. Also, called "thread leakage"

The Timer thread doesn't catch the exception, so an unchecked exception thrown from a TimerTask terminates the timer thread. Timer also doesn't resurrect the thread in this situation; instead, it erroneously assumes the entire Timer was cancelled. In this case, TimerTasks that are already scheduled but not yet executed are never run, and new tasks cannot be scheduled.

And another recommendation if you need to build your own scheduling service, you may still be able to take advantage of the library by using a DelayQueue, a BlockingQueue implementation that provides the scheduling functionality of ScheduledThreadPoolExecutor. A DelayQueue manages a collection of Delayed objects. A Delayed has a delay time associated with it: DelayQueue lets you take an element only if its delay has expired. Objects are returned from a DelayQueue ordered by the time associated with their delay.

Something better than .NET Reflector?

9Rays used to have a decompiler, but I haven't checked in a while. It was not free, I remember...

There is also a new one (at least for me) named Dis#.

The name 'ViewBag' does not exist in the current context

I had a ./Views/Web.Config file but this error happened after publishing the site. Turns out the build action property on the file was set to None instead of Content. Changing this to Content allowed publishing to work correctly.

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

I think the solution is to combine techniques from video encoding, namely the discrete cosine transformation. In digital video, rather recording the changing the brightness or colour of video as regular values such as 110 112 115 116, each is subtracted from the last (similar to run length encoding). 110 112 115 116 becomes 110 2 3 1. The values, 2 3 1 require less bits than the originals.

So lets say we create a list of the input values as they arrive on the socket. We are storing in each element, not the value, but the offset of the one before it. We sort as we go, so the offsets are only going to be positive. But the offset could be 8 decimal digits wide which this fits in 3 bytes. Each element can't be 3 bytes, so we need to pack these. We could use the top bit of each byte as a "continue bit", indicating that the next byte is part of the number and the lower 7 bits of each byte need to be combined. zero is valid for duplicates.

As the list fills up, the numbers should be get closer together, meaning on average only 1 byte is used to determine the distance to the next value. 7 bits of value and 1 bit of offset if convenient, but there may be a sweet spot that requires less than 8 bits for a "continue" value.

Anyway, I did some experiment. I use a random number generator and I can fit a million sorted 8 digit decimal numbers into about 1279000 bytes. The average space between each number is consistently 99...

public class Test {
    public static void main(String[] args) throws IOException {
        // 1 million values
        int[] values = new int[1000000];

        // create random values up to 8 digits lrong
        Random random = new Random();
        for (int x=0;x<values.length;x++) {
            values[x] = random.nextInt(100000000);
        }
        Arrays.sort(values);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        int av = 0;    
        writeCompact(baos, values[0]);     // first value
        for (int x=1;x<values.length;x++) {
            int v = values[x] - values[x-1];  // difference
            av += v;
            System.out.println(values[x] + " diff " + v);
            writeCompact(baos, v);
        }

        System.out.println("Average offset " + (av/values.length));
        System.out.println("Fits in " + baos.toByteArray().length);
    }

    public static void writeCompact(OutputStream os, long value) throws IOException {
        do {
            int b = (int) value & 0x7f;
            value = (value & 0x7fffffffffffffffl) >> 7;
            os.write(value == 0 ? b : (b | 0x80));
        } while (value != 0);
    }
}

How can I disable an <option> in a <select> based on its value in JavaScript?

For some reason other answers are unnecessarily complex, it's easy to do it in one line in pure JavaScript:

Array.prototype.find.call(selectElement.options, o => o.value === optionValue).disabled = true;

or

selectElement.querySelector('option[value="'+optionValue.replace(/["\\]/g, '\\$&')+'"]').disabled = true;

The performance depends on the number of the options (the more the options, the slower the first one) and whether you can omit the escaping (the replace call) from the second one. Also the first one uses Array.find and arrow functions that are not available in IE11.

How to convert UTF8 string to byte array?

I was using Joni's solution and it worked fine, but this one is much shorter.

This was inspired by the atobUTF16() function of Solution #3 of Mozilla's Base64 Unicode discussion

function convertStringToUTF8ByteArray(str) {
    let binaryArray = new Uint8Array(str.length)
    Array.prototype.forEach.call(binaryArray, function (el, idx, arr) { arr[idx] = str.charCodeAt(idx) })
    return binaryArray
}

Java client certificates over HTTPS/SSL

Have you set the KeyStore and/or TrustStore System properties?

java -Djavax.net.ssl.keyStore=pathToKeystore -Djavax.net.ssl.keyStorePassword=123456

or from with the code

System.setProperty("javax.net.ssl.keyStore", pathToKeyStore);

Same with javax.net.ssl.trustStore

Getting list of items inside div using Selenium Webdriver

alternatively, you can try writing a specific element:

    //label[1] is the first element.
    el =  await driver.findElement(By.xpath("//div[@class=\"facetContainerDiv\"]/div/label[1]/input")));
    await el.click();

More information can be found here: https://www.browserstack.com/guide/locators-in-selenium

How to normalize a NumPy array to within a certain range?

You can also rescale using sklearn. The advantages are that you can adjust normalize the standard deviation, in addition to mean-centering the data, and that you can do this on either axis, by features, or by records.

from sklearn.preprocessing import scale
X = scale( X, axis=0, with_mean=True, with_std=True, copy=True )

The keyword arguments axis, with_mean, with_std are self explanatory, and are shown in their default state. The argument copy performs the operation in-place if it is set to False. Documentation here.

Changing the background color of a drop down list transparent in html

Or maybe

 background: transparent !important;
 color: #ffffff;

How do I configure modprobe to find my module?

Follow following steps:

  1. Copy hello.ko to /lib/modules/'uname-r'/misc/
  2. Add misc/hello.ko entry in /lib/modules/'uname-r'/modules.dep
  3. sudo depmod
  4. sudo modprobe hello

modprobe will check modules.dep file for any dependency.

How do you tell if caps lock is on using JavaScript?

In jQuery:

$('some_element').keypress(function(e){
       if(e.keyCode == 20){
             //caps lock was pressed
       }
});

This jQuery plugin (code) implements the same idea as in Rajesh's answer a bit more succinctly.

JavaScript math, round to two decimal places

A small variation on the accepted answer. toFixed(2) returns a string, and you will always get two decimal places. These might be zeros. If you would like to suppress final zero(s), simply do this:

var discount = + ((price / listprice).toFixed(2));

Edited: I've just discovered what seems to be a bug in Firefox 35.0.1, which means that the above may give NaN with some values.
I've changed my code to

var discount = Math.round(price / listprice * 100) / 100;

This gives a number with up to two decimal places. If you wanted three, you would multiply and divide by 1000, and so on.
The OP wants two decimal places always, but if toFixed() is broken in Firefox it needs fixing first.
See https://bugzilla.mozilla.org/show_bug.cgi?id=1134388

TimeStamp on file name using PowerShell

Thanks for the above script. One little modification to add in the file ending correctly. Try this ...

$filenameFormat = "MyFileName" + " " + (Get-Date -Format "yyyy-MM-dd") **+ ".txt"**

Rename-Item -Path "C:\temp\MyFileName.txt" -NewName $filenameFormat

Why do I get permission denied when I try use "make" to install something?

I had a very similar error message as you, although listing a particular file:

$ make
make: execvp: ../HoughLineExtractor/houghlineextractor.hh: Permission denied
make: *** [../HoughLineAccumulator/houghlineaccumulator.o] Error 127

$ sudo make
make: execvp: ../HoughLineExtractor/houghlineextractor.hh: Permission denied
make: *** [../HoughLineAccumulator/houghlineaccumulator.o] Error 127

In my case, I forgot to add a trailing slash to indicate continuation of the line as shown:

${LINEDETECTOR_OBJECTS}:\
    ../HoughLineAccumulator/houghlineaccumulator.hh  # <-- missing slash!!
    ../HoughLineExtractor/houghlineextractor.hh

Hope that helps someone else who lands here from a search engine.

What exactly does big ? notation represent?

First of All Theory

  1. Big O = Upper Limit O(n)

  2. Theta = Order Function - theta(n)

  3. Omega = Q-Notation(Lower Limit) Q(n)

Why People Are so Confused?

In many Blogs & Books How this Statement is emphasised is Like

"This is Big O(n^3)" etc.

and people often Confuse like weather

O(n) == theta(n) == Q(n)

But What Worth keeping in mind is They Are Just Mathematical Function With Names O, Theta & Omega

so they have same General Formula of Polynomial,

Let,

f(n) = 2n4 + 100n2 + 10n + 50 then,

g(n) = n4, So g(n) is Function which Take function as Input and returns Variable with Biggerst Power,

Same f(n) & g(n) for Below all explainations

Big O - Function (Provides Upper Bound)

Big O(n4) = 3n4, Because 3n4 > 2n4

3n4 is value of Big O(n4) Just like f(x) = 3x

n4 is playing a role of x here so,

Replacing n4 with x'so, Big O(x') = 2x', Now we both are happy General Concept is

So 0 = f(n) = O(x')

O(x') = cg(n) = 3n4

Putting Value,

0 = 2n4 + 100n2 + 10n + 50 = 3n4

3n4 is our Upper Bound

Theta(n) Provides Lower Bound

Theta(n4) = cg(n) = 2n4 Because 2n4 = Our Example f(n)

2n4 is Value of Theta(n4)

so, 0 = cg(n) = f(n)

0 = 2n4 = 2n4 + 100n2 + 10n + 50

2n4 is our Lower Bound

Omega n - Order Function

This is Calculated to find out that weather lower Bound is similar to Upper bound,

Case 1). Upper Bound is Similar to Lower Bound

if Upper Bound is Similar to Lower Bound, The Average Case is Similar

Example, 2n4 = f(x) = 2n4,
Then Omega(n) = 2n4

Case 2). if Upper Bound is not Similar to Lower Bound

in this case, Omega(n) is Not fixed but Omega(n) is the set of functions with the same order of growth as g(n).

Example 2n4 = f(x) = 3n4, This is Our Default Case,
Then, Omega(n) = c'n4, is a set of functions with 2 = c' = 3

Hope This Explained!!

Python pip install fails: invalid command egg_info

try the following command:

pip install setuptools==28.8.0

Java: Get last element after split

Also you can use java.util.ArrayDeque

String last = new ArrayDeque<>(Arrays.asList("1-2".split("-"))).getLast();

Updating Python on Mac

You can also use:

brew upgrade python3

Xcode - ld: library not found for -lPods

My way

  1. create new project and install pod it will can run without error.

  2. Copy text in "Other Linker Flags" in new project to old project. Make old project to same new project.

  3. Check "Header Search Paths" too.

How to make a drop down list in yii2?

If you made it to the bottom of the list. Save some php code and just bring everything back from the DB as you need like this:

 $items = Standard::find()->select(['name'])->indexBy('s_id')->column();

how to set the background color of the whole page in css

Looks to me like you need to set the yellow on #doc3 and then get rid of the white that is called out on the #yui-main (which is covering up the color of the #doc3). This gets you yellow between header and footer.

Element-wise addition of 2 lists?

This is simple with numpy.add()

import numpy

list1 = numpy.array([1, 2, 3])
list2 = numpy.array([4, 5, 6])
result = numpy.add(list1, list2) # result receive element-wise addition of list1 and list2
print(result)
array([5, 7, 9])

See doc here

If you want to receiver a python list:

result.tolist()

LoDash: Get an array of values from an array of object properties

And if you need to extract several properties from each object, then

let newArr = _.map(arr, o => _.pick(o, ['name', 'surname', 'rate']));

How do I best silence a warning about unused variables?

Your current solution is best - comment out the parameter name if you don't use it. That applies to all compilers, so you don't have to use the pre-processor to do it specially for GCC.

How can I declare and use Boolean variables in a shell script?

There seems to be some misunderstanding here about the Bash builtin true, and more specifically, about how Bash expands and interprets expressions inside brackets.

The code in miku's answer has absolutely nothing to do with the Bash builtin true, nor /bin/true, nor any other flavor of the true command. In this case, true is nothing more than a simple character string, and no call to the true command/builtin is ever made, neither by the variable assignment, nor by the evaluation of the conditional expression.

The following code is functionally identical to the code in the miku's answer:

the_world_is_flat=yeah
if [ "$the_world_is_flat" = yeah ]; then
    echo 'Be careful not to fall off!'
fi

The only difference here is that the four characters being compared are 'y', 'e', 'a', and 'h' instead of 't', 'r', 'u', and 'e'. That's it. There's no attempt made to call a command or builtin named yeah, nor is there (in miku's example) any sort of special handling going on when Bash parses the token true. It's just a string, and a completely arbitrary one at that.

Update (2014-02-19): After following the link in miku's answer, now I see where some of the confusion is coming from. Miku's answer uses single brackets, but the code snippet he links to does not use brackets. It's just:

the_world_is_flat=true
if $the_world_is_flat; then
  echo 'Be careful not to fall off!'
fi

Both code snippets will behave the same way, but the brackets completely change what's going on under the hood.

Here's what Bash is doing in each case:

No brackets:

  1. Expand the variable $the_world_is_flat to the string "true".
  2. Attempt to parse the string "true" as a command.
  3. Find and run the true command (either a builtin or /bin/true, depending on the Bash version).
  4. Compare the exit code of the true command (which is always 0) with 0. Recall that in most shells, an exit code of 0 indicates success and anything else indicates failure.
  5. Since the exit code was 0 (success), execute the if statement's then clause

Brackets:

  1. Expand the variable $the_world_is_flat to the string "true".
  2. Parse the now-fully-expanded conditional expression, which is of the form string1 = string2. The = operator is bash's string comparison operator. So...
  3. Do a string comparison on "true" and "true".
  4. Yep, the two strings were the same, so the value of the conditional is true.
  5. Execute the if statement's then clause.

The no-brackets code works, because the true command returns an exit code of 0, which indicates success. The bracketed code works, because the value of $the_world_is_flat is identical to the string literal true on the right side of the =.

Just to drive the point home, consider the following two snippets of code:

This code (if run with root privileges) will reboot your computer:

var=reboot
if $var; then
  echo 'Muahahaha! You are going down!'
fi

This code just prints "Nice try." The reboot command is not called.

var=reboot
if [ $var ]; then
  echo 'Nice try.'
fi

Update (2014-04-14) To answer the question in the comments regarding the difference between = and ==: AFAIK, there is no difference. The == operator is a Bash-specific synonym for =, and as far as I've seen, they work exactly the same in all contexts.

Note, however, that I'm specifically talking about the = and == string comparison operators used in either [ ] or [[ ]] tests. I'm not suggesting that = and == are interchangeable everywhere in bash.

For example, you obviously can't do variable assignment with ==, such as var=="foo" (well technically you can do this, but the value of var will be "=foo", because Bash isn't seeing an == operator here, it's seeing an = (assignment) operator, followed by the literal value ="foo", which just becomes "=foo").

Also, although = and == are interchangeable, you should keep in mind that how those tests work does depend on whether you're using it inside [ ] or [[ ]], and also on whether or not the operands are quoted. You can read more about that in Advanced Bash Scripting Guide: 7.3 Other Comparison Operators (scroll down to the discussion of = and ==).

How can I make the browser wait to display the page until it's fully loaded?

Hope this code will help

 <html>  
    <head>
        <style type="text/css">
          .js #flash {display: none;}
        </style>
        <script type="text/javascript">
          document.documentElement.className = 'js';
        </script>
      </head>
      <body>
        <!-- the rest of your code goes here -->

        <script type="text/javascript" src="/scripts/jquery.js"></script>
        <script type="text/javascript">
          // Stuff to do as soon as the body finishes loading.
          // No need for $(document).ready() here.
        </script>
      </body>
    </html>

Execute Immediate within a stored procedure keeps giving insufficient priviliges error

you could use "AUTHID CURRENT_USER" in body of your procedure definition for your requirements.

How to use PHP with Visual Studio

Try Visual Studio Code. Very good support for PHP and other languages directly or via extensions. It can not replace power of Visual Studio but it is powerful addition to Visual Studio. And you can run it on all OS (Windows, Linux, Mac...).

https://code.visualstudio.com/

You don't have write permissions for the /var/lib/gems/2.3.0 directory

(January 2019) To install Ruby using the Rbenv script, follow these steps:

1. First, update the packages index and install the packages required for the ruby-build tool to build Ruby from source:

sudo apt-get remove ruby
sudo apt update
sudo apt install git curl libssl-dev libreadline-dev zlib1g-dev autoconf bison build-essential libyaml-dev libreadline-dev libncurses5-dev libffi-dev libgdbm-dev

2. Next, run the following curl command to install both rbenv and ruby-build:

curl -sL https://github.com/rbenv/rbenv-installer/raw/master/bin/rbenv-installer | bash -

3. Add $HOME/.rbenv/bin to the system PATH.

If you are using Bash, run:

echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bashrc
echo 'eval "$(rbenv init -)"' >> ~/.bashrc
source ~/.bashrc

If you are using Zsh run:

echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.zshrc
echo 'eval "$(rbenv init -)"' >> ~/.zshrc
source ~/.zshrc

4. Install the latest stable version of Ruby and set it as a default version with:

rbenv install 2.5.1
rbenv global 2.5.1

To list all available Ruby versions you can use: rbenv install -l

5. Verify that Ruby was properly installed by printing out the version number:

ruby -v

# Output
ruby 2.5.1p57 (2018-03-29 revision 63029) [x86_64-linux]

SOURCE: How To Install Ruby on Ubuntu 18.04

EDIT: Install rubygems:

sudo apt-get install rubygems

Using a batch to copy from network drive to C: or D: drive

Just do the following change

echo off
cls

echo Would you like to do a backup?

pause

copy "\\My_Servers_IP\Shared Drive\FolderName\*" C:\TEST_BACKUP_FOLDER

pause

Location of the mongodb database on mac

I had the same problem, with version 3.4.2

to run it (if you installed it with homebrew) run the process like this:

$ mongod --dbpath /usr/local/var/mongodb

String replace a Backslash

Try replaceAll("\\\\", "") or replaceAll("\\\\/", "/").

The problem here is that a backslash is (1) an escape chararacter in Java string literals, and (2) an escape character in regular expressions – each of this uses need doubling the character, in effect needing 4 \ in row.

Of course, as Bozho said, you need to do something with the result (assign it to some variable) and not throw it away. And in this case the non-regex variant is better.

Make div (height) occupy parent remaining height

Abstract

I didn't find a fully satisfying answer so I had to find it out myself.

My requirements:

  • the element should take exactly the remaining space either when its content size is smaller or bigger than the remaining space size (in the second case scrollbar should be shown);
  • the solution should work when the parent height is computed, and not specified;
  • calc() should not be used as the remaining element shouldn't know anything about another element sizes;
  • modern and familar layout technique such as flexboxes should be used.

The solution

  • Turn into flexboxes all direct parents with computed height (if any) and the next parent whose height is specified;
  • Specify flex-grow: 1 to all direct parents with computed height (if any) and the element so they will take up all remaining space when the element content size is smaller;
  • Specify flex-shrink: 0 to all flex items with fixed height so they won't become smaller when the element content size is bigger than the remaining space size;
  • Specify overflow: hidden to all direct parents with computed height (if any) to disable scrolling and forbid displaying overflow content;
  • Specify overflow: auto to the element to enable scrolling inside it.

JSFiddle (element has direct parents with computed height)

JSFiddle (simple case: no direct parents with computed height)

How to make RatingBar to show five stars

Another possibility is you are using the Rating in Adapter of list view

View android.view.LayoutInflater.inflate(int resource, ViewGroup root, boolean attachToRoot)

Below params are necessary for all the attributes to work properly:

  1. Set the root to parent
  2. boolean attachToRoot as false

Ex: convertView = inflater.inflate(R.layout.myId, parent, false);

Error TF30063: You are not authorized to access ... \DefaultCollection

I went through a number of these solutions too, here what worked for me:

For some reason Team explorer thought I was trying to upload to a new project.

Under Team Explorer -> Sync

I clicked "Advanced" which then showed a Project dropdown as well, which I didn't have to change in my case, I just clicked Publish Repository, and voila.

Best way to incorporate Volley (or other library) into Android Studio project

add

compile 'com.mcxiaoke.volley:library:1.0.19'
        compile project('volley')

in the dependencies, under build.gradle file of your app

DO NOT DISTURB THE build.gradle FILE OF YOUR LIBRARY. IT'S YOUR APP'S GRADLE FILE ONLY YOU NEED TO ALTER

Could not load file or assembly 'System.Web.Mvc'

I just wrote a blog post addressing this. You could install ASP.NET MVC on your server OR you can follow the steps here.


EDIT: (by jcolebrand) I went through this link, then had the same issue as Victor below, so I suggest you also add these:

* Microsoft.Web.Infrastructure
* System.Web.Razor
* System.Web.WebPages.Deployment
* System.Web.WebPages.Razor

How to read keyboard-input?

try

raw_input('Enter your input:')  # If you use Python 2
input('Enter your input:')      # If you use Python 3

and if you want to have a numeric value just convert it:

try:
    mode=int(raw_input('Input:'))
except ValueError:
    print "Not a number"

SSL handshake fails with - a verisign chain certificate - that contains two CA signed certificates and one self-signed certificate

It sounds like the intermediate certificate is missing. As of April 2006, all SSL certificates issued by VeriSign require the installation of an Intermediate CA Certificate.

It could be that you don't have the entire certificate chain loaded on your server. Some businesses do not allow their computers to download additional certificates, causing a failure to complete an SSL handshake.

Here is some information on intermediate chains:
https://knowledge.verisign.com/support/ssl-certificates-support/index?page=content&id=AR657
https://knowledge.verisign.com/support/ssl-certificates-support/index?page=content&id=AD146

Intermediate CA Certificates

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

Ctrl + . shows the menu. I find this easier to type than the alternative, Alt + Shift + F10.

This can be re-bound to something more familiar by going to Tools > Options > Environment > Keyboard > Visual C# > View.QuickActions

How to get images in Bootstrap's card to be the same height/width?

.card-img-top {
width: 100%;
height: 40vh;
object-fit: cover;
}

As shown above but when you add height i suggest using "vh" (Viewport Height units) for a more mobile-friendly experience.

Is there a way to "limit" the result with ELOQUENT ORM of Laravel?

Create a Game model which extends Eloquent and use this:

Game::take(30)->skip(30)->get();

take() here will get 30 records and skip() here will offset to 30 records.


In recent Laravel versions you can also use:

Game::limit(30)->offset(30)->get();

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

If you have a VPN needed to connect to your enterprise account and do a "git pull" this error will occur, just switch on your VPN and it will work.

How to export a Vagrant virtual machine to transfer it

As stated in

How can I change where Vagrant looks for its virtual hard drive?

the virtual-machine state is stored in a predefined VirtualBox folder. Copying the corresponding machine (folder) besides your vagrant-project to your other host should preserve your virtual machine state.

Do I need to explicitly call the base virtual destructor?

No you don't need to call the base destructor, a base destructor is always called for you by the derived destructor. Please see my related answer here for order of destruction.

To understand why you want a virtual destructor in the base class, please see the code below:

class B
{
public:
    virtual ~B()
    {
        cout<<"B destructor"<<endl;
    }
};


class D : public B
{
public:
    virtual ~D()
    {
        cout<<"D destructor"<<endl;
    }
};

When you do:

B *pD = new D();
delete pD;

Then if you did not have a virtual destructor in B, only ~B() would be called. But since you have a virtual destructor, first ~D() will be called, then ~B().

How to get the size of the current screen in WPF?

double screenWidth = System.Windows.SystemParameters.PrimaryScreenWidth;
double screenhight= System.Windows.SystemParameters.PrimaryScreenHeight;

What equivalents are there to TortoiseSVN, on Mac OSX?

I use svnX (http://code.google.com/p/svnx/downloads/list), it is free and usable, but not as user friendly as tortoise. It shows you the review before commit with diff for every file... but sometimes I still had to go to command line to fix some things

Removing elements from array Ruby

You may do:

a= [1,1,1,2,2,3]
delete_list = [1,3]
delete_list.each do |del|
    a.delete_at(a.index(del))
end

result : [1, 1, 2, 2]

Can I embed a .png image into an html page?

The 64base method works for large images as well, I use that method to embed all the images into my website, and it works every time. I've done with files up to 2Mb size, jpg and png.

How do I use a compound drawable instead of a LinearLayout that contains an ImageView and a TextView

TextView comes with 4 compound drawables, one for each of left, top, right and bottom.

In your case, you do not need the LinearLayout and ImageView at all. Just add android:drawableLeft="@drawable/up_count_big" to your TextView.

See TextView#setCompoundDrawablesWithIntrinsicBounds for more info.

How can I recursively find all files in current and subfolders based on wildcard matching?

Use find for that:

find . -name "foo*"

find needs a starting point, and the . (dot) points to the current directory.

using lodash .groupBy. how to add your own keys for grouped output?

Example groupBy and sum of a column using Lodash 4.17.4

   var data = [{
                "name": "jim",
                "color": "blue",
                "amount": 22
                }, {
                "name": "Sam",
                "color": "blue",
                "amount": 33
                }, {
               "name": "eddie",
               "color": "green",
               "amount": 77
              }];

      var result = _(data)
                   .groupBy(x => x.color)
                   .map((value, key) => 
                   ({color: key,
                    totalamount: _.sumBy(value,'amount'),
                    users: value})).value();

                    console.log(result);

Create Excel files from C# without office

You could use the ExcelStorage Class of the FileHelpers library, it's very easy and simple... you will need Excel 2000 or later installed on the machine.

The FileHelpers is a free and easy to use .NET library to import/export data from fixed length or delimited records in files, strings or streams.

What is the difference between Integrated Security = True and Integrated Security = SSPI?

True is only valid if you're using the .NET SqlClient library. It isn't valid when using OLEDB. Where SSPI is bvaid in both either you are using .net SqlClient library or OLEDB.

How do I copy a range of formula values and paste them to a specific range in another sheet?

How about if you're copying each column in a sheet to different sheets? Example: row B of mysheet to row B of sheet1, row C of mysheet to row B of sheet 2...

Remove an element from a Bash array

If anyone finds themselves in a position where they need to remember set -e or set -x values and be able to restore them, please check out this gist which uses the first array deletion solution to manage it's own stack:

https://gist.github.com/kigster/94799325e39d2a227ef89676eed44cc6

Using ResourceManager

The quick and dirty way to check what string you need it to look at the generated .resources files.

Your .resources are generated in the resources projects obj/Debug directory. (if not right click on .resx file in solution explorer and hit 'Run Custom Tool' to generate the .resources files)

Navigate to this directory and have a look at the filenames. You should see a file ending in XYZ.resources. Copy that filename and remove the trailing .resources and that is the file you should be loading.

For example in my obj/Bin directory I have the file:

MyLocalisation.Properties.Resources.resources

If the resource files are in the same Class library/Application I would use the following C#

ResourceManager RM = new ResourceManager("MyLocalisation.Properties.Resources", Assembly.GetExecutingAssembly());

However, as it sounds like you are using the resources file from a separate Class library/Application you probably want

Assembly localisationAssembly = Assembly.Load("MyLocalisation");
ResourceManager RM =  new ResourceManager("MyLocalisation.Properties.Resources", localisationAssembly);

How to change JAVA.HOME for Eclipse/ANT

In Eclipse the Ant java.home variable is not based on the Windows JAVA_HOME environment variable. Instead it is set to the home directory of the project's JRE.

To change the default JRE (e.g. change it to a JDK) you can go to Windows->Preferences... and choose Java->Installed JREs.

To change just a single project's JRE you can go to Project->Properties and choose Java Build Path and choose the Libraries tab. Find the JRE System Library and click it, then choose Edit and choose the JRE (or JDK) that you want.

If that doesn't work then when running the build file you can choose Run as->Ant Build... and click the JRE tab, choose separate JRE and specify the JRE you want there.

Can't find bundle for base name

If you are using IntelliJ IDE just right click on resources package and go to new and then select Resource Boundle it automatically create a .properties file for you. This did work for me .

PANIC: Cannot find AVD system path. Please define ANDROID_SDK_ROOT (in windows 10)

My problem was solved by creating a Windows user without an accent or special characters and reinstalling android studio on that user. Another change is to change the environment variables:

Left Click in My Computer > Advanced System Settings> Advanced > Environment Variables

ANDROID_HOME = c:\my_sdk_path

ANDROID_SDK_ROOT = c:\my_sdk_path

JAVA_HOME = c:\program files\Java\yourJavaPath

  • the default path of SDK is c:\users\youruser\AppData\LocalAndroid\sdk

Environment variables

Add in Path Variable the values:

  1. %ANDROID_HOME%\platform-tools

  2. %ANDROID_HOME%\tools

path variables

path values

After changes, restart windows and try again!

Iterate through a C++ Vector using a 'for' loop

The right way to do that is:

for(std::vector<T>::iterator it = v.begin(); it != v.end(); ++it) {
    it->doSomething();
 }

Where T is the type of the class inside the vector. For example if the class was CActivity, just write CActivity instead of T.

This type of method will work on every STL (Not only vectors, which is a bit better).

If you still want to use indexes, the way is:

for(std::vector<T>::size_type i = 0; i != v.size(); i++) {
    v[i].doSomething();
}

iframe refuses to display

The reason for the error is that the host server for https://cw.na1.hgncloud.com has provided some HTTP headers to protect the document. One of which is that the frame ancestors must be from the same domain as the original content. It seems you are attempting to put the iframe at a domain location that is not the same as the content of the iframe - thus violating the Content Security Policy that the host has set.

Check out this link on Content Security Policy for more details.

error UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

It simply means that one chose the wrong encoding to read the file.

On Mac, use file -I file.txt to find the correct encoding. On Linux, use file -i file.txt.

Importing large sql file to MySql via command line

+1 to @MartinNuc, you can run the mysql client in batch mode and then you won't see the long stream of "OK" lines.

The amount of time it takes to import a given SQL file depends on a lot of things. Not only the size of the file, but the type of statements in it, how powerful your server server is, and how many other things are running at the same time.

@MartinNuc says he can load 4GB of SQL in 4-5 minutes, but I have run 0.5 GB SQL files and had it take 45 minutes on a smaller server.

We can't really guess how long it will take to run your SQL script on your server.


Re your comment,

@MartinNuc is correct you can choose to make the mysql client print every statement. Or you could open a second session and run mysql> SHOW PROCESSLIST to see what's running. But you probably are more interested in a "percentage done" figure or an estimate for how long it will take to complete the remaining statements.

Sorry, there is no such feature. The mysql client doesn't know how long it will take to run later statements, or even how many there are. So it can't give a meaningful estimate for how much time it will take to complete.

How do you add input from user into list in Python

shopList = [] 
maxLengthList = 6
while len(shopList) < maxLengthList:
    item = input("Enter your Item to the List: ")
    shopList.append(item)
    print shopList
print "That's your Shopping List"
print shopList

How to set URL query params in Vue with Vue-Router

Without reloading the page or refreshing the dom, history.pushState can do the job.
Add this method in your component or elsewhere to do that:

addParamsToLocation(params) {
  history.pushState(
    {},
    null,
    this.$route.path +
      '?' +
      Object.keys(params)
        .map(key => {
          return (
            encodeURIComponent(key) + '=' + encodeURIComponent(params[key])
          )
        })
        .join('&')
  )
}

So anywhere in your component, call addParamsToLocation({foo: 'bar'}) to push the current location with query params in the window.history stack.

To add query params to current location without pushing a new history entry, use history.replaceState instead.

Tested with Vue 2.6.10 and Nuxt 2.8.1.

Be careful with this method!
Vue Router don't know that url has changed, so it doesn't reflect url after pushState.

How to avoid the "Windows Defender SmartScreen prevented an unrecognized app from starting warning"

After clicking on Properties of any installer(.exe) which block your application to install (Windows Defender SmartScreen prevented an unrecognized app ) for that issue i found one solution

  1. Right click on installer(.exe)
  2. Select properties option.
  3. Click on checkbox to check Unblock at the bottom of Properties.

This solution work for Heroku CLI (heroku-x64) installer(.exe)

Run Python script at startup in Ubuntu

In similar situations, I've done well by putting something like the following into /etc/rc.local:

cd /path/to/my/script
./my_script.py &
cd -
echo `date +%Y-%b-%d_%H:%M:%S` > /tmp/ran_rc_local  # check that rc.local ran

This has worked on multiple versions of Fedora and on Ubuntu 14.04 LTS, for both python and perl scripts.

ConnectivityManager getNetworkInfo(int) deprecated

Something like this:

public boolean hasConnection(final Context context){
    ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNW = cm.getActiveNetworkInfo();
    if (activeNW != null && activeNW.isConnected())
    {
        return true;
    }
    return false;
}

And in the main program body:

if(hasConnection(this)) {
    Toast.makeText(this, "Active networks OK ", Toast.LENGTH_LONG).show();
    getAccountData(token, tel);
}
else  Toast.makeText(this, "No active networks... ", Toast.LENGTH_LONG).show();

What's the difference between a word and byte?

BYTE

I am trying to answer this question from C++ perspective.

The C++ standard defines ‘byte’ as “Addressable unit of data large enough to hold any member of the basic character set of the execution environment.”

What this means is that the byte consists of at least enough adjacent bits to accommodate the basic character set for the implementation. That is, the number of possible values must equal or exceed the number of distinct characters. In the United States, the basic character sets are usually the ASCII and EBCDIC sets, each of which can be accommodated by 8 bits. Hence it is guaranteed that a byte will have at least 8 bits.

In other words, a byte is the amount of memory required to store a single character.

If you want to verify ‘number of bits’ in your C++ implementation, check the file ‘limits.h’. It should have an entry like below.

#define CHAR_BIT      8         /* number of bits in a char */

WORD

A Word is defined as specific number of bits which can be processed together (i.e. in one attempt) by the machine/system. Alternatively, we can say that Word defines the amount of data that can be transferred between CPU and RAM in a single operation.

The hardware registers in a computer machine are word sized. The Word size also defines the largest possible memory address (each memory address points to a byte sized memory).

Note – In C++ programs, the memory addresses points to a byte of memory and not to a word.

How to add and remove classes in Javascript without jQuery

The following 3 functions work in browsers which don't support classList:

function hasClass(el, className)
{
    if (el.classList)
        return el.classList.contains(className);
    return !!el.className.match(new RegExp('(\\s|^)' + className + '(\\s|$)'));
}

function addClass(el, className)
{
    if (el.classList)
        el.classList.add(className)
    else if (!hasClass(el, className))
        el.className += " " + className;
}

function removeClass(el, className)
{
    if (el.classList)
        el.classList.remove(className)
    else if (hasClass(el, className))
    {
        var reg = new RegExp('(\\s|^)' + className + '(\\s|$)');
        el.className = el.className.replace(reg, ' ');
    }
}

https://jaketrent.com/post/addremove-classes-raw-javascript/

.htaccess redirect all pages to new domain

This is a bug in older versions of apache (and thus mod_rewrite) where the path prefix was appended to the rewritten path if it got changed. See here

I think it was fixed in apache2 V2.2.12, there is a special flag you need to use which i will add here when i find it, (i think it was NP for No Path)

RewriteRule ^(.*)$ http://newdomain.com/ [??]

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...

Search and replace a particular string in a file using Perl

You could also do this:

#!/usr/bin/perl

use strict;
use warnings;

$^I = '.bak'; # create a backup copy 

while (<>) {
   s/<PREF>/ABCD/g; # do the replacement
   print; # print to the modified file
}

Invoke the script with by

./script.pl input_file

You will get a file named input_file, containing your changes, and a file named input_file.bak, which is simply a copy of the original file.

Check if a value exists in ArrayList

When Array List contains object of Primitive DataType.

Use this function:
arrayList.contains(value);

if list contains that value then it will return true else false.

When Array List contains object of UserDefined DataType.

Follow this below Link 

How to compare Objects attributes in an ArrayList?

I hope this solution will help you. Thanks

How to create new div dynamically, change it, move it, modify it in every way possible, in JavaScript?

Have you tried JQuery? Vanilla javascript can be tough. Try using this:

$('.container-element').add('<div>Insert Div Content</div>');

.container-element is a JQuery selector that marks the element with the class "container-element" (presumably the parent element in which you want to insert your divs). Then the add() function inserts HTML into the container-element.

What certificates are trusted in truststore?

Trust store generally (actually should only contain root CAs but this rule is violated in general) contains the certificates that of the root CAs (public CAs or private CAs). You can verify the list of certs in trust store using

keytool -list -v -keystore truststore.jks

Powershell folder size of folders without listing Subdirectories

Interesting how powerful yet how helpless PS can be in the same time, coming from a Nix learning PS. after install crgwin/gitbash, you can do any combination in one commands:

size of current folder: du -sk .

size of all files and folders under current directory du -sk *

size of all subfolders (including current folders) find ./ -type d -exec du -sk {} \;

"Non-resolvable parent POM: Could not transfer artifact" when trying to refer to a parent pom from a child pom with ${parent.groupid}

As Nayan said the Path has to updated properly in my case the apache-maven was installed in C:\apache-maven and settings.xml was found inside C:\apache-maven\conf\settings.xml

if this doesn't work go to your local repos
in my case C:\Users\<<"name">>.m2\
and search for .lastUpdated and delete them
then build the maven

Calculating time difference between 2 dates in minutes

I am using below code for today and database date.

TIMESTAMPDIFF(MINUTE,T.runTime,NOW()) > 20

According to the documentation, the first argument can be any of the following:

MICROSECOND
SECOND
MINUTE
HOUR
DAY
WEEK
MONTH
QUARTER
YEAR

How to install plugin for Eclipse from .zip

Download the plugin, extract it inside eclipse/dropins folder and restart your Eclipse IDE. You may require to pass --clean along with eclipse command

How to install PyQt4 on Windows using pip?

I am using PyCharm, and was able to install PyQt5.

PyQt4, as well as PyQt4Enhanced and windows_whl both failed to install, I'm guessing that's because Qt4 is no longer supported.

How to rename files and folder in Amazon S3?

We have 2 ways by which we can rename a file on AWS S3 storage -

1 .Using the CLI tool -

aws s3 --recursive mv s3://bucket-name/dirname/oldfile s3://bucket-name/dirname/newfile

2.Using SDK

$s3->copyObject(array(
'Bucket'     => $targetBucket,
'Key'        => $targetKeyname,
'CopySource' => "{$sourceBucket}/{$sourceKeyname}",));

How to write a multidimensional array to a text file?

ndarray.tofile() should also work

e.g. if your array is called a:

a.tofile('yourfile.txt',sep=" ",format="%s")

Not sure how to get newline formatting though.

Edit (credit Kevin J. Black's comment here):

Since version 1.5.0, np.tofile() takes an optional parameter newline='\n' to allow multi-line output. https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.savetxt.html

While loop in batch

@echo off

set countfiles=10

:loop

set /a countfiles -= 1

echo hi

if %countfiles% GTR 0 goto loop

pause

on the first "set countfiles" the 10 you see is the amount it will loop the echo hi is the thing you want to loop

...i'm 5 years late

How to pull remote branch from somebody else's repo

No, you don't need to add them as a remote. That would be clumbersome and a pain to do each time.

Grabbing their commits:

git fetch [email protected]:theirusername/reponame.git theirbranch:ournameforbranch

This creates a local branch named ournameforbranch which is exactly the same as what theirbranch was for them. For the question example, the last argument would be foo:foo.

Note :ournameforbranch part can be further left off if thinking up a name that doesn't conflict with one of your own branches is bothersome. In that case, a reference called FETCH_HEAD is available. You can git log FETCH_HEAD to see their commits then do things like cherry-picked to cherry pick their commits.

Pushing it back to them:

Oftentimes, you want to fix something of theirs and push it right back. That's possible too:

git fetch [email protected]:theirusername/reponame.git theirbranch
git checkout FETCH_HEAD

# fix fix fix

git push [email protected]:theirusername/reponame.git HEAD:theirbranch

If working in detached state worries you, by all means create a branch using :ournameforbranch and replace FETCH_HEAD and HEAD above with ournameforbranch.

Convert from days to milliseconds

You can use this utility class -

public class DateUtils
{
    public static final long SECOND_IN_MILLIS = 1000;
    public static final long MINUTE_IN_MILLIS = SECOND_IN_MILLIS * 60;
    public static final long HOUR_IN_MILLIS = MINUTE_IN_MILLIS * 60;
    public static final long DAY_IN_MILLIS = HOUR_IN_MILLIS * 24;
    public static final long WEEK_IN_MILLIS = DAY_IN_MILLIS * 7;
}

If you are working on Android framework then just import it (also named DateUtils) under package android.text.format

A generic list of anonymous class

I'm very surprised nobody has suggested collection initializers. This way can only add objects when the list is created hence the name however it seems like the nicest way of doing it. No need to create an array then convert it to a list.

var list = new List<dynamic>() 
{ 
    new { Id = 1, Name = "Foo" }, 
    new { Id = 2, Name = "Bar" } 
};

You can always use object instead of dynamic but trying to keep it in a true generic way then dynamic makes more sense.

SQL Query - how do filter by null or not null

WHERE something IS NULL

and

WHERE something IS NOT NULL